@intelliweave/embedded 2.0.72-beta.3 → 2.0.72-beta.5
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.
|
@@ -92,7 +92,7 @@ ${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"ope
|
|
|
92
92
|
`;break;case"id":a=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new qy(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:g}));break;default:r(new qy(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:y,line:g}));break}}function f(){l.length>0&&e({id:a,event:c||void 0,data:l.endsWith(`
|
|
93
93
|
`)?l.slice(0,-1):l}),a=void 0,l="",c=""}function m(h={}){o&&h.consume&&d(o),s=!0,a=void 0,l="",c="",o=""}return{feed:u,reset:m}}function n8(t){let e=[],r="",n=0;for(;n<t.length;){let i=t.indexOf("\r",n),o=t.indexOf(`
|
|
94
94
|
`,n),s=-1;if(i!==-1&&o!==-1?s=Math.min(i,o):i!==-1?s=i:o!==-1&&(s=o),s===-1){r=t.slice(n);break}else{let a=t.slice(n,s);e.push(a),n=s+1,t[n-1]==="\r"&&t[n]===`
|
|
95
|
-
`&&n++}}return[e,r]}var By=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=Wy({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}};var i8={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},As=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Gy=class{constructor(e,r){var n;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Vy(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:i8}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=ku((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i,o;let{resumptionToken:s}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);let l=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!l.ok){if(await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.status===401&&this._authProvider)return await this._authThenStart();if(l.status===405)return;throw new As(l.status,`Failed to open SSE stream: ${l.statusText}`)}this._handleSseStream(l.body,e,!0)}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){var n;let i=this._reconnectionOptions.maxRetries;if(r>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,l=!1;(async()=>{var u,d,p,f;try{let m=e.pipeThrough(new TextDecoderStream).pipeThrough(new By({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:_}=await m.read();if(_)break;if(g.id&&(s=g.id,a=!0,i?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let b=Gc.parse(JSON.parse(g.data));ka(b)&&(l=!0,o!==void 0&&(b.id=o)),(u=this.onmessage)===null||u===void 0||u.call(this,b)}catch(b){(d=this.onerror)===null||d===void 0||d.call(this,b)}}(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(m){if((p=this.onerror)===null||p===void 0||p.call(this,new Error(`SSE stream disconnected: ${m}`)),(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(g){(f=this.onerror)===null||f===void 0||f.call(this,new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Br("No auth provider");if(await No(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,i,o,s,a,l,c;try{let{resumptionToken:u,onresumptiontoken:d}=r||{};if(u){this._startOrAuthSse({resumptionToken:u,replayMessageId:df(e)?e.id:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let p=await this._commonHeaders();p.set("content-type","application/json"),p.set("accept","application/json, text/event-stream");let f={...this._requestInit,method:"POST",headers:p,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},m=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,f),h=m.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!m.ok){let b=await m.text().catch(()=>null);if(m.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new As(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:E,scope:I}=Su(m);if(this._resourceMetadataUrl=E,this._scope=I,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this._hasCompletedAuthFlow=!0,this.send(e)}if(m.status===403&&this._authProvider){let{resourceMetadataUrl:E,scope:I,error:P}=Su(m);if(P==="insufficient_scope"){let M=m.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===M)throw new As(403,"Server returned 403 after trying upscoping");if(I&&(this._scope=I),E&&(this._resourceMetadataUrl=E),this._lastUpscopingHeader=M??void 0,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Br;return this.send(e)}}throw new As(m.status,`Error POSTing to endpoint: ${b}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,m.status===202){await((o=m.body)===null||o===void 0?void 0:o.cancel()),WA(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let g=(Array.isArray(e)?e:[e]).filter(b=>"method"in b&&"id"in b&&b.id!==void 0).length>0,_=m.headers.get("content-type");if(g)if(_?.includes("text/event-stream"))this._handleSseStream(m.body,{onresumptiontoken:d},!1);else if(_?.includes("application/json")){let b=await m.json(),E=Array.isArray(b)?b.map(I=>Gc.parse(I)):[Gc.parse(b)];for(let I of E)(s=this.onmessage)===null||s===void 0||s.call(this,I)}else throw await((a=m.body)===null||a===void 0?void 0:a.cancel()),new As(-1,`Unexpected content type: ${_}`);else await((l=m.body)===null||l===void 0?void 0:l.cancel())}catch(u){throw(c=this.onerror)===null||c===void 0||c.call(this,u),u}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n,i;if(this._sessionId)try{let o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(await((n=a.body)===null||n===void 0?void 0:n.cancel()),!a.ok&&a.status!==405)throw new As(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Xy=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(vM(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(vM(this),r)}};function o8(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function BS(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(BS).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${BS(t.cause)}`:t.message:`${t}`}function vM(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var bM=t=>{throw TypeError(t)},eI=(t,e,r)=>e.has(t)||bM("Cannot "+r),Ze=(t,e,r)=>(eI(t,e,"read from private field"),r?r.call(t):e.get(t)),er=(t,e,r)=>e.has(t)?bM("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Et=(t,e,r,n)=>(eI(t,e,"write to private field"),e.set(t,r),r),Co=(t,e,r)=>(eI(t,e,"access private method"),r),ln,Ja,Iu,Hy,Ky,jp,Tu,Dp,zs,Eu,Au,Pu,Rp,hi,GS,HS,XS,_M,KS,JS,Mp,YS,QS,Ya=class extends EventTarget{constructor(e,r){var n,i;super(),er(this,hi),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,er(this,ln),er(this,Ja),er(this,Iu),er(this,Hy),er(this,Ky),er(this,jp),er(this,Tu),er(this,Dp,null),er(this,zs),er(this,Eu),er(this,Au,null),er(this,Pu,null),er(this,Rp,null),er(this,HS,async o=>{var s;Ze(this,Eu).reset();let{body:a,redirected:l,status:c,headers:u}=o;if(c===204){Co(this,hi,Mp).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Et(this,Iu,new URL(o.url)):Et(this,Iu,void 0),c!==200){Co(this,hi,Mp).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Co(this,hi,Mp).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Ze(this,ln)===this.CLOSED)return;Et(this,ln,this.OPEN);let d=new Event("open");if((s=Ze(this,Rp))==null||s.call(this,d),this.dispatchEvent(d),typeof a!="object"||!a||!("getReader"in a)){Co(this,hi,Mp).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let p=new TextDecoder,f=a.getReader(),m=!0;do{let{done:h,value:y}=await f.read();y&&Ze(this,Eu).feed(p.decode(y,{stream:!h})),h&&(m=!1,Ze(this,Eu).reset(),Co(this,hi,YS).call(this))}while(m)}),er(this,XS,o=>{Et(this,zs,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Co(this,hi,YS).call(this,BS(o))}),er(this,KS,o=>{typeof o.id=="string"&&Et(this,Dp,o.id);let s=new MessageEvent(o.event||"message",{data:o.data,origin:Ze(this,Iu)?Ze(this,Iu).origin:Ze(this,Ja).origin,lastEventId:o.id||""});Ze(this,Pu)&&(!o.event||o.event==="message")&&Ze(this,Pu).call(this,s),this.dispatchEvent(s)}),er(this,JS,o=>{Et(this,jp,o)}),er(this,QS,()=>{Et(this,Tu,void 0),Ze(this,ln)===this.CONNECTING&&Co(this,hi,GS).call(this)});try{if(e instanceof URL)Et(this,Ja,e);else if(typeof e=="string")Et(this,Ja,new URL(e,s8()));else throw new Error("Invalid URL")}catch{throw o8("An invalid or illegal string was specified")}Et(this,Eu,Wy({onEvent:Ze(this,KS),onRetry:Ze(this,JS)})),Et(this,ln,this.CONNECTING),Et(this,jp,3e3),Et(this,Ky,(n=r?.fetch)!=null?n:globalThis.fetch),Et(this,Hy,(i=r?.withCredentials)!=null?i:!1),Co(this,hi,GS).call(this)}get readyState(){return Ze(this,ln)}get url(){return Ze(this,Ja).href}get withCredentials(){return Ze(this,Hy)}get onerror(){return Ze(this,Au)}set onerror(e){Et(this,Au,e)}get onmessage(){return Ze(this,Pu)}set onmessage(e){Et(this,Pu,e)}get onopen(){return Ze(this,Rp)}set onopen(e){Et(this,Rp,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){Ze(this,Tu)&&clearTimeout(Ze(this,Tu)),Ze(this,ln)!==this.CLOSED&&(Ze(this,zs)&&Ze(this,zs).abort(),Et(this,ln,this.CLOSED),Et(this,zs,void 0))}};ln=new WeakMap,Ja=new WeakMap,Iu=new WeakMap,Hy=new WeakMap,Ky=new WeakMap,jp=new WeakMap,Tu=new WeakMap,Dp=new WeakMap,zs=new WeakMap,Eu=new WeakMap,Au=new WeakMap,Pu=new WeakMap,Rp=new WeakMap,hi=new WeakSet,GS=function(){Et(this,ln,this.CONNECTING),Et(this,zs,new AbortController),Ze(this,Ky)(Ze(this,Ja),Co(this,hi,_M).call(this)).then(Ze(this,HS)).catch(Ze(this,XS))},HS=new WeakMap,XS=new WeakMap,_M=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ze(this,Dp)?{"Last-Event-ID":Ze(this,Dp)}:void 0},cache:"no-store",signal:(t=Ze(this,zs))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},KS=new WeakMap,JS=new WeakMap,Mp=function(t,e){var r;Ze(this,ln)!==this.CLOSED&&Et(this,ln,this.CLOSED);let n=new Xy("error",{code:e,message:t});(r=Ze(this,Au))==null||r.call(this,n),this.dispatchEvent(n)},YS=function(t,e){var r;if(Ze(this,ln)===this.CLOSED)return;Et(this,ln,this.CONNECTING);let n=new Xy("error",{code:e,message:t});(r=Ze(this,Au))==null||r.call(this,n),this.dispatchEvent(n),Et(this,Tu,setTimeout(Ze(this,QS),Ze(this,jp)))},QS=new WeakMap,Ya.CONNECTING=0,Ya.OPEN=1,Ya.CLOSED=2;function s8(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var tI=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Jy=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Vy(r?.fetch,r?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=ku((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}_startOrAuth(){var e,r,n;let i=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,s)=>{this._eventSource=new Ya(this._url.href,{...this._eventSourceInit,fetch:async(a,l)=>{let c=await this._commonHeaders();c.set("Accept","text/event-stream");let u=await i(a,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){let{resourceMetadataUrl:d,scope:p}=Su(u);this._resourceMetadataUrl=d,this._scope=p}return u}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var l;if(a.code===401&&this._authProvider){this._authThenStart().then(o,s);return}let c=new tI(a.code,a.message,a);s(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var l;let c=a;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){s(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}o()}),this._eventSource.onmessage=a=>{var l,c;let u=a,d;try{d=Gc.parse(JSON.parse(u.data))}catch(p){(l=this.onerror)===null||l===void 0||l.call(this,p);return}(c=this.onmessage)===null||c===void 0||c.call(this,d)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Br("No auth provider");if(await No(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,i,o;if(!this._endpoint)throw new Error("Not connected");try{let s=await this._commonHeaders();s.set("content-type","application/json");let a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},l=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,a);if(!l.ok){let c=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){let{resourceMetadataUrl:u,scope:d}=Su(l);if(this._resourceMetadataUrl=u,this._scope=d,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}await((i=l.body)===null||i===void 0?void 0:i.cancel())}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}};var Fi={name:"@intelliweave/embedded",version:"2.0.72-beta.3",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};var tr=new Ve("MCPKnowledgeClient"),Yy=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){tr.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new xp({name:Fi.name,version:Fi.version}),n=new Gy(new URL(this.config.baseURL));return await r.connect(n),tr.debug("Connected with HTTP streaming mode"),r}).catch(async r=>{let n=new xp({name:Fi.name,version:Fi.version}),i=new Jy(new URL(this.config.baseURL));return await n.connect(i),tr.debug("Connected with SSE mode"),n});return await this.disconnect(),this.client=e,e.onerror=r=>{tr.error(`MCP client error: ${r.message}`)},e.onclose=()=>{tr.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(ax,r=>{r.params.level=="critical"?tr.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?tr.error(`[Server] ${r.params.data}`):r.params.level=="error"?tr.error(`[Server] ${r.params.data}`):r.params.level=="warning"?tr.warn(`[Server] ${r.params.data}`):r.params.level=="info"?tr.info(`[Server] ${r.params.data}`):r.params.level=="debug"?tr.debug(`[Server] ${r.params.data}`):tr.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(sx,r=>{tr.debug("Tool list changed",r),this.fetchTools()}),tr.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],r;for(;;){let i=await this.client.listTools({cursor:r});r=i.nextCursor;for(let o of i.tools||[])e.push(o);if(!i?.tools?.length||!r)break}let n=[];for(let i of e){let o=!!(this.config.searchToolName&&i.name==this.config.searchToolName&&!this.config.searchToolVisible);n.push({id:i.name,name:i.name,content:i.description||"",type:"action",isContext:!0,parameters:i.inputSchema,action:s=>this.performToolCall(i.name,s),disabled:o})}tr.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let r=this.iwActions.slice(),n=await this.performSearchCall(e);return r=r.concat(n),this.lastSearchQuery=e,this.lastSearchResults=r,tr.debug(`Search completed, found ${r.length} items.`),r}async performSearchCall(e){let r=[];if(!this.config.searchToolName)return r;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return tr.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),r;let i;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let s=i[o];r.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else r.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof i=="string"?i:JSON.stringify(i)});return r}async performToolCall(e,r){await this.connect(),tr.debug(`Performing tool call for ${e} with params:`,r),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:r});if(n.isError){let i=n.content?.[0]?.text||"Unknown error";throw tr.error(`Error calling tool ${e}: ${i}`),new Error(`Error calling tool ${e}: ${i}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};var l8=new Ve("Statistics"),Lp=[];async function Gr(t,e){let r={...e,event_id:dr(),event_date:new Date().toISOString(),sdk_version:Fi.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(Lp.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),Lp.length===0))return;let n=Lp.slice();Lp.length=0;try{let i=await fetch(t.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){l8.warn("Failed to submit analytics event:",i),Lp.push(...n);return}}var Qa=new Ve("KnowledgeBase"),rI=1,Qy=class t{constructor(e){this._sources=[{id:"core.internal",query:async()=>hP(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=e}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${rI++}`),this._sources.push({id:n,query:r}),n}removeSource(e){this._sources=this.sources.filter(r=>r.id!==e&&r.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(r=>r.id!==e)}get sources(){let e=this._sources;return St().knowledgeBaseSources&&(e=e.concat(St().knowledgeBaseSources)),e=e.concat(this._windowSources),e=e.filter(r=>!r.disabled),e}async search(e){let r=Date.now();Qa.debug(`Searching knowledge base for: ${e}`);let n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],typeof document<"u"&&document.dispatchEvent(n),this._windowSources=n.sources;let o=(await Promise.all(this.sources.map(async c=>{try{let u=Date.now(),d=await c.query(e);return Qa.debug(`Source '${c.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return Qa.warn(`Knowledge source '${c.id}' failed:`,u),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),St().knowledgeBase&&(o=o.concat(St().knowledgeBase)),o=o.filter(c=>c&&!c.disabled);for(let c=0;c<o.length;c++){let u=o[c];u.id=u.id||`temp.${c}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new mP({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let l=s.search(e).map(c=>o.find(u=>u.id==c.id));for(let c of o)c.isContext&&(l.find(u=>u.id===c.id)||l.push(c));return this.lastResults=l,Gr(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Qa.debug("Found results:",l),l}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${rI++}`),Qa.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(l,c)=>{Qa.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,actionID:l.id,parameters:c},d=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let p=await d.json();return a(p.updateItems||[]),p.response},a=l=>{for(let c of l){if(!c.id){Qa.warn("KB item skipped since it has no ID.",c);continue}let u=n.find(d=>d.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}n.push({...c,action:d=>s(c,d)})}};this.registerSource(r,async l=>{if(o&&i.includes(l))return n;let c={type:"search",userID:this.ai?.userID||"",query:l},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(l)||i.push(l),a(d.items),n})}clone(){let e=new t(this.ai);return e._sources=this._sources,e._windowSources=this._windowSources,e.manualEntries=this.manualEntries,e}registerMCPSource(e){e.id||(e.id=`external.${rI++}`);let r=new Yy(e);return this.registerSource(e.id,n=>r.search(n)),r}};var ev=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
95
|
+
`&&n++}}return[e,r]}var By=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=Wy({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}};var i8={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},As=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Gy=class{constructor(e,r){var n;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Vy(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:i8}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=ku((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i,o;let{resumptionToken:s}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);let l=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!l.ok){if(await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.status===401&&this._authProvider)return await this._authThenStart();if(l.status===405)return;throw new As(l.status,`Failed to open SSE stream: ${l.statusText}`)}this._handleSseStream(l.body,e,!0)}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){var n;let i=this._reconnectionOptions.maxRetries;if(r>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,l=!1;(async()=>{var u,d,p,f;try{let m=e.pipeThrough(new TextDecoderStream).pipeThrough(new By({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:_}=await m.read();if(_)break;if(g.id&&(s=g.id,a=!0,i?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let b=Gc.parse(JSON.parse(g.data));ka(b)&&(l=!0,o!==void 0&&(b.id=o)),(u=this.onmessage)===null||u===void 0||u.call(this,b)}catch(b){(d=this.onerror)===null||d===void 0||d.call(this,b)}}(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(m){if((p=this.onerror)===null||p===void 0||p.call(this,new Error(`SSE stream disconnected: ${m}`)),(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(g){(f=this.onerror)===null||f===void 0||f.call(this,new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Br("No auth provider");if(await No(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,i,o,s,a,l,c;try{let{resumptionToken:u,onresumptiontoken:d}=r||{};if(u){this._startOrAuthSse({resumptionToken:u,replayMessageId:df(e)?e.id:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let p=await this._commonHeaders();p.set("content-type","application/json"),p.set("accept","application/json, text/event-stream");let f={...this._requestInit,method:"POST",headers:p,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},m=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,f),h=m.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!m.ok){let b=await m.text().catch(()=>null);if(m.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new As(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:E,scope:I}=Su(m);if(this._resourceMetadataUrl=E,this._scope=I,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this._hasCompletedAuthFlow=!0,this.send(e)}if(m.status===403&&this._authProvider){let{resourceMetadataUrl:E,scope:I,error:P}=Su(m);if(P==="insufficient_scope"){let M=m.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===M)throw new As(403,"Server returned 403 after trying upscoping");if(I&&(this._scope=I),E&&(this._resourceMetadataUrl=E),this._lastUpscopingHeader=M??void 0,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Br;return this.send(e)}}throw new As(m.status,`Error POSTing to endpoint: ${b}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,m.status===202){await((o=m.body)===null||o===void 0?void 0:o.cancel()),WA(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let g=(Array.isArray(e)?e:[e]).filter(b=>"method"in b&&"id"in b&&b.id!==void 0).length>0,_=m.headers.get("content-type");if(g)if(_?.includes("text/event-stream"))this._handleSseStream(m.body,{onresumptiontoken:d},!1);else if(_?.includes("application/json")){let b=await m.json(),E=Array.isArray(b)?b.map(I=>Gc.parse(I)):[Gc.parse(b)];for(let I of E)(s=this.onmessage)===null||s===void 0||s.call(this,I)}else throw await((a=m.body)===null||a===void 0?void 0:a.cancel()),new As(-1,`Unexpected content type: ${_}`);else await((l=m.body)===null||l===void 0?void 0:l.cancel())}catch(u){throw(c=this.onerror)===null||c===void 0||c.call(this,u),u}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n,i;if(this._sessionId)try{let o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(await((n=a.body)===null||n===void 0?void 0:n.cancel()),!a.ok&&a.status!==405)throw new As(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Xy=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(vM(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(vM(this),r)}};function o8(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function BS(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(BS).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${BS(t.cause)}`:t.message:`${t}`}function vM(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var bM=t=>{throw TypeError(t)},eI=(t,e,r)=>e.has(t)||bM("Cannot "+r),Ze=(t,e,r)=>(eI(t,e,"read from private field"),r?r.call(t):e.get(t)),er=(t,e,r)=>e.has(t)?bM("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Et=(t,e,r,n)=>(eI(t,e,"write to private field"),e.set(t,r),r),Co=(t,e,r)=>(eI(t,e,"access private method"),r),ln,Ja,Iu,Hy,Ky,jp,Tu,Dp,zs,Eu,Au,Pu,Rp,hi,GS,HS,XS,_M,KS,JS,Mp,YS,QS,Ya=class extends EventTarget{constructor(e,r){var n,i;super(),er(this,hi),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,er(this,ln),er(this,Ja),er(this,Iu),er(this,Hy),er(this,Ky),er(this,jp),er(this,Tu),er(this,Dp,null),er(this,zs),er(this,Eu),er(this,Au,null),er(this,Pu,null),er(this,Rp,null),er(this,HS,async o=>{var s;Ze(this,Eu).reset();let{body:a,redirected:l,status:c,headers:u}=o;if(c===204){Co(this,hi,Mp).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Et(this,Iu,new URL(o.url)):Et(this,Iu,void 0),c!==200){Co(this,hi,Mp).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Co(this,hi,Mp).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Ze(this,ln)===this.CLOSED)return;Et(this,ln,this.OPEN);let d=new Event("open");if((s=Ze(this,Rp))==null||s.call(this,d),this.dispatchEvent(d),typeof a!="object"||!a||!("getReader"in a)){Co(this,hi,Mp).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let p=new TextDecoder,f=a.getReader(),m=!0;do{let{done:h,value:y}=await f.read();y&&Ze(this,Eu).feed(p.decode(y,{stream:!h})),h&&(m=!1,Ze(this,Eu).reset(),Co(this,hi,YS).call(this))}while(m)}),er(this,XS,o=>{Et(this,zs,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Co(this,hi,YS).call(this,BS(o))}),er(this,KS,o=>{typeof o.id=="string"&&Et(this,Dp,o.id);let s=new MessageEvent(o.event||"message",{data:o.data,origin:Ze(this,Iu)?Ze(this,Iu).origin:Ze(this,Ja).origin,lastEventId:o.id||""});Ze(this,Pu)&&(!o.event||o.event==="message")&&Ze(this,Pu).call(this,s),this.dispatchEvent(s)}),er(this,JS,o=>{Et(this,jp,o)}),er(this,QS,()=>{Et(this,Tu,void 0),Ze(this,ln)===this.CONNECTING&&Co(this,hi,GS).call(this)});try{if(e instanceof URL)Et(this,Ja,e);else if(typeof e=="string")Et(this,Ja,new URL(e,s8()));else throw new Error("Invalid URL")}catch{throw o8("An invalid or illegal string was specified")}Et(this,Eu,Wy({onEvent:Ze(this,KS),onRetry:Ze(this,JS)})),Et(this,ln,this.CONNECTING),Et(this,jp,3e3),Et(this,Ky,(n=r?.fetch)!=null?n:globalThis.fetch),Et(this,Hy,(i=r?.withCredentials)!=null?i:!1),Co(this,hi,GS).call(this)}get readyState(){return Ze(this,ln)}get url(){return Ze(this,Ja).href}get withCredentials(){return Ze(this,Hy)}get onerror(){return Ze(this,Au)}set onerror(e){Et(this,Au,e)}get onmessage(){return Ze(this,Pu)}set onmessage(e){Et(this,Pu,e)}get onopen(){return Ze(this,Rp)}set onopen(e){Et(this,Rp,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){Ze(this,Tu)&&clearTimeout(Ze(this,Tu)),Ze(this,ln)!==this.CLOSED&&(Ze(this,zs)&&Ze(this,zs).abort(),Et(this,ln,this.CLOSED),Et(this,zs,void 0))}};ln=new WeakMap,Ja=new WeakMap,Iu=new WeakMap,Hy=new WeakMap,Ky=new WeakMap,jp=new WeakMap,Tu=new WeakMap,Dp=new WeakMap,zs=new WeakMap,Eu=new WeakMap,Au=new WeakMap,Pu=new WeakMap,Rp=new WeakMap,hi=new WeakSet,GS=function(){Et(this,ln,this.CONNECTING),Et(this,zs,new AbortController),Ze(this,Ky)(Ze(this,Ja),Co(this,hi,_M).call(this)).then(Ze(this,HS)).catch(Ze(this,XS))},HS=new WeakMap,XS=new WeakMap,_M=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ze(this,Dp)?{"Last-Event-ID":Ze(this,Dp)}:void 0},cache:"no-store",signal:(t=Ze(this,zs))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},KS=new WeakMap,JS=new WeakMap,Mp=function(t,e){var r;Ze(this,ln)!==this.CLOSED&&Et(this,ln,this.CLOSED);let n=new Xy("error",{code:e,message:t});(r=Ze(this,Au))==null||r.call(this,n),this.dispatchEvent(n)},YS=function(t,e){var r;if(Ze(this,ln)===this.CLOSED)return;Et(this,ln,this.CONNECTING);let n=new Xy("error",{code:e,message:t});(r=Ze(this,Au))==null||r.call(this,n),this.dispatchEvent(n),Et(this,Tu,setTimeout(Ze(this,QS),Ze(this,jp)))},QS=new WeakMap,Ya.CONNECTING=0,Ya.OPEN=1,Ya.CLOSED=2;function s8(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var tI=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Jy=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Vy(r?.fetch,r?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=ku((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}_startOrAuth(){var e,r,n;let i=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,s)=>{this._eventSource=new Ya(this._url.href,{...this._eventSourceInit,fetch:async(a,l)=>{let c=await this._commonHeaders();c.set("Accept","text/event-stream");let u=await i(a,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){let{resourceMetadataUrl:d,scope:p}=Su(u);this._resourceMetadataUrl=d,this._scope=p}return u}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var l;if(a.code===401&&this._authProvider){this._authThenStart().then(o,s);return}let c=new tI(a.code,a.message,a);s(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var l;let c=a;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){s(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}o()}),this._eventSource.onmessage=a=>{var l,c;let u=a,d;try{d=Gc.parse(JSON.parse(u.data))}catch(p){(l=this.onerror)===null||l===void 0||l.call(this,p);return}(c=this.onmessage)===null||c===void 0||c.call(this,d)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Br("No auth provider");if(await No(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,i,o;if(!this._endpoint)throw new Error("Not connected");try{let s=await this._commonHeaders();s.set("content-type","application/json");let a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},l=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,a);if(!l.ok){let c=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){let{resourceMetadataUrl:u,scope:d}=Su(l);if(this._resourceMetadataUrl=u,this._scope=d,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}await((i=l.body)===null||i===void 0?void 0:i.cancel())}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}};var Fi={name:"@intelliweave/embedded",version:"2.0.72-beta.5",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};var tr=new Ve("MCPKnowledgeClient"),Yy=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){tr.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new xp({name:Fi.name,version:Fi.version}),n=new Gy(new URL(this.config.baseURL));return await r.connect(n),tr.debug("Connected with HTTP streaming mode"),r}).catch(async r=>{let n=new xp({name:Fi.name,version:Fi.version}),i=new Jy(new URL(this.config.baseURL));return await n.connect(i),tr.debug("Connected with SSE mode"),n});return await this.disconnect(),this.client=e,e.onerror=r=>{tr.error(`MCP client error: ${r.message}`)},e.onclose=()=>{tr.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(ax,r=>{r.params.level=="critical"?tr.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?tr.error(`[Server] ${r.params.data}`):r.params.level=="error"?tr.error(`[Server] ${r.params.data}`):r.params.level=="warning"?tr.warn(`[Server] ${r.params.data}`):r.params.level=="info"?tr.info(`[Server] ${r.params.data}`):r.params.level=="debug"?tr.debug(`[Server] ${r.params.data}`):tr.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(sx,r=>{tr.debug("Tool list changed",r),this.fetchTools()}),tr.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],r;for(;;){let i=await this.client.listTools({cursor:r});r=i.nextCursor;for(let o of i.tools||[])e.push(o);if(!i?.tools?.length||!r)break}let n=[];for(let i of e){let o=!!(this.config.searchToolName&&i.name==this.config.searchToolName&&!this.config.searchToolVisible);n.push({id:i.name,name:i.name,content:i.description||"",type:"action",isContext:!0,parameters:i.inputSchema,action:s=>this.performToolCall(i.name,s),disabled:o})}tr.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let r=this.iwActions.slice(),n=await this.performSearchCall(e);return r=r.concat(n),this.lastSearchQuery=e,this.lastSearchResults=r,tr.debug(`Search completed, found ${r.length} items.`),r}async performSearchCall(e){let r=[];if(!this.config.searchToolName)return r;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return tr.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),r;let i;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let s=i[o];r.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else r.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof i=="string"?i:JSON.stringify(i)});return r}async performToolCall(e,r){await this.connect(),tr.debug(`Performing tool call for ${e} with params:`,r),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:r});if(n.isError){let i=n.content?.[0]?.text||"Unknown error";throw tr.error(`Error calling tool ${e}: ${i}`),new Error(`Error calling tool ${e}: ${i}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};var l8=new Ve("Statistics"),Lp=[];async function Gr(t,e){let r={...e,event_id:dr(),event_date:new Date().toISOString(),sdk_version:Fi.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(Lp.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),Lp.length===0))return;let n=Lp.slice();Lp.length=0;try{let i=await fetch(t.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){l8.warn("Failed to submit analytics event:",i),Lp.push(...n);return}}var Qa=new Ve("KnowledgeBase"),rI=1,Qy=class t{constructor(e){this._sources=[{id:"core.internal",query:async()=>hP(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=e}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${rI++}`),this._sources.push({id:n,query:r}),n}removeSource(e){this._sources=this.sources.filter(r=>r.id!==e&&r.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(r=>r.id!==e)}get sources(){let e=this._sources;return St().knowledgeBaseSources&&(e=e.concat(St().knowledgeBaseSources)),e=e.concat(this._windowSources),e=e.filter(r=>!r.disabled),e}async search(e){let r=Date.now();Qa.debug(`Searching knowledge base for: ${e}`);let n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],typeof document<"u"&&document.dispatchEvent(n),this._windowSources=n.sources;let o=(await Promise.all(this.sources.map(async c=>{try{let u=Date.now(),d=await c.query(e);return Qa.debug(`Source '${c.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return Qa.warn(`Knowledge source '${c.id}' failed:`,u),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),St().knowledgeBase&&(o=o.concat(St().knowledgeBase)),o=o.filter(c=>c&&!c.disabled);for(let c=0;c<o.length;c++){let u=o[c];u.id=u.id||`temp.${c}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new mP({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let l=s.search(e).map(c=>o.find(u=>u.id==c.id));for(let c of o)c.isContext&&(l.find(u=>u.id===c.id)||l.push(c));return this.lastResults=l,Gr(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Qa.debug("Found results:",l),l}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${rI++}`),Qa.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(l,c)=>{Qa.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,actionID:l.id,parameters:c},d=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let p=await d.json();return a(p.updateItems||[]),p.response},a=l=>{for(let c of l){if(!c.id){Qa.warn("KB item skipped since it has no ID.",c);continue}let u=n.find(d=>d.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}n.push({...c,action:d=>s(c,d)})}};this.registerSource(r,async l=>{if(o&&i.includes(l))return n;let c={type:"search",userID:this.ai?.userID||"",query:l},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(l)||i.push(l),a(d.items),n})}clone(){let e=new t(this.ai);return e._sources=this._sources,e._windowSources=this._windowSources,e.manualEntries=this.manualEntries,e}registerMCPSource(e){e.id||(e.id=`external.${rI++}`);let r=new Yy(e);return this.registerSource(e.id,n=>r.search(n)),r}};var ev=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
96
96
|
|
|
97
97
|
Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(r.toLowerCase().includes("true"))return!0;if(r.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+r)}async choose(e){let r=await this.instruct({...e,instruction:`${e.instruction}
|
|
98
98
|
|
|
@@ -405,7 +405,7 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
|
|
|
405
405
|
<div class='llm-selector-item-icon' style="background-image: url('${n.icon}'); "></div>
|
|
406
406
|
<div class='llm-selector-item-name'>${n.name}</div>
|
|
407
407
|
<div class='llm-selector-item-provider'>${n.provider}</div>
|
|
408
|
-
`,i.addEventListener("click",o=>{this.dispatchEvent(new CustomEvent("select",{detail:n.id}))}),r.appendChild(i)}}};pm.observedAttributes=["open"];var ju=new Ve("ONNXModel"),yi=class t{constructor(e){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=e,ju.debug(`Model input parameters: ${e.inputNames.join(", ")}`),ju.debug(`Model output parameters: ${e.outputNames.join(", ")}`)}static isSupported(){return!!t.lib}static async load(e){if(!t.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(ju.debug("Loading ONNX runtime"),this.onnx=await t.lib()),ju.debug(`Loading model: ${e}`);let r=await this.onnx.InferenceSession.create(e);return new t(r)}makeTensor(e,r,n=0){let i=1;for(let s of r)i*=s;let o;if(e=="float32")o=new t.onnx.Tensor(new Float32Array(i),r);else if(e=="int8")o=new t.onnx.Tensor(new Int8Array(i),r);else if(e=="int16")o=new t.onnx.Tensor(new Int16Array(i),r);else if(e=="int32")o=new t.onnx.Tensor(new Int32Array(i),r);else if(e=="int64")o=new t.onnx.Tensor(new BigInt64Array(i),r);else if(e=="uint8")o=new t.onnx.Tensor(new Uint8Array(i),r);else if(e=="uint16")o=new t.onnx.Tensor(new Uint16Array(i),r);else if(e=="uint32")o=new t.onnx.Tensor(new Uint32Array(i),r);else if(e=="uint64")o=new t.onnx.Tensor(new BigUint64Array(i),r);else throw new Error(`Invalid type: ${e}`);return n!==0&&(e=="int64"||e=="uint64")?o.data.fill(BigInt(n)):n!==0&&o.data.fill(n),o}registerConstant(e,r){if(!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);return this.constantTensors[e]=r,r}makeConstant(e,r,n,i=0){return this.registerConstant(e,this.makeTensor(r,n,i))}registerState(e,r,n){if(r||(r=e),!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);if(!this.session.outputNames.includes(r))throw new Error(`Model does not have an output named: ${r}`);return this.stateTensors[e]={outputName:r,tensor:n},n}makeState(e,r,n,i,o=0){return this.registerState(e,r,this.makeTensor(n,i,o))}async run(e={}){if(this._runActive&&this.ignoreIfBusy)return ju.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 r in this.stateTensors)e[r]=this.stateTensors[r].tensor;for(let r in this.constantTensors)e[r]=this.constantTensors[r];try{let r=await this.session.run(e);for(let n in this.stateTensors){let i=r[this.stateTensors[n].outputName];this.stateTensors[n].tensor=i}return r}finally{this._runActive=!1}}resetState(){ju.debug("Resetting state tensors");for(let e in this.stateTensors)this.stateTensors[e].tensor.data.fill(0)}};var jD="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNp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ayerNode"),Du=class extends AudioWorkletNode{constructor(r,n,i){super(r,"pcm-player-node",{numberOfInputs:0});this.sampleRate=0;this.format="int16";this.isCancelled=!1;if(!n||n<=0)throw new Error(`Invalid sample rate: ${n}`);if(!i||i!="int16"&&i!="float32")throw new Error(`Invalid format: ${i}`);this.sampleRate=n,this.format=i,this.port.onmessage=o=>this.onWorkletMessage(o),this.port.postMessage({action:"start",inputSampleRate:n,outputSampleRate:r.sampleRate,format:i})}static async registerModule(r){await r.audioWorklet.addModule(jD)}feed(r){this.port.postMessage({action:"data",buffer:r.buffer},[r.buffer])}async play(r){if(this.isCancelled)throw new Error("PCMPlayerNode has already been cancelled.");if(this._playPromise)throw new Error("Already playing a stream");this._playPromise=new Promise(n=>this._playPromiseResolve=n),this.dispatchEvent(new CustomEvent("start",{detail:{player:this,stream:r}}));try{let n=r.getReader();for(;!this.isCancelled;){let{done:i,value:o}=await n.read();if(i||!o)break;this.feed(o)}}catch(n){RY.warn("Stream error:",n),this.dispatchEvent(new CustomEvent("error",{detail:{player:this,stream:r,error:n}}))}this.port.postMessage({action:"end"}),await this._playPromise}onWorkletMessage(r){r.data.action=="end"&&(this._playPromiseResolve?.(),this.dispatchEvent(new CustomEvent("end",{detail:{player:this}})))}stop(){this.isCancelled=!0,this.port.postMessage({action:"cancel"}),this._playPromiseResolve?.()}};var Dv=new Ve("SpeechOutput"),DD=.5,MY=.8,Lv=class extends EventTarget{constructor(r){super();this.maxVolumeHeard=0;this.ai=r,this.ai.addEventListener("output",n=>this.onTextOutputFromAI(n)),this.ai.audio?.speechRecognition.addEventListener("speechstart",n=>this.interrupt()),this.ai.knowledgeBase.registerSource(()=>[{id:"system.voice",type:"info",name:"Voice active",isContext:!0,disabled:!1,content:"Text-to-speech is active. The user can hear your voice."}])}onTextOutputFromAI(r){r.detail.isChunk||this.ai?.audio?.speechRecognition.isRunning&&this.speak(r.detail.message)}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let r=0;for(let i of this.analyserBuffer)r+=i*i;let n=Math.sqrt(r/this.analyserBuffer.length);return n>this.maxVolumeHeard&&(this.maxVolumeHeard=n),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,n/this.maxVolumeHeard))}async speak(r){if(!this.ai?.config?.voice?.providerID)return Dv.warn("No voice provider configured");let n=`speech-${jY++}`;await this.ai.audio.beginAccess(n);try{await this._speakWithLock(r)}finally{this.ai.audio.endAccess(n)}}async _speakWithLock(r){let n=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:r}});if(this.dispatchEvent(n),r=n.detail.message,n.defaultPrevented||!r)return;this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=MY);let i=this.ai?._voiceTracker||Dv.timer(`${this.ai.config.voice.providerID} voice`);i(`Speak: ${r}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let o=new Du(this.ai.audio.context,24e3,"int16");this.currentPlayer=o,o.connect(this.analyserNode),o.addEventListener("end",a=>{let l=a;i(`PCM stream ${l.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==o&&!l.detail.interrupted&&(this.currentPlayer=void 0,this.onSpeechEnd())});let s;if(this.ai.config.voice.providerID=="openai")s=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:r,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});else if(this.ai.config.voice.providerID=="elevenlabs")s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${this.ai.config.voice.voiceID}?output_format=pcm_24000`,{method:"POST",headers:{"xi-api-key":`${this.ai.config.voice.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({text:r})});else{Dv.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}if(i(`Received response ${s.status} ${s.statusText}`),!s.ok){Dv.warn(`Failed to generate voice sample: ${s.status} ${s.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:r}})),i("Playing PCM stream"),await o.play(s.body),i("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(!this.currentPlayerVolume)return;let r=this.currentPlayerVolume,n=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=DD);let i=400;r.gain.linearRampToValueAtTime(0,i/1e3),await new Promise(o=>setTimeout(o,i+250)),r.disconnect(),n?.stop(),n?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=DD)}},jY=1;function Uv(t,e){let r=e.reduce((l,c)=>l+c.byteLength,0),n=new DataView(new ArrayBuffer(44));n.setUint8(0,82),n.setUint8(1,73),n.setUint8(2,70),n.setUint8(3,70),n.setUint32(4,44+r,!0),n.setUint8(8,87),n.setUint8(9,65),n.setUint8(10,86),n.setUint8(11,69);let i=1,o=32,s=i*o/8,a=t*s;return n.setUint8(12,102),n.setUint8(13,109),n.setUint8(14,116),n.setUint8(15,32),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,i,!0),n.setUint32(24,t,!0),n.setUint32(28,a,!0),n.setUint16(32,s,!0),n.setUint16(34,o,!0),n.setUint8(36,100),n.setUint8(37,97),n.setUint8(38,116),n.setUint8(39,97),n.setUint32(40,r,!0),new File([n,...e],"audio.wav",{type:"audio/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sZW5ndGgpO2ZvcihoLnNldChpWzBdWzBdKSx0aGlzLmlucHV0QnVmZmVyLmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var Lu=class extends AudioWorkletNode{constructor(r,n,i,o){super(r,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=i;let s=["int16","int64","float32"];if(!n||n<=0)throw new Error(`Invalid sample rate: ${n}`);if(!s.includes(i))throw new Error(`Invalid format ${i}, must be one of: ${s.join(", ")}`);if(!o||o<=0)throw new Error(`Invalid buffer size: ${o}`);this.port.onmessage=a=>this.onWorkletMessage(a),this.port.postMessage({action:"start",inputSampleRate:r.sampleRate,outputSampleRate:n,format:i,bufferSize:o})}static async registerModule(r){await r.audioWorklet.addModule(LD)}onWorkletMessage(r){if(r.data.action=="data"){let n=null;if(this.format=="int16"&&(n=new Int16Array(r.data.buffer)),this.format=="int64"&&(n=new BigInt64Array(r.data.buffer)),this.format=="float32"&&(n=new Float32Array(r.data.buffer)),!n)throw new Error(`Invalid format: ${this.format}`);this.onData(n),this.dispatchEvent(new CustomEvent("data",{detail:{data:n}}))}}onData(r){}};var sE=16e3,Zv=256,Uu=8,mm=new Ve("VoiceDetectionNode"),hm=class hm extends Lu{constructor(r){super(r,sE,"float32",Zv*Uu);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!hm.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return sE}get numberOfSamples(){return Zv}get numberOfSampleChunks(){return Uu}get outputBufferSize(){return Zv*Uu}get isModelLoaded(){return!!this.vad}async loadModel(){mm.debug("Loading VAD model"),this.vad=await yi.load(hm.vadModelURL),this.vad.ignoreIfBusy=!0,mm.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],sE),this.vad.makeState("h","hn","float32",[2,Uu,64]),this.vad.makeState("c","cn","float32",[2,Uu,64])}async onData(r){if(this.vad)try{let n=await this.vad.run({input:new yi.onnx.Tensor(r,[Uu,Zv])});if(!n)return;this.currentProbability=0;for(let s=0;s<n.output.data.length;s++)n.output.data[s]>this.currentProbability&&(this.currentProbability=n.output.data[s]);let i=this.isVoiceActive?this.sentivityEnd:this.sensitivity,o=this.currentProbability>i;if(!o&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=o,o&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),mm.debug("Started speaking")):o?this.lastVoiceActiveDate=Date.now():!o&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!o&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),mm.debug("Stopped speaking after timeout")),!o){let s=Date.now();s>this.nextVadReset&&(this.nextVadReset=s+5e3,this.vad.resetState())}}catch(n){mm.error("VAD failed:",n)}}onSpeechStart(){}onSpeechEnd(){}};hm.vadModelURL="";var Zu=hm;var UD=new Ve("VoiceChunkOutputNode"),Fu=class extends Zu{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((r,n)=>r+n.length,0)/8e3}async onData(r){if(await super.onData(r),this.isVoiceActive&&!this._voiceRecording){UD.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let n of this.buffers)this.recordedBuffers.push(n),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:n,isFinal:!1}})),this.onVoiceChunk(n);this.recordedBuffers.push(r),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:r,isFinal:!1}})),this.onVoiceChunk(r),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(r),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:r,isFinal:!1}})),this.onVoiceChunk(r);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(r),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:r,isFinal:!0}})),this.onVoiceChunk(r),this._voiceRecording=!1;let n=this.recordedBuffers.reduce((i,o)=>i+o.length,0);UD.debug(`Voice complete, recorded ${(n/8e3).toFixed(2)} seconds of audio, ${n*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(r);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(r){}onVoiceEnd(r){}};var Fv=new Ve("OpenAITranscriptionNode"),Vv=class extends Fu{constructor(r,n){super(r);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=n}async onVoiceEnd(r){let n=Fv.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...r);let i=Uv(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let o="";try{let s=new FormData;s.append("file",i),s.append("model","whisper-1"),s.append("response_format","text");let a=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s,signal:this.lastRequestAbortController.signal});if(!a.ok)throw new Error(`Failed to generate voice sample: ${a.status} ${a.statusText}`);n("Response received"),o=await a.text(),n("Content received: "+o),this.lastRequestAbortController=void 0}catch(s){Fv.error(`Failed to transcribe speech: ${s.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!o)return Fv.debug("Transcription complete, but no text was found");Fv.debug(`Transcription: ${o}`),this.onVoiceTranscription(o),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o}}))}onVoiceTranscription(r){}};var qv=class extends WebSocket{constructor(r){super(r);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(r){this.readyState==WebSocket.OPEN?super.send(r):this.pendingData.push(r)}_onOpen(){for(let r of this.pendingData)super.send(r);this.pendingData=[]}};var Gi=new Ve("IntelliWeaveTranscriptionNode"),LY="wss://speech.intelliweave.ai/api/v1/transcribe",Bv=class Bv extends Fu{constructor(r,n){super(r);this.apiAddress=LY;this.apiKey="";this.isTranscribing=!1;this.apiKey=n}async onVoiceChunk(r){this.isTranscribing=!0,this.ws?this.ws.send(r):(Gi.debug("Opening WebSocket connection"),this.ws=new qv(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(r.buffer),this.ws.onopen=()=>{Gi.debug("WebSocket connection opened")},this.ws.addEventListener("message",i=>{let o=JSON.parse(i.data);if(o.error)return Gi.warn("Error: "+o.error);if(o.type!="transcription")return Gi.warn("Invalid response type",o);if(o.streaming&&!o.final)return Gi.debug("Partial transcription: "+o.partialText);if(this.isTranscribing=!1,!o.text.trim())return Gi.warn(`Empty transcription (${o.processingTime}ms)`);Gi.debug(`Transcription: ${o.text} (${o.processingTime}ms)`),this.onVoiceTranscription(o.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",i=>Gi.warn("WebSocket error")));let n=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{Gi.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},n)}async onVoiceEnd(r){if(this.ws?.send(JSON.stringify({type:"end"})),Bv.debugExportWav){let n=Uv(this.sampleRate,r),i=document.createElement("a");i.href=URL.createObjectURL(n),i.download="recording.wav",i.click()}}onVoiceTranscription(r){}onSocketClose(){Gi.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};Bv.debugExportWav=!1;var Wv=Bv;var aE=new Ve("SpeechRecognition"),Gv=class extends EventTarget{constructor(r){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=r,this.ai.knowledgeBase.registerSource(()=>[{id:"system.microphone.enable",type:"action",name:"Enable or disable microphone",isContext:!0,content:`Starts or stops listening to input from the user through the microphone. ${this.isRunning?"Microphone access is currently enabled and you can hear the user.":"Microphone access is currently disabled."}.`,parameters:[{name:"enable",type:"boolean",description:"If true, enables the microphone. If false, disables it."}],action:async n=>{n.enable?await this.start():this.stop()}}])}get isSupported(){if(!yi.lib||!this.ai?.vadModel||!rs().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey))return!1}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let r=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,r.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),Zu.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new Vv(this.ai.audio.context,this.ai.config.transcription.apiKey),r.connect(this.voiceDetection)):(this.voiceDetection=new Wv(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,r.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",n=>{this.ai._voiceTracker=aE.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),Gr(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(n.type,{detail:n.detail}))}),this.voiceDetection.addEventListener("speechend",n=>{this.ai._voiceTracker?.("Speech ended");let i=this.recordingStartTime?Date.now()-this.recordingStartTime:0;Gr(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:i}}),this.dispatchEvent(new CustomEvent(n.type,{detail:n.detail}))}),this.voiceDetection.addEventListener("transcription",n=>{this.ai._voiceTracker?.(`Transcription: ${n.detail.text}`),Gr(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:n.detail.confidence||void 0}}),this.onTranscription(n)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(r){aE.error("Failed to start speech recognition:",r),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(r=>r.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let r=0;for(let i of this.analyserBuffer)r+=i*i;let n=Math.sqrt(r/this.analyserBuffer.length);return n>this.maxVolumeHeard&&(this.maxVolumeHeard=n),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,n/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(r){let n=r.detail.text;aE.debug("Heard:",n),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:n,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(r){throw this._skipEvents=!1,r}}}};var Hv=new Ve("AudioSystem"),gm=class t{constructor(e){this.locks=[];if(!e)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=e,this.ai.audio=this,this.speechRecognition=new Gv(this.ai),this.speechOutput=new Lv(this.ai)}static get isSupported(){return!(!yi.lib||!rs().AudioWorkletNode)}static async registerModules(e){await Promise.all([Du.registerModule(e),Lu.registerModule(e)])}async beginAccess(e){Hv.debug(`Began access for: ${e}`),this.locks.includes(e)||this.locks.push(e),!this.context&&(Hv.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await t.registerModules(this.context))}endAccess(e){Hv.debug(`Ended access for: ${e}`),this.locks=this.locks.filter(r=>r!=e),!this.locks.length&&(Hv.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var un=new Ve("Embed"),Vu=class extends kn{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this.html=()=>`
|
|
408
|
+
`,i.addEventListener("click",o=>{this.dispatchEvent(new CustomEvent("select",{detail:n.id}))}),r.appendChild(i)}}};pm.observedAttributes=["open"];var ju=new Ve("ONNXModel"),yi=class t{constructor(e){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=e,ju.debug(`Model input parameters: ${e.inputNames.join(", ")}`),ju.debug(`Model output parameters: ${e.outputNames.join(", ")}`)}static isSupported(){return!!t.lib}static async load(e){if(!t.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(ju.debug("Loading ONNX runtime"),this.onnx=await t.lib()),ju.debug(`Loading model: ${e}`);let r=await this.onnx.InferenceSession.create(e);return new t(r)}makeTensor(e,r,n=0){let i=1;for(let s of r)i*=s;let o;if(e=="float32")o=new t.onnx.Tensor(new Float32Array(i),r);else if(e=="int8")o=new t.onnx.Tensor(new Int8Array(i),r);else if(e=="int16")o=new t.onnx.Tensor(new Int16Array(i),r);else if(e=="int32")o=new t.onnx.Tensor(new Int32Array(i),r);else if(e=="int64")o=new t.onnx.Tensor(new BigInt64Array(i),r);else if(e=="uint8")o=new t.onnx.Tensor(new Uint8Array(i),r);else if(e=="uint16")o=new t.onnx.Tensor(new Uint16Array(i),r);else if(e=="uint32")o=new t.onnx.Tensor(new Uint32Array(i),r);else if(e=="uint64")o=new t.onnx.Tensor(new BigUint64Array(i),r);else throw new Error(`Invalid type: ${e}`);return n!==0&&(e=="int64"||e=="uint64")?o.data.fill(BigInt(n)):n!==0&&o.data.fill(n),o}registerConstant(e,r){if(!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);return this.constantTensors[e]=r,r}makeConstant(e,r,n,i=0){return this.registerConstant(e,this.makeTensor(r,n,i))}registerState(e,r,n){if(r||(r=e),!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);if(!this.session.outputNames.includes(r))throw new Error(`Model does not have an output named: ${r}`);return this.stateTensors[e]={outputName:r,tensor:n},n}makeState(e,r,n,i,o=0){return this.registerState(e,r,this.makeTensor(n,i,o))}async run(e={}){if(this._runActive&&this.ignoreIfBusy)return ju.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 r in this.stateTensors)e[r]=this.stateTensors[r].tensor;for(let r in this.constantTensors)e[r]=this.constantTensors[r];try{let r=await this.session.run(e);for(let n in this.stateTensors){let i=r[this.stateTensors[n].outputName];this.stateTensors[n].tensor=i}return r}finally{this._runActive=!1}}resetState(){ju.debug("Resetting state tensors");for(let e in this.stateTensors)this.stateTensors[e].tensor.data.fill(0)}};var jD="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgaT10aGlzLkF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h1bmtzLnNoaWZ0KCksdGhpcy5jaHVua1Bvc2l0aW9uPTApLHR9cHJvY2Vzcyh0LHIsYSl7aWYodGhpcy5pc0NhbmNlbGxlZClyZXR1cm4hMTtpZih0aGlzLmlzRW5kZWQmJiF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIHRoaXMuX2hhc1NlbnRFbmRFdmVudHx8KHRoaXMuX2hhc1NlbnRFbmRFdmVudD0hMCx0aGlzLnBvcnQucG9zdE1lc3NhZ2Uoe2FjdGlvbjoiZW5kIn0pKSwhMTtsZXQgcz1yWzBdPy5bMF0/Lmxlbmd0aDtpZighcylyZXR1cm4hMDt0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplPXM7Zm9yKGxldCBmPTA7ZjxzO2YrKyl7bGV0IGg9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var RY=new Ve("PCMPlayerNode"),Du=class extends AudioWorkletNode{constructor(r,n,i){super(r,"pcm-player-node",{numberOfInputs:0});this.sampleRate=0;this.format="int16";this.isCancelled=!1;if(!n||n<=0)throw new Error(`Invalid sample rate: ${n}`);if(!i||i!="int16"&&i!="float32")throw new Error(`Invalid format: ${i}`);this.sampleRate=n,this.format=i,this.port.onmessage=o=>this.onWorkletMessage(o),this.port.postMessage({action:"start",inputSampleRate:n,outputSampleRate:r.sampleRate,format:i})}static async registerModule(r){await r.audioWorklet.addModule(jD)}feed(r){this.port.postMessage({action:"data",buffer:r.buffer},[r.buffer])}async play(r){if(this.isCancelled)throw new Error("PCMPlayerNode has already been cancelled.");if(this._playPromise)throw new Error("Already playing a stream");this._playPromise=new Promise(n=>this._playPromiseResolve=n),this.dispatchEvent(new CustomEvent("start",{detail:{player:this,stream:r}}));try{let n=r.getReader();for(;!this.isCancelled;){let{done:i,value:o}=await n.read();if(i||!o)break;this.feed(o)}}catch(n){RY.warn("Stream error:",n),this.dispatchEvent(new CustomEvent("error",{detail:{player:this,stream:r,error:n}}))}this.port.postMessage({action:"end"}),await this._playPromise}onWorkletMessage(r){r.data.action=="end"&&(this._playPromiseResolve?.(),this.dispatchEvent(new CustomEvent("end",{detail:{player:this}})))}stop(){this.isCancelled=!0,this.port.postMessage({action:"cancel"}),this._playPromiseResolve?.()}};var Dv=new Ve("SpeechOutput"),DD=.5,MY=.8,Lv=class extends EventTarget{constructor(r){super();this.maxVolumeHeard=0;this.ai=r,this.ai.addEventListener("output",n=>this.onTextOutputFromAI(n)),this.ai.audio?.speechRecognition.addEventListener("speechstart",n=>this.interrupt()),this.ai.knowledgeBase.registerSource(()=>[{id:"system.voice",type:"info",name:"Voice active",isContext:!0,disabled:!1,content:"Text-to-speech is active. The user can hear your voice."}])}onTextOutputFromAI(r){r.detail.isChunk||this.ai?.audio?.speechRecognition.isRunning&&this.speak(r.detail.message)}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let r=0;for(let i of this.analyserBuffer)r+=i*i;let n=Math.sqrt(r/this.analyserBuffer.length);return n>this.maxVolumeHeard&&(this.maxVolumeHeard=n),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,n/this.maxVolumeHeard))}async speak(r){if(!this.ai?.config?.voice?.providerID)return Dv.warn("No voice provider configured");let n=`speech-${jY++}`;await this.ai.audio.beginAccess(n);try{await this._speakWithLock(r)}finally{this.ai.audio.endAccess(n)}}async _speakWithLock(r){let n=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:r}});if(this.dispatchEvent(n),r=n.detail.message,n.defaultPrevented||!r)return;this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=MY);let i=this.ai?._voiceTracker||Dv.timer(`${this.ai.config.voice.providerID} voice`);i(`Speak: ${r}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let o=new Du(this.ai.audio.context,24e3,"int16");this.currentPlayer=o,o.connect(this.analyserNode),o.addEventListener("end",a=>{let l=a;i(`PCM stream ${l.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==o&&!l.detail.interrupted&&(this.currentPlayer=void 0,this.onSpeechEnd())});let s;if(this.ai.config.voice.providerID=="openai")s=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:r,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});else if(this.ai.config.voice.providerID=="elevenlabs")s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${this.ai.config.voice.voiceID}?output_format=pcm_24000`,{method:"POST",headers:{"xi-api-key":`${this.ai.config.voice.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({text:r})});else{Dv.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}if(i(`Received response ${s.status} ${s.statusText}`),!s.ok){Dv.warn(`Failed to generate voice sample: ${s.status} ${s.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:r}})),i("Playing PCM stream"),await o.play(s.body),i("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(!this.currentPlayerVolume)return;let r=this.currentPlayerVolume,n=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=DD);let i=400;r.gain.linearRampToValueAtTime(0,i/1e3),await new Promise(o=>setTimeout(o,i+250)),r.disconnect(),n?.stop(),n?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=DD)}},jY=1;function Uv(t,e){let r=e.reduce((l,c)=>l+c.byteLength,0),n=new DataView(new ArrayBuffer(44));n.setUint8(0,82),n.setUint8(1,73),n.setUint8(2,70),n.setUint8(3,70),n.setUint32(4,44+r,!0),n.setUint8(8,87),n.setUint8(9,65),n.setUint8(10,86),n.setUint8(11,69);let i=1,o=32,s=i*o/8,a=t*s;return n.setUint8(12,102),n.setUint8(13,109),n.setUint8(14,116),n.setUint8(15,32),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,i,!0),n.setUint32(24,t,!0),n.setUint32(28,a,!0),n.setUint16(32,s,!0),n.setUint16(34,o,!0),n.setUint8(36,100),n.setUint8(37,97),n.setUint8(38,116),n.setUint8(39,97),n.setUint32(40,r,!0),new File([n,...e],"audio.wav",{type:"audio/wav"})}var LD="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWYsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1lPT5lLHRoaXMucmF0a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YT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var Lu=class extends AudioWorkletNode{constructor(r,n,i,o){super(r,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=i;let s=["int16","int64","float32"];if(!n||n<=0)throw new Error(`Invalid sample rate: ${n}`);if(!s.includes(i))throw new Error(`Invalid format ${i}, must be one of: ${s.join(", ")}`);if(!o||o<=0)throw new Error(`Invalid buffer size: ${o}`);this.port.onmessage=a=>this.onWorkletMessage(a),this.port.postMessage({action:"start",inputSampleRate:r.sampleRate,outputSampleRate:n,format:i,bufferSize:o})}static async registerModule(r){await r.audioWorklet.addModule(LD)}onWorkletMessage(r){if(r.data.action=="data"){let n=null;if(this.format=="int16"&&(n=new Int16Array(r.data.buffer)),this.format=="int64"&&(n=new BigInt64Array(r.data.buffer)),this.format=="float32"&&(n=new Float32Array(r.data.buffer)),!n)throw new Error(`Invalid format: ${this.format}`);this.onData(n),this.dispatchEvent(new CustomEvent("data",{detail:{data:n}}))}}onData(r){}};var sE=16e3,Zv=256,Uu=8,mm=new Ve("VoiceDetectionNode"),hm=class hm extends Lu{constructor(r){super(r,sE,"float32",Zv*Uu);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!hm.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return sE}get numberOfSamples(){return Zv}get numberOfSampleChunks(){return Uu}get outputBufferSize(){return Zv*Uu}get isModelLoaded(){return!!this.vad}async loadModel(){mm.debug("Loading VAD model"),this.vad=await yi.load(hm.vadModelURL),this.vad.ignoreIfBusy=!0,mm.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],sE),this.vad.makeState("h","hn","float32",[2,Uu,64]),this.vad.makeState("c","cn","float32",[2,Uu,64])}async onData(r){if(this.vad)try{let n=await this.vad.run({input:new yi.onnx.Tensor(r,[Uu,Zv])});if(!n)return;this.currentProbability=0;for(let s=0;s<n.output.data.length;s++)n.output.data[s]>this.currentProbability&&(this.currentProbability=n.output.data[s]);let i=this.isVoiceActive?this.sentivityEnd:this.sensitivity,o=this.currentProbability>i;if(!o&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=o,o&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),mm.debug("Started speaking")):o?this.lastVoiceActiveDate=Date.now():!o&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!o&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),mm.debug("Stopped speaking after timeout")),!o){let s=Date.now();s>this.nextVadReset&&(this.nextVadReset=s+5e3,this.vad.resetState())}}catch(n){mm.error("VAD failed:",n)}}onSpeechStart(){}onSpeechEnd(){}};hm.vadModelURL="";var Zu=hm;var UD=new Ve("VoiceChunkOutputNode"),Fu=class extends Zu{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((r,n)=>r+n.length,0)/8e3}async onData(r){if(await super.onData(r),this.isVoiceActive&&!this._voiceRecording){UD.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let n of this.buffers)this.recordedBuffers.push(n),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:n,isFinal:!1}})),this.onVoiceChunk(n);this.recordedBuffers.push(r),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:r,isFinal:!1}})),this.onVoiceChunk(r),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(r),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:r,isFinal:!1}})),this.onVoiceChunk(r);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(r),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:r,isFinal:!0}})),this.onVoiceChunk(r),this._voiceRecording=!1;let n=this.recordedBuffers.reduce((i,o)=>i+o.length,0);UD.debug(`Voice complete, recorded ${(n/8e3).toFixed(2)} seconds of audio, ${n*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(r);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(r){}onVoiceEnd(r){}};var Fv=new Ve("OpenAITranscriptionNode"),Vv=class extends Fu{constructor(r,n){super(r);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=n}async onVoiceEnd(r){let n=Fv.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...r);let i=Uv(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let o="";try{let s=new FormData;s.append("file",i),s.append("model","whisper-1"),s.append("response_format","text");let a=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s,signal:this.lastRequestAbortController.signal});if(!a.ok)throw new Error(`Failed to generate voice sample: ${a.status} ${a.statusText}`);n("Response received"),o=await a.text(),n("Content received: "+o),this.lastRequestAbortController=void 0}catch(s){Fv.error(`Failed to transcribe speech: ${s.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!o)return Fv.debug("Transcription complete, but no text was found");Fv.debug(`Transcription: ${o}`),this.onVoiceTranscription(o),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o}}))}onVoiceTranscription(r){}};var qv=class extends WebSocket{constructor(r){super(r);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(r){this.readyState==WebSocket.OPEN?super.send(r):this.pendingData.push(r)}_onOpen(){for(let r of this.pendingData)super.send(r);this.pendingData=[]}};var Gi=new Ve("IntelliWeaveTranscriptionNode"),LY="wss://speech.intelliweave.ai/api/v1/transcribe",Bv=class Bv extends Fu{constructor(r,n){super(r);this.apiAddress=LY;this.apiKey="";this.isTranscribing=!1;this.apiKey=n}async onVoiceChunk(r){this.isTranscribing=!0,this.ws?this.ws.send(r):(Gi.debug("Opening WebSocket connection"),this.ws=new qv(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(r.buffer),this.ws.onopen=()=>{Gi.debug("WebSocket connection opened")},this.ws.addEventListener("message",i=>{let o=JSON.parse(i.data);if(o.error)return Gi.warn("Error: "+o.error);if(o.type!="transcription")return Gi.warn("Invalid response type",o);if(o.streaming&&!o.final)return Gi.debug("Partial transcription: "+o.partialText);if(this.isTranscribing=!1,!o.text.trim())return Gi.warn(`Empty transcription (${o.processingTime}ms)`);Gi.debug(`Transcription: ${o.text} (${o.processingTime}ms)`),this.onVoiceTranscription(o.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",i=>Gi.warn("WebSocket error")));let n=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{Gi.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},n)}async onVoiceEnd(r){if(this.ws?.send(JSON.stringify({type:"end"})),Bv.debugExportWav){let n=Uv(this.sampleRate,r),i=document.createElement("a");i.href=URL.createObjectURL(n),i.download="recording.wav",i.click()}}onVoiceTranscription(r){}onSocketClose(){Gi.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};Bv.debugExportWav=!1;var Wv=Bv;var aE=new Ve("SpeechRecognition"),Gv=class extends EventTarget{constructor(r){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=r}get isSupported(){if(!yi.lib||!this.ai?.vadModel||!rs().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey))return!1}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let r=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,r.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),Zu.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new Vv(this.ai.audio.context,this.ai.config.transcription.apiKey),r.connect(this.voiceDetection)):(this.voiceDetection=new Wv(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,r.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",n=>{this.ai._voiceTracker=aE.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),Gr(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(n.type,{detail:n.detail}))}),this.voiceDetection.addEventListener("speechend",n=>{this.ai._voiceTracker?.("Speech ended");let i=this.recordingStartTime?Date.now()-this.recordingStartTime:0;Gr(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:i}}),this.dispatchEvent(new CustomEvent(n.type,{detail:n.detail}))}),this.voiceDetection.addEventListener("transcription",n=>{this.ai._voiceTracker?.(`Transcription: ${n.detail.text}`),Gr(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:n.detail.confidence||void 0}}),this.onTranscription(n)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(r){aE.error("Failed to start speech recognition:",r),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(r=>r.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let r=0;for(let i of this.analyserBuffer)r+=i*i;let n=Math.sqrt(r/this.analyserBuffer.length);return n>this.maxVolumeHeard&&(this.maxVolumeHeard=n),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,n/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(r){let n=r.detail.text;aE.debug("Heard:",n),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:n,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(r){throw this._skipEvents=!1,r}}}};var Hv=new Ve("AudioSystem"),gm=class t{constructor(e){this.locks=[];if(!e)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=e,this.ai.audio=this,this.speechRecognition=new Gv(this.ai),this.speechOutput=new Lv(this.ai)}static get isSupported(){return!(!yi.lib||!rs().AudioWorkletNode)}static async registerModules(e){await Promise.all([Du.registerModule(e),Lu.registerModule(e)])}async beginAccess(e){Hv.debug(`Began access for: ${e}`),this.locks.includes(e)||this.locks.push(e),!this.context&&(Hv.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await t.registerModules(this.context))}endAccess(e){Hv.debug(`Ended access for: ${e}`),this.locks=this.locks.filter(r=>r!=e),!this.locks.length&&(Hv.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var un=new Ve("Embed"),Vu=class extends kn{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this.html=()=>`
|
|
409
409
|
|
|
410
410
|
<!-- Styling -->
|
|
411
411
|
<style>
|
|
@@ -765,7 +765,7 @@ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="functi
|
|
|
765
765
|
|
|
766
766
|
</div>
|
|
767
767
|
|
|
768
|
-
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new tv,gm.isSupported&&(this.ai.audio=new gm(this.ai))}onCreate(){St().embed&&un.warn("Only one <web-weaver-embed> element should be on the page."),St().embed=this;let r=St();un.debug("[WebWeaverEmbed] Client config:",r),r.displayMode&&!this.attr.displayMode&&(un.debug("[WebWeaverEmbed] Setting displayMode from client config:",r.displayMode),this.attr.displayMode=r.displayMode),r.layout&&!this.attr.layout&&(un.debug("[WebWeaverEmbed] Setting layout from client config:",r.layout),this.attr.layout=r.layout),r.positioningMode&&!this.attr.positioningMode&&(un.debug("[WebWeaverEmbed] Setting positioningMode from client config:",r.positioningMode),this.attr.positioningMode=r.positioningMode),r.positionX&&!this.attr.positionX&&(un.debug("[WebWeaverEmbed] Setting positionX from client config:",r.positionX),this.attr.positionX=r.positionX),r.positionY&&!this.attr.positionY&&(un.debug("[WebWeaverEmbed] Setting positionY from client config:",r.positionY),this.attr.positionY=r.positionY),r.offsetX!==void 0&&!this.attr.offsetX&&(un.debug("[WebWeaverEmbed] Setting offsetX from client config:",r.offsetX),this.attr.offsetX=String(r.offsetX)),r.offsetY!==void 0&&!this.attr.offsetY&&(un.debug("[WebWeaverEmbed] Setting offsetY from client config:",r.offsetY),this.attr.offsetY=String(r.offsetY)),un.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",o=>this.onContainerClick(o)),this.child("web-weaver-logo").addEventListener("click",o=>this.onLogoClick(o)),this.child("interaction-bar").addEventListener("input-message",o=>this.processInput(o.detail)),this.child("interaction-bar").addEventListener("llm-button-click",o=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",o=>this.onLLMModelSelect(o)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:o=>(this.suggestions.push(o.text),"Suggestion button added")});let i=this.attr.apiKey||St().apiKey;if(!i)return un.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(i).then(o=>{this.config=o.config,St().introductionMessage=this.config.introductionMessage,St().analytics=this.config.analytics!==void 0?!!this.config.analytics:St().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.resetConversation()}).catch(o=>{un.error("Failed to load AI configuration:",o),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");s&&(s.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(r,n){if(!n){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.removeProperty("--intelliweave-interaction-bg");return}let i=this.parseColorToRGB(n);if(!i){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.setProperty("--intelliweave-interaction-bg",n);return}let{r:o,g:s,b:a}=i;r.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${o}, ${s}, ${a}, 0.65)`),r.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(o*.85)}, ${Math.round(s*.85)}, ${Math.round(a*.85)}, 0.85)`),r.style.setProperty("--intelliweave-interaction-bg",`rgba(${o}, ${s}, ${a}, 0.9)`)}parseColorToRGB(r){if(!r)return null;let n=r.trim();if(n.startsWith("#")){let i=n.slice(1);if(i.length===3){let o=parseInt(i[0]+i[0],16),s=parseInt(i[1]+i[1],16),a=parseInt(i[2]+i[2],16);return{r:o,g:s,b:a}}if(i.length===6){let o=parseInt(i.slice(0,2),16),s=parseInt(i.slice(2,4),16),a=parseInt(i.slice(4,6),16);return{r:o,g:s,b:a}}return null}if(n.startsWith("rgb")){let i=n.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return i?{r:Math.max(0,Math.min(255,Math.round(Number(i[1])))),g:Math.max(0,Math.min(255,Math.round(Number(i[2])))),b:Math.max(0,Math.min(255,Math.round(Number(i[3]))))}:null}return null}applyConfigStylesAndAttributes(){let r=this.config,n=this.child("root");if(!n)return;let i=!1,s=this.attr.logo||r.logo;if(s&&s!==this._lastLogo){this._lastLogo=s,i=!0;let ie=this.child("web-weaver-logo");ie&&ie.setAttribute("logo",s)}let a=this.root?.getElementById("fullscreen-logo"),l=this.root?.getElementById("fullscreen-name"),c=r.name||"";c!==this._lastPersonaName&&(this._lastPersonaName=c,l&&(l.textContent=c),i=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",a&&(s?(a.src=s,a.style.display=""):a.style.display="none"),i=!0);let u=this.root?.getElementById("fullscreen-header"),d=(this.attr.header||"").toLowerCase();if(u){let ie=d==="hidden"||d==="none"||d==="false";u.style.display=!ie&&(s||c)?"":"none"}let f=this.attr.background||r.background;f!==this._lastBackground&&(this._lastBackground=f,i=!0,f?(n.style.background=f,n.style.setProperty("--intelliweave-persona-bg",f),this.applyPersonaColorVariants(n,f)):(n.style.background="",n.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(n,void 0)));let h=this.attr.textColor||r.textColor,y=this.child("interaction-bar");h!==this._lastTextColor&&(this._lastTextColor=h,i=!0,h?(n.style.color=h,n.style.setProperty("--intelliweave-user-bubble-text",h),n.style.setProperty("--intelliweave-assistant-bubble-text",h),y&&y.setAttribute("textColor",h)):(n.style.color="",n.style.removeProperty("--intelliweave-user-bubble-text"),n.style.removeProperty("--intelliweave-assistant-bubble-text"),y&&y.removeAttribute("textColor")));let _=this.attr.displayMode||r.displayMode||"closed";_!==this._lastDisplayMode&&(this._lastDisplayMode=_,i=!0,_==="open"&&!this.attr.open&&(this.attr.open=!0));let E=this.attr.layout||r.layout||"widget";E!==this._lastLayout&&(this._lastLayout=E,i=!0);let P=this.attr.positioningMode||r.positioningMode||"fixed";P!==this._lastPositioningMode&&(this._lastPositioningMode=P,i=!0);let V=this.attr.positionX||r.positionX||"right";V!==this._lastPositionX&&(this._lastPositionX=V,i=!0);let L=this.attr.positionY||r.positionY||"bottom";L!==this._lastPositionY&&(this._lastPositionY=L,i=!0);let G=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,H=G!==void 0?G:r.offsetX!==void 0?r.offsetX:20;H!==this._lastOffsetX&&(this._lastOffsetX=H,i=!0);let W=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,Y=W!==void 0?W:r.offsetY!==void 0?r.offsetY:20;Y!==this._lastOffsetY&&(this._lastOffsetY=Y,i=!0),i&&un.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:n.style.background,finalTextColor:n.style.color,finalDisplayMode:_,finalLayout:E,finalPositioningMode:P,finalPositionX:V,finalPositionY:L,finalOffsetX:H,finalOffsetY:Y})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),Gr(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let c=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;Gr(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:c}})}this._previousOpenState=this.attr.open;let r=this.child("root");this.attr.open?r.classList.add("open"):r.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(r.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):r.classList.remove("layout-fullscreen");let i=this._lastPositioningMode||"fixed",o=this._lastPositionX||"right",s=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,l=this._lastOffsetY!==void 0?this._lastOffsetY:20;i==="container"?(r.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):r.classList.remove("container-mode"),i!=="container"&&(r.style.left="",r.style.right="",r.style.top="",r.style.bottom="",o==="left"?r.style.left=a+"px":r.style.right=a+"px",s==="top"?r.style.top=l+"px":r.style.bottom=l+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((c,u)=>(u.priority||0)-(c.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){St().embed==this&&(St().embed=void 0)}onContainerClick(r){let n=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&n!=="open"&&(this.attr.open||(r.preventDefault(),this.attr.open=!0))}onLogoClick(r){if(r.preventDefault(),r.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let n=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||n==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let r=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;r.children.length>0;)r.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let n=document.createElement("div");n.className="introduction-message",n.innerHTML=St().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,r.appendChild(n),this.ai.insertAssistantMessage(n.innerText);for(let i of St().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=i,o.addEventListener("click",s=>this.onSuggestionClick(s,i)),r.appendChild(o)}}async processInput(r){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let n=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let a of Array.from(n.querySelectorAll(".suggestion-button")))a.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=r,n.appendChild(i);let o=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",n.appendChild(this.currentOutputElement);let s=Math.ceil(n.clientHeight-300);s<0&&(s=0),s>600&&(s=600),o&&(o.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"}),await this.ai.sendMessage(r);for(let a of this.suggestions){let l=document.createElement("div");l.className="suggestion-button",l.innerText=a,l.addEventListener("click",c=>this.onSuggestionClick(c,a)),this.currentOutputElement.appendChild(l)}}catch(i){un.error("Failed to process input:",i);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+i.message,n.appendChild(o);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",a=>this.resetConversation()),n.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(r,n){let i=[];for(let o of r)for(let s=0;s<(o.sections?.length||0);s++){let a=o.sections[s],l=`msgelem-${o.id||""}_${s}_${a.type||"unknown"}`;if(l=l.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let c=a.text||"";c.includes(`
|
|
768
|
+
`;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new tv,gm.isSupported&&(this.ai.audio=new gm(this.ai))}onCreate(){St().embed&&un.warn("Only one <web-weaver-embed> element should be on the page."),St().embed=this;let r=St();un.debug("[WebWeaverEmbed] Client config:",r),r.displayMode&&!this.attr.displayMode&&(un.debug("[WebWeaverEmbed] Setting displayMode from client config:",r.displayMode),this.attr.displayMode=r.displayMode),r.layout&&!this.attr.layout&&(un.debug("[WebWeaverEmbed] Setting layout from client config:",r.layout),this.attr.layout=r.layout),r.positioningMode&&!this.attr.positioningMode&&(un.debug("[WebWeaverEmbed] Setting positioningMode from client config:",r.positioningMode),this.attr.positioningMode=r.positioningMode),r.positionX&&!this.attr.positionX&&(un.debug("[WebWeaverEmbed] Setting positionX from client config:",r.positionX),this.attr.positionX=r.positionX),r.positionY&&!this.attr.positionY&&(un.debug("[WebWeaverEmbed] Setting positionY from client config:",r.positionY),this.attr.positionY=r.positionY),r.offsetX!==void 0&&!this.attr.offsetX&&(un.debug("[WebWeaverEmbed] Setting offsetX from client config:",r.offsetX),this.attr.offsetX=String(r.offsetX)),r.offsetY!==void 0&&!this.attr.offsetY&&(un.debug("[WebWeaverEmbed] Setting offsetY from client config:",r.offsetY),this.attr.offsetY=String(r.offsetY)),un.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",o=>this.onContainerClick(o)),this.child("web-weaver-logo").addEventListener("click",o=>this.onLogoClick(o)),this.child("interaction-bar").addEventListener("input-message",o=>this.processInput(o.detail)),this.child("interaction-bar").addEventListener("llm-button-click",o=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",o=>this.onLLMModelSelect(o)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:o=>(this.suggestions.push(o.text),"Suggestion button added")});let i=this.attr.apiKey||St().apiKey;if(!i)return un.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(i).then(o=>{this.config=o.config,St().introductionMessage=this.config.introductionMessage,St().analytics=this.config.analytics!==void 0?!!this.config.analytics:St().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.resetConversation()}).catch(o=>{un.error("Failed to load AI configuration:",o),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");s&&(s.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(r,n){if(!n){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.removeProperty("--intelliweave-interaction-bg");return}let i=this.parseColorToRGB(n);if(!i){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.setProperty("--intelliweave-interaction-bg",n);return}let{r:o,g:s,b:a}=i;r.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${o}, ${s}, ${a}, 0.65)`),r.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(o*.85)}, ${Math.round(s*.85)}, ${Math.round(a*.85)}, 0.85)`),r.style.setProperty("--intelliweave-interaction-bg",`rgba(${o}, ${s}, ${a}, 0.9)`)}parseColorToRGB(r){if(!r)return null;let n=r.trim();if(n.startsWith("#")){let i=n.slice(1);if(i.length===3){let o=parseInt(i[0]+i[0],16),s=parseInt(i[1]+i[1],16),a=parseInt(i[2]+i[2],16);return{r:o,g:s,b:a}}if(i.length===6){let o=parseInt(i.slice(0,2),16),s=parseInt(i.slice(2,4),16),a=parseInt(i.slice(4,6),16);return{r:o,g:s,b:a}}return null}if(n.startsWith("rgb")){let i=n.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return i?{r:Math.max(0,Math.min(255,Math.round(Number(i[1])))),g:Math.max(0,Math.min(255,Math.round(Number(i[2])))),b:Math.max(0,Math.min(255,Math.round(Number(i[3]))))}:null}return null}applyConfigStylesAndAttributes(){let r=this.config,n=this.child("root");if(!n)return;let i=!1,s=this.attr.logo||r.logo;if(s&&s!==this._lastLogo){this._lastLogo=s,i=!0;let ie=this.child("web-weaver-logo");ie&&ie.setAttribute("logo",s)}let a=this.root?.getElementById("fullscreen-logo"),l=this.root?.getElementById("fullscreen-name"),c=r.name||"";c!==this._lastPersonaName&&(this._lastPersonaName=c,l&&(l.textContent=c),i=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",a&&(s?(a.src=s,a.style.display=""):a.style.display="none"),i=!0);let u=this.root?.getElementById("fullscreen-header"),d=(this.attr.header||"").toLowerCase();if(u){let ie=d==="hidden"||d==="none"||d==="false";u.style.display=!ie&&(s||c)?"":"none"}let f=this.attr.background||r.background;f!==this._lastBackground&&(this._lastBackground=f,i=!0,f?(n.style.background=f,n.style.setProperty("--intelliweave-persona-bg",f),this.applyPersonaColorVariants(n,f)):(n.style.background="",n.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(n,void 0)));let h=this.attr.textColor||r.textColor,y=this.child("interaction-bar");h!==this._lastTextColor&&(this._lastTextColor=h,i=!0,h?(n.style.color=h,n.style.setProperty("--intelliweave-user-bubble-text",h),n.style.setProperty("--intelliweave-assistant-bubble-text",h),y&&y.setAttribute("textColor",h)):(n.style.color="",n.style.removeProperty("--intelliweave-user-bubble-text"),n.style.removeProperty("--intelliweave-assistant-bubble-text"),y&&y.removeAttribute("textColor")));let _=this.attr.displayMode||r.displayMode||"closed";_!==this._lastDisplayMode&&(this._lastDisplayMode=_,i=!0,_==="open"&&!this.attr.open&&(this.attr.open=!0));let E=this.attr.layout||r.layout||"widget";E!==this._lastLayout&&(this._lastLayout=E,i=!0);let P=this.attr.positioningMode||r.positioningMode||"fixed";P!==this._lastPositioningMode&&(this._lastPositioningMode=P,i=!0);let V=this.attr.positionX||r.positionX||"right";V!==this._lastPositionX&&(this._lastPositionX=V,i=!0);let L=this.attr.positionY||r.positionY||"bottom";L!==this._lastPositionY&&(this._lastPositionY=L,i=!0);let G=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,H=G!==void 0?G:r.offsetX!==void 0?r.offsetX:20;H!==this._lastOffsetX&&(this._lastOffsetX=H,i=!0);let W=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,Y=W!==void 0?W:r.offsetY!==void 0?r.offsetY:20;Y!==this._lastOffsetY&&(this._lastOffsetY=Y,i=!0),i&&un.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:n.style.background,finalTextColor:n.style.color,finalDisplayMode:_,finalLayout:E,finalPositioningMode:P,finalPositionX:V,finalPositionY:L,finalOffsetX:H,finalOffsetY:Y})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),Gr(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let c=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;Gr(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:c}})}this._previousOpenState=this.attr.open;let r=this.child("root");this.attr.open?r.classList.add("open"):r.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(r.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):r.classList.remove("layout-fullscreen");let i=this._lastPositioningMode||"fixed",o=this._lastPositionX||"right",s=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,l=this._lastOffsetY!==void 0?this._lastOffsetY:20;i==="container"?(r.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):r.classList.remove("container-mode"),i!=="container"&&(r.style.left="",r.style.right="",r.style.top="",r.style.bottom="",o==="left"?r.style.left=a+"px":r.style.right=a+"px",s==="top"?r.style.top=l+"px":r.style.bottom=l+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((c,u)=>(u.priority||0)-(c.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){St().embed==this&&(St().embed=void 0)}onContainerClick(r){let n=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&n!=="open"&&(this.attr.open||(r.preventDefault(),this.attr.open=!0))}onLogoClick(r){if(r.preventDefault(),r.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let n=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||n==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let r=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;r.children.length>0;)r.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let n=document.createElement("div");n.className="introduction-message",n.innerHTML=St().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,r.appendChild(n),this.ai.insertAssistantMessage(n.innerText);for(let i of St().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=i,o.addEventListener("click",s=>this.onSuggestionClick(s,i)),r.appendChild(o)}}async processInput(r){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let n=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let c of Array.from(n.querySelectorAll(".suggestion-button")))c.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=r,n.appendChild(i);let o=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",n.appendChild(this.currentOutputElement);let s=Math.ceil(n.clientHeight-300);s<0&&(s=0),s>600&&(s=600),o&&(o.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"});let a=await this.ai.sendMessage(r);for(let c of this.suggestions){let u=document.createElement("div");u.className="suggestion-button",u.innerText=c,u.addEventListener("click",d=>this.onSuggestionClick(d,c)),this.currentOutputElement.appendChild(u)}let l=a.text()||"";this.ai.audio?.speechRecognition?.isRunning&&this.ai.audio.speechOutput.speak(l)}catch(i){un.error("Failed to process input:",i);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+i.message,n.appendChild(o);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",a=>this.resetConversation()),n.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(r,n){let i=[];for(let o of r)for(let s=0;s<(o.sections?.length||0);s++){let a=o.sections[s],l=`msgelem-${o.id||""}_${s}_${a.type||"unknown"}`;if(l=l.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let c=a.text||"";c.includes(`
|
|
769
769
|
`)&&(c=c.split(`
|
|
770
770
|
`)[0]),this.updateInfoElement(l,c,"thinking-icon"),i.push(l)}else if(a.type=="tool_call"){let u=new zu(r).toolResult(a.toolCallInstanceID||"");if(a.toolCallHiddenInUI!="always"){if(u?.toolErrorResponse)this.updateInfoElement(l,"**Error:** "+u.toolErrorResponse||"","tool-icon"),i.push(l);else if(!(a.toolCallHiddenInUI=="after-complete"&&u))if(a.toolKbID=="search"){let d=a.toolParameters?.query?`**Search:** ${a.toolParameters.query}`:"**Search**";this.updateInfoElement(l,d,"tool-icon"),i.push(l)}else this.updateInfoElement(l,a.toolKbName||"","tool-icon"),i.push(l)}}else if(a.type!="tool_result"){if(!a.text)continue;this.updateTextElement(l,a.text||""),i.push(l)}}for(let o of Array.from(this.currentOutputElement.children))i.includes(o.id)||o.remove()}updateTextElement(r,n){let i=this.currentOutputElement.querySelector(`#${r}`);i||(i=document.createElement("div"),i.id=r,i.className="output",this.currentOutputElement.appendChild(i));let o=jv().use(lm).use(cm).use(Kp,{target:"_blank",rel:["noopener","noreferrer"]}).use(Jp).use(tm).processSync(n||"");i.innerHTML=o.toString("utf-8")}updateInfoElement(r,n,i){let o=this.currentOutputElement.querySelector(`#${r}`);o||(o=document.createElement("div"),o.id=r,o.className="info-block",o.innerHTML=`
|
|
771
771
|
<div class='info-block-icon'></div>
|