UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

84 lines (83 loc) • 24.6 kB
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } } import{randomBytes}from"node:crypto";import{createServer}from"node:http";function processSingleton(key,create){let slot=Symbol.for(key),existing=Reflect.get(globalThis,slot);if(existing!==void 0)return existing;let created=create();return Reflect.set(globalThis,slot,created),created}var brandSlot=processSingleton("@code-yeongyu/senpi-ai:oauth-page-brand",()=>({current:void 0}));function configuredOAuthBrandName(){return brandSlot.current?.name}function escapeHtml(value){return value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function renderPage(options){let title=escapeHtml(options.title),heading=escapeHtml(options.heading),message=escapeHtml(options.message),details=options.details?escapeHtml(options.details):void 0,brand=brandSlot.current,logo=brand?.logo?`<img class="logo" src="${brand.logo}" alt="" />`:"",brandName=brand?`<div class="brand-name">${escapeHtml(brand.name)}</div>`:"";return`<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>${title}</title> <style> :root { --text: #fafafa; --text-dim: #a1a1aa; --page-bg: #09090b; --font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; } * { box-sizing: border-box; } html { color-scheme: dark; } body { margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 24px; background: var(--page-bg); color: var(--text); font-family: var(--font-sans); text-align: center; } main { width: 100%; max-width: 560px; display: flex; flex-direction: column; align-items: center; justify-content: center; } .logo { width: 72px; height: 72px; display: block; margin-bottom: 16px; } .brand-name { margin-bottom: 24px; font-size: 15px; font-weight: 600; letter-spacing: 0.02em; color: var(--text-dim); } h1 { margin: 0 0 10px; font-size: 28px; line-height: 1.15; font-weight: 650; color: var(--text); } p { margin: 0; line-height: 1.7; color: var(--text-dim); font-size: 15px; } .details { margin-top: 16px; font-family: var(--font-mono); font-size: 13px; color: var(--text-dim); white-space: pre-wrap; word-break: break-word; } </style> </head> <body> <main> ${logo} ${brandName} <h1>${heading}</h1> <p>${message}</p> ${details?`<div class="details">${details}</div>`:""} </main> </body> </html>`}function oauthSuccessHtml(message){return renderPage({title:"Authentication successful",heading:"Authentication successful",message})}function oauthErrorHtml(message,details){return renderPage({title:"Authentication failed",heading:"Authentication failed",message,details})}function formatThrownValue(value){return value instanceof Error?value.message||value.name:typeof value=="string"?value:String(value)}var ModelsError=class extends Error{constructor(code,message,options){super(withCauseDetail(message,options?.cause),options),this.name="ModelsError",this.code=code}};function withCauseDetail(message,cause){if(cause==null)return message;let detail=formatThrownValue(cause).trim();return!detail||message.includes(detail)?message:`${message}: ${detail}`}var _a,OAuthTokenEndpointError=class extends Error{constructor(message,status,facts={}){super(message),this.status=status,this.oauthError=facts.oauthError,this.credentialRefused=facts.credentialRefused??!1}},OAuthReauthorizationRequiredError=class extends OAuthTokenEndpointError{constructor(code,status){super(`OAuth refresh requires reauthorization (${code})`,status,{oauthError:code,credentialRefused:!0}),this.name="OAuthReauthorizationRequiredError",this.code=code}},OAuthClientConfigurationError=class extends OAuthTokenEndpointError{constructor(status){super("OAuth refresh failed: invalid client configuration (invalid_client)",status,{oauthError:"invalid_client"}),this.code="invalid_client",this.name="OAuthClientConfigurationError"}},TRANSPORT_CODES=new Set(["ConnectionRefused","FailedToOpenSocket","ConnectionClosed","ECONNREFUSED","ECONNRESET","ENOTFOUND","EAI_AGAIN","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET"]),MAX_CAUSE_LINKS=16;function oauthRefreshFailureCause(error){let seen=new Set;for(;typeof error=="object"&&error!==null&&!seen.has(error)&&seen.size<MAX_CAUSE_LINKS;){if(seen.add(error),Reflect.get(error,"name")==="TimeoutError")return"timeout";let code=Reflect.get(error,"code");if(typeof code=="string"&&TRANSPORT_CODES.has(code))return code==="ConnectionRefused"||code==="ECONNREFUSED"?"connection_refused":code.toLowerCase();let status=Reflect.get(error,"status");if(typeof status=="number"&&(status===408||status===429||status>=500&&status<600))return`http_${status}`;error=Reflect.get(error,"cause")}}function classifyOAuthRefreshFailure(error){return oauthRefreshFailureCause(error)===void 0?"permanent":"transient"}var UNAVAILABLE=Symbol.for("senpi.oauthRefreshUnavailable"),OAuthRefreshUnavailableError=class extends ModelsError{static{_a=UNAVAILABLE}constructor(provider,cause){super("oauth",`OAuth refresh failed for ${provider}`,{cause}),this[_a]=!0,this.name="OAuthRefreshUnavailableError"}};var ISSUER="https://auth.openai.com",DISCOVERY_URL=`${ISSUER}/.well-known/openid-configuration`,CACHE_MS=300*1e3,OpenAIIdTokenValidationError=class extends Error{constructor(message){super(`OpenAI ID token validation failed: ${message}`),this.name="OpenAIIdTokenValidationError"}};function object(value){if(typeof value!="object"||value===null||Array.isArray(value))throw new OpenAIIdTokenValidationError("expected an object");return value}function decode(value){if(!/^[A-Za-z0-9_-]+$/.test(value))throw new OpenAIIdTokenValidationError("invalid JWT encoding");return Uint8Array.from(atob(value.replace(/-/g,"+").replace(/_/g,"/")),char=>char.charCodeAt(0))}function createOpenAIIdTokenVerifier(deps){let discovery,jwks;async function loadKeys(signal,force=!1){if(!discovery||discovery.expires<=deps.now()){let response=await deps.fetch(DISCOVERY_URL,{signal});if(!response.ok)throw new OpenAIIdTokenValidationError("discovery request failed");let config=object(await response.json());if(typeof config.jwks_uri!="string"||new URL(config.jwks_uri).protocol!=="https:")throw new OpenAIIdTokenValidationError("invalid discovery JWKS URI");discovery={jwksUri:config.jwks_uri,expires:deps.now()+CACHE_MS},jwks=void 0}if(force||!jwks||jwks.expires<=deps.now()){let response=await deps.fetch(discovery.jwksUri,{signal});if(!response.ok)throw new OpenAIIdTokenValidationError("JWKS request failed");let data=object(await response.json());if(!Array.isArray(data.keys))throw new OpenAIIdTokenValidationError("invalid JWKS");jwks={keys:data.keys.map(object),expires:deps.now()+CACHE_MS}}return jwks.keys}return async(idToken,clientId,nonce,signal)=>{try{if(typeof idToken!="string")throw new OpenAIIdTokenValidationError("missing ID token");let parts=idToken.split(".");if(parts.length!==3)throw new OpenAIIdTokenValidationError("invalid JWT");let[headerPart,payloadPart,signaturePart]=parts,header=object(JSON.parse(new TextDecoder().decode(decode(headerPart))));if(header.alg!=="RS256"||typeof header.kid!="string"||!header.kid||header.crit!==void 0)throw new OpenAIIdTokenValidationError("unsupported signing header");let matchingKey=key2=>key2.kid===header.kid&&key2.kty==="RSA"&&(key2.alg===void 0||key2.alg==="RS256")&&(key2.use===void 0||key2.use==="sig"),keys=await loadKeys(signal);keys.some(matchingKey)||(keys=await loadKeys(signal,!0));let matches=keys.filter(matchingKey);if(matches.length!==1)throw new OpenAIIdTokenValidationError("signing key not found or ambiguous");let key=await crypto.subtle.importKey("jwk",matches[0],{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);if(!await crypto.subtle.verify("RSASSA-PKCS1-v1_5",key,decode(signaturePart),new TextEncoder().encode(`${headerPart}.${payloadPart}`)))throw new OpenAIIdTokenValidationError("invalid signature");let claims=object(JSON.parse(new TextDecoder().decode(decode(payloadPart))));if(claims.iss!==ISSUER)throw new OpenAIIdTokenValidationError("issuer mismatch");let audiences=typeof claims.aud=="string"?[claims.aud]:claims.aud;if(!Array.isArray(audiences)||!audiences.every(aud=>typeof aud=="string")||!audiences.includes(clientId))throw new OpenAIIdTokenValidationError("audience mismatch");if(typeof claims.exp!="number"||!Number.isFinite(claims.exp)||claims.exp<=deps.now()/1e3)throw new OpenAIIdTokenValidationError("expired or missing expiration");if(claims.nonce!==nonce)throw new OpenAIIdTokenValidationError("nonce mismatch");if(typeof claims.sub!="string"||!claims.sub.trim())throw new OpenAIIdTokenValidationError("missing subject");return{subject:claims.sub,issuer:ISSUER,...typeof claims.email=="string"?{email:claims.email}:{}}}catch(error){throw error instanceof OpenAIIdTokenValidationError?error:new OpenAIIdTokenValidationError("could not verify ID token")}}}var DEFAULT_WIRE_IDENTITY="senpi",wireIdentity=DEFAULT_WIRE_IDENTITY;function getWireIdentity(){return wireIdentity}function base64urlEncode(bytes){let binary="";for(let byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function generatePKCE(){let verifierBytes=new Uint8Array(32);crypto.getRandomValues(verifierBytes);let verifier=base64urlEncode(verifierBytes),data=new TextEncoder().encode(verifier),hashBuffer=await crypto.subtle.digest("SHA-256",data),challenge=base64urlEncode(new Uint8Array(hashBuffer));return{verifier,challenge}}var DYNAMIC_CLIENT_ID="dynamic_agent_client",UUID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,AUTHORIZE_URL="https://auth.openai.com/api/accounts/authorize",TOKEN_URL="https://auth.openai.com/api/accounts/oauth/token",DISCOVERY_URL2="https://auth.openai.com/.well-known/openid-configuration",RESOURCE="https://api.openai.com/v1",CALLBACK_HOST="127.0.0.1",CALLBACK_PORT=1455,CALLBACK_PATH="/auth/callback",REDIRECT_URI=`http://127.0.0.1:${CALLBACK_PORT}${CALLBACK_PATH}`,DIRECT_TOKEN_SCOPE="chatgpt.tokens.use.direct",SCOPE=`openid profile email offline_access resource.invoke ${DIRECT_TOKEN_SCOPE}`,EXPIRY_MARGIN_MS=180*1e3,OpenAIReauthorizationError=class extends Error{constructor(code){super(code==="invalid_account"?"The selected ChatGPT account needs an issued client ID and verified subject":code==="client_mismatch"?"ChatGPT reauthorization returned a different client ID":"ChatGPT reauthorization returned a different account"),this.name="OpenAIReauthorizationError",this.code=code}},OpenAIConsentDeclinedError=class extends Error{constructor(){super("ChatGPT consent declined"),this.code="consent_declined",this.name="OpenAIConsentDeclinedError"}},OpenAIPlanUsageNotEnabledError=class extends Error{constructor(){super("ChatGPT plan usage is not enabled. Enable ChatGPT plan usage or use an API key."),this.code="plan_usage_not_enabled",this.recovery=["enable_plan_usage","use_api_key"],this.name="OpenAIPlanUsageNotEnabledError"}};function randomValue(){return randomBytes(32).toString("base64url")}function authorizationResultFromCallback(url,expectedState,knownClient){let state=url.searchParams.get("state");if(!state)throw new Error("Missing OAuth state");if(state!==expectedState)throw new Error("OAuth state mismatch");let error=url.searchParams.get("error");if(error==="access_denied")throw new OpenAIConsentDeclinedError;if(error)throw new Error(`ChatGPT authorization failed: ${error}`);let code=url.searchParams.get("code");if(!code)throw new Error("Missing authorization code");let suppliedClientId=url.searchParams.get("client_id");if(knownClient?.purpose==="reauthorize"&&suppliedClientId!==null&&suppliedClientId!==knownClient.clientId)throw new OpenAIReauthorizationError("client_mismatch");let callbackClientId=suppliedClientId?.trim();if(knownClient?.purpose==="consent"&&callbackClientId&&callbackClientId!==knownClient.clientId)throw new Error("ChatGPT consent callback client ID mismatch");let clientId=knownClient?.clientId??callbackClientId;if(!clientId)throw new Error("OpenAI OAuth registration callback did not contain an issued client ID");return{code,clientId}}function authorizationResultFromManualInput(input,expectedState,redirectUri,knownClient){let url;try{url=new URL(input.trim())}catch{throw new Error("Paste the full callback URL from the browser")}let expected=new URL(redirectUri);if(url.origin!==expected.origin||url.pathname!==expected.pathname)throw new Error(`The pasted callback URL must start with ${redirectUri}`);return authorizationResultFromCallback(url,expectedState,knownClient)}function sendHtml(response,status,body){response.writeHead(status,{"Content-Type":"text/html; charset=utf-8"}),response.end(body)}function startCallbackServer(expectedState,preferredPort,knownClient){return new Promise((resolve,reject)=>{let redirectUri=REDIRECT_URI,resolveResult,rejectResult,result=new Promise((resolveAuthorization,rejectAuthorization)=>{resolveResult=resolveAuthorization,rejectResult=rejectAuthorization}),server=createServer((request,response)=>{try{let url=new URL(request.url||"",redirectUri);if(url.pathname!==CALLBACK_PATH){sendHtml(response,404,oauthErrorHtml("Callback route not found."));return}let authorizationResult;try{authorizationResult=authorizationResultFromCallback(url,expectedState,knownClient)}catch(error){let message=error instanceof Error?error.message:"Invalid callback";sendHtml(response,400,oauthErrorHtml(message)),(error instanceof OpenAIReauthorizationError||url.searchParams.get("state")===expectedState&&url.searchParams.has("error"))&&rejectResult(error instanceof Error?error:new Error(message));return}sendHtml(response,200,oauthSuccessHtml("ChatGPT authentication completed. You can close this window.")),resolveResult(authorizationResult)}catch{sendHtml(response,500,oauthErrorHtml("Internal error while processing the callback."))}}),onListening=()=>{server.removeListener("error",onBindError),server.removeListener("error",reject);let address=server.address();if(!address||typeof address=="string"){server.close(),reject(new Error("OpenAI OAuth callback server did not bind to TCP"));return}redirectUri=`http://${CALLBACK_HOST}:${address.port}${CALLBACK_PATH}`,server.on("error",rejectResult),resolve({server,result,redirectUri})},onBindError=error=>{if(server.removeListener("listening",onListening),error.code!=="EADDRINUSE"){reject(error);return}server.once("error",reject),server.listen(0,CALLBACK_HOST,onListening)};server.once("error",onBindError),server.listen(preferredPort,CALLBACK_HOST,onListening)})}function tokenErrorCode(value){if(typeof value!="object"||value===null||Array.isArray(value))return;let error=Reflect.get(value,"error");if(typeof error=="string")return error;let code=Reflect.get(value,"code");if(typeof code=="string")return code;let type=Reflect.get(value,"type");return tokenErrorCode(error)??(typeof type=="string"?type:void 0)}async function requestToken(body,signal,fetchToken){let response=await fetchToken(TOKEN_URL,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body,signal});if(!response.ok){let responseBody=await response.text().catch(()=>""),error=new OAuthTokenEndpointError(`OpenAI OAuth token request failed (${response.status}): ${responseBody||response.statusText}`,response.status);if(body.get("grant_type")==="refresh_token"&&classifyOAuthRefreshFailure(error)==="permanent"){let code;try{let parsed=JSON.parse(responseBody);code=tokenErrorCode(parsed)}catch{}switch(code){case"invalid_grant":case"invalid_refresh_token":case"token_expired":case"refresh_token_expired":case"refresh_token_invalidated":case"refresh_token_reused":throw new OAuthReauthorizationRequiredError(code,response.status);case"invalid_client":throw new OAuthClientConfigurationError(response.status)}}throw error}let data=await response.json();if(typeof data!="object"||data===null||Array.isArray(data))throw new Error("OpenAI OAuth token response must be an object");return data}function requireTokenString(value,field){if(typeof value!="string"||value.trim().length===0)throw new Error(`OpenAI OAuth token response has invalid ${field}`);return value}function credentialFromTokenResponse(token,clientId,now){let access=requireTokenString(token.access_token,"access_token"),refresh=requireTokenString(token.refresh_token,"refresh_token"),scope=requireTokenString(token.scope,"scope");if(typeof token.expires_in!="number"||!Number.isFinite(token.expires_in)||token.expires_in<=0)throw new Error("OpenAI OAuth token response has invalid expires_in");let scopes=scope.trim().split(/\s+/).filter(Boolean);return{type:"oauth",access,refresh,expires:now()+token.expires_in*1e3-EXPIRY_MARGIN_MS,clientId,scopes,planUsageEnabled:scopes.includes(DIRECT_TOKEN_SCOPE)}}async function exchangeAuthorizationCode(code,verifier,clientId,redirectUri,signal,nonce,deps,verifyIdToken){let token=await requestToken(new URLSearchParams({grant_type:"authorization_code",client_id:clientId,code,code_verifier:verifier,redirect_uri:redirectUri,resource:RESOURCE}),signal,deps.fetch),identity=await verifyIdToken(token.id_token,clientId,nonce,signal);return{...credentialFromTokenResponse(token,clientId,deps.now),...identity,idToken:token.id_token}}async function refreshAccessToken(credential,signal,deps){let clientId=credential.clientId;if(typeof clientId!="string"||clientId.trim().length===0)throw new Error("Stored OpenAI OAuth credential does not contain an issued client ID; reconnect ChatGPT");let token=await requestToken(new URLSearchParams({grant_type:"refresh_token",client_id:clientId,refresh_token:credential.refresh,resource:RESOURCE}),signal,deps.fetch);return{...credential,...credentialFromTokenResponse(token,clientId,deps.now)}}async function revokeSession(credential,options){let unconfirmed={status:"remote_revocation_unconfirmed"};if(!credential.refresh||typeof credential.clientId!="string"||!credential.clientId.trim())return unconfirmed;let signal=AbortSignal.any([...options?.signal?[options.signal]:[],AbortSignal.timeout(15e3)]),sleep=options?.sleep??(milliseconds=>new Promise((resolve,reject)=>{signal.throwIfAborted();let onAbort=()=>{clearTimeout(timer),reject(signal.reason)},timer=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},milliseconds);signal.addEventListener("abort",onAbort,{once:!0})})),endpoint,delays=[250,1e3];for(let attempt=0;attempt<=delays.length;attempt++)try{if(signal.throwIfAborted(),attempt>0&&await sleep(delays[attempt-1]),!endpoint){let discovery=await fetch(DISCOVERY_URL2,{signal,redirect:"error"});if(!discovery.ok){if(discovery.status>=500)continue;return unconfirmed}let metadata=await discovery.json();if(typeof metadata!="object"||metadata===null||!("revocation_endpoint"in metadata)||typeof metadata.revocation_endpoint!="string")return unconfirmed;let url=new URL(metadata.revocation_endpoint);if(url.protocol!=="https:"||url.username||url.password)return unconfirmed;endpoint=url.href}let response=await fetch(endpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:credential.refresh,token_type_hint:"refresh_token",client_id:credential.clientId}),signal,redirect:"error"});if(response.status===200)return{status:"revoked"};if(response.status<500)return unconfirmed}catch{if(signal.aborted)return unconfirmed}return unconfirmed}function agentHostId(deviceId){if(!deviceId||!UUID_PATTERN.test(deviceId))throw new Error("Sign in with ChatGPT requires a device ID (UUID) for this installation");return`urn:uuid:${deviceId.toLowerCase()}`}async function loginOpenAIChatGPT(interaction,options,deps,verifyIdToken){let existing=options?.reauthorize;if(existing&&(typeof existing.clientId!="string"||!existing.clientId.trim()||existing.clientId===DYNAMIC_CLIENT_ID||typeof existing.subject!="string"||!existing.subject.trim()))throw new OpenAIReauthorizationError("invalid_account");let pendingClientId=existing?.clientId,hostId=agentHostId(options?.getDeviceId?.()),consentClientId=options?.planUsageConsent?.clientId;if(options?.planUsageConsent&&(!consentClientId?.trim()||consentClientId===DYNAMIC_CLIENT_ID))throw new Error("Enabling ChatGPT plan usage requires the saved issued client ID");let knownClient=pendingClientId?{clientId:pendingClientId,purpose:"reauthorize"}:consentClientId?{clientId:consentClientId,purpose:"consent"}:void 0,{verifier,challenge}=await generatePKCE(),state=randomValue(),nonce=randomValue(),callback;try{callback=await startCallbackServer(state,options?.preferredCallbackPort??CALLBACK_PORT,knownClient)}catch(error){interaction.notify({type:"info",message:`Could not listen on ${REDIRECT_URI}; paste the final redirect URL to continue. ${error instanceof Error?error.message:String(error)}`})}let redirectUri=callback?.redirectUri??REDIRECT_URI,authorizationUrl=new URL(AUTHORIZE_URL);authorizationUrl.search=new URLSearchParams({client_id:pendingClientId??DYNAMIC_CLIENT_ID,ext_agent_host_id:hostId,response_type:"code",redirect_uri:redirectUri,resource:RESOURCE,scope:SCOPE,state,code_challenge:challenge,code_challenge_method:"S256",nonce}).toString(),existing?(existing.idToken&&authorizationUrl.searchParams.set("id_token_hint",existing.idToken),existing.email&&authorizationUrl.searchParams.set("login_hint",existing.email)):authorizationUrl.searchParams.set("agent_name_hint",options?.appName??configuredOAuthBrandName()??getWireIdentity()),consentClientId&&(authorizationUrl.searchParams.set("client_id",consentClientId),authorizationUrl.searchParams.set("prompt","consent")),interaction.notify({type:"auth_url",url:authorizationUrl.toString(),instructions:"Complete sign-in in your browser. If the callback does not complete, paste the final redirect URL here."});let manualAbort=new AbortController,manualCode=interaction.prompt({type:"manual_code",message:"Complete login in your browser, or paste the final redirect URL here:",placeholder:redirectUri,signal:AbortSignal.any([manualAbort.signal,interaction.signal])}).then(input=>authorizationResultFromManualInput(input,state,redirectUri,knownClient));try{let result=await(callback?Promise.race([callback.result,manualCode]):manualCode);interaction.notify({type:"progress",message:"Exchanging authorization code for tokens..."});let credential=await exchangeAuthorizationCode(result.code,verifier,result.clientId,redirectUri,interaction.signal,nonce,deps,verifyIdToken);if(existing&&credential.subject!==existing.subject)throw new OpenAIReauthorizationError("subject_mismatch");return credential}catch(error){throw interaction.signal.aborted?new Error("Login cancelled"):error}finally{manualAbort.abort(),callback?.server.close(),callback?.server.closeAllConnections()}}function createOpenAIChatGPTOAuth(dependencies={}){let deps={fetch:dependencies.fetch??((url,init)=>fetch(url,init)),now:dependencies.now??(()=>Date.now())},verifyIdToken=createOpenAIIdTokenVerifier(deps);return{name:"OpenAI (ChatGPT subscription)",isSubscription:!0,loginLabel:"Sign in with ChatGPT",login:(interaction,options)=>loginOpenAIChatGPT(interaction,options,deps,verifyIdToken),refresh:(credential,signal)=>refreshAccessToken(credential,signal,deps),revoke:revokeSession,async check({credential}){if(!(!credential?.access||!credential.refresh||credential.signedOut===!0))return{type:"oauth",source:"OAuth"}},async toAuth(credential){if(credential.planUsageEnabled===!1||!credential.scopes?.includes(DIRECT_TOKEN_SCOPE))throw new OpenAIPlanUsageNotEnabledError;return{apiKey:credential.access}}}}var openaiChatGPTOAuth=createOpenAIChatGPTOAuth();export{createOpenAIChatGPTOAuth,openaiChatGPTOAuth};