From ddb58e6c775964c2eca5efff82de49204f509b95 Mon Sep 17 00:00:00 2001 From: SabyaXSachi Date: Sat, 7 Nov 2026 01:36:36 +0530 Subject: [PATCH 1/2] Fix workspace dialog accessibility and keyboard focus --- bus/hostedweb/app.js | 6 +++--- web/build.mjs | 3 ++- web/src/app.js | 10 ++++++--- web/tests/workspace.spec.js | 43 +++++++++++++++++++++++++++++++++++++ 4 files changed, 55 insertions(+), 7 deletions(-) diff --git a/bus/hostedweb/app.js b/bus/hostedweb/app.js index ee96353..bebfbc3 100644 --- a/bus/hostedweb/app.js +++ b/bus/hostedweb/app.js @@ -17,6 +17,6 @@ Resources:`;for(let v of u){if(!v||typeof v!="string")throw new Error(`@supabase ${O}`}var U=class extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=t}toJSON(){return{name:this.name,message:this.message,code:this.code}}},me=class extends U{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function hr({error:n,options:e}){var t,r,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new U({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else if(n.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new U({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:n});if(e.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new U({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:n});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new U({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:n})}else{if(n.name==="InvalidStateError")return new U({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});if(n.name==="NotAllowedError")return new U({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new U({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:n}):new U({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:n});if(n.name==="SecurityError"){let o=window.location.hostname;if(wt(o)){if(i.rp.id!==o)return new U({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new U({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new U({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:n})}else if(n.name==="UnknownError")return new U({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new U({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}function fr({error:n,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new U({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else{if(n.name==="NotAllowedError")return new U({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="SecurityError"){let r=window.location.hostname;if(wt(r)){if(t.rpId!==r)return new U({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new U({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="UnknownError")return new U({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new U({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}var gt=class{createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},Ye=new gt;function yt(n){if(!n)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(n);let{challenge:e,user:t,excludeCredentials:r}=n,s=ue(n,["challenge","user","excludeCredentials"]),i=ae(e).buffer,o=Object.assign(Object.assign({},t),{id:ae(t.id).buffer}),l=Object.assign(Object.assign({},s),{challenge:i,user:o});if(r&&r.length>0){l.excludeCredentials=new Array(r.length);for(let c=0;c0){i.allowCredentials=new Array(t.length);for(let o=0;os!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(let s of n)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(t(o))r[i]=o;else if(e(o)){let l=r[i];e(l)?r[i]=Je(l,o):r[i]=Je(o)}else r[i]=o}return r}function Wr(n,e){return Je(Kr,n,e||{})}function Br(n,e){return Je(Fr,n,e||{})}var He=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){var o;try{let{data:l,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!l)return{data:null,error:c};let u=s??Ye.createNewAbortSignal();if(l.webauthn.type==="create"){let{user:h}=l.webauthn.credential_options.publicKey;if(!h.name){let f=r;if(f)h.name=`${h.id}:${f}`;else{let p=(await this.client.getUser()).data.user,k=((o=p?.user_metadata)===null||o===void 0?void 0:o.name)||p?.email||p?.id||"User";h.name=`${h.id}:${k}`}}h.displayName||(h.displayName=h.name)}switch(l.webauthn.type){case"create":{let h=Wr(l.webauthn.credential_options.publicKey,i?.create),{data:f,error:g}=await bt({publicKey:h,signal:u});return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:g}}case"request":{let h=Br(l.webauthn.credential_options.publicKey,i?.request),{data:f,error:g}=await kt(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:h,signal:u}));return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:g}}}}catch(l){return w(l)?{data:null,error:l}:{data:null,error:new K("Unexpected error in challenge",l)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ie("rpId is required for WebAuthn authentication")};try{if(!$e())return{data:null,error:new K("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!o)return{data:null,error:l};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:t,rpOrigins:r,credential_response:c.credential_response}})}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new K("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ie("rpId is required for WebAuthn registration")};try{if(!$e())return{data:null,error:new K("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(h=>{var f;return(f=h.data)===null||f===void 0?void 0:f.all.find(g=>g.factor_type==="webauthn"&&g.friendly_name===e&&g.status==="unverified")}).then(h=>h?this.client.mfa.unenroll({factorId:h?.id}):void 0),{data:null,error:l};let{data:c,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:t,rpOrigins:r,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new K("Unexpected error in register",o)}}}};lr();var Gr={url:jt,storageKey:$t,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Dt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};var Se={},pr=!1,Xe=class n{get jwks(){var e,t;return(t=(e=Se[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){Se[this.storageKey]=Object.assign(Object.assign({},Se[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=Se[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Se[this.storageKey]=Object.assign(Object.assign({},Se[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},Gr),e);if(this.storageKey=i.storageKey,this.instanceID=(t=n.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,n.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&L()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(r=i.experimental)!==null&&r!==void 0?r:{},this.admin=new ye({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=Be(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock!=null&&(this.lock=i.lock,pr||(pr=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new He(this),recoveryCodes:{getStatus:this._getRecoveryCodesStatus.bind(this),generate:this._generateRecoveryCodes.bind(this),verify:this._verifyRecoveryCode.bind(this),regenerate:this._regenerateRecoveryCodes.bind(this),unenroll:this._unenrollRecoveryCodes.bind(this)}},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:We()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=ft(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=ft(this.memoryStorage)),L()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),(o.data.event==="TOKEN_REFRESHED"||o.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ne}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();let t=await this.initializePromise,r=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(let s of r)await this._notifyAllSubscribers(s.event,s.session,s.broadcast);return t}async _initialize(){var e;try{let t={},r="none";if(L()&&(t=lt(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),L()&&this.detectSessionInUrl&&r!=="none"){let{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Mt(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:l}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return w(t)?this._returnResult({error:t}):this._returnResult({error:new K("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let i=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:V}),{data:o,error:l}=i;if(l||!o)return this._returnResult({data:{user:null,session:null},error:l});let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(w(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,r,s;let i=null;try{let o;if("email"in e){let{email:f,password:g,options:p}=e,k=null,E=null;this.flowType==="pkce"&&([k,E,i]=await this._getCodeChallengeAndMethod()),o=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(p?.emailRedirectTo,i),body:{email:f,password:g,data:(t=p?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:k,code_challenge_method:E},xform:V})}else if("phone"in e){let{phone:f,password:g,options:p}=e;o=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:g,data:(r=p?.data)!==null&&r!==void 0?r:{},channel:(s=p?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:V})}else throw new de("You must provide either an email or phone number and a password");let{data:l,error:c}=o;if(c||!l)return await J(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:c});let u=l.session,h=l.user;return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:h,session:u},error:null})}catch(o){if(await J(this.storage,this.storageKey,i),w(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:l}=e;t=await y(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:dt})}else if("phone"in e){let{phone:i,password:o,options:l}=e;t=await y(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:dt})}else throw new de("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let i=new se;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,t){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,t)):this._exchangeCodeForSession(e,t)}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,o,l,c,u,h,f,g;let p,k;if("message"in e)p=e.message,k=e.signature;else{let{chain:E,wallet:A,statement:O,options:R}=e,v;if(L())if(typeof A=="object")v=A;else{let x=window;if("ethereum"in x&&typeof x.ethereum=="object"&&"request"in x.ethereum&&typeof x.ethereum.request=="function")v=x.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof A!="object"||!R?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=A}let P=new URL((t=R?.url)!==null&&t!==void 0?t:window.location.href),S=await v.request({method:"eth_requestAccounts"}).then(x=>x).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!S||S.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let m=pt(S[0]),I=(r=R?.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!I){let x=await v.request({method:"eth_chainId"});I=cr(x)}let T={domain:P.host,address:m,statement:O,uri:P.href,version:"1",chainId:I,nonce:(s=R?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=R?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(l=R?.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=R?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=R?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(h=R?.signInWithEthereum)===null||h===void 0?void 0:h.resources};p=dr(T),k=await v.request({method:"personal_sign",params:[ur(p),m]})}try{let{data:E,error:A}=await y(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:k},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:V});if(A)throw A;if(!E||!E.session||!E.user){let O=new se;return this._returnResult({data:{user:null,session:null},error:O})}return E.session&&(await this._saveSession(E.session),await this._notifyAllSubscribers("SIGNED_IN",E.session)),this._returnResult({data:Object.assign({},E),error:A})}catch(E){if(w(E))return this._returnResult({data:{user:null,session:null},error:E});throw E}}async signInWithSolana(e){var t,r,s,i,o,l,c,u,h,f,g,p;let k,E;if("message"in e)k=e.message,E=e.signature;else{let{chain:A,wallet:O,statement:R,options:v}=e,P;if(L())if(typeof O=="object")P=O;else{let m=window;if("solana"in m&&typeof m.solana=="object"&&("signIn"in m.solana&&typeof m.solana.signIn=="function"||"signMessage"in m.solana&&typeof m.solana.signMessage=="function"))P=m.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof O!="object"||!v?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");P=O}let S=new URL((t=v?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in P&&P.signIn){let m=await P.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},v?.signInWithSolana),{version:"1",domain:S.host,uri:S.href}),R?{statement:R}:null)),I;if(Array.isArray(m)&&m[0]&&typeof m[0]=="object")I=m[0];else if(m&&typeof m=="object"&&"signedMessage"in m&&"signature"in m)I=m;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in I&&"signature"in I&&(typeof I.signedMessage=="string"||I.signedMessage instanceof Uint8Array)&&I.signature instanceof Uint8Array)k=typeof I.signedMessage=="string"?I.signedMessage:new TextDecoder().decode(I.signedMessage),E=I.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in P)||typeof P.signMessage!="function"||!("publicKey"in P)||typeof P!="object"||!P.publicKey||!("toBase58"in P.publicKey)||typeof P.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");k=[`${S.host} wants you to sign in with your Solana account:`,P.publicKey.toBase58(),...R?["",R,""]:[""],"Version: 1",`URI: ${S.href}`,`Issued At: ${(s=(r=v?.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=v?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${v.signInWithSolana.notBefore}`]:[],...!((o=v?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${v.signInWithSolana.expirationTime}`]:[],...!((l=v?.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${v.signInWithSolana.chainId}`]:[],...!((c=v?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${v.signInWithSolana.nonce}`]:[],...!((u=v?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${v.signInWithSolana.requestId}`]:[],...!((f=(h=v?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||f===void 0)&&f.length?["Resources",...v.signInWithSolana.resources.map(I=>`- ${I}`)]:[]].join(` `);let m=await P.signMessage(new TextEncoder().encode(k),"utf8");if(!m||!(m instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");E=m}}try{let{data:A,error:O}=await y(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:k,signature:ne(E)},!((g=e.options)===null||g===void 0)&&g.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:V});if(O)throw O;if(!A||!A.session||!A.user){let R=new se;return this._returnResult({data:{user:null,session:null},error:R})}return A.session&&(await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session)),this._returnResult({data:Object.assign({},A),error:O})}catch(A){if(w(A))return this._returnResult({data:{user:null,session:null},error:A});throw A}}async _exchangeCodeForSession(e,t){let r=t?.flowId!=null,s=r?je(t?.flowId):L()?je(lt(window.location.href)[re]):null;r&&!s&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",t?.flowId);let{verifier:i,flowId:o}=r&&!s?{verifier:null,flowId:null}:await Yt(this.storage,this.storageKey,s),[l,c]=(i??"").split("/");try{if(!l&&this.flowType==="pkce")throw new Me;let{data:u,error:h}=await y(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:l},xform:V});if(await J(this.storage,this.storageKey,o),h)throw h;if(!u||!u.session||!u.user){let f=new se;return this._returnResult({data:{user:null,session:null,redirectType:null},error:f})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers(c==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:c??null}),error:h})}catch(u){if(await J(this.storage,this.storageKey,o),w(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:o}=e,l=await y(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:V}),{data:c,error:u}=l;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){let h=new se;return this._returnResult({data:{user:null,session:null},error:h})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,s,i,o;let l=null;try{if("email"in e){let{email:c,options:u}=e,h=null,f=null;this.flowType==="pkce"&&([h,f,l]=await this._getCodeChallengeAndMethod());let{error:g}=await y(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(t=u?.data)!==null&&t!==void 0?t:{},create_user:(r=u?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},code_challenge:h,code_challenge_method:f},redirectTo:this._maybeAppendFlowIdToRedirect(u?.emailRedirectTo,l)});return this._returnResult({data:{user:null,session:null},error:g})}if("phone"in e){let{phone:c,options:u}=e,{data:h,error:f}=await y(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(s=u?.data)!==null&&s!==void 0?s:{},create_user:(i=u?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},channel:(o=u?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:h?.message_id},error:f})}throw new de("You must provide either an email or phone number.")}catch(c){if(await J(this.storage,this.storageKey,l),w(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:l}=await y(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:V});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(s){if(w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,r,s,i;let o=null;try{let l=null,c=null;this.flowType==="pkce"&&([l,c,o]=await this._getCodeChallengeAndMethod());let u=await y(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:this._maybeAppendFlowIdToRedirect((t=e.options)===null||t===void 0?void 0:t.redirectTo,o)}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:or});return!((s=u.data)===null||s===void 0)&&s.url&&L()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await J(this.storage,this.storageKey,o),w(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new j;let{error:s}=await y(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(w(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let t=null;try{let r=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:o}=e,l=null,c=null;this.flowType==="pkce"&&([l,c,t]=await this._getCodeChallengeAndMethod());let{error:u}=await y(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken},code_challenge:l,code_challenge_method:c},redirectTo:this._maybeAppendFlowIdToRedirect(o?.emailRedirectTo,t)});return u&&await J(this.storage,this.storageKey,t),this._returnResult({data:{user:null,session:null},error:u})}else if("phone"in e){let{phone:s,type:i,options:o}=e,{data:l,error:c}=await y(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:l?.message_id},error:c})}throw new de("You must provide either an email or phone number and a type")}catch(r){if(await J(this.storage,this.storageKey,t),w(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await M(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at*1e3-Date.now()Date.now()?this._returnResult({data:{session:await this._hydrateSessionUser(o)},error:null}):this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async _hydrateSessionUser(e){if(this.userStorage){let t=await M(this.userStorage,this.storageKey+"-user");e.user=t?.user?t.user:Ge()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let t={value:this.suppressGetSessionWarning};e.user=sr(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return e}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t;return this.lock!=null?t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):t=await this._getUser(),t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await y(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ee}):await this._useSession(async t=>{var r,s,i;let{data:o,error:l}=t;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new j}:await y(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:ee})})}catch(t){if(w(t))return xe(t)&&await this._removeSession(),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t)):await this._updateUser(e,t)}async _updateUser(e,t={}){let r=null;try{return await this._useSession(async s=>{let{data:i,error:o}=s;if(o)throw o;if(!i.session)throw new j;let l=i.session,c=null,u=null;this.flowType==="pkce"&&e.email!=null&&([c,u,r]=await this._getCodeChallengeAndMethod());let{data:h,error:f}=await y(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t?.emailRedirectTo,r),body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:u}),jwt:l.access_token,xform:ee});if(f)throw f;return l.user=h.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),this._returnResult({data:{user:l.user},error:null})})}catch(s){if(await J(this.storage,this.storageKey,r),w(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new j;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:o}=Ue(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){let{data:l,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};i=l}else{let{data:l,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(w(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}async refreshSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:l}=t;if(l)throw l;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new j;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){var r;try{if(!L())throw new he("No browser detected.");if(e.error||e.error_description||e.error_code)throw new he(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new Ae("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new he("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Ae("No code detected.");let{data:v,error:P}=await this._exchangeCodeForSession(e.code,{flowId:e[re]});if(P)throw P;let S=new URL(window.location.href);return S.searchParams.delete("code"),S.searchParams.delete(re),window.history.replaceState(window.history.state,"",S.toString()),{data:{session:v.session,redirectType:(r=v.redirectType)!==null&&r!==void 0?r:null},error:null}}let{provider_token:s,provider_refresh_token:i,access_token:o,refresh_token:l,expires_in:c,expires_at:u,token_type:h}=e;if(!o||!c||!l||!h)throw new he("No session defined in URL");let f=Math.round(Date.now()/1e3),g=parseInt(c),p=f+g;u&&(p=parseInt(u));let k=p-f;k*1e3<=X&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${k}s, should have been closer to ${g}s`);let E=p-g;f-E>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",E,p,f):f-E<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",E,p,f);let{data:A,error:O}=await this._getUser(o);if(O)throw O;let R={provider_token:s,provider_refresh_token:i,access_token:o,expires_in:g,expires_at:p,refresh_token:l,token_type:h,user:A.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:R,redirectType:e.type},error:null})}catch(s){if(w(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let t=je(e[re]);return t&&await M(this.storage,we(this.storageKey,t))?!0:!!await M(this.storage,`${this.storageKey}-code-verifier`)}async signOut(e={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let s=async()=>{await this._removeSession()},{data:i,error:o}=t;if(o&&!xe(o))return this._returnResult({error:o});let l=(r=i.session)===null||r===void 0?void 0:r.access_token;if(l){let{error:c}=await this.admin.signOut(l,e);if(c&&!(it(c)&&(c.status===404||c.status===401||c.status===403)||xe(c)))return e!=="others"&&await s(),this._returnResult({error:c})}return e!=="others"&&await s(),this._returnResult({error:null})})}onAuthStateChange(e){let t=Gt(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)}):await this._emitInitialSession(t)))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:i},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){if(await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),ot(i))return;xe(i)||Ce(i)||it(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null,i=null;this.flowType==="pkce"&&([r,s,i]=await this._getCodeChallengeAndMethod(!0));try{return await y(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t.redirectTo,i)})}catch(o){if(await J(this.storage,this.storageKey,i),w(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;let r=null;try{let{data:s,error:i}=await this._useSession(async o=>{var l,c,u,h,f;let{data:g,error:p}=o;if(p)throw p;let{url:k,flowId:E}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(l=e.options)===null||l===void 0?void 0:l.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return r=E,await y(this.fetch,"GET",k,{headers:this.headers,jwt:(f=(h=g.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(i)throw i;return L()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url,flowId:r},error:null})}catch(s){if(w(s))return this._returnResult({data:{provider:e.provider,url:null,flowId:r},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:o,provider:l,token:c,access_token:u,nonce:h}=e,f=await y(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i?.access_token)!==null&&r!==void 0?r:void 0,body:{provider:l,id_token:c,access_token:u,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:V}),{data:g,error:p}=f;return p?this._returnResult({data:{user:null,session:null},error:p}):!g||!g.session||!g.user?this._returnResult({data:{user:null,session:null},error:new se}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:p}))}catch(s){if(await J(this.storage,this.storageKey,null),w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)throw o;return await y(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){let t="#_refreshAccessToken()";this._debug(t,"begin");try{let r=Date.now();return await Jt(async s=>(s>0&&await zt(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await y(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:V})),(s,i)=>{let o=200*Math.pow(2,s);return i&&Ce(i)&&Date.now()+o-r{});let i=await M(this.storage,this.storageKey),{data:o,error:l}=await this._refreshAccessToken(e);if(l)throw l;if(!o.session)throw new j;let c=await M(this.storage,this.storageKey);if(i!==null&&(c===null||c.refresh_token!==i.refresh_token)){this._debug(s,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:c?"replaced":"cleared"});let g={data:null,error:new Ie};return this.refreshingDeferred.resolve(g),g}let h=this._sessionRemovalEpoch;if(await this._saveSession(o.session),this._sessionRemovalEpoch!==h){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await W(this.storage,this.storageKey),this.userStorage&&await W(this.userStorage,this.storageKey+"-user");let g={data:null,error:new Ie};return this.refreshingDeferred.resolve(g),g}await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);let f={data:o.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(f),f}catch(i){if(this._debug(s,"error",i),w(i)){let o={data:null,error:i};if(!Ce(i)){let l=await M(this.storage,this.storageKey);!!(l?.expires_at&&l.expires_at*1e3>Date.now())?this._debug(s,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:o,expiresAt:Date.now()+Ut},(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){if(this._pendingInitNotifications!==null&&r){this._pendingInitNotifications.push({event:e,session:t,broadcast:r});return}let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let l=0;lthis._autoRefreshTokenTick(),X);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/X);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${X}ms, refresh threshold is ${be} ticks`),s<=be&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof ze)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/X);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${X}ms, refresh threshold is ${be} ticks`),s<=be&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!L()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(t,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=r?.redirectTo,i=null,o=null,l=null;this.flowType==="pkce"&&([i,o,l]=await this._getCodeChallengeAndMethod(),s=this._maybeAppendFlowIdToRedirect(s,l));let c=[`provider=${encodeURIComponent(t)}`];if(s&&c.push(`redirect_to=${encodeURIComponent(s)}`),r?.scopes&&c.push(`scopes=${encodeURIComponent(r.scopes)}`),i!=null&&o!=null){let u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});c.push(u.toString())}if(r?.queryParams){let u=new URLSearchParams(r.queryParams);c.push(u.toString())}return r?.skipBrowserRedirect&&c.push(`skip_http_redirect=${r.skipBrowserRedirect}`),{url:`${e}?${c.join("&")}`,flowId:l}}_maybeAppendFlowIdToRedirect(e,t){return!e||!t||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:Qt(e,t)}async _getCodeChallengeAndMethod(e=!1){return Zt(this.storage,this.storageKey,e,t=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",t))}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await y(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await y(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((s=c?.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?_t(e.webauthn.credential_response):vt(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:u}=await y(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:l,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:u}))})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challenge(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=await y(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(l.error)return l;let{data:c}=l;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:yt(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:mt(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let i of(e=t?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&i.factor_type in s&&Array.isArray(s[i.factor_type])&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,i;if(e)try{let{payload:p}=Ue(e),k=null;p.aal&&(k=p.aal);let E=k,{data:{user:A},error:O}=await this.getUser(e);if(O)return this._returnResult({data:null,error:O});((r=(t=A?.factors)===null||t===void 0?void 0:t.filter(P=>P.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(E="aal2");let v=p.amr||[];return{data:{currentLevel:k,nextLevel:E,currentAuthenticationMethods:v},error:null}}catch(p){if(w(p))return this._returnResult({data:null,error:p});throw p}let{data:{session:o},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=Ue(o.access_token),u=null;c.aal&&(u=c.aal);let h=u;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(p=>p.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");let g=c.amr||[];return{data:{currentLevel:u,nextLevel:h,currentAuthenticationMethods:g},error:null}}async _getRecoveryCodesStatus(){ke(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await y(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _generateRecoveryCodes(e){ke(this.experimental);try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let{data:o,error:l}=await y(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:e?.friendlyName?{friendly_name:e.friendlyName}:void 0,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):this._returnResult({data:o,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verifyRecoveryCode(e){ke(this.experimental);let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let{data:l,error:c}=await y(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:e.code},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(c)return this._returnResult({data:null,error:c});let u=Object.assign({expires_at:Fe(l.expires_in)},l);return await this._saveSession(u),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:l,error:null})})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _regenerateRecoveryCodes(){ke(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await y(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _unenrollRecoveryCodes(){ke(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await y(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await y(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new j})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new j});let o=await y(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&L()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new j});let o=await y(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&L()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await y(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new j})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await y(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new j})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(l=>l.kid===e);if(r)return r;let s=Date.now();if(r=this.jwks.keys.find(l=>l.kid===e),r&&this.jwks_cached_at+qt>s)return r;let{data:i,error:o}=await y(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(l=>l.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){let{data:p,error:k}=await this.getSession();if(k||!p.session)return this._returnResult({data:null,error:k});r=p.session.access_token}let{header:s,payload:i,signature:o,raw:{header:l,payload:c}}=Ue(r);if(!t?.allowExpired)try{tr(i.exp)}catch(p){throw new oe(p instanceof Error?p.message:"JWT validation failed")}let u=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!u){let{error:p}=await this.getUser(r);if(p)throw p;return{data:{claims:i,header:s,signature:o},error:null}}let h=rr(s.alg),f=await crypto.subtle.importKey("jwk",u,h,!0,["verify"]);if(!await crypto.subtle.verify(h,f,o,Bt(`${l}.${c}`)))throw new oe("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async signInWithPasskey(e){var t,r,s,i;try{if(!$e())return this._returnResult({data:null,error:new K("Browser does not support WebAuthn",null)});let{data:o,error:l}=await this._startPasskeyAuthentication({options:{captchaToken:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}});if(l||!o)return this._returnResult({data:null,error:l});let c=mt(o.options),u=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:Ye.createNewAbortSignal(),{data:h,error:f}=await kt({publicKey:c,signal:u,mediation:(i=e?.options)===null||i===void 0?void 0:i.mediation});if(f||!h)return this._returnResult({data:null,error:f??new K("WebAuthn ceremony failed",null)});let g=vt(h);return this._verifyPasskeyAuthentication({challengeId:o.challenge_id,credential:g})}catch(o){if(w(o))return this._returnResult({data:null,error:o});throw o}}async registerPasskey(e){var t,r;try{if(!$e())return this._returnResult({data:null,error:new K("Browser does not support WebAuthn",null)});let{data:s,error:i}=await this._startPasskeyRegistration();if(i||!s)return this._returnResult({data:null,error:i});let o=yt(s.options),l=(r=(t=e?.options)===null||t===void 0?void 0:t.signal)!==null&&r!==void 0?r:Ye.createNewAbortSignal(),{data:c,error:u}=await bt({publicKey:o,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new K("WebAuthn ceremony failed",null)});let h=_t(c);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:h})}catch(s){if(w(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyRegistration(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new j});let{data:s,error:i}=await y(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{data:i,error:o}=await y(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _startPasskeyAuthentication(e){var t;try{let{data:r,error:s}=await y(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:r,error:null})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _verifyPasskeyAuthentication(e){try{let{data:t,error:r}=await y(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:V});return r?this._returnResult({data:null,error:r}):(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:t,error:null}))}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _listPasskeys(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new j});let{data:s,error:i}=await y(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{data:i,error:o}=await y(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _deletePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{error:i}=await y(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}};Xe.nextInstanceID={};var St=Xe;var Vr=St,Rt=Vr;var le=document.querySelector("#app"),De=document.querySelector("#notice"),d={auth:null,config:null,user:null,workspaces:[],workspace:null,tab:"sessions",generation:0,conversationAgent:"",search:"",channelId:"",threadId:"",channelSearch:""},wr,Ze=[];function mr(){for(let n of Ze.splice(0))n()}var _e=new URLSearchParams(location.search);_e.has("billing")&&(d.tab="billing");var xt="agentintercom-pending",$={};try{let n=JSON.parse(sessionStorage.getItem(xt)||"{}");n.until>Date.now()&&($=n)}catch{}_e.get("authorization_id")&&($.authorization=_e.get("authorization_id"));var _r=new URLSearchParams(location.hash.slice(1)),gr=_r.get("invite"),yr=_r.get("device")||_e.get("device_code");yr&&($.device=yr,history.replaceState(null,"",location.pathname+location.search));gr&&($.invite=gr,history.replaceState(null,"",location.pathname+location.search));($.authorization||$.invite||$.device)&&sessionStorage.setItem(xt,JSON.stringify({...$,until:Date.now()+1200*1e3}));function a(n,e={},...t){let r=document.createElement(n);for(let[s,i]of Object.entries(e))i==null||i===!1||(s.startsWith("on")?r.addEventListener(s.slice(2),i):s==="class"?r.className=i:s==="text"?r.textContent=i:r.setAttribute(s,i===!0?"":String(i)));for(let s of t.flat(1/0))s!=null&&r.append(s instanceof Node?s:document.createTextNode(String(s)));return r}function H(n,e=!1){clearTimeout(wr),De.textContent=n,De.hidden=!1,De.className=e?"error":"",De.setAttribute("role",e?"alert":"status"),wr=setTimeout(()=>{De.hidden=!0},e?15e3:6e3)}async function Re(n,e){if(!n?.disabled){n&&(n.disabled=!0);try{return await e()}catch(t){H(t.message||"Something went wrong. Please try again.",!0)}finally{n&&(n.disabled=!1)}}}function _(n,e,t=""){return a("button",{type:"button",class:t,onclick:r=>Re(r.currentTarget,e)},n)}function N(n,e={}){let t=a(e.multiline?"textarea":"input",{...e,multiline:null});return{input:t,node:a("label",{},n,t)}}function F(n,e,t){let r=a("button",{type:"submit",class:"primary"},e);return a("form",{onsubmit:s=>{s.preventDefault(),Re(r,()=>t(new FormData(s.currentTarget)))}},n,r)}var ce=()=>a("div",{class:"brand"},a("span",{class:"mark","aria-hidden":!0},"o"),"agent intercom"),B=n=>n?new Date(n).toLocaleString():"\u2014",D=n=>`/api/workspaces/${encodeURIComponent(d.workspace.id)}${n}`;async function b(n,e={}){let t={"Content-Type":"application/json"};if(d.auth&&n!=="/api/config"){let{data:i,error:o}=await d.auth.getSession();if(o)throw o;i.session&&(t.Authorization=`Bearer ${i.session.access_token}`)}let r=await fetch(n,{method:e.method||"GET",credentials:"omit",headers:t,body:e.body==null?void 0:JSON.stringify(e.body),signal:AbortSignal.timeout(e.timeout||15e3)}),s=await r.json();if(!r.ok||s.ok===!1||s.error)throw new Error(s.error?.message||"The request could not be completed. Please try again.");return s.result}async function rt(n){await navigator.clipboard.writeText(n),H("Copied to clipboard.")}var Et=new WeakMap;async function Ct(n,e={}){let{data:t,error:r}=await d.auth.getSession();if(r)throw r;if(!t.session)throw new Error("Sign in again to access workspace files.");let s=await fetch(n,{...e,credentials:"omit",redirect:"error",headers:{Authorization:`Bearer ${t.session.access_token}`,"Content-Type":"application/octet-stream"},signal:AbortSignal.timeout(3e4)});if(!s.ok){let i=await s.json().catch(()=>({}));throw new Error(i.error?.message||"File transfer failed. Please try again.")}return s}async function vr(n,e){if(e.size>16*1024*1024)throw new Error("Files can be up to 16 MiB.");Et.has(e)||Et.set(e,crypto.randomUUID());let t=new URLSearchParams({name:e.name,mediaType:e.type.split(";")[0]||"application/octet-stream",idempotencyKey:Et.get(e)}),s=await(await Ct(n+"/attachments?"+t,{method:"POST",body:e})).json();if(!s.ok)throw new Error(s.error?.message||"Upload failed.");return s.result}async function br(n,e,t){let r=await Ct(n+"/attachments/"+encodeURIComponent(e)+"/content"),s=await r.arrayBuffer();if([...new Uint8Array(await crypto.subtle.digest("SHA-256",s))].map(u=>u.toString(16).padStart(2,"0")).join("")!==r.headers.get("X-Content-SHA256"))throw new Error("File checksum did not match. The download was stopped.");let o=r.headers.get("Content-Disposition")||"";if(!t)try{t=decodeURIComponent(o.match(/filename\*=utf-8''([^;]+)/i)?.[1]||"")||o.match(/filename="([^"]+)"/)?.[1]||o.match(/filename=([^;]+)/)?.[1]}catch{}let l=URL.createObjectURL(new Blob([s],{type:"application/octet-stream"})),c=a("a",{href:l,download:(t||e).replace(/[\\/\x00-\x1f]/g,"_")});document.body.append(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(l),3e4)}function kr(n,e){let t=N("Attach a file",{type:"file"}),r=_("Upload and attach",async()=>{let s=t.input.files[0];if(!s)throw new Error("Choose a file first.");let i=t.input.closest("form")?.querySelector('[type="submit"]');i&&(i.disabled=!0);try{let o=await vr(n,s);e.value+=`${e.value?` -`:""}${o.name}: ${o.uri}`,t.input.value="",H("File attached. Send your message to share the reference.")}finally{i&&(i.disabled=!1)}});return a("details",{},a("summary",{},"Attach a file"),t.node,r,a("p",{class:"help"},"Up to 16 MiB. Uploaded files are visible to everyone in this workspace."))}function Sr(n,e,t=[]){let r=new Map;for(let s of String(e).matchAll(/october-bus:\/\/attachments\/(att_[0-9a-f]{32})(?![0-9a-f])/g))r.set(s[1],"");for(let s of t||[]){let i=s.uri?.match(/^october-bus:\/\/attachments\/(att_[0-9a-f]{32})$/)?.[1];i&&r.set(i,s.title)}return a("div",{class:"actions"},[...r].map(([s,i])=>_(i?`Download ${i}`:"Download shared file",()=>br(n,s,i))))}async function zr(){let n=D(""),e=a("div"),t=a("div",{class:"grid"}),r=o=>{for(let l of o.attachments){let u=l.authorKind==="human"&&l.authorId===d.user.id||["owner","admin"].includes(d.workspace.role)?_("Delete file",()=>te("Delete this file?",h=>a("div",{},a("p",{},`Delete ${l.name}? Existing message references will stop working.`),_("Delete permanently",async()=>{await b(n+"/attachments/"+l.id,{method:"DELETE"}),h(),await C()})))):null;t.append(a("article",{class:"card"},a("h2",{},l.name),a("p",{class:"help"},`${(l.size/1024).toFixed(1)} KiB \xB7 ${l.mediaType} \xB7 ${B(l.createdAt)}`),a("div",{class:"actions"},_("Download",()=>br(n,l.id,l.name)),_("Copy reference",()=>rt(l.uri)),u)))}},s=await b(n+"/attachments");r(s),s.attachments.length||t.append(a("section",{class:"card empty"},a("h2",{},"Share the files your work needs."),a("p",{},"Upload a file here or attach one to a conversation. Files stay private to this workspace.")));let i=N("File to upload",{type:"file",required:!0});if(e.append(a("section",{class:"card"},F([i.node,a("p",{class:"help"},"Up to 16 MiB per file. Everyone in the workspace can download it.")],"Upload file",async()=>{let o=i.input.files[0];if(!o)throw new Error("Choose a file first.");await vr(n,o),await C()})),t),s.nextCursor){let o=s.nextCursor,l=_("More files",async()=>{let c=await b(n+"/attachments?after="+encodeURIComponent(o));r(c),o=c.nextCursor,o||l.remove()});e.append(l)}return e}function et(n){delete $[n],sessionStorage.setItem(xt,JSON.stringify({...$,until:Date.now()+1200*1e3})),history.replaceState(null,"","/app")}function te(n,e){let t=a("dialog",{},a("h2",{},n)),r=()=>{t.close(),t.remove()};return t.append(e(r),a("div",{class:"actions end"},_("Close",r))),t.addEventListener("close",()=>t.remove()),document.body.append(t),t.showModal(),t}function tt(n,e,t){te(n,()=>a("div",{},a("p",{},t),a("pre",{class:"secret"},e),_("Copy",()=>rt(e))))}function At(){mr(),d.user=null;let n=N("Email address",{type:"email",name:"email",autocomplete:"email",required:!0}),e=F([n.node],"Continue with email",async i=>{let{error:o}=await d.auth.signInWithOtp({email:i.get("email"),options:{emailRedirectTo:location.origin+"/app"+($.authorization?"?authorization_id="+encodeURIComponent($.authorization):$.device?"?device_code="+encodeURIComponent($.device):""),shouldCreateUser:!0}});if(o)throw o;H("Check your email for an October sign-in link. Open it in this browser."),e.append(a("p",{class:"notice-inline"},"Check your email for a sign-in link. Keep this tab open so you can return to your connection request."))}),t=N("Email address",{name:"email",type:"email",autocomplete:"username",required:!0}),r=N("Password",{name:"password",type:"password",autocomplete:"current-password",required:!0}),s=F([t.node,r.node],"Sign in",async i=>{let{error:o}=await d.auth.signInWithPassword({email:i.get("email"),password:i.get("password")});if(o)throw o;await Y()});le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("div",{class:"auth-layout"},a("div",{class:"auth-copy"},a("div",{class:"eyebrow"},"One place to work together"),a("h1",{},`Your agents. -A shared conversation.`),a("p",{},"Connect your AI apps, bring in another machine, and keep the work moving with your team.")),a("section",{class:"card auth-card","aria-labelledby":"signin-title"},a("h2",{id:"signin-title"},"Sign in to October"),a("p",{class:"help"},"Use your existing October account, or create one with your email."),e,a("details",{},a("summary",{},"Use an existing password"),s),a("p",{class:"help"},"Your AI subscriptions stay with your apps. Agent Intercom connects the work.")))))}async function Y(){d.user=await b("/api/me"),d.workspaces=await b("/api/workspaces");let n=_e.has("billing")&&_e.get("workspace")||localStorage.getItem("agentintercom-workspace");if(d.workspace=d.workspaces.find(e=>e.id===n)||d.workspaces[0]||null,$.invite)return Jr();if($.authorization)return It();if($.device)return Tt();if(!d.workspace)return Rr();await C()}function st(n){let e=N("Workspace name",{name:"name",placeholder:"My team",maxlength:100,required:!0});return F([e.node,a("p",{class:"help"},"Your first workspace starts a 14-day trial. Additional workspaces share its end date. Up to 5 people; no payment details needed.")],"Create workspace",async t=>{let r=await b("/api/workspaces",{method:"POST",body:{name:t.get("name")}});d.workspaces.push(r),d.workspace=r,localStorage.setItem("agentintercom-workspace",r.id),await n()})}function Rr(){le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("section",{class:"card consent"},a("h1",{},"Make room for your team."),a("p",{},"A workspace holds your connected sessions, messages and shared work."),st(C),_("Sign out",Ot))))}async function Ot(){let{error:n}=await d.auth.signOut({scope:"local"});if(n)throw n;d.generation++,At()}function Pt(n){return a("select",{"aria-label":"Workspace",onchange:t=>{d.workspace=d.workspaces.find(r=>r.id===t.target.value),localStorage.setItem("agentintercom-workspace",d.workspace.id),Re(null,n)}},d.workspaces.map(t=>a("option",{value:t.id,selected:t.id===d.workspace?.id},t.name)))}async function It(){let n=await b(`/api/oauth/requests/${encodeURIComponent($.authorization)}`),e=d.workspace?.id,r=(e?await b(D("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="mcp"),s=a("select",{"aria-label":"App connection"},a("option",{value:""},"Create a new app connection"),r.map(c=>a("option",{value:c.id},`Reconnect ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"The old app credentials will stop working. This app will receive the same session inbox, including its pending messages.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");let u=await b(`/api/oauth/requests/${encodeURIComponent($.authorization)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}});et("authorization"),location.assign(u.redirectUrl)},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Pt(It)),r.length?a("label",{},"App connection",s):null,i,a("div",{class:"actions"},_("Allow connection",()=>o(!0),"primary"),_("Cancel",()=>o(!1)))):st(It);le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect an app"),a("h1",{},n.clientName),a("p",{},"wants to connect to your Agent Intercom workspace."),a("p",{class:"help"},"This app registered itself. October has not verified its publisher. Only continue if you started this connection in an app you trust."),a("ul",{class:"permission-list"},a("li",{},"Read and share messages, files and channels in the selected workspace."),a("li",{},"Discover connected sessions and coordinate shared tasks."),a("li",{},"Remain connected until you revoke access or the connection expires.")),a("p",{class:"help"},"You can revoke access at any time in Members & devices."),a("p",{class:"help"},"Returns to: ",a("code",{},new URL(n.redirectUri).origin)),l)))}async function Tt(){let n=await b(`/api/device/authorizations/${encodeURIComponent($.device)}`),e=d.workspace?.id,r=(e?await b(D("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="device"),s=a("select",{"aria-label":"Device connection"},a("option",{value:""},"Connect a new machine"),r.map(c=>a("option",{value:c.id},`Replace ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"Replacing a connection signs out its existing sessions. Their inboxes stay available. Resume each session using its existing session ID after this login completes.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");await b(`/api/device/authorizations/${encodeURIComponent($.device)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}}),et("device"),le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("h1",{},c?"Your device can connect.":"Connection declined."),a("p",{},c?"Return to your terminal to finish. Each session on this device will appear in your workspace.":"No device credential was issued."),_("Open workspace",Y,"primary"))))},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Pt(Tt)),r.length?a("label",{},"Device connection",s):null,i,a("div",{class:"actions"},_("Connect this device",()=>o(!0),"primary"),_("Decline",()=>o(!1)))):st(Tt);le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect a machine"),a("h1",{},n.name),a("p",{},"Check that this code matches the one in your terminal:"),a("pre",{},n.userCode),a("p",{class:"help"},"Only approve a request you started. This device can read and send workspace messages and start its own agent sessions. You can revoke it in Members & devices."),l)))}function Jr(){le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("h1",{},"Join a workspace"),a("p",{},`You are signed in as ${d.user.email}. The invitation must match this address.`),a("div",{class:"actions"},_("Accept invitation",async()=>{let n=await b("/api/invites/accept",{method:"POST",body:{token:$.invite}});localStorage.setItem("agentintercom-workspace",n.workspaceId),et("invite"),await Y()},"primary"),_("Use another account",Ot),_("Cancel",async()=>{et("invite"),await Y()})))))}var Qe={sessions:["Sessions","Choose the connected session you want to work with."],messages:["Conversations","Messages and receipts shared with this workspace."],channels:["Channels","Shared discussions and threads for this workspace."],tasks:["Tasks","Shared work, claimed by the session doing it."],questions:["Needs you","Help your agents continue when they need a decision."],files:["Files","Private files shared with your workspace."],connect:["Connect an app","Use your favorite AI app, on this machine or another one."],members:["Members & devices","Give each person and machine their own access."],data:["Data & recovery","Export your workspace and manage retained history."],billing:["Billing & usage","Your workspace plan, payment details and included usage."]};async function C(){if(mr(),!d.workspace)return Rr();let n=++d.generation,e=a("main",{id:"main",class:"content"}),t=a("nav",{"aria-label":"Workspace"},Object.entries(Qe).map(([s,[i]])=>_(i,async()=>{d.tab=s,await C()},s===d.tab?"selected":"")));[...t.children].forEach((s,i)=>{Object.keys(Qe)[i]===d.tab&&s.setAttribute("aria-current","page")}),le.replaceChildren(a("div",{class:"shell"},a("aside",{class:"sidebar"},ce(),a("div",{class:"workspace-switch"},Pt(C),_("+ New workspace",()=>te("New workspace",s=>st(async()=>{s(),await C()})),"subtle-button")),t,a("div",{class:"account"},a("p",{},d.user.email),_("Sign out",Ot,"subtle-button"))),e)),e.append(a("header",{class:"topline"},a("div",{},a("div",{class:"eyebrow"},d.workspace.name),a("h1",{},Qe[d.tab][0]),a("p",{class:"muted"},Qe[d.tab][1])),d.tab==="sessions"?_("Connect an app",async()=>{d.tab="connect",await C()},"primary"):null));let r=a("p",{class:"progress"},"Loading\u2026");e.append(r);try{let s=await{data:ns,billing:ss,files:zr,channels:rs,messages:Zr,tasks:es,questions:ts,sessions:Hr,connect:Yr,members:Xr}[d.tab]();if(n!==d.generation)return;r.replaceWith(s)}catch(s){n===d.generation&&r.replaceWith(a("div",{class:"card"},a("p",{},s.message),_("Try again",C)))}}async function Hr(){let n=a("div"),e=a("div",{class:"grid"}),t=await b(D("/sessions")),r=s=>{for(let i of s.sessions){let o=i.reachable===!0;e.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},i.displayName||i.agentId||i.id),a("span",{class:`badge ${o?"live":""}`},o?"Connected":"Offline")),a("p",{class:"help"},i.deviceName),a("p",{class:"help"},i.deliveryMode==="poll"?"Inbox available when this app checks for messages. It may need you to resume the conversation.":"Native listener connected. Your app\u2019s permissions still apply."),a("small",{},`Last seen ${B(i.updatedAt)}`),i.wake?.uncertain?a("p",{class:"notice-inline"},"A wake submission is uncertain. Inspect the app before retrying; the message is still in its inbox."):null,a("div",{class:"actions"},_("Open conversation",async()=>{d.conversationAgent=i.id,d.tab="messages",await C()})))),i.userId===d.user.id&&e.lastChild.append(a("details",{},a("summary",{},"Session details"),a("p",{class:"help"},"This ID identifies the inbox. Terminal sessions can resume it with --id after reconnecting their owning machine."),a("code",{},i.id),_("Copy session ID",()=>rt(i.id))))}};if(!t.sessions.length)return a("section",{class:"card empty"},a("h2",{},"Your first connection starts here."),a("p",{class:"muted"},"Connect an AI app or terminal session. It will appear here under its own name, ready for shared work."),_("Connect an app",async()=>{d.tab="connect",await C()},"primary"));if(r(t),n.append(e),t.nextCursor){let s=t.nextCursor,i=_("Show more sessions",async()=>{let o=await b(D("/sessions")+"?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});n.append(i)}return n.append(a("p",{class:"help"},"Connected means the app contacted Agent Intercom recently. It does not mean the model is currently working."),_("Refresh sessions",C)),n}function Yr(){let n=d.config.mcpUrl,e=D("");return a("div",{class:"grid"},a("section",{class:"card"},a("h2",{},"An app with remote MCP"),a("p",{},"In your app\u2019s connectors or MCP settings, add Agent Intercom using this address."),a("pre",{},n),_("Copy connector URL",()=>rt(n)),a("ol",{},a("li",{},"Add the connector in your app."),a("li",{},"Sign in to October and choose this workspace."),a("li",{},"Ask your app to check its Bus inbox or find connected sessions.")),a("p",{class:"help"},"Works with compatible Streamable HTTP MCP clients. Your app controls which conversations can use tools and whether an idle conversation can resume.")),a("section",{class:"card"},a("h2",{},"An app that asks for an API key"),a("p",{},"Use the same remote MCP URL. Create a separate key for each app so you can revoke it independently."),F([N("App connection name",{name:"name",required:!0,maxlength:100,placeholder:"My AI app"}).node,a("p",{class:"help"},"The app can read and share workspace messages, files, channels and tasks. A key expires after 90 days and cannot manage your account or members.")],"Create MCP key",async t=>{let r=await b(e+"/mcp-keys",{method:"POST",body:{name:t.get("name")}});tt("MCP connection key",r.token,`Paste this into your app\u2019s secret/API key field, or use Authorization: Bearer . It is shown once and expires ${B(r.expiresAt)}. Keep it out of chat, URLs and source control.`)}),a("p",{class:"help"},"Choose OAuth instead if your app offers it. Neither connection method can make an unsupported app resume an idle conversation.")),a("section",{class:"card"},a("h2",{},"Another machine or automation"),a("p",{},"Install the Agent Intercom CLI on that machine, then run:"),a("pre",{},"agentintercom hosted login --server "+location.origin),a("p",{},"Open the link it prints, confirm the code and choose this workspace. For any app with a local MCP connection, run:"),a("pre",{},"agentintercom connect --hosted default"),a("p",{},"Or start a terminal session with native message wake:"),a("pre",{},`agentintercom session start claude --hosted default -agentintercom session start codex --hosted default`),a("p",{class:"help"},"Choose the app you use. Keep its terminal open; normal app permissions apply. Codex native wake is experimental."),a("details",{},a("summary",{},"Create a credential for custom automation"),F([N("Device name",{name:"name",required:!0,maxlength:100,placeholder:"My laptop"}).node],"Create device credential",async t=>{let r=await b(D("/devices"),{method:"POST",body:{name:t.get("name")}});tt("Device credential",r.token,"Save this in your device\u2019s secret store. It is shown only once. Anyone with it can join sessions to this workspace as you.")}),a("p",{class:"help"},"Keep credentials out of chat messages, shell history and source control."))))}async function Xr(){let n=D(""),[e,t]=await Promise.all([b(D("/members")),b(D("/devices"))]),r=d.workspace.role!=="member",s=a("section",{class:"card"},a("h2",{},"People"));for(let l of e){let c=[];if(d.workspace.role==="owner"){let u=a("select",{"aria-label":`Role for ${l.email}`},["member","admin","owner"].map(h=>a("option",{value:h,selected:h===l.role},h)));c.push(u,_("Save role",async()=>{await b(D(`/members/${encodeURIComponent(l.userId)}`),{method:"PATCH",body:{role:u.value}}),await Y()}))}else c.push(a("span",{class:"badge"},l.role));(r||l.userId===d.user.id)&&c.push(_(l.userId===d.user.id?"Leave":"Remove",()=>te("Remove workspace access?",u=>a("div",{},a("p",{},`${l.email} will lose access and their connected sessions will be revoked.`),_("Remove access",async()=>{await b(D(`/members/${encodeURIComponent(l.userId)}`),{method:"DELETE"}),u(),await Y()},"danger"))),"danger")),s.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.email),a("p",{class:"help"},`Joined ${B(l.joinedAt)}`)),a("div",{class:"actions"},c)))}let i=a("section",{class:"card"},a("h2",{},"Apps & devices"));t.length||i.append(a("p",{class:"muted"},"No devices connected yet."));for(let l of t){let c=!!l.revokedAt,u=[];l.kind==="mcp_key"&&l.userId===d.user.id&&u.push(_("Replace key",()=>te("Replace this MCP key?",h=>a("div",{},a("p",{},`The old key for ${l.name} will stop working immediately. The replacement keeps its session inbox and pending messages. Update the key in your app after replacing it.`),_("Create replacement key",async()=>{let f=await b(n+"/mcp-keys",{method:"POST",body:{name:l.name,replaceDeviceId:l.id}});h(),tt("Replacement MCP key",f.token,`Update your app\u2019s secret/API key field. Shown once; expires ${B(f.expiresAt)}. If this value is lost, replace it again from Members & devices.`)},"primary"))))),!c&&(r||l.userId===d.user.id)&&u.push(_("Revoke",()=>te("Revoke connection?",h=>a("div",{},a("p",{},`${l.name} will stop receiving access to this workspace.`),_("Revoke connection",async()=>{await b(n+`/devices/${encodeURIComponent(l.id)}`,{method:"DELETE"}),h(),await C()},"danger"))),"danger")),i.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.name),a("p",{class:"help"},`${l.kind==="mcp"?"MCP app":l.kind==="mcp_key"?"MCP key":"Device"} \xB7 ${c?"Revoked":`Expires ${B(l.expiresAt)}`}`)),a("div",{class:"actions"},u)))}let o=a("div",{},s,i);if(r){let l=N("Teammate\u2019s email",{name:"email",type:"email",required:!0}),c=F([l.node],"Create invitation",async f=>{let g=await b(D("/invites"),{method:"POST",body:{email:f.get("email"),role:"member"}});tt("Share this invitation",`${location.origin}/app#invite=${encodeURIComponent(g.token)}`,`Share this link with ${g.email}. It expires ${B(g.expiresAt)} and can be accepted once by that address. October has not sent an email.`)}),u=await b(D("/invites")),h=a("section",{class:"card"},a("h2",{},"Invite a teammate"),c);for(let f of u)h.append(a("div",{class:"row"},a("div",{},a("strong",{},f.email),a("p",{class:"help"},`Expires ${B(f.expiresAt)}`)),_("Revoke invitation",async()=>{await b(D(`/invites/${encodeURIComponent(f.id)}`),{method:"DELETE"}),await C()},"danger")));o.append(h)}return o}async function Qr(){if(d.config=await b("/api/config"),!d.config.authUrl||!d.config.authPublicKey)throw new Error("Sign-in is not configured on this server. Contact its operator.");d.auth=new Rt({url:d.config.authUrl+"/auth/v1",headers:{apikey:d.config.authPublicKey,Authorization:`Bearer ${d.config.authPublicKey}`},storageKey:"agentintercom-auth",flowType:"pkce",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0});let{data:n,error:e}=await d.auth.getSession();if(e)throw e;n.session?await Y():At(),d.auth.onAuthStateChange((t,r)=>{t==="SIGNED_OUT"&&setTimeout(()=>{d.generation++,At()},0),t==="SIGNED_IN"&&r&&!d.user&&setTimeout(()=>Re(null,Y),0)})}Qr().catch(n=>{le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("section",{class:"card consent"},a("h1",{},"Couldn\u2019t open your workspace"),a("p",{},n.message),_("Try again",()=>location.reload()))))});async function Zr(){let n=d.generation,e=D(""),[t,r]=await Promise.all([b(e+"/sessions"),b(e+"/members")]),s=t.sessions,i=new Map(s.map(S=>["agent:"+S.id,S.displayName]));for(let S of r)i.set("human:"+S.userId,S.email);let o=(S,m)=>i.get(S+":"+m)||m,l=new URLSearchParams;d.conversationAgent&&l.set("agentId",d.conversationAgent),d.search&&l.set("query",d.search);let c=a("select",{"aria-label":"Filter by session",onchange:S=>{d.conversationAgent=S.target.value,Re(null,C)}},a("option",{value:""},"All sessions"),s.map(S=>a("option",{value:S.id,selected:S.id===d.conversationAgent},S.displayName))),u=N("Search messages",{name:"query",value:d.search,type:"search",maxlength:256}),h=F([u.node],"Search",async S=>{d.search=S.get("query").trim(),await C()}),f=a("div",{},a("div",{class:"card grid"},a("label",{},"Conversation",c),h)),g=a("div",{class:"conversation-list","aria-label":"Workspace messages"}),p=new Map,k=!0,E=!1;Ze.push(()=>{k=!1});let A=S=>S.responseMessageId?"Replied":S.state==="acknowledged"?S.toKind==="human"?"Read":"Acknowledged":S.state==="delivered"?"Delivered to app":S.state==="expired"?"Expired":"Waiting for delivery",O=(S,m=!1)=>{let I=m?[...S.messages].reverse():S.messages;for(let T of I){let x=JSON.stringify(T),q=p.get(T.id);if(q?.fingerprint===x)continue;let G=a("article",{class:"card",id:T.id},a("div",{class:"row"},a("div",{class:"details"},a("strong",{},o(T.fromKind,T.from))," \u2192 ",o(T.toKind,T.to),a("p",{class:"help"},B(T.createdAt))),a("span",{class:"badge"},A(T))),a("p",{class:"message"},T.body));G.append(Sr(e,T.body,T.context)),T.responseTo&&G.append(a("p",{class:"help"},"Reply to ",a("code",{},T.responseTo))),T.toKind==="human"&&T.to===d.user.id&&T.state!=="acknowledged"&&T.state!=="expired"&&G.append(_("Mark read",async()=>{await b(e+"/messages/read",{method:"POST",body:{messageIds:[T.id]}}),await C()},"subtle-button")),q?q.node.replaceWith(G):m?g.prepend(G):g.append(G),p.set(T.id,{fingerprint:x,node:G})}},R=await b(e+"/messages?"+l);O(R);let v=l.toString(),P=setInterval(async()=>{if(d.generation!==n){clearInterval(P);return}if(!(!k||E||document.hidden)){E=!0;try{let S=await b(e+"/messages?"+v);k&&(S.messages.length&&g.querySelector(".empty")?.remove(),O(S,!0))}catch(S){k&&H("Conversation refresh failed. "+S.message,!0)}finally{E=!1}}},5e3);if(Ze.push(()=>clearInterval(P)),R.messages.length||g.append(a("section",{class:"card empty"},a("h2",{},d.search?"No matching messages":"Start a conversation"),a("p",{class:"muted"},d.search?"Try a different phrase or session.":"Choose a connected session below and send it a request."))),f.append(g),R.nextCursor){let S=R.nextCursor,m=_("Earlier messages",async()=>{l.set("before",S);let I=await b(e+"/messages?"+l);O(I),S=I.nextCursor,S||m.remove()});f.append(m)}if(s.length){let S=a("select",{name:"to",required:!0},s.map(q=>a("option",{value:q.id,selected:q.id===d.conversationAgent},q.displayName+(q.reachable?"":" \xB7 offline")))),m=N("Your message",{name:"body",multiline:!0,required:!0,maxlength:65536,placeholder:"What would you like this session to help with?"}),I=crypto.randomUUID(),T="",x=F([a("label",{},"Send to",S),m.node,kr(e,m.input),a("p",{class:"help"},"Visible to workspace members. An MCP app may need you to resume it or ask it to check its inbox.")],"Send request",async q=>{let G=JSON.stringify([q.get("to"),q.get("body")]);T&&T!==G&&(I=crypto.randomUUID()),T=G,await b(e+"/messages",{method:"POST",body:{to:q.get("to"),body:q.get("body"),mode:"request",idempotencyKey:I}}),d.conversationAgent=q.get("to"),d.search="",H("Request saved. Delivery status will update when the app checks its inbox."),await C()});f.append(a("section",{class:"card"},a("h2",{},"Send a message"),x))}else f.append(_("Connect an app",async()=>{d.tab="connect",await C()},"primary"));return f.append(_("Refresh conversation",C)),f}async function es(){let n=D(""),e=await b(n+"/tasks"),t=a("div"),r=a("div",{class:"grid"}),s=l=>{for(let c of l.tasks)r.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},c.title),a("span",{class:"badge"},c.status)),a("p",{class:"message"},c.description),c.claimedBy?a("p",{class:"help"},"Claimed by ",a("code",{},c.claimedBy)):a("p",{class:"help"},c.ready?"Ready for an agent to claim.":"Waiting for dependencies."),c.note?a("p",{},c.note):null,(c.recentProgress||[]).map(u=>a("p",{class:"help message"},`${u.kind}: ${u.text}`)),a("small",{},B(c.updatedAt))))};if(s(e),e.tasks.length||r.append(a("section",{class:"card empty"},a("h2",{},"Give the work a place to land."),a("p",{},"Create a task, then ask a connected session to claim it. Claims prevent two agents from taking the same work."))),t.append(r),e.nextCursor){let l=e.nextCursor,c=_("More tasks",async()=>{let u=await b(n+"/tasks?after="+encodeURIComponent(l));s(u),l=u.nextCursor,l||c.remove()});t.append(c)}let i=N("Task title",{name:"title",maxlength:256,required:!0}),o=N("Description",{name:"description",multiline:!0,maxlength:16384});return t.append(a("section",{class:"card"},a("h2",{},"New task"),F([i.node,o.node],"Create task",async l=>{await b(n+"/tasks",{method:"POST",body:{title:l.get("title"),description:l.get("description")}}),H("Task created. An agent can now claim it."),await C()}))),t}async function ts(){let n=D(""),e=await b(n+"/questions"),t=a("div"),r=s=>{for(let i of s.escalations){let o=N("Your answer",{name:"answer",multiline:!0,required:!0,maxlength:16384}),l=(i.options||[]).map(c=>_(c,()=>{o.input.value=c,o.input.focus()}));t.append(a("section",{class:"card"},a("h2",{class:"message"},i.question),a("p",{class:"help"},"From ",a("code",{},i.agentId)," \xB7 ",B(i.createdAt)),a("div",{class:"actions"},l),F([o.node],"Send answer",async c=>{await b(n+`/questions/${encodeURIComponent(i.id)}/answer`,{method:"POST",body:{answer:c.get("answer")}}),H("Answer saved for the requesting session."),await C()})))}};if(r(e),e.escalations.length||t.append(a("section",{class:"card empty"},a("h2",{},"Nothing waiting on you."),a("p",{class:"muted"},"When an agent asks for a decision, you can answer it here."))),e.nextCursor){let s=e.nextCursor,i=_("More questions",async()=>{let o=await b(n+"/questions?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});t.append(i)}return t.append(_("Refresh questions",C)),t}async function rs(){let n=d.generation,e=D(""),t=await b(e+"/channels"),r=t.find(m=>m.id===d.channelId)||t[0];r?.id!==d.channelId&&(d.threadId=""),d.channelId=r?.id||"";let s=()=>te("Create a channel",m=>F([N("Channel name",{name:"name",required:!0,maxlength:64,pattern:"[a-z0-9][a-z0-9_-]*",placeholder:"project-updates"}).node,N("Description",{name:"description",maxlength:2e3}).node,a("p",{class:"help"},"All workspace members and connected sessions can read this channel.")],"Create channel",async I=>{let T=await b(e+"/channels",{method:"POST",body:{name:I.get("name"),description:I.get("description")}});d.channelId=T.id,d.threadId="",d.channelSearch="",m(),await C()}));if(!r)return a("section",{class:"card empty"},a("h2",{},"Give a discussion its own space."),a("p",{},"Create a channel for a project or topic. Sessions can subscribe to receive new posts in their inbox."),_("Create a channel",s,"primary"));let i=a("select",{"aria-label":"Channel",onchange:m=>{d.channelId=m.target.value,d.threadId="",d.channelSearch="",Re(null,C)}},t.map(m=>a("option",{value:m.id,selected:m.id===r.id},"#"+m.name))),o=F([N("Search channel",{name:"query",type:"search",value:d.channelSearch,maxlength:256}).node],"Search posts",async m=>{d.channelSearch=m.get("query").trim(),d.threadId="",await C()}),l=a("div",{},a("section",{class:"card"},a("div",{class:"actions"},a("label",{},"Channel",i),_("New channel",s)),a("p",{},r.description),a("p",{class:"help"},`${r.subscribers} subscribed sessions. Ask a connected session to join #${r.name} using subscribe_channel to receive future notifications.`),o));d.threadId&&l.append(a("div",{class:"actions"},a("h2",{},"Thread"),_("Back to channel",async()=>{d.threadId="",await C()})));let c=new URLSearchParams({channelId:r.id});d.threadId&&c.set("threadId",d.threadId),d.channelSearch&&c.set("query",d.channelSearch);let[u,h,f]=await Promise.all([b(e+"/channel-posts?"+c),b(e+"/members"),b(e+"/sessions")]),g=new Map(h.map(m=>["human:"+m.userId,m.email]));for(let m of f.sessions)g.set("agent:"+m.id,m.displayName);let p=a("div",{class:"conversation-list","aria-label":"Channel posts"}),k=new Map,E=(m,I=!1)=>{let T=I?[...m.posts].reverse():m.posts;for(let x of T){let q=JSON.stringify(x),G=k.get(x.id);if(G?.fingerprint===q)continue;let ve=a("article",{class:"card"},a("div",{class:"row"},a("strong",{},g.get(x.authorKind+":"+x.authorId)||x.authorId),a("small",{},B(x.createdAt))),a("p",{class:"message"},x.body));ve.append(Sr(e,x.body)),(!d.threadId||d.channelSearch)&&ve.append(_(x.replies?`${x.replies} ${x.replies===1?"reply":"replies"}`:"Open thread",async()=>{d.threadId=x.threadId||x.id,d.channelSearch="",await C()})),G?G.node.replaceWith(ve):I?p.prepend(ve):p.append(ve),k.set(x.id,{fingerprint:q,node:ve})}};if(E(u),u.posts.length||p.append(a("section",{class:"card empty"},a("p",{},d.channelSearch?"No matching posts.":"No posts yet. Start the discussion below."))),l.append(p),u.nextCursor){let m=u.nextCursor,I=_("Earlier posts",async()=>{let T=new URLSearchParams(c);T.set("before",m);let x=await b(e+"/channel-posts?"+T);E(x),m=x.nextCursor,m||I.remove()});l.append(I)}let A=N(d.threadId?"Your reply":"Your post",{name:"body",multiline:!0,required:!0,maxlength:65536}),O=crypto.randomUUID(),R="";l.append(a("section",{class:"card"},F([A.node,kr(e,A.input),a("p",{class:"help"},"Shared with the workspace. Subscribed sessions receive an inbox notification; delivery does not mean a model has acted.")],d.threadId?"Reply in thread":"Post to channel",async m=>{let I=m.get("body");R&&R!==I&&(O=crypto.randomUUID()),R=I,await b(e+"/channel-posts",{method:"POST",body:{channelId:r.id,body:I,threadId:d.threadId||void 0,idempotencyKey:O}}),d.channelSearch="",await C()})));let v=!0,P=!1,S=setInterval(async()=>{if(d.generation!==n){clearInterval(S);return}if(!(!v||P||document.hidden)){P=!0;try{let m=await b(e+"/channel-posts?"+c);v&&(m.posts.length&&p.querySelector(".empty")?.remove(),E(m,!0))}catch(m){v&&H("Channel refresh failed. "+m.message,!0)}finally{P=!1}}},5e3);return Ze.push(()=>{v=!1,clearInterval(S)}),l}async function ss(){let n=D("/billing"),e=await b(n),t=e.paidUntil&&Date.parse(e.paidUntil)>Date.now(),r=!t&&Date.parse(e.trialEndsAt)>Date.now(),s=f=>new Intl.NumberFormat(void 0,{style:"currency",currency:e.currency.toUpperCase(),maximumFractionDigits:0}).format(f/100),i=f=>f>=1024**3?`${(f/1024**3).toFixed(1)} GiB`:`${(f/1024**2).toFixed(1)} MiB`,o=f=>Number(f).toLocaleString(),l=a("div");e.configured&&!e.live&&l.append(a("p",{class:"notice-inline",role:"status"},"Test billing \u2014 this service is not accepting real payments.")),_e.has("billing")&&l.append(a("p",{class:"notice-inline"},"Returned from billing. Check payment status below; returning from checkout does not confirm a payment.")),l.append(a("section",{class:"card"},a("h2",{},t?"Paid workspace":r?"Workspace trial":"Hosting inactive"),a("p",{},t?`Hosting paid through ${B(e.paidUntil)}.`:r?`Trial ends ${B(e.trialEndsAt)}.`:"New work is paused. Existing history remains available."),e.cancelAtPeriodEnd?a("p",{},`Your subscription will end on ${B(e.currentPeriodEnd)}. It will not renew.`):null,["past_due","unpaid","incomplete"].includes(e.status)?a("p",{class:"notice-inline"},"Your subscription needs payment attention. Open payment settings to review it."):null));let c=a("div",{class:"actions"});async function u(f,g){let p=await b(n+"/"+f,{method:"POST",body:g,timeout:3e4}),k=new URL(p.url);if(k.protocol!=="https:"||k.username||k.password||!["checkout.stripe.com","billing.stripe.com"].includes(k.host))throw new Error("Payment destination could not be verified.");location.assign(k.href)}e.canManage&&e.configured&&(["none","canceled","incomplete_expired"].includes(e.status)?c.append(_(`${s(e.monthlyPriceCents)} / month`,()=>u("checkout",{interval:"month"}),"primary"),_(`${s(e.annualPriceCents)} / year`,()=>u("checkout",{interval:"year"}))):c.append(_("Payment settings & cancellation",()=>u("portal"),"primary")),c.append(_("Check payment status",async()=>{await b(n+"/refresh",{method:"POST",timeout:3e4}),await C(),H("Payment status checked.")})),e.pendingCheckout&&c.append(_("Close unfinished checkout",async()=>{await b(n+"/cancel-checkout",{method:"POST",timeout:3e4}),await C()}))),l.append(a("section",{class:"card"},a("h2",{},`${s(e.monthlyPriceCents)} per workspace per month`),a("p",{},`Or ${s(e.annualPriceCents)} per year, billed annually. Applicable tax is shown at checkout. Includes 5 people, 50 concurrent sessions, 100,000 new deliveries per calendar month and 5 GiB of files.`),a("p",{class:"help"},"Includes 25 GiB of uploads and 25 GiB of downloads per calendar month. Each file can be up to 16 MiB. Model and compute costs are separate. No automatic usage overage charges."),e.pendingCheckout?a("p",{class:"notice-inline"},`An unfinished ${e.pendingInterval==="year"?"annual":"monthly"} checkout is saved. Choosing the same plan resumes it; choosing the other plan closes it before starting another.`):null,e.configured?e.canManage?c:a("p",{},"Only a workspace owner can manage payments."):a("p",{},"Paid hosting is not available on this service yet.")));let h=a("section",{class:"card"},a("h2",{},"Included usage"),a("p",{class:"help"},t?`Delivery and file-transfer counters reset each calendar month (UTC). Current month: ${e.month}.`:"The trial includes 2,000 new deliveries in total, 256 MiB of files and 1 GiB in each transfer direction per calendar month."));for(let[f,g,p,k]of[["New deliveries",e.deliveries,e.deliveryLimit,o],["People",e.members,e.memberLimit,o],["Concurrent sessions",e.sessions,e.sessionLimit,o],["Retained coordination data",e.retainedBytes||0,e.textLimit||5*1024**3,i],["File storage",e.fileBytes,e.fileStorageLimit,i],["Uploads this month",e.uploadedBytes,e.fileTransferLimit,i],["Downloads this month",e.downloadedBytes,e.fileTransferLimit,i]])h.append(a("div",{class:"usage"},a("div",{class:"row"},a("span",{},f),a("span",{},`${k(g)} / ${k(p)}`)),a("progress",{max:p,value:Math.min(g,p),"aria-label":f})));return h.append(a("p",{class:"help"},"A new message counts once per recipient. Channel notifications count per subscriber. Retries, acknowledgements and replies do not consume delivery allowance.")),l.append(h),l}async function ns(){let n=D(""),e=d.workspace,t=await b(n+"/storage"),r=d.workspace.role==="owner",s=a("div",{},a("section",{class:"card"},a("h2",{},"Retention"),a("p",{},"Completed conversations, completed tasks, resolved questions and quiet channel threads are eligible for removal after 90 days. Unfinished work and linked records that still need each other remain. Files stay until you delete them."),a("p",{class:"help"},"The notification log keeps roughly the latest 100,000 events or 90 days, whichever is shorter. This does not delete the corresponding messages or tasks. New work pauses when estimated retained coordination data reaches 5 GiB; final replies and acknowledgements remain available.")));if(!r)return s.append(a("p",{},"A workspace owner can pause sessions, export data and prune completed history.")),s;e.deleting?s.append(a("section",{class:"card"},a("h2",{},"Deletion in progress"),a("p",{},"Sessions and purchases are stopped. Billing must be closed before the remaining data can be deleted. The service retries automatically; you can also retry below."))):s.append(a("section",{class:"card"},a("h2",{},d.workspace.paused?"Sessions paused":"Pause sessions for an export"),a("p",{},"Pausing disconnects all sessions and prevents new connections while you export. Members can still read history here. Resume and reconnect your apps when finished. Pausing does not cancel billing."),_(d.workspace.paused?"Resume sessions":"Pause sessions",()=>te(d.workspace.paused?"Resume this workspace?":"Disconnect workspace sessions?",o=>a("div",{},a("p",{},d.workspace.paused?"Connected apps can rejoin when hosting is active.":"Every connected session will lose its current connection. Queued work and history are retained."),_("Confirm",async()=>{await b(n+"/pause",{method:"POST",body:{paused:!d.workspace.paused}}),o(),await Y()},"primary")))))),s.append(a("section",{class:"card"},a("h2",{},"Download a portable archive"),a("p",{},"Includes retained messages, tasks, questions, channels, output values and file bytes. Does not contain account credentials or payment details. Pause sessions first so the archive is consistent."),a("p",{class:"help"},"Portable archives are limited to 64 MiB, including encoded files. Larger workspaces need an operator-assisted database and file export. File bytes in an archive count toward download allowance. Store the download privately."),_("Download workspace archive",async()=>{let l=await(await Ct(n+"/export")).blob(),c=URL.createObjectURL(l),u=a("a",{href:c,download:"agentintercom-workspace.json"});document.body.append(u),u.click(),u.remove(),setTimeout(()=>URL.revokeObjectURL(c),3e4)})));let i=N("Remove eligible history completed before",{name:"before",type:"date",required:!0,value:new Date(Date.now()-90*864e5).toISOString().slice(0,10),max:new Date(Date.now()-2*864e5).toISOString().slice(0,10)});return s.append(a("section",{class:"card"},a("h2",{},"Prune completed history"),a("p",{},"Review a preview before deleting anything. Export first if you need to retain a copy. This does not remove unfinished work, files or your subscription."),F([i.node],"Preview cleanup",async o=>{let l=new Date(o.get("before")+"T00:00:00Z").toISOString(),c=await b(n+"/prune",{method:"POST",body:{before:l,execute:!1},timeout:3e4});te("Delete eligible history?",u=>a("div",{},a("p",{},"This permanently deletes eligible records before the selected date. Counts may change if work finishes before confirmation."),a("pre",{},JSON.stringify(c.records,null,2)),_("Delete eligible history",async()=>{await b(n+"/prune",{method:"POST",body:{before:l,execute:!0},timeout:3e4}),u(),await C(),H("Completed history pruned.")},"danger")))}))),s.append(a("section",{class:"card"},a("h2",{},"Retained records"),a("p",{class:"help"},"Payload estimates below exclude database indexes and some record overhead; billing usage includes a per-record estimate."),(t.records||[]).map(o=>a("div",{class:"row"},a("span",{},`${o.recordType} \xB7 ${o.state}`),a("span",{},Number(o.count).toLocaleString()))))),s.append(a("section",{class:"card"},a("h2",{},"Delete workspace"),a("p",{},"Permanently removes this workspace for everyone, including messages, unfinished work, files and connections. Its hosting subscription ends immediately; unused time is not automatically refunded. Export first if you need a copy."),a("p",{class:"help"},"Your October account and other workspaces remain. Minimal payment references are retained for support. Private backups expire on the operator\u2019s retention schedule."),_(e.deleting?"Retry workspace deletion":"Delete workspace",()=>te("Permanently delete this workspace?",o=>{let l=N("Type the workspace name to confirm",{name:"confirmation",required:!0,autocomplete:"off"});return a("div",{},a("p",{},`This cannot be undone. Enter ${e.name} to confirm. Once requested, deletion continues even if this page closes.`),F([l.node],"Delete permanently",async c=>{if(c.get("confirmation")!==e.name)throw new Error("The workspace name does not match.");try{await b(n,{method:"DELETE",body:{confirmName:c.get("confirmation")},timeout:3e4})}catch(u){throw o(),await Y(),u}o(),await Y(),H("Workspace deleted.")}))}),"danger"))),s} +`:""}${o.name}: ${o.uri}`,t.input.value="",H("File attached. Send your message to share the reference.")}finally{i&&(i.disabled=!1)}});return a("details",{},a("summary",{},"Attach a file"),t.node,r,a("p",{class:"help"},"Up to 16 MiB. Uploaded files are visible to everyone in this workspace."))}function Sr(n,e,t=[]){let r=new Map;for(let s of String(e).matchAll(/october-bus:\/\/attachments\/(att_[0-9a-f]{32})(?![0-9a-f])/g))r.set(s[1],"");for(let s of t||[]){let i=s.uri?.match(/^october-bus:\/\/attachments\/(att_[0-9a-f]{32})$/)?.[1];i&&r.set(i,s.title)}return a("div",{class:"actions"},[...r].map(([s,i])=>_(i?`Download ${i}`:"Download shared file",()=>br(n,s,i))))}async function zr(){let n=D(""),e=a("div"),t=a("div",{class:"grid"}),r=o=>{for(let l of o.attachments){let u=l.authorKind==="human"&&l.authorId===d.user.id||["owner","admin"].includes(d.workspace.role)?_("Delete file",()=>te("Delete this file?",h=>a("div",{},a("p",{},`Delete ${l.name}? Existing message references will stop working.`),_("Delete permanently",async()=>{await b(n+"/attachments/"+l.id,{method:"DELETE"}),h(),await C()})))):null;t.append(a("article",{class:"card"},a("h2",{},l.name),a("p",{class:"help"},`${(l.size/1024).toFixed(1)} KiB \xB7 ${l.mediaType} \xB7 ${B(l.createdAt)}`),a("div",{class:"actions"},_("Download",()=>br(n,l.id,l.name)),_("Copy reference",()=>rt(l.uri)),u)))}},s=await b(n+"/attachments");r(s),s.attachments.length||t.append(a("section",{class:"card empty"},a("h2",{},"Share the files your work needs."),a("p",{},"Upload a file here or attach one to a conversation. Files stay private to this workspace.")));let i=N("File to upload",{type:"file",required:!0});if(e.append(a("section",{class:"card"},F([i.node,a("p",{class:"help"},"Up to 16 MiB per file. Everyone in the workspace can download it.")],"Upload file",async()=>{let o=i.input.files[0];if(!o)throw new Error("Choose a file first.");await vr(n,o),await C()})),t),s.nextCursor){let o=s.nextCursor,l=_("More files",async()=>{let c=await b(n+"/attachments?after="+encodeURIComponent(o));r(c),o=c.nextCursor,o||l.remove()});e.append(l)}return e}function et(n){delete $[n],sessionStorage.setItem(xt,JSON.stringify({...$,until:Date.now()+1200*1e3})),history.replaceState(null,"","/app")}var Jr=0;function te(n,e){let t=`modal-title-${++Jr}`,r=document.activeElement,s=a("dialog",{"aria-labelledby":t},a("h2",{id:t},n)),i=()=>s.close();return s.append(e(i),a("div",{class:"actions end"},_("Close",i))),s.addEventListener("close",()=>{s.remove(),r?.isConnected&&r.focus()}),document.body.append(s),s.showModal(),s}function tt(n,e,t){te(n,()=>a("div",{},a("p",{},t),a("pre",{class:"secret"},e),_("Copy",()=>rt(e))))}function At(){mr(),d.user=null;let n=N("Email address",{type:"email",name:"email",autocomplete:"email",required:!0}),e=F([n.node],"Continue with email",async i=>{let{error:o}=await d.auth.signInWithOtp({email:i.get("email"),options:{emailRedirectTo:location.origin+"/app"+($.authorization?"?authorization_id="+encodeURIComponent($.authorization):$.device?"?device_code="+encodeURIComponent($.device):""),shouldCreateUser:!0}});if(o)throw o;H("Check your email for an October sign-in link. Open it in this browser."),e.append(a("p",{class:"notice-inline"},"Check your email for a sign-in link. Keep this tab open so you can return to your connection request."))}),t=N("Email address",{name:"email",type:"email",autocomplete:"username",required:!0}),r=N("Password",{name:"password",type:"password",autocomplete:"current-password",required:!0}),s=F([t.node,r.node],"Sign in",async i=>{let{error:o}=await d.auth.signInWithPassword({email:i.get("email"),password:i.get("password")});if(o)throw o;await Y()});le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("div",{class:"auth-layout"},a("div",{class:"auth-copy"},a("div",{class:"eyebrow"},"One place to work together"),a("h1",{},`Your agents. +A shared conversation.`),a("p",{},"Connect your AI apps, bring in another machine, and keep the work moving with your team.")),a("section",{class:"card auth-card","aria-labelledby":"signin-title"},a("h2",{id:"signin-title"},"Sign in to October"),a("p",{class:"help"},"Use your existing October account, or create one with your email."),e,a("details",{},a("summary",{},"Use an existing password"),s),a("p",{class:"help"},"Your AI subscriptions stay with your apps. Agent Intercom connects the work.")))))}async function Y(){d.user=await b("/api/me"),d.workspaces=await b("/api/workspaces");let n=_e.has("billing")&&_e.get("workspace")||localStorage.getItem("agentintercom-workspace");if(d.workspace=d.workspaces.find(e=>e.id===n)||d.workspaces[0]||null,$.invite)return Hr();if($.authorization)return It();if($.device)return Tt();if(!d.workspace)return Rr();await C()}function st(n){let e=N("Workspace name",{name:"name",placeholder:"My team",maxlength:100,required:!0});return F([e.node,a("p",{class:"help"},"Your first workspace starts a 14-day trial. Additional workspaces share its end date. Up to 5 people; no payment details needed.")],"Create workspace",async t=>{let r=await b("/api/workspaces",{method:"POST",body:{name:t.get("name")}});d.workspaces.push(r),d.workspace=r,localStorage.setItem("agentintercom-workspace",r.id),await n()})}function Rr(){le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("section",{class:"card consent"},a("h1",{},"Make room for your team."),a("p",{},"A workspace holds your connected sessions, messages and shared work."),st(C),_("Sign out",Ot))))}async function Ot(){let{error:n}=await d.auth.signOut({scope:"local"});if(n)throw n;d.generation++,At()}function Pt(n){return a("select",{"aria-label":"Workspace",onchange:t=>{d.workspace=d.workspaces.find(r=>r.id===t.target.value),localStorage.setItem("agentintercom-workspace",d.workspace.id),Re(null,n)}},d.workspaces.map(t=>a("option",{value:t.id,selected:t.id===d.workspace?.id},t.name)))}async function It(){let n=await b(`/api/oauth/requests/${encodeURIComponent($.authorization)}`),e=d.workspace?.id,r=(e?await b(D("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="mcp"),s=a("select",{"aria-label":"App connection"},a("option",{value:""},"Create a new app connection"),r.map(c=>a("option",{value:c.id},`Reconnect ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"The old app credentials will stop working. This app will receive the same session inbox, including its pending messages.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");let u=await b(`/api/oauth/requests/${encodeURIComponent($.authorization)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}});et("authorization"),location.assign(u.redirectUrl)},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Pt(It)),r.length?a("label",{},"App connection",s):null,i,a("div",{class:"actions"},_("Allow connection",()=>o(!0),"primary"),_("Cancel",()=>o(!1)))):st(It);le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect an app"),a("h1",{},n.clientName),a("p",{},"wants to connect to your Agent Intercom workspace."),a("p",{class:"help"},"This app registered itself. October has not verified its publisher. Only continue if you started this connection in an app you trust."),a("ul",{class:"permission-list"},a("li",{},"Read and share messages, files and channels in the selected workspace."),a("li",{},"Discover connected sessions and coordinate shared tasks."),a("li",{},"Remain connected until you revoke access or the connection expires.")),a("p",{class:"help"},"You can revoke access at any time in Members & devices."),a("p",{class:"help"},"Returns to: ",a("code",{},new URL(n.redirectUri).origin)),l)))}async function Tt(){let n=await b(`/api/device/authorizations/${encodeURIComponent($.device)}`),e=d.workspace?.id,r=(e?await b(D("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="device"),s=a("select",{"aria-label":"Device connection"},a("option",{value:""},"Connect a new machine"),r.map(c=>a("option",{value:c.id},`Replace ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"Replacing a connection signs out its existing sessions. Their inboxes stay available. Resume each session using its existing session ID after this login completes.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");await b(`/api/device/authorizations/${encodeURIComponent($.device)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}}),et("device"),le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("h1",{},c?"Your device can connect.":"Connection declined."),a("p",{},c?"Return to your terminal to finish. Each session on this device will appear in your workspace.":"No device credential was issued."),_("Open workspace",Y,"primary"))))},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Pt(Tt)),r.length?a("label",{},"Device connection",s):null,i,a("div",{class:"actions"},_("Connect this device",()=>o(!0),"primary"),_("Decline",()=>o(!1)))):st(Tt);le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect a machine"),a("h1",{},n.name),a("p",{},"Check that this code matches the one in your terminal:"),a("pre",{},n.userCode),a("p",{class:"help"},"Only approve a request you started. This device can read and send workspace messages and start its own agent sessions. You can revoke it in Members & devices."),l)))}function Hr(){le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("h1",{},"Join a workspace"),a("p",{},`You are signed in as ${d.user.email}. The invitation must match this address.`),a("div",{class:"actions"},_("Accept invitation",async()=>{let n=await b("/api/invites/accept",{method:"POST",body:{token:$.invite}});localStorage.setItem("agentintercom-workspace",n.workspaceId),et("invite"),await Y()},"primary"),_("Use another account",Ot),_("Cancel",async()=>{et("invite"),await Y()})))))}var Qe={sessions:["Sessions","Choose the connected session you want to work with."],messages:["Conversations","Messages and receipts shared with this workspace."],channels:["Channels","Shared discussions and threads for this workspace."],tasks:["Tasks","Shared work, claimed by the session doing it."],questions:["Needs you","Help your agents continue when they need a decision."],files:["Files","Private files shared with your workspace."],connect:["Connect an app","Use your favorite AI app, on this machine or another one."],members:["Members & devices","Give each person and machine their own access."],data:["Data & recovery","Export your workspace and manage retained history."],billing:["Billing & usage","Your workspace plan, payment details and included usage."]};async function C(){if(mr(),!d.workspace)return Rr();let n=++d.generation,e=a("main",{id:"main",class:"content"}),t=a("nav",{"aria-label":"Workspace"},Object.entries(Qe).map(([s,[i]])=>_(i,async()=>{d.tab=s,await C()},s===d.tab?"selected":"")));[...t.children].forEach((s,i)=>{Object.keys(Qe)[i]===d.tab&&s.setAttribute("aria-current","page")}),le.replaceChildren(a("div",{class:"shell"},a("aside",{class:"sidebar"},ce(),a("div",{class:"workspace-switch"},Pt(C),_("+ New workspace",()=>te("New workspace",s=>st(async()=>{s(),await C()})),"subtle-button")),t,a("div",{class:"account"},a("p",{},d.user.email),_("Sign out",Ot,"subtle-button"))),e)),e.append(a("header",{class:"topline"},a("div",{},a("div",{class:"eyebrow"},d.workspace.name),a("h1",{},Qe[d.tab][0]),a("p",{class:"muted"},Qe[d.tab][1])),d.tab==="sessions"?_("Connect an app",async()=>{d.tab="connect",await C()},"primary"):null));let r=a("p",{class:"progress"},"Loading\u2026");e.append(r);try{let s=await{data:is,billing:ns,files:zr,channels:ss,messages:es,tasks:ts,questions:rs,sessions:Yr,connect:Xr,members:Qr}[d.tab]();if(n!==d.generation)return;r.replaceWith(s)}catch(s){n===d.generation&&r.replaceWith(a("div",{class:"card"},a("p",{},s.message),_("Try again",C)))}}async function Yr(){let n=a("div"),e=a("div",{class:"grid"}),t=await b(D("/sessions")),r=s=>{for(let i of s.sessions){let o=i.reachable===!0;e.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},i.displayName||i.agentId||i.id),a("span",{class:`badge ${o?"live":""}`},o?"Connected":"Offline")),a("p",{class:"help"},i.deviceName),a("p",{class:"help"},i.deliveryMode==="poll"?"Inbox available when this app checks for messages. It may need you to resume the conversation.":"Native listener connected. Your app\u2019s permissions still apply."),a("small",{},`Last seen ${B(i.updatedAt)}`),i.wake?.uncertain?a("p",{class:"notice-inline"},"A wake submission is uncertain. Inspect the app before retrying; the message is still in its inbox."):null,a("div",{class:"actions"},_("Open conversation",async()=>{d.conversationAgent=i.id,d.tab="messages",await C()})))),i.userId===d.user.id&&e.lastChild.append(a("details",{},a("summary",{},"Session details"),a("p",{class:"help"},"This ID identifies the inbox. Terminal sessions can resume it with --id after reconnecting their owning machine."),a("code",{},i.id),_("Copy session ID",()=>rt(i.id))))}};if(!t.sessions.length)return a("section",{class:"card empty"},a("h2",{},"Your first connection starts here."),a("p",{class:"muted"},"Connect an AI app or terminal session. It will appear here under its own name, ready for shared work."),_("Connect an app",async()=>{d.tab="connect",await C()},"primary"));if(r(t),n.append(e),t.nextCursor){let s=t.nextCursor,i=_("Show more sessions",async()=>{let o=await b(D("/sessions")+"?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});n.append(i)}return n.append(a("p",{class:"help"},"Connected means the app contacted Agent Intercom recently. It does not mean the model is currently working."),_("Refresh sessions",C)),n}function Xr(){let n=d.config.mcpUrl,e=D("");return a("div",{class:"grid"},a("section",{class:"card"},a("h2",{},"An app with remote MCP"),a("p",{},"In your app\u2019s connectors or MCP settings, add Agent Intercom using this address."),a("pre",{},n),_("Copy connector URL",()=>rt(n)),a("ol",{},a("li",{},"Add the connector in your app."),a("li",{},"Sign in to October and choose this workspace."),a("li",{},"Ask your app to check its Bus inbox or find connected sessions.")),a("p",{class:"help"},"Works with compatible Streamable HTTP MCP clients. Your app controls which conversations can use tools and whether an idle conversation can resume.")),a("section",{class:"card"},a("h2",{},"An app that asks for an API key"),a("p",{},"Use the same remote MCP URL. Create a separate key for each app so you can revoke it independently."),F([N("App connection name",{name:"name",required:!0,maxlength:100,placeholder:"My AI app"}).node,a("p",{class:"help"},"The app can read and share workspace messages, files, channels and tasks. A key expires after 90 days and cannot manage your account or members.")],"Create MCP key",async t=>{let r=await b(e+"/mcp-keys",{method:"POST",body:{name:t.get("name")}});tt("MCP connection key",r.token,`Paste this into your app\u2019s secret/API key field, or use Authorization: Bearer . It is shown once and expires ${B(r.expiresAt)}. Keep it out of chat, URLs and source control.`)}),a("p",{class:"help"},"Choose OAuth instead if your app offers it. Neither connection method can make an unsupported app resume an idle conversation.")),a("section",{class:"card"},a("h2",{},"Another machine or automation"),a("p",{},"Install the Agent Intercom CLI on that machine, then run:"),a("pre",{},"agentintercom hosted login --server "+location.origin),a("p",{},"Open the link it prints, confirm the code and choose this workspace. For any app with a local MCP connection, run:"),a("pre",{},"agentintercom connect --hosted default"),a("p",{},"Or start a terminal session with native message wake:"),a("pre",{},`agentintercom session start claude --hosted default +agentintercom session start codex --hosted default`),a("p",{class:"help"},"Choose the app you use. Keep its terminal open; normal app permissions apply. Codex native wake is experimental."),a("details",{},a("summary",{},"Create a credential for custom automation"),F([N("Device name",{name:"name",required:!0,maxlength:100,placeholder:"My laptop"}).node],"Create device credential",async t=>{let r=await b(D("/devices"),{method:"POST",body:{name:t.get("name")}});tt("Device credential",r.token,"Save this in your device\u2019s secret store. It is shown only once. Anyone with it can join sessions to this workspace as you.")}),a("p",{class:"help"},"Keep credentials out of chat messages, shell history and source control."))))}async function Qr(){let n=D(""),[e,t]=await Promise.all([b(D("/members")),b(D("/devices"))]),r=d.workspace.role!=="member",s=a("section",{class:"card"},a("h2",{},"People"));for(let l of e){let c=[];if(d.workspace.role==="owner"){let u=a("select",{"aria-label":`Role for ${l.email}`},["member","admin","owner"].map(h=>a("option",{value:h,selected:h===l.role},h)));c.push(u,_("Save role",async()=>{await b(D(`/members/${encodeURIComponent(l.userId)}`),{method:"PATCH",body:{role:u.value}}),await Y()}))}else c.push(a("span",{class:"badge"},l.role));(r||l.userId===d.user.id)&&c.push(_(l.userId===d.user.id?"Leave":"Remove",()=>te("Remove workspace access?",u=>a("div",{},a("p",{},`${l.email} will lose access and their connected sessions will be revoked.`),_("Remove access",async()=>{await b(D(`/members/${encodeURIComponent(l.userId)}`),{method:"DELETE"}),u(),await Y()},"danger"))),"danger")),s.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.email),a("p",{class:"help"},`Joined ${B(l.joinedAt)}`)),a("div",{class:"actions"},c)))}let i=a("section",{class:"card"},a("h2",{},"Apps & devices"));t.length||i.append(a("p",{class:"muted"},"No devices connected yet."));for(let l of t){let c=!!l.revokedAt,u=[];l.kind==="mcp_key"&&l.userId===d.user.id&&u.push(_("Replace key",()=>te("Replace this MCP key?",h=>a("div",{},a("p",{},`The old key for ${l.name} will stop working immediately. The replacement keeps its session inbox and pending messages. Update the key in your app after replacing it.`),_("Create replacement key",async()=>{let f=await b(n+"/mcp-keys",{method:"POST",body:{name:l.name,replaceDeviceId:l.id}});h(),tt("Replacement MCP key",f.token,`Update your app\u2019s secret/API key field. Shown once; expires ${B(f.expiresAt)}. If this value is lost, replace it again from Members & devices.`)},"primary"))))),!c&&(r||l.userId===d.user.id)&&u.push(_("Revoke",()=>te("Revoke connection?",h=>a("div",{},a("p",{},`${l.name} will stop receiving access to this workspace.`),_("Revoke connection",async()=>{await b(n+`/devices/${encodeURIComponent(l.id)}`,{method:"DELETE"}),h(),await C()},"danger"))),"danger")),i.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.name),a("p",{class:"help"},`${l.kind==="mcp"?"MCP app":l.kind==="mcp_key"?"MCP key":"Device"} \xB7 ${c?"Revoked":`Expires ${B(l.expiresAt)}`}`)),a("div",{class:"actions"},u)))}let o=a("div",{},s,i);if(r){let l=N("Teammate\u2019s email",{name:"email",type:"email",required:!0}),c=F([l.node],"Create invitation",async f=>{let g=await b(D("/invites"),{method:"POST",body:{email:f.get("email"),role:"member"}});tt("Share this invitation",`${location.origin}/app#invite=${encodeURIComponent(g.token)}`,`Share this link with ${g.email}. It expires ${B(g.expiresAt)} and can be accepted once by that address. October has not sent an email.`)}),u=await b(D("/invites")),h=a("section",{class:"card"},a("h2",{},"Invite a teammate"),c);for(let f of u)h.append(a("div",{class:"row"},a("div",{},a("strong",{},f.email),a("p",{class:"help"},`Expires ${B(f.expiresAt)}`)),_("Revoke invitation",async()=>{await b(D(`/invites/${encodeURIComponent(f.id)}`),{method:"DELETE"}),await C()},"danger")));o.append(h)}return o}async function Zr(){if(d.config=await b("/api/config"),!d.config.authUrl||!d.config.authPublicKey)throw new Error("Sign-in is not configured on this server. Contact its operator.");d.auth=new Rt({url:d.config.authUrl+"/auth/v1",headers:{apikey:d.config.authPublicKey,Authorization:`Bearer ${d.config.authPublicKey}`},storageKey:"agentintercom-auth",flowType:"pkce",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0});let{data:n,error:e}=await d.auth.getSession();if(e)throw e;n.session?await Y():At(),d.auth.onAuthStateChange((t,r)=>{t==="SIGNED_OUT"&&setTimeout(()=>{d.generation++,At()},0),t==="SIGNED_IN"&&r&&!d.user&&setTimeout(()=>Re(null,Y),0)})}Zr().catch(n=>{le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("section",{class:"card consent"},a("h1",{},"Couldn\u2019t open your workspace"),a("p",{},n.message),_("Try again",()=>location.reload()))))});async function es(){let n=d.generation,e=D(""),[t,r]=await Promise.all([b(e+"/sessions"),b(e+"/members")]),s=t.sessions,i=new Map(s.map(S=>["agent:"+S.id,S.displayName]));for(let S of r)i.set("human:"+S.userId,S.email);let o=(S,m)=>i.get(S+":"+m)||m,l=new URLSearchParams;d.conversationAgent&&l.set("agentId",d.conversationAgent),d.search&&l.set("query",d.search);let c=a("select",{"aria-label":"Filter by session",onchange:S=>{d.conversationAgent=S.target.value,Re(null,C)}},a("option",{value:""},"All sessions"),s.map(S=>a("option",{value:S.id,selected:S.id===d.conversationAgent},S.displayName))),u=N("Search messages",{name:"query",value:d.search,type:"search",maxlength:256}),h=F([u.node],"Search",async S=>{d.search=S.get("query").trim(),await C()}),f=a("div",{},a("div",{class:"card grid"},a("label",{},"Conversation",c),h)),g=a("div",{class:"conversation-list","aria-label":"Workspace messages"}),p=new Map,k=!0,E=!1;Ze.push(()=>{k=!1});let A=S=>S.responseMessageId?"Replied":S.state==="acknowledged"?S.toKind==="human"?"Read":"Acknowledged":S.state==="delivered"?"Delivered to app":S.state==="expired"?"Expired":"Waiting for delivery",O=(S,m=!1)=>{let I=m?[...S.messages].reverse():S.messages;for(let T of I){let x=JSON.stringify(T),q=p.get(T.id);if(q?.fingerprint===x)continue;let G=a("article",{class:"card",id:T.id},a("div",{class:"row"},a("div",{class:"details"},a("strong",{},o(T.fromKind,T.from))," \u2192 ",o(T.toKind,T.to),a("p",{class:"help"},B(T.createdAt))),a("span",{class:"badge"},A(T))),a("p",{class:"message"},T.body));G.append(Sr(e,T.body,T.context)),T.responseTo&&G.append(a("p",{class:"help"},"Reply to ",a("code",{},T.responseTo))),T.toKind==="human"&&T.to===d.user.id&&T.state!=="acknowledged"&&T.state!=="expired"&&G.append(_("Mark read",async()=>{await b(e+"/messages/read",{method:"POST",body:{messageIds:[T.id]}}),await C()},"subtle-button")),q?q.node.replaceWith(G):m?g.prepend(G):g.append(G),p.set(T.id,{fingerprint:x,node:G})}},R=await b(e+"/messages?"+l);O(R);let v=l.toString(),P=setInterval(async()=>{if(d.generation!==n){clearInterval(P);return}if(!(!k||E||document.hidden)){E=!0;try{let S=await b(e+"/messages?"+v);k&&(S.messages.length&&g.querySelector(".empty")?.remove(),O(S,!0))}catch(S){k&&H("Conversation refresh failed. "+S.message,!0)}finally{E=!1}}},5e3);if(Ze.push(()=>clearInterval(P)),R.messages.length||g.append(a("section",{class:"card empty"},a("h2",{},d.search?"No matching messages":"Start a conversation"),a("p",{class:"muted"},d.search?"Try a different phrase or session.":"Choose a connected session below and send it a request."))),f.append(g),R.nextCursor){let S=R.nextCursor,m=_("Earlier messages",async()=>{l.set("before",S);let I=await b(e+"/messages?"+l);O(I),S=I.nextCursor,S||m.remove()});f.append(m)}if(s.length){let S=a("select",{name:"to",required:!0},s.map(q=>a("option",{value:q.id,selected:q.id===d.conversationAgent},q.displayName+(q.reachable?"":" \xB7 offline")))),m=N("Your message",{name:"body",multiline:!0,required:!0,maxlength:65536,placeholder:"What would you like this session to help with?"}),I=crypto.randomUUID(),T="",x=F([a("label",{},"Send to",S),m.node,kr(e,m.input),a("p",{class:"help"},"Visible to workspace members. An MCP app may need you to resume it or ask it to check its inbox.")],"Send request",async q=>{let G=JSON.stringify([q.get("to"),q.get("body")]);T&&T!==G&&(I=crypto.randomUUID()),T=G,await b(e+"/messages",{method:"POST",body:{to:q.get("to"),body:q.get("body"),mode:"request",idempotencyKey:I}}),d.conversationAgent=q.get("to"),d.search="",H("Request saved. Delivery status will update when the app checks its inbox."),await C()});f.append(a("section",{class:"card"},a("h2",{},"Send a message"),x))}else f.append(_("Connect an app",async()=>{d.tab="connect",await C()},"primary"));return f.append(_("Refresh conversation",C)),f}async function ts(){let n=D(""),e=await b(n+"/tasks"),t=a("div"),r=a("div",{class:"grid"}),s=l=>{for(let c of l.tasks)r.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},c.title),a("span",{class:"badge"},c.status)),a("p",{class:"message"},c.description),c.claimedBy?a("p",{class:"help"},"Claimed by ",a("code",{},c.claimedBy)):a("p",{class:"help"},c.ready?"Ready for an agent to claim.":"Waiting for dependencies."),c.note?a("p",{},c.note):null,(c.recentProgress||[]).map(u=>a("p",{class:"help message"},`${u.kind}: ${u.text}`)),a("small",{},B(c.updatedAt))))};if(s(e),e.tasks.length||r.append(a("section",{class:"card empty"},a("h2",{},"Give the work a place to land."),a("p",{},"Create a task, then ask a connected session to claim it. Claims prevent two agents from taking the same work."))),t.append(r),e.nextCursor){let l=e.nextCursor,c=_("More tasks",async()=>{let u=await b(n+"/tasks?after="+encodeURIComponent(l));s(u),l=u.nextCursor,l||c.remove()});t.append(c)}let i=N("Task title",{name:"title",maxlength:256,required:!0}),o=N("Description",{name:"description",multiline:!0,maxlength:16384});return t.append(a("section",{class:"card"},a("h2",{},"New task"),F([i.node,o.node],"Create task",async l=>{await b(n+"/tasks",{method:"POST",body:{title:l.get("title"),description:l.get("description")}}),H("Task created. An agent can now claim it."),await C()}))),t}async function rs(){let n=D(""),e=await b(n+"/questions"),t=a("div"),r=s=>{for(let i of s.escalations){let o=N("Your answer",{name:"answer",multiline:!0,required:!0,maxlength:16384}),l=(i.options||[]).map(c=>_(c,()=>{o.input.value=c,o.input.focus()}));t.append(a("section",{class:"card"},a("h2",{class:"message"},i.question),a("p",{class:"help"},"From ",a("code",{},i.agentId)," \xB7 ",B(i.createdAt)),a("div",{class:"actions"},l),F([o.node],"Send answer",async c=>{await b(n+`/questions/${encodeURIComponent(i.id)}/answer`,{method:"POST",body:{answer:c.get("answer")}}),H("Answer saved for the requesting session."),await C()})))}};if(r(e),e.escalations.length||t.append(a("section",{class:"card empty"},a("h2",{},"Nothing waiting on you."),a("p",{class:"muted"},"When an agent asks for a decision, you can answer it here."))),e.nextCursor){let s=e.nextCursor,i=_("More questions",async()=>{let o=await b(n+"/questions?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});t.append(i)}return t.append(_("Refresh questions",C)),t}async function ss(){let n=d.generation,e=D(""),t=await b(e+"/channels"),r=t.find(m=>m.id===d.channelId)||t[0];r?.id!==d.channelId&&(d.threadId=""),d.channelId=r?.id||"";let s=()=>te("Create a channel",m=>F([N("Channel name",{name:"name",required:!0,maxlength:64,pattern:"[a-z0-9][a-z0-9_-]*",placeholder:"project-updates"}).node,N("Description",{name:"description",maxlength:2e3}).node,a("p",{class:"help"},"All workspace members and connected sessions can read this channel.")],"Create channel",async I=>{let T=await b(e+"/channels",{method:"POST",body:{name:I.get("name"),description:I.get("description")}});d.channelId=T.id,d.threadId="",d.channelSearch="",m(),await C()}));if(!r)return a("section",{class:"card empty"},a("h2",{},"Give a discussion its own space."),a("p",{},"Create a channel for a project or topic. Sessions can subscribe to receive new posts in their inbox."),_("Create a channel",s,"primary"));let i=a("select",{"aria-label":"Channel",onchange:m=>{d.channelId=m.target.value,d.threadId="",d.channelSearch="",Re(null,C)}},t.map(m=>a("option",{value:m.id,selected:m.id===r.id},"#"+m.name))),o=F([N("Search channel",{name:"query",type:"search",value:d.channelSearch,maxlength:256}).node],"Search posts",async m=>{d.channelSearch=m.get("query").trim(),d.threadId="",await C()}),l=a("div",{},a("section",{class:"card"},a("div",{class:"actions"},a("label",{},"Channel",i),_("New channel",s)),a("p",{},r.description),a("p",{class:"help"},`${r.subscribers} subscribed sessions. Ask a connected session to join #${r.name} using subscribe_channel to receive future notifications.`),o));d.threadId&&l.append(a("div",{class:"actions"},a("h2",{},"Thread"),_("Back to channel",async()=>{d.threadId="",await C()})));let c=new URLSearchParams({channelId:r.id});d.threadId&&c.set("threadId",d.threadId),d.channelSearch&&c.set("query",d.channelSearch);let[u,h,f]=await Promise.all([b(e+"/channel-posts?"+c),b(e+"/members"),b(e+"/sessions")]),g=new Map(h.map(m=>["human:"+m.userId,m.email]));for(let m of f.sessions)g.set("agent:"+m.id,m.displayName);let p=a("div",{class:"conversation-list","aria-label":"Channel posts"}),k=new Map,E=(m,I=!1)=>{let T=I?[...m.posts].reverse():m.posts;for(let x of T){let q=JSON.stringify(x),G=k.get(x.id);if(G?.fingerprint===q)continue;let ve=a("article",{class:"card"},a("div",{class:"row"},a("strong",{},g.get(x.authorKind+":"+x.authorId)||x.authorId),a("small",{},B(x.createdAt))),a("p",{class:"message"},x.body));ve.append(Sr(e,x.body)),(!d.threadId||d.channelSearch)&&ve.append(_(x.replies?`${x.replies} ${x.replies===1?"reply":"replies"}`:"Open thread",async()=>{d.threadId=x.threadId||x.id,d.channelSearch="",await C()})),G?G.node.replaceWith(ve):I?p.prepend(ve):p.append(ve),k.set(x.id,{fingerprint:q,node:ve})}};if(E(u),u.posts.length||p.append(a("section",{class:"card empty"},a("p",{},d.channelSearch?"No matching posts.":"No posts yet. Start the discussion below."))),l.append(p),u.nextCursor){let m=u.nextCursor,I=_("Earlier posts",async()=>{let T=new URLSearchParams(c);T.set("before",m);let x=await b(e+"/channel-posts?"+T);E(x),m=x.nextCursor,m||I.remove()});l.append(I)}let A=N(d.threadId?"Your reply":"Your post",{name:"body",multiline:!0,required:!0,maxlength:65536}),O=crypto.randomUUID(),R="";l.append(a("section",{class:"card"},F([A.node,kr(e,A.input),a("p",{class:"help"},"Shared with the workspace. Subscribed sessions receive an inbox notification; delivery does not mean a model has acted.")],d.threadId?"Reply in thread":"Post to channel",async m=>{let I=m.get("body");R&&R!==I&&(O=crypto.randomUUID()),R=I,await b(e+"/channel-posts",{method:"POST",body:{channelId:r.id,body:I,threadId:d.threadId||void 0,idempotencyKey:O}}),d.channelSearch="",await C()})));let v=!0,P=!1,S=setInterval(async()=>{if(d.generation!==n){clearInterval(S);return}if(!(!v||P||document.hidden)){P=!0;try{let m=await b(e+"/channel-posts?"+c);v&&(m.posts.length&&p.querySelector(".empty")?.remove(),E(m,!0))}catch(m){v&&H("Channel refresh failed. "+m.message,!0)}finally{P=!1}}},5e3);return Ze.push(()=>{v=!1,clearInterval(S)}),l}async function ns(){let n=D("/billing"),e=await b(n),t=e.paidUntil&&Date.parse(e.paidUntil)>Date.now(),r=!t&&Date.parse(e.trialEndsAt)>Date.now(),s=f=>new Intl.NumberFormat(void 0,{style:"currency",currency:e.currency.toUpperCase(),maximumFractionDigits:0}).format(f/100),i=f=>f>=1024**3?`${(f/1024**3).toFixed(1)} GiB`:`${(f/1024**2).toFixed(1)} MiB`,o=f=>Number(f).toLocaleString(),l=a("div");e.configured&&!e.live&&l.append(a("p",{class:"notice-inline",role:"status"},"Test billing \u2014 this service is not accepting real payments.")),_e.has("billing")&&l.append(a("p",{class:"notice-inline"},"Returned from billing. Check payment status below; returning from checkout does not confirm a payment.")),l.append(a("section",{class:"card"},a("h2",{},t?"Paid workspace":r?"Workspace trial":"Hosting inactive"),a("p",{},t?`Hosting paid through ${B(e.paidUntil)}.`:r?`Trial ends ${B(e.trialEndsAt)}.`:"New work is paused. Existing history remains available."),e.cancelAtPeriodEnd?a("p",{},`Your subscription will end on ${B(e.currentPeriodEnd)}. It will not renew.`):null,["past_due","unpaid","incomplete"].includes(e.status)?a("p",{class:"notice-inline"},"Your subscription needs payment attention. Open payment settings to review it."):null));let c=a("div",{class:"actions"});async function u(f,g){let p=await b(n+"/"+f,{method:"POST",body:g,timeout:3e4}),k=new URL(p.url);if(k.protocol!=="https:"||k.username||k.password||!["checkout.stripe.com","billing.stripe.com"].includes(k.host))throw new Error("Payment destination could not be verified.");location.assign(k.href)}e.canManage&&e.configured&&(["none","canceled","incomplete_expired"].includes(e.status)?c.append(_(`${s(e.monthlyPriceCents)} / month`,()=>u("checkout",{interval:"month"}),"primary"),_(`${s(e.annualPriceCents)} / year`,()=>u("checkout",{interval:"year"}))):c.append(_("Payment settings & cancellation",()=>u("portal"),"primary")),c.append(_("Check payment status",async()=>{await b(n+"/refresh",{method:"POST",timeout:3e4}),await C(),H("Payment status checked.")})),e.pendingCheckout&&c.append(_("Close unfinished checkout",async()=>{await b(n+"/cancel-checkout",{method:"POST",timeout:3e4}),await C()}))),l.append(a("section",{class:"card"},a("h2",{},`${s(e.monthlyPriceCents)} per workspace per month`),a("p",{},`Or ${s(e.annualPriceCents)} per year, billed annually. Applicable tax is shown at checkout. Includes 5 people, 50 concurrent sessions, 100,000 new deliveries per calendar month and 5 GiB of files.`),a("p",{class:"help"},"Includes 25 GiB of uploads and 25 GiB of downloads per calendar month. Each file can be up to 16 MiB. Model and compute costs are separate. No automatic usage overage charges."),e.pendingCheckout?a("p",{class:"notice-inline"},`An unfinished ${e.pendingInterval==="year"?"annual":"monthly"} checkout is saved. Choosing the same plan resumes it; choosing the other plan closes it before starting another.`):null,e.configured?e.canManage?c:a("p",{},"Only a workspace owner can manage payments."):a("p",{},"Paid hosting is not available on this service yet.")));let h=a("section",{class:"card"},a("h2",{},"Included usage"),a("p",{class:"help"},t?`Delivery and file-transfer counters reset each calendar month (UTC). Current month: ${e.month}.`:"The trial includes 2,000 new deliveries in total, 256 MiB of files and 1 GiB in each transfer direction per calendar month."));for(let[f,g,p,k]of[["New deliveries",e.deliveries,e.deliveryLimit,o],["People",e.members,e.memberLimit,o],["Concurrent sessions",e.sessions,e.sessionLimit,o],["Retained coordination data",e.retainedBytes||0,e.textLimit||5*1024**3,i],["File storage",e.fileBytes,e.fileStorageLimit,i],["Uploads this month",e.uploadedBytes,e.fileTransferLimit,i],["Downloads this month",e.downloadedBytes,e.fileTransferLimit,i]])h.append(a("div",{class:"usage"},a("div",{class:"row"},a("span",{},f),a("span",{},`${k(g)} / ${k(p)}`)),a("progress",{max:p,value:Math.min(g,p),"aria-label":f})));return h.append(a("p",{class:"help"},"A new message counts once per recipient. Channel notifications count per subscriber. Retries, acknowledgements and replies do not consume delivery allowance.")),l.append(h),l}async function is(){let n=D(""),e=d.workspace,t=await b(n+"/storage"),r=d.workspace.role==="owner",s=a("div",{},a("section",{class:"card"},a("h2",{},"Retention"),a("p",{},"Completed conversations, completed tasks, resolved questions and quiet channel threads are eligible for removal after 90 days. Unfinished work and linked records that still need each other remain. Files stay until you delete them."),a("p",{class:"help"},"The notification log keeps roughly the latest 100,000 events or 90 days, whichever is shorter. This does not delete the corresponding messages or tasks. New work pauses when estimated retained coordination data reaches 5 GiB; final replies and acknowledgements remain available.")));if(!r)return s.append(a("p",{},"A workspace owner can pause sessions, export data and prune completed history.")),s;e.deleting?s.append(a("section",{class:"card"},a("h2",{},"Deletion in progress"),a("p",{},"Sessions and purchases are stopped. Billing must be closed before the remaining data can be deleted. The service retries automatically; you can also retry below."))):s.append(a("section",{class:"card"},a("h2",{},d.workspace.paused?"Sessions paused":"Pause sessions for an export"),a("p",{},"Pausing disconnects all sessions and prevents new connections while you export. Members can still read history here. Resume and reconnect your apps when finished. Pausing does not cancel billing."),_(d.workspace.paused?"Resume sessions":"Pause sessions",()=>te(d.workspace.paused?"Resume this workspace?":"Disconnect workspace sessions?",o=>a("div",{},a("p",{},d.workspace.paused?"Connected apps can rejoin when hosting is active.":"Every connected session will lose its current connection. Queued work and history are retained."),_("Confirm",async()=>{await b(n+"/pause",{method:"POST",body:{paused:!d.workspace.paused}}),o(),await Y()},"primary")))))),s.append(a("section",{class:"card"},a("h2",{},"Download a portable archive"),a("p",{},"Includes retained messages, tasks, questions, channels, output values and file bytes. Does not contain account credentials or payment details. Pause sessions first so the archive is consistent."),a("p",{class:"help"},"Portable archives are limited to 64 MiB, including encoded files. Larger workspaces need an operator-assisted database and file export. File bytes in an archive count toward download allowance. Store the download privately."),_("Download workspace archive",async()=>{let l=await(await Ct(n+"/export")).blob(),c=URL.createObjectURL(l),u=a("a",{href:c,download:"agentintercom-workspace.json"});document.body.append(u),u.click(),u.remove(),setTimeout(()=>URL.revokeObjectURL(c),3e4)})));let i=N("Remove eligible history completed before",{name:"before",type:"date",required:!0,value:new Date(Date.now()-90*864e5).toISOString().slice(0,10),max:new Date(Date.now()-2*864e5).toISOString().slice(0,10)});return s.append(a("section",{class:"card"},a("h2",{},"Prune completed history"),a("p",{},"Review a preview before deleting anything. Export first if you need to retain a copy. This does not remove unfinished work, files or your subscription."),F([i.node],"Preview cleanup",async o=>{let l=new Date(o.get("before")+"T00:00:00Z").toISOString(),c=await b(n+"/prune",{method:"POST",body:{before:l,execute:!1},timeout:3e4});te("Delete eligible history?",u=>a("div",{},a("p",{},"This permanently deletes eligible records before the selected date. Counts may change if work finishes before confirmation."),a("pre",{},JSON.stringify(c.records,null,2)),_("Delete eligible history",async()=>{await b(n+"/prune",{method:"POST",body:{before:l,execute:!0},timeout:3e4}),u(),await C(),H("Completed history pruned.")},"danger")))}))),s.append(a("section",{class:"card"},a("h2",{},"Retained records"),a("p",{class:"help"},"Payload estimates below exclude database indexes and some record overhead; billing usage includes a per-record estimate."),(t.records||[]).map(o=>a("div",{class:"row"},a("span",{},`${o.recordType} \xB7 ${o.state}`),a("span",{},Number(o.count).toLocaleString()))))),s.append(a("section",{class:"card"},a("h2",{},"Delete workspace"),a("p",{},"Permanently removes this workspace for everyone, including messages, unfinished work, files and connections. Its hosting subscription ends immediately; unused time is not automatically refunded. Export first if you need a copy."),a("p",{class:"help"},"Your October account and other workspaces remain. Minimal payment references are retained for support. Private backups expire on the operator\u2019s retention schedule."),_(e.deleting?"Retry workspace deletion":"Delete workspace",()=>te("Permanently delete this workspace?",o=>{let l=N("Type the workspace name to confirm",{name:"confirmation",required:!0,autocomplete:"off"});return a("div",{},a("p",{},`This cannot be undone. Enter ${e.name} to confirm. Once requested, deletion continues even if this page closes.`),F([l.node],"Delete permanently",async c=>{if(c.get("confirmation")!==e.name)throw new Error("The workspace name does not match.");try{await b(n,{method:"DELETE",body:{confirmName:c.get("confirmation")},timeout:3e4})}catch(u){throw o(),await Y(),u}o(),await Y(),H("Workspace deleted.")}))}),"danger"))),s} diff --git a/web/build.mjs b/web/build.mjs index b50422a..05f6104 100644 --- a/web/build.mjs +++ b/web/build.mjs @@ -1,6 +1,7 @@ import { build } from 'esbuild'; import { copyFile, mkdir } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; const output = new URL('../bus/hostedweb/', import.meta.url); await mkdir(output, { recursive: true }); -await build({ entryPoints: ['src/app.js'], bundle: true, minify: true, format: 'esm', target: ['es2022'], outfile: new URL('app.js', output).pathname, legalComments: 'linked' }); +await build({ entryPoints: ['src/app.js'], bundle: true, minify: true, format: 'esm', target: ['es2022'], outfile: fileURLToPath(new URL('app.js', output)), legalComments: 'linked' }); await Promise.all(['index.html', 'style.css'].map(name => copyFile(new URL(`src/${name}`, import.meta.url), new URL(name, output)))); diff --git a/web/src/app.js b/web/src/app.js index bba9d0f..141a947 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -123,11 +123,15 @@ async function filesView() { return container; } function closePending(key) { delete pending[key]; sessionStorage.setItem(pendingKey, JSON.stringify({ ...pending, until: Date.now() + 20 * 60 * 1000 })); history.replaceState(null, '', '/app'); } +let modalCount = 0; function modal(title, build) { - const dialog = el('dialog', {}, el('h2', {}, title)); - const close = () => { dialog.close(); dialog.remove(); }; + const headingId = `modal-title-${++modalCount}`; + const opener = document.activeElement; + const dialog = el('dialog', { 'aria-labelledby': headingId }, el('h2', { id: headingId }, title)); + const close = () => dialog.close(); dialog.append(build(close), el('div', { class: 'actions end' }, button('Close', close))); - dialog.addEventListener('close', () => dialog.remove()); document.body.append(dialog); dialog.showModal(); return dialog; + dialog.addEventListener('close', () => { dialog.remove(); if (opener?.isConnected) opener.focus(); }); + document.body.append(dialog); dialog.showModal(); return dialog; } function secretDialog(title, value, description) { modal(title, () => el('div', {}, el('p', {}, description), el('pre', { class: 'secret' }, value), button('Copy', () => copy(value)))); diff --git a/web/tests/workspace.spec.js b/web/tests/workspace.spec.js index 752e0cf..fbfe3dc 100644 --- a/web/tests/workspace.spec.js +++ b/web/tests/workspace.spec.js @@ -342,3 +342,46 @@ test('workspace deletion requires its name and recovers a failed cancellation', await expect(page.getByRole('heading', { name: 'Make room for your team.', exact: true })).toBeVisible(); expect(attempts).toEqual([{ confirmName: 'My workspace' }, { confirmName: 'My workspace' }]); }); + +test('dialogs are found by their accessible name and keyboard focus stays predictable', async ({ page }) => { + const events = await fixture(page); + await page.goto('/app'); + const newWorkspaceTrigger = page.getByRole('button', { name: '+ New workspace', exact: true }); + await newWorkspaceTrigger.focus(); + await page.keyboard.press('Enter'); + const newWorkspace = page.getByRole('dialog', { name: 'New workspace', exact: true }); + await expect(newWorkspace).toBeVisible(); + await expect(page.getByLabel('Workspace name', { exact: true })).toBeFocused(); + await page.keyboard.press('Tab'); + await expect(page.getByRole('button', { name: 'Create workspace', exact: true })).toBeFocused(); + expect(events).toHaveLength(0); + await page.keyboard.press('Escape'); + await expect(newWorkspace).toHaveCount(0); + await expect(newWorkspaceTrigger).toBeFocused(); + await newWorkspaceTrigger.press('Enter'); + await expect(page.getByRole('dialog', { name: 'New workspace', exact: true })).toBeVisible(); + await page.getByRole('dialog', { name: 'New workspace', exact: true }).getByRole('button', { name: 'Close', exact: true }).press('Enter'); + await expect(page.getByRole('dialog', { name: 'New workspace' })).toHaveCount(0); + await expect(newWorkspaceTrigger).toBeFocused(); + expect(events).toHaveLength(0); +}); + +test('confirmation dialogs are named, keyboard-operable and still guard destructive actions', async ({ page }) => { + const events = await fixture(page); + await page.goto('/app'); + await page.getByRole('button', { name: 'Members & devices', exact: true }).click(); + await page.getByRole('button', { name: 'Revoke', exact: true }).focus(); + await page.keyboard.press('Enter'); + const confirmation = page.getByRole('dialog', { name: 'Revoke connection?', exact: true }); + await expect(confirmation).toBeVisible(); + await expect(confirmation.getByText('My AI app will stop receiving access to this workspace.', { exact: true })).toBeVisible(); + expect(events).toHaveLength(0); + await page.keyboard.press('Escape'); + await expect(confirmation).toHaveCount(0); + await expect(page.getByRole('button', { name: 'Revoke', exact: true })).toBeFocused(); + expect(events).toHaveLength(0); + await page.getByRole('button', { name: 'Revoke', exact: true }).press('Enter'); + await page.getByRole('dialog', { name: 'Revoke connection?', exact: true }).getByRole('button', { name: 'Revoke connection', exact: true }).press('Enter'); + await expect(page.getByText(/MCP app · Revoked/)).toBeVisible(); + expect(events.filter(event => event.method === 'DELETE')).toHaveLength(1); +}); From 6f3dbaf94d736f4aa8869815c3c77869495e5140 Mon Sep 17 00:00:00 2001 From: Harsh Date: Thu, 12 Nov 2026 15:17:11 -0800 Subject: [PATCH 2/2] fix(web): rely on native dialog focus restoration Per maintainer review: remove the manual opener.focus() restoration, which duplicates the platform behavior of modal dialogs, and regenerate the committed bundle. Accessible names and keyboard tests are unchanged. --- bus/hostedweb/app.js | 2 +- web/src/app.js | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/bus/hostedweb/app.js b/bus/hostedweb/app.js index bebfbc3..c9a1ed2 100644 --- a/bus/hostedweb/app.js +++ b/bus/hostedweb/app.js @@ -17,6 +17,6 @@ Resources:`;for(let v of u){if(!v||typeof v!="string")throw new Error(`@supabase ${O}`}var U=class extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=t}toJSON(){return{name:this.name,message:this.message,code:this.code}}},me=class extends U{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function hr({error:n,options:e}){var t,r,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new U({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else if(n.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new U({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:n});if(e.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new U({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:n});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new U({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:n})}else{if(n.name==="InvalidStateError")return new U({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});if(n.name==="NotAllowedError")return new U({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new U({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:n}):new U({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:n});if(n.name==="SecurityError"){let o=window.location.hostname;if(wt(o)){if(i.rp.id!==o)return new U({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new U({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new U({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:n})}else if(n.name==="UnknownError")return new U({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new U({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}function fr({error:n,options:e}){let{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new U({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else{if(n.name==="NotAllowedError")return new U({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="SecurityError"){let r=window.location.hostname;if(wt(r)){if(t.rpId!==r)return new U({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new U({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="UnknownError")return new U({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new U({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}var gt=class{createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},Ye=new gt;function yt(n){if(!n)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(n);let{challenge:e,user:t,excludeCredentials:r}=n,s=ue(n,["challenge","user","excludeCredentials"]),i=ae(e).buffer,o=Object.assign(Object.assign({},t),{id:ae(t.id).buffer}),l=Object.assign(Object.assign({},s),{challenge:i,user:o});if(r&&r.length>0){l.excludeCredentials=new Array(r.length);for(let c=0;c0){i.allowCredentials=new Array(t.length);for(let o=0;os!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(let s of n)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(t(o))r[i]=o;else if(e(o)){let l=r[i];e(l)?r[i]=Je(l,o):r[i]=Je(o)}else r[i]=o}return r}function Wr(n,e){return Je(Kr,n,e||{})}function Br(n,e){return Je(Fr,n,e||{})}var He=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){var o;try{let{data:l,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!l)return{data:null,error:c};let u=s??Ye.createNewAbortSignal();if(l.webauthn.type==="create"){let{user:h}=l.webauthn.credential_options.publicKey;if(!h.name){let f=r;if(f)h.name=`${h.id}:${f}`;else{let p=(await this.client.getUser()).data.user,k=((o=p?.user_metadata)===null||o===void 0?void 0:o.name)||p?.email||p?.id||"User";h.name=`${h.id}:${k}`}}h.displayName||(h.displayName=h.name)}switch(l.webauthn.type){case"create":{let h=Wr(l.webauthn.credential_options.publicKey,i?.create),{data:f,error:g}=await bt({publicKey:h,signal:u});return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:g}}case"request":{let h=Br(l.webauthn.credential_options.publicKey,i?.request),{data:f,error:g}=await kt(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:h,signal:u}));return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:g}}}}catch(l){return w(l)?{data:null,error:l}:{data:null,error:new K("Unexpected error in challenge",l)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ie("rpId is required for WebAuthn authentication")};try{if(!$e())return{data:null,error:new K("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!o)return{data:null,error:l};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:t,rpOrigins:r,credential_response:c.credential_response}})}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new K("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new ie("rpId is required for WebAuthn registration")};try{if(!$e())return{data:null,error:new K("Browser does not support WebAuthn",null)};let{data:o,error:l}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(h=>{var f;return(f=h.data)===null||f===void 0?void 0:f.all.find(g=>g.factor_type==="webauthn"&&g.friendly_name===e&&g.status==="unverified")}).then(h=>h?this.client.mfa.unenroll({factorId:h?.id}):void 0),{data:null,error:l};let{data:c,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:t,rpOrigins:r,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(o){return w(o)?{data:null,error:o}:{data:null,error:new K("Unexpected error in register",o)}}}};lr();var Gr={url:jt,storageKey:$t,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Dt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};var Se={},pr=!1,Xe=class n{get jwks(){var e,t;return(t=(e=Se[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){Se[this.storageKey]=Object.assign(Object.assign({},Se[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=Se[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Se[this.storageKey]=Object.assign(Object.assign({},Se[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},Gr),e);if(this.storageKey=i.storageKey,this.instanceID=(t=n.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,n.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&L()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(r=i.experimental)!==null&&r!==void 0?r:{},this.admin=new ye({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=Be(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock!=null&&(this.lock=i.lock,pr||(pr=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new He(this),recoveryCodes:{getStatus:this._getRecoveryCodesStatus.bind(this),generate:this._generateRecoveryCodes.bind(this),verify:this._verifyRecoveryCode.bind(this),regenerate:this._regenerateRecoveryCodes.bind(this),unenroll:this._unenrollRecoveryCodes.bind(this)}},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:We()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=ft(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=ft(this.memoryStorage)),L()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),(o.data.event==="TOKEN_REFRESHED"||o.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ne}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();let t=await this.initializePromise,r=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(let s of r)await this._notifyAllSubscribers(s.event,s.session,s.broadcast);return t}async _initialize(){var e;try{let t={},r="none";if(L()&&(t=lt(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),L()&&this.detectSessionInUrl&&r!=="none"){let{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Mt(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:l}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return w(t)?this._returnResult({error:t}):this._returnResult({error:new K("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let i=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:V}),{data:o,error:l}=i;if(l||!o)return this._returnResult({data:{user:null,session:null},error:l});let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(w(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,r,s;let i=null;try{let o;if("email"in e){let{email:f,password:g,options:p}=e,k=null,E=null;this.flowType==="pkce"&&([k,E,i]=await this._getCodeChallengeAndMethod()),o=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(p?.emailRedirectTo,i),body:{email:f,password:g,data:(t=p?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:k,code_challenge_method:E},xform:V})}else if("phone"in e){let{phone:f,password:g,options:p}=e;o=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:g,data:(r=p?.data)!==null&&r!==void 0?r:{},channel:(s=p?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:V})}else throw new de("You must provide either an email or phone number and a password");let{data:l,error:c}=o;if(c||!l)return await J(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:c});let u=l.session,h=l.user;return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:h,session:u},error:null})}catch(o){if(await J(this.storage,this.storageKey,i),w(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:l}=e;t=await y(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:dt})}else if("phone"in e){let{phone:i,password:o,options:l}=e;t=await y(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l?.captchaToken}},xform:dt})}else throw new de("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let i=new se;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,t){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,t)):this._exchangeCodeForSession(e,t)}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,o,l,c,u,h,f,g;let p,k;if("message"in e)p=e.message,k=e.signature;else{let{chain:E,wallet:A,statement:O,options:R}=e,v;if(L())if(typeof A=="object")v=A;else{let x=window;if("ethereum"in x&&typeof x.ethereum=="object"&&"request"in x.ethereum&&typeof x.ethereum.request=="function")v=x.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof A!="object"||!R?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=A}let P=new URL((t=R?.url)!==null&&t!==void 0?t:window.location.href),S=await v.request({method:"eth_requestAccounts"}).then(x=>x).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!S||S.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let m=pt(S[0]),I=(r=R?.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!I){let x=await v.request({method:"eth_chainId"});I=cr(x)}let T={domain:P.host,address:m,statement:O,uri:P.href,version:"1",chainId:I,nonce:(s=R?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=R?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(l=R?.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=R?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=R?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(h=R?.signInWithEthereum)===null||h===void 0?void 0:h.resources};p=dr(T),k=await v.request({method:"personal_sign",params:[ur(p),m]})}try{let{data:E,error:A}=await y(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:k},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:V});if(A)throw A;if(!E||!E.session||!E.user){let O=new se;return this._returnResult({data:{user:null,session:null},error:O})}return E.session&&(await this._saveSession(E.session),await this._notifyAllSubscribers("SIGNED_IN",E.session)),this._returnResult({data:Object.assign({},E),error:A})}catch(E){if(w(E))return this._returnResult({data:{user:null,session:null},error:E});throw E}}async signInWithSolana(e){var t,r,s,i,o,l,c,u,h,f,g,p;let k,E;if("message"in e)k=e.message,E=e.signature;else{let{chain:A,wallet:O,statement:R,options:v}=e,P;if(L())if(typeof O=="object")P=O;else{let m=window;if("solana"in m&&typeof m.solana=="object"&&("signIn"in m.solana&&typeof m.solana.signIn=="function"||"signMessage"in m.solana&&typeof m.solana.signMessage=="function"))P=m.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof O!="object"||!v?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");P=O}let S=new URL((t=v?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in P&&P.signIn){let m=await P.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},v?.signInWithSolana),{version:"1",domain:S.host,uri:S.href}),R?{statement:R}:null)),I;if(Array.isArray(m)&&m[0]&&typeof m[0]=="object")I=m[0];else if(m&&typeof m=="object"&&"signedMessage"in m&&"signature"in m)I=m;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in I&&"signature"in I&&(typeof I.signedMessage=="string"||I.signedMessage instanceof Uint8Array)&&I.signature instanceof Uint8Array)k=typeof I.signedMessage=="string"?I.signedMessage:new TextDecoder().decode(I.signedMessage),E=I.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in P)||typeof P.signMessage!="function"||!("publicKey"in P)||typeof P!="object"||!P.publicKey||!("toBase58"in P.publicKey)||typeof P.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");k=[`${S.host} wants you to sign in with your Solana account:`,P.publicKey.toBase58(),...R?["",R,""]:[""],"Version: 1",`URI: ${S.href}`,`Issued At: ${(s=(r=v?.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=v?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${v.signInWithSolana.notBefore}`]:[],...!((o=v?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${v.signInWithSolana.expirationTime}`]:[],...!((l=v?.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${v.signInWithSolana.chainId}`]:[],...!((c=v?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${v.signInWithSolana.nonce}`]:[],...!((u=v?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${v.signInWithSolana.requestId}`]:[],...!((f=(h=v?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||f===void 0)&&f.length?["Resources",...v.signInWithSolana.resources.map(I=>`- ${I}`)]:[]].join(` `);let m=await P.signMessage(new TextEncoder().encode(k),"utf8");if(!m||!(m instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");E=m}}try{let{data:A,error:O}=await y(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:k,signature:ne(E)},!((g=e.options)===null||g===void 0)&&g.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:V});if(O)throw O;if(!A||!A.session||!A.user){let R=new se;return this._returnResult({data:{user:null,session:null},error:R})}return A.session&&(await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session)),this._returnResult({data:Object.assign({},A),error:O})}catch(A){if(w(A))return this._returnResult({data:{user:null,session:null},error:A});throw A}}async _exchangeCodeForSession(e,t){let r=t?.flowId!=null,s=r?je(t?.flowId):L()?je(lt(window.location.href)[re]):null;r&&!s&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",t?.flowId);let{verifier:i,flowId:o}=r&&!s?{verifier:null,flowId:null}:await Yt(this.storage,this.storageKey,s),[l,c]=(i??"").split("/");try{if(!l&&this.flowType==="pkce")throw new Me;let{data:u,error:h}=await y(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:l},xform:V});if(await J(this.storage,this.storageKey,o),h)throw h;if(!u||!u.session||!u.user){let f=new se;return this._returnResult({data:{user:null,session:null,redirectType:null},error:f})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers(c==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:c??null}),error:h})}catch(u){if(await J(this.storage,this.storageKey,o),w(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:o}=e,l=await y(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:V}),{data:c,error:u}=l;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){let h=new se;return this._returnResult({data:{user:null,session:null},error:h})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,s,i,o;let l=null;try{if("email"in e){let{email:c,options:u}=e,h=null,f=null;this.flowType==="pkce"&&([h,f,l]=await this._getCodeChallengeAndMethod());let{error:g}=await y(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(t=u?.data)!==null&&t!==void 0?t:{},create_user:(r=u?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},code_challenge:h,code_challenge_method:f},redirectTo:this._maybeAppendFlowIdToRedirect(u?.emailRedirectTo,l)});return this._returnResult({data:{user:null,session:null},error:g})}if("phone"in e){let{phone:c,options:u}=e,{data:h,error:f}=await y(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(s=u?.data)!==null&&s!==void 0?s:{},create_user:(i=u?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:u?.captchaToken},channel:(o=u?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:h?.message_id},error:f})}throw new de("You must provide either an email or phone number.")}catch(c){if(await J(this.storage,this.storageKey,l),w(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:l}=await y(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:V});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(s){if(w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,r,s,i;let o=null;try{let l=null,c=null;this.flowType==="pkce"&&([l,c,o]=await this._getCodeChallengeAndMethod());let u=await y(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:this._maybeAppendFlowIdToRedirect((t=e.options)===null||t===void 0?void 0:t.redirectTo,o)}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:or});return!((s=u.data)===null||s===void 0)&&s.url&&L()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await J(this.storage,this.storageKey,o),w(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new j;let{error:s}=await y(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(w(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let t=null;try{let r=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:o}=e,l=null,c=null;this.flowType==="pkce"&&([l,c,t]=await this._getCodeChallengeAndMethod());let{error:u}=await y(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken},code_challenge:l,code_challenge_method:c},redirectTo:this._maybeAppendFlowIdToRedirect(o?.emailRedirectTo,t)});return u&&await J(this.storage,this.storageKey,t),this._returnResult({data:{user:null,session:null},error:u})}else if("phone"in e){let{phone:s,type:i,options:o}=e,{data:l,error:c}=await y(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:l?.message_id},error:c})}throw new de("You must provide either an email or phone number and a type")}catch(r){if(await J(this.storage,this.storageKey,t),w(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await M(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at*1e3-Date.now()Date.now()?this._returnResult({data:{session:await this._hydrateSessionUser(o)},error:null}):this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async _hydrateSessionUser(e){if(this.userStorage){let t=await M(this.userStorage,this.storageKey+"-user");e.user=t?.user?t.user:Ge()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let t={value:this.suppressGetSessionWarning};e.user=sr(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return e}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t;return this.lock!=null?t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):t=await this._getUser(),t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await y(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ee}):await this._useSession(async t=>{var r,s,i;let{data:o,error:l}=t;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new j}:await y(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:ee})})}catch(t){if(w(t))return xe(t)&&await this._removeSession(),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t)):await this._updateUser(e,t)}async _updateUser(e,t={}){let r=null;try{return await this._useSession(async s=>{let{data:i,error:o}=s;if(o)throw o;if(!i.session)throw new j;let l=i.session,c=null,u=null;this.flowType==="pkce"&&e.email!=null&&([c,u,r]=await this._getCodeChallengeAndMethod());let{data:h,error:f}=await y(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t?.emailRedirectTo,r),body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:u}),jwt:l.access_token,xform:ee});if(f)throw f;return l.user=h.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),this._returnResult({data:{user:l.user},error:null})})}catch(s){if(await J(this.storage,this.storageKey,r),w(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new j;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:o}=Ue(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){let{data:l,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};i=l}else{let{data:l,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:l.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(w(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}async refreshSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:l}=t;if(l)throw l;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new j;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(w(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){var r;try{if(!L())throw new he("No browser detected.");if(e.error||e.error_description||e.error_code)throw new he(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new Ae("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new he("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Ae("No code detected.");let{data:v,error:P}=await this._exchangeCodeForSession(e.code,{flowId:e[re]});if(P)throw P;let S=new URL(window.location.href);return S.searchParams.delete("code"),S.searchParams.delete(re),window.history.replaceState(window.history.state,"",S.toString()),{data:{session:v.session,redirectType:(r=v.redirectType)!==null&&r!==void 0?r:null},error:null}}let{provider_token:s,provider_refresh_token:i,access_token:o,refresh_token:l,expires_in:c,expires_at:u,token_type:h}=e;if(!o||!c||!l||!h)throw new he("No session defined in URL");let f=Math.round(Date.now()/1e3),g=parseInt(c),p=f+g;u&&(p=parseInt(u));let k=p-f;k*1e3<=X&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${k}s, should have been closer to ${g}s`);let E=p-g;f-E>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",E,p,f):f-E<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",E,p,f);let{data:A,error:O}=await this._getUser(o);if(O)throw O;let R={provider_token:s,provider_refresh_token:i,access_token:o,expires_in:g,expires_at:p,refresh_token:l,token_type:h,user:A.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:R,redirectType:e.type},error:null})}catch(s){if(w(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let t=je(e[re]);return t&&await M(this.storage,we(this.storageKey,t))?!0:!!await M(this.storage,`${this.storageKey}-code-verifier`)}async signOut(e={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let s=async()=>{await this._removeSession()},{data:i,error:o}=t;if(o&&!xe(o))return this._returnResult({error:o});let l=(r=i.session)===null||r===void 0?void 0:r.access_token;if(l){let{error:c}=await this.admin.signOut(l,e);if(c&&!(it(c)&&(c.status===404||c.status===401||c.status===403)||xe(c)))return e!=="others"&&await s(),this._returnResult({error:c})}return e!=="others"&&await s(),this._returnResult({error:null})})}onAuthStateChange(e){let t=Gt(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)}):await this._emitInitialSession(t)))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:i},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){if(await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),ot(i))return;xe(i)||Ce(i)||it(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null,i=null;this.flowType==="pkce"&&([r,s,i]=await this._getCodeChallengeAndMethod(!0));try{return await y(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t.redirectTo,i)})}catch(o){if(await J(this.storage,this.storageKey,i),w(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;let r=null;try{let{data:s,error:i}=await this._useSession(async o=>{var l,c,u,h,f;let{data:g,error:p}=o;if(p)throw p;let{url:k,flowId:E}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(l=e.options)===null||l===void 0?void 0:l.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return r=E,await y(this.fetch,"GET",k,{headers:this.headers,jwt:(f=(h=g.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(i)throw i;return L()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url,flowId:r},error:null})}catch(s){if(w(s))return this._returnResult({data:{provider:e.provider,url:null,flowId:r},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:o,provider:l,token:c,access_token:u,nonce:h}=e,f=await y(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i?.access_token)!==null&&r!==void 0?r:void 0,body:{provider:l,id_token:c,access_token:u,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:V}),{data:g,error:p}=f;return p?this._returnResult({data:{user:null,session:null},error:p}):!g||!g.session||!g.user?this._returnResult({data:{user:null,session:null},error:new se}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:p}))}catch(s){if(await J(this.storage,this.storageKey,null),w(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)throw o;return await y(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){let t="#_refreshAccessToken()";this._debug(t,"begin");try{let r=Date.now();return await Jt(async s=>(s>0&&await zt(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await y(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:V})),(s,i)=>{let o=200*Math.pow(2,s);return i&&Ce(i)&&Date.now()+o-r{});let i=await M(this.storage,this.storageKey),{data:o,error:l}=await this._refreshAccessToken(e);if(l)throw l;if(!o.session)throw new j;let c=await M(this.storage,this.storageKey);if(i!==null&&(c===null||c.refresh_token!==i.refresh_token)){this._debug(s,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:c?"replaced":"cleared"});let g={data:null,error:new Ie};return this.refreshingDeferred.resolve(g),g}let h=this._sessionRemovalEpoch;if(await this._saveSession(o.session),this._sessionRemovalEpoch!==h){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await W(this.storage,this.storageKey),this.userStorage&&await W(this.userStorage,this.storageKey+"-user");let g={data:null,error:new Ie};return this.refreshingDeferred.resolve(g),g}await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);let f={data:o.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(f),f}catch(i){if(this._debug(s,"error",i),w(i)){let o={data:null,error:i};if(!Ce(i)){let l=await M(this.storage,this.storageKey);!!(l?.expires_at&&l.expires_at*1e3>Date.now())?this._debug(s,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:o,expiresAt:Date.now()+Ut},(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){if(this._pendingInitNotifications!==null&&r){this._pendingInitNotifications.push({event:e,session:t,broadcast:r});return}let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let l=0;lthis._autoRefreshTokenTick(),X);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/X);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${X}ms, refresh threshold is ${be} ticks`),s<=be&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof ze)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/X);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${X}ms, refresh threshold is ${be} ticks`),s<=be&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!L()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(t,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=r?.redirectTo,i=null,o=null,l=null;this.flowType==="pkce"&&([i,o,l]=await this._getCodeChallengeAndMethod(),s=this._maybeAppendFlowIdToRedirect(s,l));let c=[`provider=${encodeURIComponent(t)}`];if(s&&c.push(`redirect_to=${encodeURIComponent(s)}`),r?.scopes&&c.push(`scopes=${encodeURIComponent(r.scopes)}`),i!=null&&o!=null){let u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});c.push(u.toString())}if(r?.queryParams){let u=new URLSearchParams(r.queryParams);c.push(u.toString())}return r?.skipBrowserRedirect&&c.push(`skip_http_redirect=${r.skipBrowserRedirect}`),{url:`${e}?${c.join("&")}`,flowId:l}}_maybeAppendFlowIdToRedirect(e,t){return!e||!t||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:Qt(e,t)}async _getCodeChallengeAndMethod(e=!1){return Zt(this.storage,this.storageKey,e,t=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",t))}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await y(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await y(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((s=c?.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?_t(e.webauthn.credential_response):vt(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:u}=await y(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:l,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:u}))})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challenge(e){let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let l=await y(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(l.error)return l;let{data:c}=l;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:yt(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:mt(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let i of(e=t?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&i.factor_type in s&&Array.isArray(s[i.factor_type])&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,i;if(e)try{let{payload:p}=Ue(e),k=null;p.aal&&(k=p.aal);let E=k,{data:{user:A},error:O}=await this.getUser(e);if(O)return this._returnResult({data:null,error:O});((r=(t=A?.factors)===null||t===void 0?void 0:t.filter(P=>P.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(E="aal2");let v=p.amr||[];return{data:{currentLevel:k,nextLevel:E,currentAuthenticationMethods:v},error:null}}catch(p){if(w(p))return this._returnResult({data:null,error:p});throw p}let{data:{session:o},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=Ue(o.access_token),u=null;c.aal&&(u=c.aal);let h=u;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(p=>p.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");let g=c.amr||[];return{data:{currentLevel:u,nextLevel:h,currentAuthenticationMethods:g},error:null}}async _getRecoveryCodesStatus(){ke(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await y(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _generateRecoveryCodes(e){ke(this.experimental);try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let{data:o,error:l}=await y(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:e?.friendlyName?{friendly_name:e.friendlyName}:void 0,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):this._returnResult({data:o,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _verifyRecoveryCode(e){ke(this.experimental);let t=async()=>{try{return await this._useSession(async r=>{var s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let{data:l,error:c}=await y(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:e.code},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});if(c)return this._returnResult({data:null,error:c});let u=Object.assign({expires_at:Fe(l.expires_in)},l);return await this._saveSession(u),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:l,error:null})})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,t):t()}async _regenerateRecoveryCodes(){ke(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await y(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _unenrollRecoveryCodes(){ke(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:o}=await y(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(t=r?.session)===null||t===void 0?void 0:t.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await y(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new j})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new j});let o=await y(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&L()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new j});let o=await y(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&L()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await y(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new j})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await y(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new j})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(l=>l.kid===e);if(r)return r;let s=Date.now();if(r=this.jwks.keys.find(l=>l.kid===e),r&&this.jwks_cached_at+qt>s)return r;let{data:i,error:o}=await y(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(l=>l.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){let{data:p,error:k}=await this.getSession();if(k||!p.session)return this._returnResult({data:null,error:k});r=p.session.access_token}let{header:s,payload:i,signature:o,raw:{header:l,payload:c}}=Ue(r);if(!t?.allowExpired)try{tr(i.exp)}catch(p){throw new oe(p instanceof Error?p.message:"JWT validation failed")}let u=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!u){let{error:p}=await this.getUser(r);if(p)throw p;return{data:{claims:i,header:s,signature:o},error:null}}let h=rr(s.alg),f=await crypto.subtle.importKey("jwk",u,h,!0,["verify"]);if(!await crypto.subtle.verify(h,f,o,Bt(`${l}.${c}`)))throw new oe("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async signInWithPasskey(e){var t,r,s,i;try{if(!$e())return this._returnResult({data:null,error:new K("Browser does not support WebAuthn",null)});let{data:o,error:l}=await this._startPasskeyAuthentication({options:{captchaToken:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}});if(l||!o)return this._returnResult({data:null,error:l});let c=mt(o.options),u=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:Ye.createNewAbortSignal(),{data:h,error:f}=await kt({publicKey:c,signal:u,mediation:(i=e?.options)===null||i===void 0?void 0:i.mediation});if(f||!h)return this._returnResult({data:null,error:f??new K("WebAuthn ceremony failed",null)});let g=vt(h);return this._verifyPasskeyAuthentication({challengeId:o.challenge_id,credential:g})}catch(o){if(w(o))return this._returnResult({data:null,error:o});throw o}}async registerPasskey(e){var t,r;try{if(!$e())return this._returnResult({data:null,error:new K("Browser does not support WebAuthn",null)});let{data:s,error:i}=await this._startPasskeyRegistration();if(i||!s)return this._returnResult({data:null,error:i});let o=yt(s.options),l=(r=(t=e?.options)===null||t===void 0?void 0:t.signal)!==null&&r!==void 0?r:Ye.createNewAbortSignal(),{data:c,error:u}=await bt({publicKey:o,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new K("WebAuthn ceremony failed",null)});let h=_t(c);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:h})}catch(s){if(w(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyRegistration(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new j});let{data:s,error:i}=await y(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{data:i,error:o}=await y(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _startPasskeyAuthentication(e){var t;try{let{data:r,error:s}=await y(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(t=e?.options)===null||t===void 0?void 0:t.captchaToken}}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:r,error:null})}catch(r){if(w(r))return this._returnResult({data:null,error:r});throw r}}async _verifyPasskeyAuthentication(e){try{let{data:t,error:r}=await y(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:V});return r?this._returnResult({data:null,error:r}):(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:t,error:null}))}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _listPasskeys(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new j});let{data:s,error:i}=await y(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(w(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{data:i,error:o}=await y(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}async _deletePasskey(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new j});let{error:i}=await y(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(t){if(w(t))return this._returnResult({data:null,error:t});throw t}}};Xe.nextInstanceID={};var St=Xe;var Vr=St,Rt=Vr;var le=document.querySelector("#app"),De=document.querySelector("#notice"),d={auth:null,config:null,user:null,workspaces:[],workspace:null,tab:"sessions",generation:0,conversationAgent:"",search:"",channelId:"",threadId:"",channelSearch:""},wr,Ze=[];function mr(){for(let n of Ze.splice(0))n()}var _e=new URLSearchParams(location.search);_e.has("billing")&&(d.tab="billing");var xt="agentintercom-pending",$={};try{let n=JSON.parse(sessionStorage.getItem(xt)||"{}");n.until>Date.now()&&($=n)}catch{}_e.get("authorization_id")&&($.authorization=_e.get("authorization_id"));var _r=new URLSearchParams(location.hash.slice(1)),gr=_r.get("invite"),yr=_r.get("device")||_e.get("device_code");yr&&($.device=yr,history.replaceState(null,"",location.pathname+location.search));gr&&($.invite=gr,history.replaceState(null,"",location.pathname+location.search));($.authorization||$.invite||$.device)&&sessionStorage.setItem(xt,JSON.stringify({...$,until:Date.now()+1200*1e3}));function a(n,e={},...t){let r=document.createElement(n);for(let[s,i]of Object.entries(e))i==null||i===!1||(s.startsWith("on")?r.addEventListener(s.slice(2),i):s==="class"?r.className=i:s==="text"?r.textContent=i:r.setAttribute(s,i===!0?"":String(i)));for(let s of t.flat(1/0))s!=null&&r.append(s instanceof Node?s:document.createTextNode(String(s)));return r}function H(n,e=!1){clearTimeout(wr),De.textContent=n,De.hidden=!1,De.className=e?"error":"",De.setAttribute("role",e?"alert":"status"),wr=setTimeout(()=>{De.hidden=!0},e?15e3:6e3)}async function Re(n,e){if(!n?.disabled){n&&(n.disabled=!0);try{return await e()}catch(t){H(t.message||"Something went wrong. Please try again.",!0)}finally{n&&(n.disabled=!1)}}}function _(n,e,t=""){return a("button",{type:"button",class:t,onclick:r=>Re(r.currentTarget,e)},n)}function N(n,e={}){let t=a(e.multiline?"textarea":"input",{...e,multiline:null});return{input:t,node:a("label",{},n,t)}}function F(n,e,t){let r=a("button",{type:"submit",class:"primary"},e);return a("form",{onsubmit:s=>{s.preventDefault(),Re(r,()=>t(new FormData(s.currentTarget)))}},n,r)}var ce=()=>a("div",{class:"brand"},a("span",{class:"mark","aria-hidden":!0},"o"),"agent intercom"),B=n=>n?new Date(n).toLocaleString():"\u2014",D=n=>`/api/workspaces/${encodeURIComponent(d.workspace.id)}${n}`;async function b(n,e={}){let t={"Content-Type":"application/json"};if(d.auth&&n!=="/api/config"){let{data:i,error:o}=await d.auth.getSession();if(o)throw o;i.session&&(t.Authorization=`Bearer ${i.session.access_token}`)}let r=await fetch(n,{method:e.method||"GET",credentials:"omit",headers:t,body:e.body==null?void 0:JSON.stringify(e.body),signal:AbortSignal.timeout(e.timeout||15e3)}),s=await r.json();if(!r.ok||s.ok===!1||s.error)throw new Error(s.error?.message||"The request could not be completed. Please try again.");return s.result}async function rt(n){await navigator.clipboard.writeText(n),H("Copied to clipboard.")}var Et=new WeakMap;async function Ct(n,e={}){let{data:t,error:r}=await d.auth.getSession();if(r)throw r;if(!t.session)throw new Error("Sign in again to access workspace files.");let s=await fetch(n,{...e,credentials:"omit",redirect:"error",headers:{Authorization:`Bearer ${t.session.access_token}`,"Content-Type":"application/octet-stream"},signal:AbortSignal.timeout(3e4)});if(!s.ok){let i=await s.json().catch(()=>({}));throw new Error(i.error?.message||"File transfer failed. Please try again.")}return s}async function vr(n,e){if(e.size>16*1024*1024)throw new Error("Files can be up to 16 MiB.");Et.has(e)||Et.set(e,crypto.randomUUID());let t=new URLSearchParams({name:e.name,mediaType:e.type.split(";")[0]||"application/octet-stream",idempotencyKey:Et.get(e)}),s=await(await Ct(n+"/attachments?"+t,{method:"POST",body:e})).json();if(!s.ok)throw new Error(s.error?.message||"Upload failed.");return s.result}async function br(n,e,t){let r=await Ct(n+"/attachments/"+encodeURIComponent(e)+"/content"),s=await r.arrayBuffer();if([...new Uint8Array(await crypto.subtle.digest("SHA-256",s))].map(u=>u.toString(16).padStart(2,"0")).join("")!==r.headers.get("X-Content-SHA256"))throw new Error("File checksum did not match. The download was stopped.");let o=r.headers.get("Content-Disposition")||"";if(!t)try{t=decodeURIComponent(o.match(/filename\*=utf-8''([^;]+)/i)?.[1]||"")||o.match(/filename="([^"]+)"/)?.[1]||o.match(/filename=([^;]+)/)?.[1]}catch{}let l=URL.createObjectURL(new Blob([s],{type:"application/octet-stream"})),c=a("a",{href:l,download:(t||e).replace(/[\\/\x00-\x1f]/g,"_")});document.body.append(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(l),3e4)}function kr(n,e){let t=N("Attach a file",{type:"file"}),r=_("Upload and attach",async()=>{let s=t.input.files[0];if(!s)throw new Error("Choose a file first.");let i=t.input.closest("form")?.querySelector('[type="submit"]');i&&(i.disabled=!0);try{let o=await vr(n,s);e.value+=`${e.value?` -`:""}${o.name}: ${o.uri}`,t.input.value="",H("File attached. Send your message to share the reference.")}finally{i&&(i.disabled=!1)}});return a("details",{},a("summary",{},"Attach a file"),t.node,r,a("p",{class:"help"},"Up to 16 MiB. Uploaded files are visible to everyone in this workspace."))}function Sr(n,e,t=[]){let r=new Map;for(let s of String(e).matchAll(/october-bus:\/\/attachments\/(att_[0-9a-f]{32})(?![0-9a-f])/g))r.set(s[1],"");for(let s of t||[]){let i=s.uri?.match(/^october-bus:\/\/attachments\/(att_[0-9a-f]{32})$/)?.[1];i&&r.set(i,s.title)}return a("div",{class:"actions"},[...r].map(([s,i])=>_(i?`Download ${i}`:"Download shared file",()=>br(n,s,i))))}async function zr(){let n=D(""),e=a("div"),t=a("div",{class:"grid"}),r=o=>{for(let l of o.attachments){let u=l.authorKind==="human"&&l.authorId===d.user.id||["owner","admin"].includes(d.workspace.role)?_("Delete file",()=>te("Delete this file?",h=>a("div",{},a("p",{},`Delete ${l.name}? Existing message references will stop working.`),_("Delete permanently",async()=>{await b(n+"/attachments/"+l.id,{method:"DELETE"}),h(),await C()})))):null;t.append(a("article",{class:"card"},a("h2",{},l.name),a("p",{class:"help"},`${(l.size/1024).toFixed(1)} KiB \xB7 ${l.mediaType} \xB7 ${B(l.createdAt)}`),a("div",{class:"actions"},_("Download",()=>br(n,l.id,l.name)),_("Copy reference",()=>rt(l.uri)),u)))}},s=await b(n+"/attachments");r(s),s.attachments.length||t.append(a("section",{class:"card empty"},a("h2",{},"Share the files your work needs."),a("p",{},"Upload a file here or attach one to a conversation. Files stay private to this workspace.")));let i=N("File to upload",{type:"file",required:!0});if(e.append(a("section",{class:"card"},F([i.node,a("p",{class:"help"},"Up to 16 MiB per file. Everyone in the workspace can download it.")],"Upload file",async()=>{let o=i.input.files[0];if(!o)throw new Error("Choose a file first.");await vr(n,o),await C()})),t),s.nextCursor){let o=s.nextCursor,l=_("More files",async()=>{let c=await b(n+"/attachments?after="+encodeURIComponent(o));r(c),o=c.nextCursor,o||l.remove()});e.append(l)}return e}function et(n){delete $[n],sessionStorage.setItem(xt,JSON.stringify({...$,until:Date.now()+1200*1e3})),history.replaceState(null,"","/app")}var Jr=0;function te(n,e){let t=`modal-title-${++Jr}`,r=document.activeElement,s=a("dialog",{"aria-labelledby":t},a("h2",{id:t},n)),i=()=>s.close();return s.append(e(i),a("div",{class:"actions end"},_("Close",i))),s.addEventListener("close",()=>{s.remove(),r?.isConnected&&r.focus()}),document.body.append(s),s.showModal(),s}function tt(n,e,t){te(n,()=>a("div",{},a("p",{},t),a("pre",{class:"secret"},e),_("Copy",()=>rt(e))))}function At(){mr(),d.user=null;let n=N("Email address",{type:"email",name:"email",autocomplete:"email",required:!0}),e=F([n.node],"Continue with email",async i=>{let{error:o}=await d.auth.signInWithOtp({email:i.get("email"),options:{emailRedirectTo:location.origin+"/app"+($.authorization?"?authorization_id="+encodeURIComponent($.authorization):$.device?"?device_code="+encodeURIComponent($.device):""),shouldCreateUser:!0}});if(o)throw o;H("Check your email for an October sign-in link. Open it in this browser."),e.append(a("p",{class:"notice-inline"},"Check your email for a sign-in link. Keep this tab open so you can return to your connection request."))}),t=N("Email address",{name:"email",type:"email",autocomplete:"username",required:!0}),r=N("Password",{name:"password",type:"password",autocomplete:"current-password",required:!0}),s=F([t.node,r.node],"Sign in",async i=>{let{error:o}=await d.auth.signInWithPassword({email:i.get("email"),password:i.get("password")});if(o)throw o;await Y()});le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("div",{class:"auth-layout"},a("div",{class:"auth-copy"},a("div",{class:"eyebrow"},"One place to work together"),a("h1",{},`Your agents. +`:""}${o.name}: ${o.uri}`,t.input.value="",H("File attached. Send your message to share the reference.")}finally{i&&(i.disabled=!1)}});return a("details",{},a("summary",{},"Attach a file"),t.node,r,a("p",{class:"help"},"Up to 16 MiB. Uploaded files are visible to everyone in this workspace."))}function Sr(n,e,t=[]){let r=new Map;for(let s of String(e).matchAll(/october-bus:\/\/attachments\/(att_[0-9a-f]{32})(?![0-9a-f])/g))r.set(s[1],"");for(let s of t||[]){let i=s.uri?.match(/^october-bus:\/\/attachments\/(att_[0-9a-f]{32})$/)?.[1];i&&r.set(i,s.title)}return a("div",{class:"actions"},[...r].map(([s,i])=>_(i?`Download ${i}`:"Download shared file",()=>br(n,s,i))))}async function zr(){let n=D(""),e=a("div"),t=a("div",{class:"grid"}),r=o=>{for(let l of o.attachments){let u=l.authorKind==="human"&&l.authorId===d.user.id||["owner","admin"].includes(d.workspace.role)?_("Delete file",()=>te("Delete this file?",h=>a("div",{},a("p",{},`Delete ${l.name}? Existing message references will stop working.`),_("Delete permanently",async()=>{await b(n+"/attachments/"+l.id,{method:"DELETE"}),h(),await C()})))):null;t.append(a("article",{class:"card"},a("h2",{},l.name),a("p",{class:"help"},`${(l.size/1024).toFixed(1)} KiB \xB7 ${l.mediaType} \xB7 ${B(l.createdAt)}`),a("div",{class:"actions"},_("Download",()=>br(n,l.id,l.name)),_("Copy reference",()=>rt(l.uri)),u)))}},s=await b(n+"/attachments");r(s),s.attachments.length||t.append(a("section",{class:"card empty"},a("h2",{},"Share the files your work needs."),a("p",{},"Upload a file here or attach one to a conversation. Files stay private to this workspace.")));let i=N("File to upload",{type:"file",required:!0});if(e.append(a("section",{class:"card"},F([i.node,a("p",{class:"help"},"Up to 16 MiB per file. Everyone in the workspace can download it.")],"Upload file",async()=>{let o=i.input.files[0];if(!o)throw new Error("Choose a file first.");await vr(n,o),await C()})),t),s.nextCursor){let o=s.nextCursor,l=_("More files",async()=>{let c=await b(n+"/attachments?after="+encodeURIComponent(o));r(c),o=c.nextCursor,o||l.remove()});e.append(l)}return e}function et(n){delete $[n],sessionStorage.setItem(xt,JSON.stringify({...$,until:Date.now()+1200*1e3})),history.replaceState(null,"","/app")}var Jr=0;function te(n,e){let t=`modal-title-${++Jr}`,r=a("dialog",{"aria-labelledby":t},a("h2",{id:t},n)),s=()=>r.close();return r.append(e(s),a("div",{class:"actions end"},_("Close",s))),r.addEventListener("close",()=>r.remove()),document.body.append(r),r.showModal(),r}function tt(n,e,t){te(n,()=>a("div",{},a("p",{},t),a("pre",{class:"secret"},e),_("Copy",()=>rt(e))))}function At(){mr(),d.user=null;let n=N("Email address",{type:"email",name:"email",autocomplete:"email",required:!0}),e=F([n.node],"Continue with email",async i=>{let{error:o}=await d.auth.signInWithOtp({email:i.get("email"),options:{emailRedirectTo:location.origin+"/app"+($.authorization?"?authorization_id="+encodeURIComponent($.authorization):$.device?"?device_code="+encodeURIComponent($.device):""),shouldCreateUser:!0}});if(o)throw o;H("Check your email for an October sign-in link. Open it in this browser."),e.append(a("p",{class:"notice-inline"},"Check your email for a sign-in link. Keep this tab open so you can return to your connection request."))}),t=N("Email address",{name:"email",type:"email",autocomplete:"username",required:!0}),r=N("Password",{name:"password",type:"password",autocomplete:"current-password",required:!0}),s=F([t.node,r.node],"Sign in",async i=>{let{error:o}=await d.auth.signInWithPassword({email:i.get("email"),password:i.get("password")});if(o)throw o;await Y()});le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("div",{class:"auth-layout"},a("div",{class:"auth-copy"},a("div",{class:"eyebrow"},"One place to work together"),a("h1",{},`Your agents. A shared conversation.`),a("p",{},"Connect your AI apps, bring in another machine, and keep the work moving with your team.")),a("section",{class:"card auth-card","aria-labelledby":"signin-title"},a("h2",{id:"signin-title"},"Sign in to October"),a("p",{class:"help"},"Use your existing October account, or create one with your email."),e,a("details",{},a("summary",{},"Use an existing password"),s),a("p",{class:"help"},"Your AI subscriptions stay with your apps. Agent Intercom connects the work.")))))}async function Y(){d.user=await b("/api/me"),d.workspaces=await b("/api/workspaces");let n=_e.has("billing")&&_e.get("workspace")||localStorage.getItem("agentintercom-workspace");if(d.workspace=d.workspaces.find(e=>e.id===n)||d.workspaces[0]||null,$.invite)return Hr();if($.authorization)return It();if($.device)return Tt();if(!d.workspace)return Rr();await C()}function st(n){let e=N("Workspace name",{name:"name",placeholder:"My team",maxlength:100,required:!0});return F([e.node,a("p",{class:"help"},"Your first workspace starts a 14-day trial. Additional workspaces share its end date. Up to 5 people; no payment details needed.")],"Create workspace",async t=>{let r=await b("/api/workspaces",{method:"POST",body:{name:t.get("name")}});d.workspaces.push(r),d.workspace=r,localStorage.setItem("agentintercom-workspace",r.id),await n()})}function Rr(){le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("section",{class:"card consent"},a("h1",{},"Make room for your team."),a("p",{},"A workspace holds your connected sessions, messages and shared work."),st(C),_("Sign out",Ot))))}async function Ot(){let{error:n}=await d.auth.signOut({scope:"local"});if(n)throw n;d.generation++,At()}function Pt(n){return a("select",{"aria-label":"Workspace",onchange:t=>{d.workspace=d.workspaces.find(r=>r.id===t.target.value),localStorage.setItem("agentintercom-workspace",d.workspace.id),Re(null,n)}},d.workspaces.map(t=>a("option",{value:t.id,selected:t.id===d.workspace?.id},t.name)))}async function It(){let n=await b(`/api/oauth/requests/${encodeURIComponent($.authorization)}`),e=d.workspace?.id,r=(e?await b(D("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="mcp"),s=a("select",{"aria-label":"App connection"},a("option",{value:""},"Create a new app connection"),r.map(c=>a("option",{value:c.id},`Reconnect ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"The old app credentials will stop working. This app will receive the same session inbox, including its pending messages.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");let u=await b(`/api/oauth/requests/${encodeURIComponent($.authorization)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}});et("authorization"),location.assign(u.redirectUrl)},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Pt(It)),r.length?a("label",{},"App connection",s):null,i,a("div",{class:"actions"},_("Allow connection",()=>o(!0),"primary"),_("Cancel",()=>o(!1)))):st(It);le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect an app"),a("h1",{},n.clientName),a("p",{},"wants to connect to your Agent Intercom workspace."),a("p",{class:"help"},"This app registered itself. October has not verified its publisher. Only continue if you started this connection in an app you trust."),a("ul",{class:"permission-list"},a("li",{},"Read and share messages, files and channels in the selected workspace."),a("li",{},"Discover connected sessions and coordinate shared tasks."),a("li",{},"Remain connected until you revoke access or the connection expires.")),a("p",{class:"help"},"You can revoke access at any time in Members & devices."),a("p",{class:"help"},"Returns to: ",a("code",{},new URL(n.redirectUri).origin)),l)))}async function Tt(){let n=await b(`/api/device/authorizations/${encodeURIComponent($.device)}`),e=d.workspace?.id,r=(e?await b(D("/devices")):[]).filter(c=>c.userId===d.user.id&&c.kind==="device"),s=a("select",{"aria-label":"Device connection"},a("option",{value:""},"Connect a new machine"),r.map(c=>a("option",{value:c.id},`Replace ${c.name}${c.revokedAt?" \xB7 revoked":""}`))),i=a("p",{class:"notice-inline",hidden:!0},"Replacing a connection signs out its existing sessions. Their inboxes stay available. Resume each session using its existing session ID after this login completes.");s.addEventListener("change",()=>{i.hidden=!s.value});let o=async c=>{if(c&&e!==d.workspace?.id)throw new Error("The selected workspace changed. Wait for its connections to load, then try again.");await b(`/api/device/authorizations/${encodeURIComponent($.device)}`,{method:"POST",body:{approve:c,workspaceId:c?e:"",...c&&s.value?{replaceDeviceId:s.value}:{}}}),et("device"),le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("h1",{},c?"Your device can connect.":"Connection declined."),a("p",{},c?"Return to your terminal to finish. Each session on this device will appear in your workspace.":"No device credential was issued."),_("Open workspace",Y,"primary"))))},l=d.workspaces.length?a("div",{},a("label",{},"Connect to workspace",Pt(Tt)),r.length?a("label",{},"Device connection",s):null,i,a("div",{class:"actions"},_("Connect this device",()=>o(!0),"primary"),_("Decline",()=>o(!1)))):st(Tt);le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("div",{class:"eyebrow"},"Connect a machine"),a("h1",{},n.name),a("p",{},"Check that this code matches the one in your terminal:"),a("pre",{},n.userCode),a("p",{class:"help"},"Only approve a request you started. This device can read and send workspace messages and start its own agent sessions. You can revoke it in Members & devices."),l)))}function Hr(){le.replaceChildren(a("main",{id:"main",class:"consent"},ce(),a("section",{class:"card"},a("h1",{},"Join a workspace"),a("p",{},`You are signed in as ${d.user.email}. The invitation must match this address.`),a("div",{class:"actions"},_("Accept invitation",async()=>{let n=await b("/api/invites/accept",{method:"POST",body:{token:$.invite}});localStorage.setItem("agentintercom-workspace",n.workspaceId),et("invite"),await Y()},"primary"),_("Use another account",Ot),_("Cancel",async()=>{et("invite"),await Y()})))))}var Qe={sessions:["Sessions","Choose the connected session you want to work with."],messages:["Conversations","Messages and receipts shared with this workspace."],channels:["Channels","Shared discussions and threads for this workspace."],tasks:["Tasks","Shared work, claimed by the session doing it."],questions:["Needs you","Help your agents continue when they need a decision."],files:["Files","Private files shared with your workspace."],connect:["Connect an app","Use your favorite AI app, on this machine or another one."],members:["Members & devices","Give each person and machine their own access."],data:["Data & recovery","Export your workspace and manage retained history."],billing:["Billing & usage","Your workspace plan, payment details and included usage."]};async function C(){if(mr(),!d.workspace)return Rr();let n=++d.generation,e=a("main",{id:"main",class:"content"}),t=a("nav",{"aria-label":"Workspace"},Object.entries(Qe).map(([s,[i]])=>_(i,async()=>{d.tab=s,await C()},s===d.tab?"selected":"")));[...t.children].forEach((s,i)=>{Object.keys(Qe)[i]===d.tab&&s.setAttribute("aria-current","page")}),le.replaceChildren(a("div",{class:"shell"},a("aside",{class:"sidebar"},ce(),a("div",{class:"workspace-switch"},Pt(C),_("+ New workspace",()=>te("New workspace",s=>st(async()=>{s(),await C()})),"subtle-button")),t,a("div",{class:"account"},a("p",{},d.user.email),_("Sign out",Ot,"subtle-button"))),e)),e.append(a("header",{class:"topline"},a("div",{},a("div",{class:"eyebrow"},d.workspace.name),a("h1",{},Qe[d.tab][0]),a("p",{class:"muted"},Qe[d.tab][1])),d.tab==="sessions"?_("Connect an app",async()=>{d.tab="connect",await C()},"primary"):null));let r=a("p",{class:"progress"},"Loading\u2026");e.append(r);try{let s=await{data:is,billing:ns,files:zr,channels:ss,messages:es,tasks:ts,questions:rs,sessions:Yr,connect:Xr,members:Qr}[d.tab]();if(n!==d.generation)return;r.replaceWith(s)}catch(s){n===d.generation&&r.replaceWith(a("div",{class:"card"},a("p",{},s.message),_("Try again",C)))}}async function Yr(){let n=a("div"),e=a("div",{class:"grid"}),t=await b(D("/sessions")),r=s=>{for(let i of s.sessions){let o=i.reachable===!0;e.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},i.displayName||i.agentId||i.id),a("span",{class:`badge ${o?"live":""}`},o?"Connected":"Offline")),a("p",{class:"help"},i.deviceName),a("p",{class:"help"},i.deliveryMode==="poll"?"Inbox available when this app checks for messages. It may need you to resume the conversation.":"Native listener connected. Your app\u2019s permissions still apply."),a("small",{},`Last seen ${B(i.updatedAt)}`),i.wake?.uncertain?a("p",{class:"notice-inline"},"A wake submission is uncertain. Inspect the app before retrying; the message is still in its inbox."):null,a("div",{class:"actions"},_("Open conversation",async()=>{d.conversationAgent=i.id,d.tab="messages",await C()})))),i.userId===d.user.id&&e.lastChild.append(a("details",{},a("summary",{},"Session details"),a("p",{class:"help"},"This ID identifies the inbox. Terminal sessions can resume it with --id after reconnecting their owning machine."),a("code",{},i.id),_("Copy session ID",()=>rt(i.id))))}};if(!t.sessions.length)return a("section",{class:"card empty"},a("h2",{},"Your first connection starts here."),a("p",{class:"muted"},"Connect an AI app or terminal session. It will appear here under its own name, ready for shared work."),_("Connect an app",async()=>{d.tab="connect",await C()},"primary"));if(r(t),n.append(e),t.nextCursor){let s=t.nextCursor,i=_("Show more sessions",async()=>{let o=await b(D("/sessions")+"?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});n.append(i)}return n.append(a("p",{class:"help"},"Connected means the app contacted Agent Intercom recently. It does not mean the model is currently working."),_("Refresh sessions",C)),n}function Xr(){let n=d.config.mcpUrl,e=D("");return a("div",{class:"grid"},a("section",{class:"card"},a("h2",{},"An app with remote MCP"),a("p",{},"In your app\u2019s connectors or MCP settings, add Agent Intercom using this address."),a("pre",{},n),_("Copy connector URL",()=>rt(n)),a("ol",{},a("li",{},"Add the connector in your app."),a("li",{},"Sign in to October and choose this workspace."),a("li",{},"Ask your app to check its Bus inbox or find connected sessions.")),a("p",{class:"help"},"Works with compatible Streamable HTTP MCP clients. Your app controls which conversations can use tools and whether an idle conversation can resume.")),a("section",{class:"card"},a("h2",{},"An app that asks for an API key"),a("p",{},"Use the same remote MCP URL. Create a separate key for each app so you can revoke it independently."),F([N("App connection name",{name:"name",required:!0,maxlength:100,placeholder:"My AI app"}).node,a("p",{class:"help"},"The app can read and share workspace messages, files, channels and tasks. A key expires after 90 days and cannot manage your account or members.")],"Create MCP key",async t=>{let r=await b(e+"/mcp-keys",{method:"POST",body:{name:t.get("name")}});tt("MCP connection key",r.token,`Paste this into your app\u2019s secret/API key field, or use Authorization: Bearer . It is shown once and expires ${B(r.expiresAt)}. Keep it out of chat, URLs and source control.`)}),a("p",{class:"help"},"Choose OAuth instead if your app offers it. Neither connection method can make an unsupported app resume an idle conversation.")),a("section",{class:"card"},a("h2",{},"Another machine or automation"),a("p",{},"Install the Agent Intercom CLI on that machine, then run:"),a("pre",{},"agentintercom hosted login --server "+location.origin),a("p",{},"Open the link it prints, confirm the code and choose this workspace. For any app with a local MCP connection, run:"),a("pre",{},"agentintercom connect --hosted default"),a("p",{},"Or start a terminal session with native message wake:"),a("pre",{},`agentintercom session start claude --hosted default agentintercom session start codex --hosted default`),a("p",{class:"help"},"Choose the app you use. Keep its terminal open; normal app permissions apply. Codex native wake is experimental."),a("details",{},a("summary",{},"Create a credential for custom automation"),F([N("Device name",{name:"name",required:!0,maxlength:100,placeholder:"My laptop"}).node],"Create device credential",async t=>{let r=await b(D("/devices"),{method:"POST",body:{name:t.get("name")}});tt("Device credential",r.token,"Save this in your device\u2019s secret store. It is shown only once. Anyone with it can join sessions to this workspace as you.")}),a("p",{class:"help"},"Keep credentials out of chat messages, shell history and source control."))))}async function Qr(){let n=D(""),[e,t]=await Promise.all([b(D("/members")),b(D("/devices"))]),r=d.workspace.role!=="member",s=a("section",{class:"card"},a("h2",{},"People"));for(let l of e){let c=[];if(d.workspace.role==="owner"){let u=a("select",{"aria-label":`Role for ${l.email}`},["member","admin","owner"].map(h=>a("option",{value:h,selected:h===l.role},h)));c.push(u,_("Save role",async()=>{await b(D(`/members/${encodeURIComponent(l.userId)}`),{method:"PATCH",body:{role:u.value}}),await Y()}))}else c.push(a("span",{class:"badge"},l.role));(r||l.userId===d.user.id)&&c.push(_(l.userId===d.user.id?"Leave":"Remove",()=>te("Remove workspace access?",u=>a("div",{},a("p",{},`${l.email} will lose access and their connected sessions will be revoked.`),_("Remove access",async()=>{await b(D(`/members/${encodeURIComponent(l.userId)}`),{method:"DELETE"}),u(),await Y()},"danger"))),"danger")),s.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.email),a("p",{class:"help"},`Joined ${B(l.joinedAt)}`)),a("div",{class:"actions"},c)))}let i=a("section",{class:"card"},a("h2",{},"Apps & devices"));t.length||i.append(a("p",{class:"muted"},"No devices connected yet."));for(let l of t){let c=!!l.revokedAt,u=[];l.kind==="mcp_key"&&l.userId===d.user.id&&u.push(_("Replace key",()=>te("Replace this MCP key?",h=>a("div",{},a("p",{},`The old key for ${l.name} will stop working immediately. The replacement keeps its session inbox and pending messages. Update the key in your app after replacing it.`),_("Create replacement key",async()=>{let f=await b(n+"/mcp-keys",{method:"POST",body:{name:l.name,replaceDeviceId:l.id}});h(),tt("Replacement MCP key",f.token,`Update your app\u2019s secret/API key field. Shown once; expires ${B(f.expiresAt)}. If this value is lost, replace it again from Members & devices.`)},"primary"))))),!c&&(r||l.userId===d.user.id)&&u.push(_("Revoke",()=>te("Revoke connection?",h=>a("div",{},a("p",{},`${l.name} will stop receiving access to this workspace.`),_("Revoke connection",async()=>{await b(n+`/devices/${encodeURIComponent(l.id)}`,{method:"DELETE"}),h(),await C()},"danger"))),"danger")),i.append(a("div",{class:"row"},a("div",{class:"details"},a("strong",{},l.name),a("p",{class:"help"},`${l.kind==="mcp"?"MCP app":l.kind==="mcp_key"?"MCP key":"Device"} \xB7 ${c?"Revoked":`Expires ${B(l.expiresAt)}`}`)),a("div",{class:"actions"},u)))}let o=a("div",{},s,i);if(r){let l=N("Teammate\u2019s email",{name:"email",type:"email",required:!0}),c=F([l.node],"Create invitation",async f=>{let g=await b(D("/invites"),{method:"POST",body:{email:f.get("email"),role:"member"}});tt("Share this invitation",`${location.origin}/app#invite=${encodeURIComponent(g.token)}`,`Share this link with ${g.email}. It expires ${B(g.expiresAt)} and can be accepted once by that address. October has not sent an email.`)}),u=await b(D("/invites")),h=a("section",{class:"card"},a("h2",{},"Invite a teammate"),c);for(let f of u)h.append(a("div",{class:"row"},a("div",{},a("strong",{},f.email),a("p",{class:"help"},`Expires ${B(f.expiresAt)}`)),_("Revoke invitation",async()=>{await b(D(`/invites/${encodeURIComponent(f.id)}`),{method:"DELETE"}),await C()},"danger")));o.append(h)}return o}async function Zr(){if(d.config=await b("/api/config"),!d.config.authUrl||!d.config.authPublicKey)throw new Error("Sign-in is not configured on this server. Contact its operator.");d.auth=new Rt({url:d.config.authUrl+"/auth/v1",headers:{apikey:d.config.authPublicKey,Authorization:`Bearer ${d.config.authPublicKey}`},storageKey:"agentintercom-auth",flowType:"pkce",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0});let{data:n,error:e}=await d.auth.getSession();if(e)throw e;n.session?await Y():At(),d.auth.onAuthStateChange((t,r)=>{t==="SIGNED_OUT"&&setTimeout(()=>{d.generation++,At()},0),t==="SIGNED_IN"&&r&&!d.user&&setTimeout(()=>Re(null,Y),0)})}Zr().catch(n=>{le.replaceChildren(a("main",{id:"main",class:"auth-wrap"},ce(),a("section",{class:"card consent"},a("h1",{},"Couldn\u2019t open your workspace"),a("p",{},n.message),_("Try again",()=>location.reload()))))});async function es(){let n=d.generation,e=D(""),[t,r]=await Promise.all([b(e+"/sessions"),b(e+"/members")]),s=t.sessions,i=new Map(s.map(S=>["agent:"+S.id,S.displayName]));for(let S of r)i.set("human:"+S.userId,S.email);let o=(S,m)=>i.get(S+":"+m)||m,l=new URLSearchParams;d.conversationAgent&&l.set("agentId",d.conversationAgent),d.search&&l.set("query",d.search);let c=a("select",{"aria-label":"Filter by session",onchange:S=>{d.conversationAgent=S.target.value,Re(null,C)}},a("option",{value:""},"All sessions"),s.map(S=>a("option",{value:S.id,selected:S.id===d.conversationAgent},S.displayName))),u=N("Search messages",{name:"query",value:d.search,type:"search",maxlength:256}),h=F([u.node],"Search",async S=>{d.search=S.get("query").trim(),await C()}),f=a("div",{},a("div",{class:"card grid"},a("label",{},"Conversation",c),h)),g=a("div",{class:"conversation-list","aria-label":"Workspace messages"}),p=new Map,k=!0,E=!1;Ze.push(()=>{k=!1});let A=S=>S.responseMessageId?"Replied":S.state==="acknowledged"?S.toKind==="human"?"Read":"Acknowledged":S.state==="delivered"?"Delivered to app":S.state==="expired"?"Expired":"Waiting for delivery",O=(S,m=!1)=>{let I=m?[...S.messages].reverse():S.messages;for(let T of I){let x=JSON.stringify(T),q=p.get(T.id);if(q?.fingerprint===x)continue;let G=a("article",{class:"card",id:T.id},a("div",{class:"row"},a("div",{class:"details"},a("strong",{},o(T.fromKind,T.from))," \u2192 ",o(T.toKind,T.to),a("p",{class:"help"},B(T.createdAt))),a("span",{class:"badge"},A(T))),a("p",{class:"message"},T.body));G.append(Sr(e,T.body,T.context)),T.responseTo&&G.append(a("p",{class:"help"},"Reply to ",a("code",{},T.responseTo))),T.toKind==="human"&&T.to===d.user.id&&T.state!=="acknowledged"&&T.state!=="expired"&&G.append(_("Mark read",async()=>{await b(e+"/messages/read",{method:"POST",body:{messageIds:[T.id]}}),await C()},"subtle-button")),q?q.node.replaceWith(G):m?g.prepend(G):g.append(G),p.set(T.id,{fingerprint:x,node:G})}},R=await b(e+"/messages?"+l);O(R);let v=l.toString(),P=setInterval(async()=>{if(d.generation!==n){clearInterval(P);return}if(!(!k||E||document.hidden)){E=!0;try{let S=await b(e+"/messages?"+v);k&&(S.messages.length&&g.querySelector(".empty")?.remove(),O(S,!0))}catch(S){k&&H("Conversation refresh failed. "+S.message,!0)}finally{E=!1}}},5e3);if(Ze.push(()=>clearInterval(P)),R.messages.length||g.append(a("section",{class:"card empty"},a("h2",{},d.search?"No matching messages":"Start a conversation"),a("p",{class:"muted"},d.search?"Try a different phrase or session.":"Choose a connected session below and send it a request."))),f.append(g),R.nextCursor){let S=R.nextCursor,m=_("Earlier messages",async()=>{l.set("before",S);let I=await b(e+"/messages?"+l);O(I),S=I.nextCursor,S||m.remove()});f.append(m)}if(s.length){let S=a("select",{name:"to",required:!0},s.map(q=>a("option",{value:q.id,selected:q.id===d.conversationAgent},q.displayName+(q.reachable?"":" \xB7 offline")))),m=N("Your message",{name:"body",multiline:!0,required:!0,maxlength:65536,placeholder:"What would you like this session to help with?"}),I=crypto.randomUUID(),T="",x=F([a("label",{},"Send to",S),m.node,kr(e,m.input),a("p",{class:"help"},"Visible to workspace members. An MCP app may need you to resume it or ask it to check its inbox.")],"Send request",async q=>{let G=JSON.stringify([q.get("to"),q.get("body")]);T&&T!==G&&(I=crypto.randomUUID()),T=G,await b(e+"/messages",{method:"POST",body:{to:q.get("to"),body:q.get("body"),mode:"request",idempotencyKey:I}}),d.conversationAgent=q.get("to"),d.search="",H("Request saved. Delivery status will update when the app checks its inbox."),await C()});f.append(a("section",{class:"card"},a("h2",{},"Send a message"),x))}else f.append(_("Connect an app",async()=>{d.tab="connect",await C()},"primary"));return f.append(_("Refresh conversation",C)),f}async function ts(){let n=D(""),e=await b(n+"/tasks"),t=a("div"),r=a("div",{class:"grid"}),s=l=>{for(let c of l.tasks)r.append(a("article",{class:"card"},a("div",{class:"actions"},a("h2",{},c.title),a("span",{class:"badge"},c.status)),a("p",{class:"message"},c.description),c.claimedBy?a("p",{class:"help"},"Claimed by ",a("code",{},c.claimedBy)):a("p",{class:"help"},c.ready?"Ready for an agent to claim.":"Waiting for dependencies."),c.note?a("p",{},c.note):null,(c.recentProgress||[]).map(u=>a("p",{class:"help message"},`${u.kind}: ${u.text}`)),a("small",{},B(c.updatedAt))))};if(s(e),e.tasks.length||r.append(a("section",{class:"card empty"},a("h2",{},"Give the work a place to land."),a("p",{},"Create a task, then ask a connected session to claim it. Claims prevent two agents from taking the same work."))),t.append(r),e.nextCursor){let l=e.nextCursor,c=_("More tasks",async()=>{let u=await b(n+"/tasks?after="+encodeURIComponent(l));s(u),l=u.nextCursor,l||c.remove()});t.append(c)}let i=N("Task title",{name:"title",maxlength:256,required:!0}),o=N("Description",{name:"description",multiline:!0,maxlength:16384});return t.append(a("section",{class:"card"},a("h2",{},"New task"),F([i.node,o.node],"Create task",async l=>{await b(n+"/tasks",{method:"POST",body:{title:l.get("title"),description:l.get("description")}}),H("Task created. An agent can now claim it."),await C()}))),t}async function rs(){let n=D(""),e=await b(n+"/questions"),t=a("div"),r=s=>{for(let i of s.escalations){let o=N("Your answer",{name:"answer",multiline:!0,required:!0,maxlength:16384}),l=(i.options||[]).map(c=>_(c,()=>{o.input.value=c,o.input.focus()}));t.append(a("section",{class:"card"},a("h2",{class:"message"},i.question),a("p",{class:"help"},"From ",a("code",{},i.agentId)," \xB7 ",B(i.createdAt)),a("div",{class:"actions"},l),F([o.node],"Send answer",async c=>{await b(n+`/questions/${encodeURIComponent(i.id)}/answer`,{method:"POST",body:{answer:c.get("answer")}}),H("Answer saved for the requesting session."),await C()})))}};if(r(e),e.escalations.length||t.append(a("section",{class:"card empty"},a("h2",{},"Nothing waiting on you."),a("p",{class:"muted"},"When an agent asks for a decision, you can answer it here."))),e.nextCursor){let s=e.nextCursor,i=_("More questions",async()=>{let o=await b(n+"/questions?after="+encodeURIComponent(s));r(o),s=o.nextCursor,s||i.remove()});t.append(i)}return t.append(_("Refresh questions",C)),t}async function ss(){let n=d.generation,e=D(""),t=await b(e+"/channels"),r=t.find(m=>m.id===d.channelId)||t[0];r?.id!==d.channelId&&(d.threadId=""),d.channelId=r?.id||"";let s=()=>te("Create a channel",m=>F([N("Channel name",{name:"name",required:!0,maxlength:64,pattern:"[a-z0-9][a-z0-9_-]*",placeholder:"project-updates"}).node,N("Description",{name:"description",maxlength:2e3}).node,a("p",{class:"help"},"All workspace members and connected sessions can read this channel.")],"Create channel",async I=>{let T=await b(e+"/channels",{method:"POST",body:{name:I.get("name"),description:I.get("description")}});d.channelId=T.id,d.threadId="",d.channelSearch="",m(),await C()}));if(!r)return a("section",{class:"card empty"},a("h2",{},"Give a discussion its own space."),a("p",{},"Create a channel for a project or topic. Sessions can subscribe to receive new posts in their inbox."),_("Create a channel",s,"primary"));let i=a("select",{"aria-label":"Channel",onchange:m=>{d.channelId=m.target.value,d.threadId="",d.channelSearch="",Re(null,C)}},t.map(m=>a("option",{value:m.id,selected:m.id===r.id},"#"+m.name))),o=F([N("Search channel",{name:"query",type:"search",value:d.channelSearch,maxlength:256}).node],"Search posts",async m=>{d.channelSearch=m.get("query").trim(),d.threadId="",await C()}),l=a("div",{},a("section",{class:"card"},a("div",{class:"actions"},a("label",{},"Channel",i),_("New channel",s)),a("p",{},r.description),a("p",{class:"help"},`${r.subscribers} subscribed sessions. Ask a connected session to join #${r.name} using subscribe_channel to receive future notifications.`),o));d.threadId&&l.append(a("div",{class:"actions"},a("h2",{},"Thread"),_("Back to channel",async()=>{d.threadId="",await C()})));let c=new URLSearchParams({channelId:r.id});d.threadId&&c.set("threadId",d.threadId),d.channelSearch&&c.set("query",d.channelSearch);let[u,h,f]=await Promise.all([b(e+"/channel-posts?"+c),b(e+"/members"),b(e+"/sessions")]),g=new Map(h.map(m=>["human:"+m.userId,m.email]));for(let m of f.sessions)g.set("agent:"+m.id,m.displayName);let p=a("div",{class:"conversation-list","aria-label":"Channel posts"}),k=new Map,E=(m,I=!1)=>{let T=I?[...m.posts].reverse():m.posts;for(let x of T){let q=JSON.stringify(x),G=k.get(x.id);if(G?.fingerprint===q)continue;let ve=a("article",{class:"card"},a("div",{class:"row"},a("strong",{},g.get(x.authorKind+":"+x.authorId)||x.authorId),a("small",{},B(x.createdAt))),a("p",{class:"message"},x.body));ve.append(Sr(e,x.body)),(!d.threadId||d.channelSearch)&&ve.append(_(x.replies?`${x.replies} ${x.replies===1?"reply":"replies"}`:"Open thread",async()=>{d.threadId=x.threadId||x.id,d.channelSearch="",await C()})),G?G.node.replaceWith(ve):I?p.prepend(ve):p.append(ve),k.set(x.id,{fingerprint:q,node:ve})}};if(E(u),u.posts.length||p.append(a("section",{class:"card empty"},a("p",{},d.channelSearch?"No matching posts.":"No posts yet. Start the discussion below."))),l.append(p),u.nextCursor){let m=u.nextCursor,I=_("Earlier posts",async()=>{let T=new URLSearchParams(c);T.set("before",m);let x=await b(e+"/channel-posts?"+T);E(x),m=x.nextCursor,m||I.remove()});l.append(I)}let A=N(d.threadId?"Your reply":"Your post",{name:"body",multiline:!0,required:!0,maxlength:65536}),O=crypto.randomUUID(),R="";l.append(a("section",{class:"card"},F([A.node,kr(e,A.input),a("p",{class:"help"},"Shared with the workspace. Subscribed sessions receive an inbox notification; delivery does not mean a model has acted.")],d.threadId?"Reply in thread":"Post to channel",async m=>{let I=m.get("body");R&&R!==I&&(O=crypto.randomUUID()),R=I,await b(e+"/channel-posts",{method:"POST",body:{channelId:r.id,body:I,threadId:d.threadId||void 0,idempotencyKey:O}}),d.channelSearch="",await C()})));let v=!0,P=!1,S=setInterval(async()=>{if(d.generation!==n){clearInterval(S);return}if(!(!v||P||document.hidden)){P=!0;try{let m=await b(e+"/channel-posts?"+c);v&&(m.posts.length&&p.querySelector(".empty")?.remove(),E(m,!0))}catch(m){v&&H("Channel refresh failed. "+m.message,!0)}finally{P=!1}}},5e3);return Ze.push(()=>{v=!1,clearInterval(S)}),l}async function ns(){let n=D("/billing"),e=await b(n),t=e.paidUntil&&Date.parse(e.paidUntil)>Date.now(),r=!t&&Date.parse(e.trialEndsAt)>Date.now(),s=f=>new Intl.NumberFormat(void 0,{style:"currency",currency:e.currency.toUpperCase(),maximumFractionDigits:0}).format(f/100),i=f=>f>=1024**3?`${(f/1024**3).toFixed(1)} GiB`:`${(f/1024**2).toFixed(1)} MiB`,o=f=>Number(f).toLocaleString(),l=a("div");e.configured&&!e.live&&l.append(a("p",{class:"notice-inline",role:"status"},"Test billing \u2014 this service is not accepting real payments.")),_e.has("billing")&&l.append(a("p",{class:"notice-inline"},"Returned from billing. Check payment status below; returning from checkout does not confirm a payment.")),l.append(a("section",{class:"card"},a("h2",{},t?"Paid workspace":r?"Workspace trial":"Hosting inactive"),a("p",{},t?`Hosting paid through ${B(e.paidUntil)}.`:r?`Trial ends ${B(e.trialEndsAt)}.`:"New work is paused. Existing history remains available."),e.cancelAtPeriodEnd?a("p",{},`Your subscription will end on ${B(e.currentPeriodEnd)}. It will not renew.`):null,["past_due","unpaid","incomplete"].includes(e.status)?a("p",{class:"notice-inline"},"Your subscription needs payment attention. Open payment settings to review it."):null));let c=a("div",{class:"actions"});async function u(f,g){let p=await b(n+"/"+f,{method:"POST",body:g,timeout:3e4}),k=new URL(p.url);if(k.protocol!=="https:"||k.username||k.password||!["checkout.stripe.com","billing.stripe.com"].includes(k.host))throw new Error("Payment destination could not be verified.");location.assign(k.href)}e.canManage&&e.configured&&(["none","canceled","incomplete_expired"].includes(e.status)?c.append(_(`${s(e.monthlyPriceCents)} / month`,()=>u("checkout",{interval:"month"}),"primary"),_(`${s(e.annualPriceCents)} / year`,()=>u("checkout",{interval:"year"}))):c.append(_("Payment settings & cancellation",()=>u("portal"),"primary")),c.append(_("Check payment status",async()=>{await b(n+"/refresh",{method:"POST",timeout:3e4}),await C(),H("Payment status checked.")})),e.pendingCheckout&&c.append(_("Close unfinished checkout",async()=>{await b(n+"/cancel-checkout",{method:"POST",timeout:3e4}),await C()}))),l.append(a("section",{class:"card"},a("h2",{},`${s(e.monthlyPriceCents)} per workspace per month`),a("p",{},`Or ${s(e.annualPriceCents)} per year, billed annually. Applicable tax is shown at checkout. Includes 5 people, 50 concurrent sessions, 100,000 new deliveries per calendar month and 5 GiB of files.`),a("p",{class:"help"},"Includes 25 GiB of uploads and 25 GiB of downloads per calendar month. Each file can be up to 16 MiB. Model and compute costs are separate. No automatic usage overage charges."),e.pendingCheckout?a("p",{class:"notice-inline"},`An unfinished ${e.pendingInterval==="year"?"annual":"monthly"} checkout is saved. Choosing the same plan resumes it; choosing the other plan closes it before starting another.`):null,e.configured?e.canManage?c:a("p",{},"Only a workspace owner can manage payments."):a("p",{},"Paid hosting is not available on this service yet.")));let h=a("section",{class:"card"},a("h2",{},"Included usage"),a("p",{class:"help"},t?`Delivery and file-transfer counters reset each calendar month (UTC). Current month: ${e.month}.`:"The trial includes 2,000 new deliveries in total, 256 MiB of files and 1 GiB in each transfer direction per calendar month."));for(let[f,g,p,k]of[["New deliveries",e.deliveries,e.deliveryLimit,o],["People",e.members,e.memberLimit,o],["Concurrent sessions",e.sessions,e.sessionLimit,o],["Retained coordination data",e.retainedBytes||0,e.textLimit||5*1024**3,i],["File storage",e.fileBytes,e.fileStorageLimit,i],["Uploads this month",e.uploadedBytes,e.fileTransferLimit,i],["Downloads this month",e.downloadedBytes,e.fileTransferLimit,i]])h.append(a("div",{class:"usage"},a("div",{class:"row"},a("span",{},f),a("span",{},`${k(g)} / ${k(p)}`)),a("progress",{max:p,value:Math.min(g,p),"aria-label":f})));return h.append(a("p",{class:"help"},"A new message counts once per recipient. Channel notifications count per subscriber. Retries, acknowledgements and replies do not consume delivery allowance.")),l.append(h),l}async function is(){let n=D(""),e=d.workspace,t=await b(n+"/storage"),r=d.workspace.role==="owner",s=a("div",{},a("section",{class:"card"},a("h2",{},"Retention"),a("p",{},"Completed conversations, completed tasks, resolved questions and quiet channel threads are eligible for removal after 90 days. Unfinished work and linked records that still need each other remain. Files stay until you delete them."),a("p",{class:"help"},"The notification log keeps roughly the latest 100,000 events or 90 days, whichever is shorter. This does not delete the corresponding messages or tasks. New work pauses when estimated retained coordination data reaches 5 GiB; final replies and acknowledgements remain available.")));if(!r)return s.append(a("p",{},"A workspace owner can pause sessions, export data and prune completed history.")),s;e.deleting?s.append(a("section",{class:"card"},a("h2",{},"Deletion in progress"),a("p",{},"Sessions and purchases are stopped. Billing must be closed before the remaining data can be deleted. The service retries automatically; you can also retry below."))):s.append(a("section",{class:"card"},a("h2",{},d.workspace.paused?"Sessions paused":"Pause sessions for an export"),a("p",{},"Pausing disconnects all sessions and prevents new connections while you export. Members can still read history here. Resume and reconnect your apps when finished. Pausing does not cancel billing."),_(d.workspace.paused?"Resume sessions":"Pause sessions",()=>te(d.workspace.paused?"Resume this workspace?":"Disconnect workspace sessions?",o=>a("div",{},a("p",{},d.workspace.paused?"Connected apps can rejoin when hosting is active.":"Every connected session will lose its current connection. Queued work and history are retained."),_("Confirm",async()=>{await b(n+"/pause",{method:"POST",body:{paused:!d.workspace.paused}}),o(),await Y()},"primary")))))),s.append(a("section",{class:"card"},a("h2",{},"Download a portable archive"),a("p",{},"Includes retained messages, tasks, questions, channels, output values and file bytes. Does not contain account credentials or payment details. Pause sessions first so the archive is consistent."),a("p",{class:"help"},"Portable archives are limited to 64 MiB, including encoded files. Larger workspaces need an operator-assisted database and file export. File bytes in an archive count toward download allowance. Store the download privately."),_("Download workspace archive",async()=>{let l=await(await Ct(n+"/export")).blob(),c=URL.createObjectURL(l),u=a("a",{href:c,download:"agentintercom-workspace.json"});document.body.append(u),u.click(),u.remove(),setTimeout(()=>URL.revokeObjectURL(c),3e4)})));let i=N("Remove eligible history completed before",{name:"before",type:"date",required:!0,value:new Date(Date.now()-90*864e5).toISOString().slice(0,10),max:new Date(Date.now()-2*864e5).toISOString().slice(0,10)});return s.append(a("section",{class:"card"},a("h2",{},"Prune completed history"),a("p",{},"Review a preview before deleting anything. Export first if you need to retain a copy. This does not remove unfinished work, files or your subscription."),F([i.node],"Preview cleanup",async o=>{let l=new Date(o.get("before")+"T00:00:00Z").toISOString(),c=await b(n+"/prune",{method:"POST",body:{before:l,execute:!1},timeout:3e4});te("Delete eligible history?",u=>a("div",{},a("p",{},"This permanently deletes eligible records before the selected date. Counts may change if work finishes before confirmation."),a("pre",{},JSON.stringify(c.records,null,2)),_("Delete eligible history",async()=>{await b(n+"/prune",{method:"POST",body:{before:l,execute:!0},timeout:3e4}),u(),await C(),H("Completed history pruned.")},"danger")))}))),s.append(a("section",{class:"card"},a("h2",{},"Retained records"),a("p",{class:"help"},"Payload estimates below exclude database indexes and some record overhead; billing usage includes a per-record estimate."),(t.records||[]).map(o=>a("div",{class:"row"},a("span",{},`${o.recordType} \xB7 ${o.state}`),a("span",{},Number(o.count).toLocaleString()))))),s.append(a("section",{class:"card"},a("h2",{},"Delete workspace"),a("p",{},"Permanently removes this workspace for everyone, including messages, unfinished work, files and connections. Its hosting subscription ends immediately; unused time is not automatically refunded. Export first if you need a copy."),a("p",{class:"help"},"Your October account and other workspaces remain. Minimal payment references are retained for support. Private backups expire on the operator\u2019s retention schedule."),_(e.deleting?"Retry workspace deletion":"Delete workspace",()=>te("Permanently delete this workspace?",o=>{let l=N("Type the workspace name to confirm",{name:"confirmation",required:!0,autocomplete:"off"});return a("div",{},a("p",{},`This cannot be undone. Enter ${e.name} to confirm. Once requested, deletion continues even if this page closes.`),F([l.node],"Delete permanently",async c=>{if(c.get("confirmation")!==e.name)throw new Error("The workspace name does not match.");try{await b(n,{method:"DELETE",body:{confirmName:c.get("confirmation")},timeout:3e4})}catch(u){throw o(),await Y(),u}o(),await Y(),H("Workspace deleted.")}))}),"danger"))),s} diff --git a/web/src/app.js b/web/src/app.js index 141a947..29eb89b 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -126,11 +126,10 @@ function closePending(key) { delete pending[key]; sessionStorage.setItem(pending let modalCount = 0; function modal(title, build) { const headingId = `modal-title-${++modalCount}`; - const opener = document.activeElement; const dialog = el('dialog', { 'aria-labelledby': headingId }, el('h2', { id: headingId }, title)); const close = () => dialog.close(); dialog.append(build(close), el('div', { class: 'actions end' }, button('Close', close))); - dialog.addEventListener('close', () => { dialog.remove(); if (opener?.isConnected) opener.focus(); }); + dialog.addEventListener('close', () => dialog.remove()); document.body.append(dialog); dialog.showModal(); return dialog; } function secretDialog(title, value, description) {