limixbot 0.3.151 → 0.3.152
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{ActivityPanel-CF1_YqWK.js → ActivityPanel-B80KWmOu.js} +1 -1
- package/dist/assets/{App-C105qZ2Q.js → App-kvV7NiY3.js} +8 -8
- package/dist/assets/{AppEventEditor-Baqu8KL7.js → AppEventEditor-bP6260DO.js} +1 -1
- package/dist/assets/{BotSettingsDialog-7Mp_GgGa.js → BotSettingsDialog-1KPW5yRw.js} +1 -1
- package/dist/assets/{BrowserPanel-CEokTHdk.js → BrowserPanel-rE5QhcPZ.js} +1 -1
- package/dist/assets/{BrowserProfilesManager-D5p3tzU_.js → BrowserProfilesManager-Bki0q9TN.js} +1 -1
- package/dist/assets/{CloudAddDialog-bQrip-Jy.js → CloudAddDialog-mQKspNDc.js} +1 -1
- package/dist/assets/{ComputerFilesPane-BCu5Rj8d.js → ComputerFilesPane-B-pkuW4h.js} +1 -1
- package/dist/assets/{ComputerPanel-CczHIs03.js → ComputerPanel-BsKZo2VK.js} +2 -2
- package/dist/assets/{DataPanel-Bk3L3TrE.js → DataPanel-Dh1tnzh6.js} +1 -1
- package/dist/assets/{GrokMoveDialog-CnQiC3hB.js → GrokMoveDialog-CHgRlZj-.js} +1 -1
- package/dist/assets/{InspectorPanel-DUSlsD3M.js → InspectorPanel-CKIE84Lx.js} +1 -1
- package/dist/assets/{KeyboardShortcutsModal-DnpyGtD2.js → KeyboardShortcutsModal-DPAw8Ad2.js} +1 -1
- package/dist/assets/{KnowledgePanel-BY5Mps13.js → KnowledgePanel-B6Tx5D3x.js} +1 -1
- package/dist/assets/{LiveDesktop-hGL5Vc_Z.js → LiveDesktop-CJmUlX7t.js} +1 -1
- package/dist/assets/{LocalVmWorkspace-B_kTCMkz.js → LocalVmWorkspace-o8CEQfvC.js} +1 -1
- package/dist/assets/{MacLocalControl-DNO_TehG.js → MacLocalControl-VHfhfP-1.js} +1 -1
- package/dist/assets/{MarkdownFilePreview-CL7juyHq.js → MarkdownFilePreview-CVg1Dv8-.js} +1 -1
- package/dist/assets/{NewBotDialog-CbkCu3Tq.js → NewBotDialog-C44BCac3.js} +1 -1
- package/dist/assets/{PhoneAppDialog-BFCCrIuS.js → PhoneAppDialog-DtK5rRue.js} +1 -1
- package/dist/assets/{PluginsPanel-DnV0nnd0.js → PluginsPanel-DpO8LuFQ.js} +1 -1
- package/dist/assets/{ProIntroduction-BqrTHZHe.js → ProIntroduction-8364k-yT.js} +1 -1
- package/dist/assets/{RemoteAgentSettingsPanel-CeUWRt9h.js → RemoteAgentSettingsPanel-DNZOyjLd.js} +1 -1
- package/dist/assets/{RoomPanel-C9ujF99f.js → RoomPanel-BjgeZyW_.js} +1 -1
- package/dist/assets/{RoutinesPage-CLqcYU0g.js → RoutinesPage-U4CYV5gy.js} +1 -1
- package/dist/assets/{SettingsModal-9llKQ2Mj.js → SettingsModal-BN-s1Vsn.js} +1 -1
- package/dist/assets/{ShareTeamDialog-qYnUdjLc.js → ShareTeamDialog-CSNzgOgX.js} +1 -1
- package/dist/assets/{SignedInSites-zx_Bqomx.js → SignedInSites-CMyBj22P.js} +1 -1
- package/dist/assets/{TeamLibraryPanel-DJzG9O6f.js → TeamLibraryPanel-CTbcwEBK.js} +1 -1
- package/dist/assets/{TeamMapPage-B6o-uzsU.js → TeamMapPage-BA1Gn4Nu.js} +1 -1
- package/dist/assets/{TriggersPage-xi-wECUl.js → TriggersPage-BIw8SsJe.js} +1 -1
- package/dist/assets/{VisibilitySection-Bzsk343C.js → VisibilitySection-VxPMnLBf.js} +1 -1
- package/dist/assets/{WebhookTrigger-B3Zjfv6_.js → WebhookTrigger-CDOPgE1u.js} +1 -1
- package/dist/assets/{WorksOnGrid-e75OUZ5l.js → WorksOnGrid-B11Ztjyn.js} +1 -1
- package/dist/assets/{core-Dkz8aucx.js → core-IJ42VnCr.js} +1 -1
- package/dist/assets/{import-name-C9VPs36v.js → import-name-BWc5rW_1.js} +1 -1
- package/dist/assets/{index-BEFKyXpE.js → index-C80Smt_v.js} +1 -1
- package/dist/assets/{index-D-YzdU6W.js → index-D5fEAMqd.js} +2 -2
- package/dist/assets/{new-bot-D_AMnybb.js → new-bot-DhYGTNqw.js} +1 -1
- package/dist/assets/{org-library-SbjlI2xi.js → org-library-Cvd8tb9X.js} +1 -1
- package/dist/assets/{package-format-B1_4B6uw.js → package-format-BoXiXUGU.js} +1 -1
- package/dist/assets/{remote-desktop-panel-DIQTDq-1.js → remote-desktop-panel-B6VIl0Qb.js} +1 -1
- package/dist/index.html +1 -1
- package/dist-server/index.js +58 -57
- package/dist-server/limixbot.js +46 -44
- package/dist-server/package.json +1 -1
- package/dist-server/pair-cli.js +46 -44
- package/dist-server/server/drivers/chatgpt-plan-auth.js +56 -3
- package/package.json +1 -1
package/dist-server/limixbot.js
CHANGED
|
@@ -4530,46 +4530,48 @@ void 0){let age=now-iat,max=validateInput("maxTokenAge option",typeof maxTokenAg
|
|
|
4530
4530
|
init_errors4()}});function isUsableJWK(jwk,entry,alg,kid){let{kty,key_ops,ext,kid:jwkKid,alg:jwkAlg,use,crv}=snapshotJwk(jwk),keyOps=Array.isArray(key_ops)?[...key_ops]:key_ops;return(ext===void 0||typeof ext=="boolean")&&(keyOps===void 0||Array.isArray(keyOps)&&keyOps.every((operation,index2)=>typeof operation=="string"&&keyOps.indexOf(operation)===index2)&&keyOps.includes("verify"))&&entry.kty.includes(kty)&&(kid===void 0||typeof kid=="string"&&kid===jwkKid)&&(jwkAlg===void 0?kty!=="AKP":alg===jwkAlg)&&(use===void 0||
|
|
4531
4531
|
use==="sig")&&(!entry.crv||crv===entry.crv)}async function importWithAlgCache(cache2,jwk,entry){let cached4=cache2.get(jwk)||cache2.set(jwk,{}).get(jwk),{alg}=entry;if(cached4[alg]===void 0){let key2=await jwkToKey(entry,{...jwk,alg,ext:!0});if(key2.type!=="public")throw new JWKSInvalid("JSON Web Key Set members must be public keys");cached4[alg]=key2}return cached4[alg]}function createLocalJWKSet(jwks){let snapshot;try{snapshot=structuredClone(jwks)}catch{}if(!isJwkSet(snapshot))throw new JWKSInvalid(
|
|
4532
4532
|
"JSON Web Key Set malformed");let cached4=new WeakMap;return Object.defineProperty(async(protectedHeader,token)=>{let{alg,kid}={...protectedHeader,...token?.header},entry=typeof alg=="string"?JWS[alg]:void 0;if(!entry||entry.secret)throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');let candidates=snapshot.keys.filter(jwk2=>isUsableJWK(jwk2,entry,alg,kid)),{0:jwk,length:length2}=candidates;if(!length2)throw new JWKSNoMatchingKey;if(length2!==1){let error62=new JWKSMultipleMatchingKeys;
|
|
4533
|
-
throw error62[Symbol.asyncIterator]=async function*(){for(let jwk2 of candidates)try{yield await importWithAlgCache(cached4,jwk2,entry)}catch{}},error62}return importWithAlgCache(cached4,jwk,entry)},"jwks",{value:()=>structuredClone(snapshot)})}var init_local=__esm({"node_modules/.pnpm/jose@6.2.10/node_modules/jose/dist/webapi/jwks/local.js"(){init_jwk_to_key();init_jws_algorithms();init_errors4();init_type_checks();init_jwk_metadata()}});var init_webapi=__esm({"node_modules/.pnpm/jose@6.2.10/node_modules/jose/dist/webapi/index.js"(){init_verify();init_local()}});import{createHash as createHash22,randomBytes as randomBytes7,randomUUID as randomUUID14,timingSafeEqual as timingSafeEqual2}from"node:crypto";import{chmodSync as chmodSync8,closeSync as closeSync16,lstatSync as lstatSync10,mkdirSync as mkdirSync32,openSync as openSync15,readFileSync as readFileSync40,rmSync as rmSync24,unlinkSync as unlinkSync9,writeFileSync as writeFileSync18}from"node:fs";import{createServer as createServer8}from"node:http";import{
|
|
4534
|
-
join as join77}from"node:path";import{setTimeout as delay}from"node:timers/promises";function object2(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("Invalid ChatGPT response.");return value}function string4(value,max=65536){return typeof value=="string"&&value.length>0&&value.length<=max}function privateDirectory(path3){if(mkdirSync32(path3,{recursive:!0,mode:448}),!lstatSync10(path3).isDirectory()||lstatSync10(
|
|
4535
|
-
|
|
4536
|
-
let
|
|
4537
|
-
|
|
4538
|
-
|
|
4539
|
-
|
|
4540
|
-
|
|
4541
|
-
|
|
4542
|
-
throw new Error("Saved ChatGPT
|
|
4543
|
-
|
|
4544
|
-
subject
|
|
4545
|
-
|
|
4546
|
-
|
|
4547
|
-
|
|
4548
|
-
|
|
4549
|
-
|
|
4550
|
-
|
|
4551
|
-
|
|
4552
|
-
|
|
4553
|
-
|
|
4554
|
-
|
|
4555
|
-
|
|
4556
|
-
|
|
4557
|
-
Bot"
|
|
4558
|
-
|
|
4559
|
-
|
|
4560
|
-
|
|
4561
|
-
|
|
4562
|
-
|
|
4563
|
-
this.
|
|
4564
|
-
|
|
4565
|
-
|
|
4566
|
-
|
|
4567
|
-
|
|
4568
|
-
"
|
|
4569
|
-
|
|
4570
|
-
|
|
4571
|
-
|
|
4572
|
-
|
|
4533
|
+
throw error62[Symbol.asyncIterator]=async function*(){for(let jwk2 of candidates)try{yield await importWithAlgCache(cached4,jwk2,entry)}catch{}},error62}return importWithAlgCache(cached4,jwk,entry)},"jwks",{value:()=>structuredClone(snapshot)})}var init_local=__esm({"node_modules/.pnpm/jose@6.2.10/node_modules/jose/dist/webapi/jwks/local.js"(){init_jwk_to_key();init_jws_algorithms();init_errors4();init_type_checks();init_jwk_metadata()}});var init_webapi=__esm({"node_modules/.pnpm/jose@6.2.10/node_modules/jose/dist/webapi/index.js"(){init_verify();init_local()}});import{createHash as createHash22,randomBytes as randomBytes7,randomUUID as randomUUID14,timingSafeEqual as timingSafeEqual2}from"node:crypto";import{chmodSync as chmodSync8,closeSync as closeSync16,lstatSync as lstatSync10,mkdirSync as mkdirSync32,openSync as openSync15,readFileSync as readFileSync40,rmSync as rmSync24,unlinkSync as unlinkSync9,writeFileSync as writeFileSync18}from"node:fs";import{createServer as createServer8}from"node:http";import{DatabaseSync as DatabaseSync4}from"node:sqlite";
|
|
4534
|
+
import{dirname as dirname35,isAbsolute as isAbsolute16,join as join77}from"node:path";import{setTimeout as delay}from"node:timers/promises";function object2(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("Invalid ChatGPT response.");return value}function string4(value,max=65536){return typeof value=="string"&&value.length>0&&value.length<=max}function privateDirectory(path3){if(mkdirSync32(path3,{recursive:!0,mode:448}),!lstatSync10(path3).isDirectory()||lstatSync10(
|
|
4535
|
+
path3).isSymbolicLink())throw new Error("ChatGPT credential storage must be a private directory.");chmodSync8(path3,448)}function readJson2(path3){try{let stat9=lstatSync10(path3);if(!stat9.isFile()||stat9.isSymbolicLink()||stat9.size>512e3)throw new Error("Invalid credential storage.");return chmodSync8(path3,384),JSON.parse(readFileSync40(path3,"utf8"))}catch(error62){if(error62.code==="ENOENT")return null;throw new Error("ChatGPT credential storage could not be read safely. Check its permissi\
|
|
4536
|
+
ons before signing in.")}}function recoverCredentialLock(path3){let guard=new DatabaseSync4(path3+".recovery.db");try{try{guard.exec("BEGIN IMMEDIATE")}catch(error62){if(error62.errcode===5)return!1;throw error62}let owner;try{owner=readFileSync40(path3,"utf8")}catch(error62){if(error62.code==="ENOENT")return!0;throw error62}if(!/^[1-9]\d{0,9}$/u.test(owner))return!1;try{process.kill(Number(owner),0)}catch(error62){if(error62.code==="ESRCH"){try{if(readFileSync40(path3,"utf8")!==owner)return!1;unlinkSync9(
|
|
4537
|
+
path3)}catch(changed2){if(changed2.code!=="ENOENT")throw changed2}return!0}}return!1}finally{guard.close()}}async function locked(directory,operation){let path3=join77(directory,".credentials.lock"),deadline=Date.now()+3e4,nextRecovery=0,fd;for(;;)try{fd=openSync15(path3,"wx",384);break}catch(error62){if(error62.code!=="EEXIST")throw new Error("ChatGPT credentials could not be locked safely.");if(Date.now()>=nextRecovery&&(nextRecovery=Date.now()+1e3,recoverCredentialLock(path3)))continue;if(Date.
|
|
4538
|
+
now()>=deadline)throw new Error("Another process is updating the ChatGPT sign-in. Please retry shortly.");await delay(50)}try{return writeFileSync18(fd,String(process.pid)),await operation()}finally{closeSync16(fd),unlinkSync9(path3)}}var ISSUER,RESOURCE,DIRECT_SCOPE,SCOPES,LIFETIME,TERMINAL_REFRESH,SIGN_IN,CONSENT,ChatGptPlanAuthController,init_chatgpt_plan_auth=__esm({"server/drivers/chatgpt-plan-auth.ts"(){"use strict";init_webapi();init_atomic();ISSUER="https://auth.openai.com",RESOURCE="htt\
|
|
4539
|
+
ps://api.openai.com/v1",DIRECT_SCOPE="chatgpt.tokens.use.direct",SCOPES=`openid profile email offline_access resource.invoke ${DIRECT_SCOPE}`,LIFETIME=15*6e4,TERMINAL_REFRESH=new Set(["invalid_grant","invalid_refresh_token","token_expired","refresh_token_expired","refresh_token_invalidated","refresh_token_reused"]),SIGN_IN="Continue with ChatGPT in Settings to use your ChatGPT plan.",CONSENT="ChatGPT plan usage is not enabled. Continue with ChatGPT in Settings and allow plan usage, or explicitly\
|
|
4540
|
+
choose another provider.";ChatGptPlanAuthController=class{options;issuer;resource;flow=null;disposed=!1;starting=null;retryClientId=null;refusedNow=new Set;constructor(options2){if(!isAbsolute16(options2.directory))throw new Error("ChatGPT credential storage must use an absolute path.");if(options2.testServerUrl){let url3=new URL(options2.testServerUrl);if(url3.protocol!=="http:"||url3.hostname!=="127.0.0.1"||url3.username||url3.password||url3.search||url3.hash||url3.pathname!=="/")throw new Error(
|
|
4541
|
+
"ChatGPT test endpoints must be a loopback origin.");this.issuer=url3.origin,this.resource=`${url3.origin}/v1`}else this.issuer=ISSUER,this.resource=RESOURCE;this.options=options2}prepare(){privateDirectory(dirname35(this.options.directory)),privateDirectory(this.options.directory)}read(){let raw=readJson2(join77(this.options.directory,"credentials.json"));if(raw===null)return null;let record12=object2(raw);if(!string4(record12.clientId,256)||record12.clientId==="dynamic_agent_client"||!string4(
|
|
4542
|
+
record12.subject,512)||!string4(record12.hostId,128)||record12.email!==void 0&&!string4(record12.email,320))throw new Error("Saved ChatGPT registration is invalid. Check credential storage before signing in.");if(record12.tokens!==void 0){let tokens2=object2(record12.tokens);if(!string4(tokens2.access)||typeof tokens2.refresh!="string"||tokens2.refresh.length>65536||!string4(tokens2.id)||!Array.isArray(tokens2.scopes)||!tokens2.scopes.every(scope=>string4(scope,256))||typeof tokens2.expiresAt!="\
|
|
4543
|
+
number"||!Number.isFinite(tokens2.expiresAt)||tokens2.scopes.includes(DIRECT_SCOPE)&&!tokens2.refresh||tokens2.earliestRefreshAt!==void 0&&(typeof tokens2.earliestRefreshAt!="number"||!Number.isFinite(tokens2.earliestRefreshAt)))throw new Error("Saved ChatGPT credentials are invalid. Continue with ChatGPT again.")}return record12}save(record12){writeFileAtomic(join77(this.options.directory,"credentials.json"),JSON.stringify(record12),{mode:384})}refusedPath(){return join77(this.options.directory,
|
|
4544
|
+
"refused-models.json")}savedRefused(subject){let raw=readJson2(this.refusedPath());if(raw===null)return[];let saved=object2(raw);return saved.subject===subject&&Array.isArray(saved.models)?saved.models.filter(slug2=>string4(slug2,256)):[]}refusedFor(subject){let saved=[];try{saved=this.savedRefused(subject)}catch{}return[...new Set([...saved,...this.refusedNow])]}clearRefused(){this.refusedNow.clear(),rmSync24(this.refusedPath(),{force:!0})}refusedModels(){try{let subject=this.read()?.subject;return subject?
|
|
4545
|
+
this.refusedFor(subject):[]}catch{return[]}}async refuseModel(slug2){this.disposed||!string4(slug2,256)||(this.refusedNow.add(slug2),this.prepare(),await locked(this.options.directory,async()=>{let subject=this.read()?.subject,models2=subject?this.savedRefused(subject):[];subject&&!models2.includes(slug2)&&writeFileAtomic(this.refusedPath(),JSON.stringify({subject,models:[...models2,slug2]}),{mode:384})}))}async hostId(){let parent=dirname35(this.options.directory);return locked(parent,async()=>{
|
|
4546
|
+
let path3=join77(parent,"host-id.json"),saved=readJson2(path3);if(saved!==null){let value2=object2(saved).hostId;if(!string4(value2)||!/^urn:uuid:[0-9a-f-]{36}$/i.test(value2))throw new Error("Saved ChatGPT host identity is invalid.");return value2}let value=`urn:uuid:${randomUUID14()}`;return writeFileAtomic(path3,JSON.stringify({hostId:value}),{mode:384}),value})}async request(url3,init={}){try{let response=await fetch(url3,{...init,redirect:"error",signal:init.signal?AbortSignal.any([init.signal,
|
|
4547
|
+
AbortSignal.timeout(15e3)]):AbortSignal.timeout(15e3)});if(Number(response.headers.get("content-length"))>1048576)throw new Error("Oversized response.");let reader=response.body?.getReader(),size=0,chunks=[];if(reader)for(;;){let{value,done}=await reader.read();if(done)break;if(size+=value.byteLength,size>1048576)throw await reader.cancel(),new Error("Oversized response.");chunks.push(value)}let text13=Buffer.concat(chunks).toString("utf8");return{response,body:text13?object2(JSON.parse(text13)):
|
|
4548
|
+
{}}}catch{throw new Error("Could not securely contact ChatGPT. Check your connection and try again; your saved account has not been removed.")}}async exchange(params,signal){return this.request(`${this.issuer}/api/accounts/oauth/token`,{method:"POST",body:params,signal})}tokenSet(body2,previous2){if(!string4(body2.access_token)||typeof body2.token_type!="string"||body2.token_type.toLowerCase()!=="bearer"||typeof body2.expires_in!="number"||!Number.isFinite(body2.expires_in)||body2.expires_in<=0||
|
|
4549
|
+
body2.expires_in>86400||body2.scope!==void 0&&typeof body2.scope!="string"||body2.id_token!==void 0&&!string4(body2.id_token))throw new Error("ChatGPT returned incomplete credentials. Continue with ChatGPT again.");let id2=string4(body2.id_token)?body2.id_token:previous2?.id;if(!id2)throw new Error("ChatGPT did not return a verifiable identity. Continue with ChatGPT again.");let scopes=typeof body2.scope=="string"?body2.scope.split(/\s+/).filter(Boolean):previous2?.scopes;if(!scopes)throw new Error(
|
|
4550
|
+
"ChatGPT did not confirm granted permissions. Continue with ChatGPT again.");if(scopes.includes(DIRECT_SCOPE)&&!string4(body2.refresh_token))throw new Error("ChatGPT did not provide renewable plan access. Continue with ChatGPT again.");return{access:body2.access_token,refresh:string4(body2.refresh_token)?body2.refresh_token:"",id:id2,scopes,expiresAt:Date.now()+body2.expires_in*1e3,...typeof body2.earliest_refresh_at=="number"&&Number.isFinite(body2.earliest_refresh_at)?{earliestRefreshAt:body2.
|
|
4551
|
+
earliest_refresh_at*1e3}:{}}}async identityKeys(signal){let{response,body:body2}=await this.request(`${this.issuer}/.well-known/jwks.json`,{signal});if(!response.ok)throw new Error("ChatGPT identity keys are unavailable. Try signing in again later.");try{if(!Array.isArray(body2.keys)||body2.keys.length===0)throw new Error("Empty identity keys.");return createLocalJWKSet(body2)}catch{throw new Error("ChatGPT identity keys could not be verified. Try signing in again later.")}}async identity(id2,clientId,keys,nonce){
|
|
4552
|
+
try{let{payload}=await jwtVerify(id2,keys,{issuer:this.issuer,audience:clientId,algorithms:["RS256","ES256"],requiredClaims:["sub","exp","iat"],clockTolerance:30});if(!string4(payload.sub,512)||typeof payload.iat!="number"||payload.iat>Date.now()/1e3+30||Array.isArray(payload.aud)&&payload.aud.length>1&&payload.azp!==clientId||nonce!==void 0&&payload.nonce!==nonce)throw new Error("Identity mismatch.");return{subject:payload.sub,...string4(payload.email,320)?{email:payload.email}:{}}}catch{throw new Error(
|
|
4553
|
+
"ChatGPT identity could not be verified. No account was replaced. Start sign-in again.")}}async start(){if(this.starting)return this.starting;this.starting=this.begin();try{return await this.starting}finally{this.starting=null}}async begin(){if(this.disposed)throw new Error("This provider was removed. Refresh Settings before signing in.");if(this.flow?.status.phase==="waiting")return{...this.flow.status,phase:"waiting"};this.prepare();let previous2=this.read(),clientId=previous2?.clientId??this.
|
|
4554
|
+
retryClientId,hostId=await this.hostId();if(previous2&&previous2.hostId!==hostId)throw new Error("This ChatGPT registration belongs to another host. Sign in using a new account entry on this host.");let state=randomBytes7(32).toString("base64url"),nonce=randomBytes7(32).toString("base64url"),verifier=randomBytes7(32).toString("base64url"),server=createServer8((request2,response)=>{response.setHeader("Cache-Control","no-store"),response.setHeader("Content-Type","text/plain; charset=utf-8"),response.
|
|
4555
|
+
setHeader("Referrer-Policy","no-referrer");let flow4=this.flow,callback;try{if(!flow4||request2.headers.host!==new URL(flow4.redirectUri).host||!request2.url?.startsWith("/"))throw new Error("Unexpected callback host.");if(callback=new URL(request2.url,flow4.redirectUri),callback.origin!==new URL(flow4.redirectUri).origin)throw new Error("Unexpected callback origin.")}catch{response.writeHead(400).end("Invalid sign-in callback. Return to Limix Bot and try again.");return}let actual=callback.searchParams.
|
|
4556
|
+
get("state")??"";if(request2.method!=="GET"||callback.pathname!=="/auth/callback"||!flow4||flow4.server!==server||flow4.consumed||flow4.status.phase!=="waiting"||Buffer.byteLength(actual)!==Buffer.byteLength(flow4.state)||!timingSafeEqual2(Buffer.from(actual),Buffer.from(flow4.state))||[...callback.searchParams.keys()].some(key2=>callback.searchParams.getAll(key2).length!==1)){response.writeHead(400).end("Invalid or expired sign-in. Return to Limix Bot and try again.");return}flow4.consumed=!0,response.
|
|
4557
|
+
end("Finishing sign-in. You can return to Limix Bot."),server.close(),this.complete(flow4,callback.searchParams)});if(await new Promise((resolve36,reject)=>{server.once("error",reject),server.listen(0,"127.0.0.1",resolve36)}),this.disposed)throw server.close(),new Error("This provider was removed.");let address2=server.address();if(!address2||typeof address2=="string")throw server.close(),new Error("ChatGPT sign-in listener could not start.");let redirectUri=`http://127.0.0.1:${address2.port}/au\
|
|
4558
|
+
th/callback`,url3=new URL(`${this.issuer}/api/accounts/authorize`);url3.search=new URLSearchParams({client_id:clientId??"dynamic_agent_client",ext_agent_host_id:hostId,...clientId?{}:{agent_name_hint:"Limix Bot"},...previous2?.email?{login_hint:previous2.email}:{},...previous2?.tokens&&!previous2.tokens.scopes.includes(DIRECT_SCOPE)?{prompt:"consent"}:{},response_type:"code",redirect_uri:redirectUri,scope:SCOPES,resource:this.resource,state,nonce,code_challenge_method:"S256",code_challenge:createHash22(
|
|
4559
|
+
"sha256").update(verifier).digest("base64url")}).toString();let status3={phase:"waiting",flowId:randomUUID14(),authorizationUrl:url3.href,expiresAt:new Date(Date.now()+LIFETIME).toISOString()},flow3={status:status3,state,nonce,verifier,redirectUri,previous:previous2,clientId,hostId,consumed:!1,server,abort:new AbortController,expiry:setTimeout(()=>this.finish(flow3,"expired","ChatGPT sign-in expired. Start again."),LIFETIME)};return flow3.expiry.unref(),this.flow=flow3,{...status3,phase:"waiting"}}finish(flow3,phase,message5){
|
|
4560
|
+
flow3.status.phase==="waiting"&&(clearTimeout(flow3.expiry),flow3.server.close(),flow3.abort.abort(),flow3.status={...flow3.status,phase,authorizationUrl:null,...message5?{message:message5}:{}})}async complete(flow3,params){try{if(params.has("error"))throw new Error("ChatGPT sign-in was not approved. You can try again in Settings.");let clientId=params.get("client_id")??flow3.clientId,code=params.get("code");if(!string4(clientId,256)||clientId==="dynamic_agent_client"||flow3.clientId&&flow3.clientId!==
|
|
4561
|
+
clientId||!string4(code,4096))throw new Error("ChatGPT registration was incomplete or did not match the selected account. Start sign-in again.");let keys=await this.identityKeys(flow3.abort.signal),{response,body:body2}=await this.exchange(new URLSearchParams({grant_type:"authorization_code",client_id:clientId,code,code_verifier:flow3.verifier,redirect_uri:flow3.redirectUri,resource:this.resource}),flow3.abort.signal);if(!response.ok)throw!flow3.previous&&body2.error==="invalid_grant"&&(this.retryClientId=
|
|
4562
|
+
clientId),new Error("ChatGPT could not finish this sign-in. Start again with a fresh authorization.");let tokens2=this.tokenSet(body2),identity=await this.identity(tokens2.id,clientId,keys,flow3.nonce);if(flow3.previous&&identity.subject!==flow3.previous.subject)throw new Error("ChatGPT returned a different account. Use a separate account entry; the saved account was not replaced.");await locked(this.options.directory,async()=>{if(!(this.disposed||flow3.status.phase!=="waiting"||flow3.abort.signal.
|
|
4563
|
+
aborted)){if(JSON.stringify(this.read())!==JSON.stringify(flow3.previous))throw new Error("The selected ChatGPT account changed during sign-in. Start again.");this.save({clientId,hostId:flow3.hostId,...identity,tokens:tokens2}),this.clearRefused(),this.retryClientId=null,this.finish(flow3,tokens2.scopes.includes(DIRECT_SCOPE)?"succeeded":"failed",tokens2.scopes.includes(DIRECT_SCOPE)?void 0:CONSENT)}}),flow3.status.phase==="succeeded"&&await this.options.onAuthenticated?.().catch(()=>{})}catch(error62){
|
|
4564
|
+
this.finish(flow3,"failed",error62 instanceof Error?error62.message:"ChatGPT sign-in could not finish. Try again.")}}async get(flowId){if(!flowId||this.flow?.status.flowId!==flowId)throw new Error("This sign-in is no longer available. Start again.");return{...this.flow.status}}async cancel(){await this.starting?.catch(()=>{}),this.flow&&this.finish(this.flow,"cancelled","ChatGPT sign-in cancelled.")}async dispose(){this.disposed=!0,await this.cancel(),this.flow=null}async snapshot(){let record12=this.
|
|
4565
|
+
read();return{authenticated:!!record12?.tokens?.scopes.includes(DIRECT_SCOPE),...record12?{account:{method:"login",...record12.email?{email:record12.email}:{},organization:`ChatGPT \xB7 ${record12.clientId.slice(-8)}`}}:{},...record12?.tokens?record12.tokens.scopes.includes(DIRECT_SCOPE)?{}:{reason:CONSENT}:{reason:SIGN_IN}}}async accessToken(){if(this.disposed)throw new Error("This ChatGPT provider was removed.");this.prepare();let cached4=this.read()?.tokens;return cached4?.scopes.includes(DIRECT_SCOPE)&&
|
|
4566
|
+
cached4.expiresAt>Date.now()+6e4?cached4.access:locked(this.options.directory,async()=>{if(this.disposed)throw new Error("This ChatGPT provider was removed.");let record12=this.read();if(!record12?.tokens)throw new Error(SIGN_IN);if(!record12.tokens.scopes.includes(DIRECT_SCOPE))throw new Error(CONSENT);if(record12.tokens.expiresAt>Date.now()+6e4)return record12.tokens.access;if((record12.tokens.earliestRefreshAt??0)>Date.now()){if(record12.tokens.expiresAt>Date.now())return record12.tokens.access;
|
|
4567
|
+
throw new Error("ChatGPT credentials cannot refresh yet. Please try again shortly.")}let keys=await this.identityKeys(),{response,body:body2}=await this.exchange(new URLSearchParams({grant_type:"refresh_token",client_id:record12.clientId,refresh_token:record12.tokens.refresh,resource:this.resource}));if(!response.ok){let code=typeof body2.error=="string"?body2.error:body2.error&&typeof body2.error=="object"?body2.error.code:void 0;throw typeof code=="string"&&TERMINAL_REFRESH.has(code)?(delete record12.
|
|
4568
|
+
tokens,this.save(record12),new Error(SIGN_IN)):code==="invalid_client"?new Error("ChatGPT did not accept this app registration. Check the integration configuration before trying again."):new Error("ChatGPT could not renew access right now. Try again later; your saved account has not been removed.")}let tokens2;try{if(tokens2=this.tokenSet(body2,record12.tokens),body2.id_token!==void 0&&(await this.identity(tokens2.id,record12.clientId,keys)).subject!==record12.subject)throw new Error("ChatGPT re\
|
|
4569
|
+
turned a different account during renewal.")}catch{throw delete record12.tokens,this.save(record12),new Error("ChatGPT renewal could not be verified. Continue with ChatGPT again in Settings.")}if(this.save({...record12,tokens:tokens2}),this.disposed)throw new Error("This ChatGPT provider was removed.");if(!tokens2.scopes.includes(DIRECT_SCOPE))throw new Error(CONSENT);return tokens2.access})}async models(){let record12=this.read();if(!record12?.tokens?.scopes.includes(DIRECT_SCOPE))return{default:"",
|
|
4570
|
+
options:[]};let refused=this.refusedFor(record12.subject),token=await this.accessToken(),{response,body:body2}=await this.request(`${this.resource}/models`,{headers:{Authorization:`Bearer ${token}`}});if(!response.ok)throw new Error(response.status===401||response.status===403?"ChatGPT did not authorize model access. Check this account's plan permissions in ChatGPT Settings.":"ChatGPT models are unavailable right now. Try refreshing later.");if(!Array.isArray(body2.models))throw new Error("ChatG\
|
|
4571
|
+
PT returned an invalid model catalog. No fallback models were selected.");let options2=[];for(let entry of body2.models){if(!entry||typeof entry!="object")continue;let row=entry;row.visibility!=="list"||!string4(row.slug,256)||/[\s\p{Cc}]/u.test(row.slug)||!string4(row.display_name,256)||options2.some(item=>item.id===row.slug)||refused.includes(row.slug)||options2.push({id:row.slug,label:row.display_name})}return{default:options2[0]?.id??"",options:options2}}async signOut(){if(this.disposed)throw new Error(
|
|
4572
|
+
"This provider was removed.");await this.cancel(),this.prepare(),await locked(this.options.directory,async()=>{let record12=this.read();if(!record12?.tokens)return;let revoked=!record12.tokens.refresh;try{if(!record12.tokens.refresh){delete record12.tokens,this.save(record12);return}let discovery=await this.request(`${this.issuer}/.well-known/openid-configuration`),endpoint=discovery.body.revocation_endpoint;if(discovery.response.ok&&discovery.body.issuer===this.issuer&&typeof endpoint=="string"&&
|
|
4573
|
+
new URL(endpoint).origin===this.issuer)for(let attempt=0;attempt<2&&!revoked;attempt++){try{let result2=await this.request(endpoint,{method:"POST",body:new URLSearchParams({token:record12.tokens.refresh,token_type_hint:"refresh_token",client_id:record12.clientId})});if(revoked=result2.response.status===200,result2.response.status<500)break}catch{}!revoked&&attempt===0&&await delay(250)}}catch{}if(delete record12.tokens,this.save(record12),this.clearRefused(),!revoked)throw Object.assign(new Error(
|
|
4574
|
+
"Signed out locally, but remote revocation was not confirmed. Disconnect Limix Bot in ChatGPT Settings \u2192 Usage to end access there."),{code:"chatgpt_revocation_unconfirmed"})})}}}});import{randomBytes as randomBytes8,timingSafeEqual as timingSafeEqual3}from"node:crypto";import{mkdtempSync as mkdtempSync9,rmSync as rmSync25}from"node:fs";import{createServer as createServer9}from"node:net";import{tmpdir as tmpdir12}from"node:os";import{join as join78}from"node:path";async function startChatGptTokenBridge(accessToken){let secret2=randomBytes8(32).toString("hex"),directory=process.platform==="win32"?void 0:mkdtempSync9(join78(tmpdir12(),"omb-auth-")),path3=directory?join78(directory,
|
|
4573
4575
|
"s"):`\\\\.\\pipe\\omb-auth-${randomBytes8(16).toString("hex")}`,connections=new Set,closed=!1,server=createServer9(socket=>{connections.add(socket),socket.on("close",()=>connections.delete(socket)),socket.on("error",()=>{});let input2="";socket.setTimeout(6e4,()=>socket.destroy()),socket.on("data",chunk=>{if(input2+=chunk.toString(),input2.length>128)return socket.destroy();if(!input2.endsWith(`
|
|
4574
4576
|
`))return;socket.removeAllListeners("data");let actual=Buffer.from(input2.trim()),expected=Buffer.from(secret2);if(actual.length!==expected.length||!timingSafeEqual3(actual,expected))return socket.destroy();accessToken().then(token=>{closed||socket.end(token)},()=>socket.destroy())})});try{await new Promise((resolve36,reject)=>{server.once("error",reject),server.listen(path3,resolve36)})}catch(error62){throw directory&&rmSync25(directory,{recursive:!0,force:!0}),error62}return{env:{OMB_CODEX_AUTH_SOCKET:path3,
|
|
4575
4577
|
OMB_CODEX_AUTH_SECRET:secret2},close(){if(!closed){closed=!0;for(let socket of connections)socket.destroy();server.close(),directory&&rmSync25(directory,{recursive:!0,force:!0})}}}}var init_chatgpt_plan_token_bridge=__esm({"server/drivers/chatgpt-plan-token-bridge.ts"(){"use strict"}});function chatgptPlanCodexArgs(renewing=!1){return["-c",'model_provider="openai_chatgpt_plan"',"-c",'model_providers.openai_chatgpt_plan.name="ChatGPT plan"',"-c",'model_providers.openai_chatgpt_plan.base_url="https://api.openai.com/v1"',...renewing?["-c",`model_providers.openai_chatgpt_plan.auth.command=${JSON.stringify(process.execPath)}`,"-c",`model_providers.openai_chatgpt_plan.auth.args=[${JSON.stringify(SPAWNED_PROXIES.chatgptPlanToken)}]`,"-c","model_providers.openai_chatgpt_plan.auth.refr\
|
|
@@ -6766,9 +6768,9 @@ bufferedBytes=0;try{waitingHandler.handler.onResponseError?.(waitingHandler.cont
|
|
|
6766
6768
|
isArray(skipHeaderNames))throw new TypeError(`expected opts.skipHeaderNames to be an array, got ${typeof skipHeaderNames}`);if(!Array.isArray(excludeHeaderNames))throw new TypeError(`expected opts.excludeHeaderNames to be an array, got ${typeof excludeHeaderNames}`);if(!Number.isFinite(maxBufferSize)||maxBufferSize<=0)throw new TypeError(`expected opts.maxBufferSize to be a positive finite number, got ${maxBufferSize}`);let skipHeaderNamesSet=new Set(skipHeaderNames.map(name=>name.toLowerCase())),
|
|
6767
6769
|
excludeHeaderNamesSet=new Set(excludeHeaderNames.map(name=>name.toLowerCase())),pendingRequests=new Map;return(dispatch,interceptorOrigin)=>(opts2,handler)=>{let requestOrigin=getInterceptorOrigin(opts2,interceptorOrigin);if(!requestOrigin||opts2.upgrade||methods.includes(opts2.method)===!1)return dispatch(opts2,handler);if(opts2={...opts2,headers:normalizeHeaders(opts2)},skipHeaderNamesSet.size>0){for(let headerName of Object.keys(opts2.headers))if(skipHeaderNamesSet.has(headerName.toLowerCase()))
|
|
6768
6770
|
return dispatch(opts2,handler)}let cacheKey2=makeCacheKey(opts2,requestOrigin),dedupeKey=makeDeduplicationKey(cacheKey2,excludeHeaderNamesSet),pendingHandler=pendingRequests.get(dedupeKey);if(pendingHandler)return pendingHandler.addWaitingHandler(handler)?!0:dispatch(opts2,handler);let deduplicationHandler=new DeduplicationHandler(handler,()=>{pendingRequests.delete(dedupeKey),pendingRequestsChannel.hasSubscribers&&pendingRequestsChannel.publish({size:pendingRequests.size,key:dedupeKey,type:"rem\
|
|
6769
|
-
oved"})},maxBufferSize);return pendingRequests.set(dedupeKey,deduplicationHandler),pendingRequestsChannel.hasSubscribers&&pendingRequestsChannel.publish({size:pendingRequests.size,key:dedupeKey,type:"added"}),dispatch(opts2,deduplicationHandler)}}}});var require_sqlite_cache_store=__commonJS({"node_modules/.pnpm/undici@8.11.2/node_modules/undici/lib/cache/sqlite-cache-store.js"(exports,module){"use strict";var{Writable}=__require("node:stream"),{assertCacheKey,assertCacheValue}=require_cache(),
|
|
6771
|
+
oved"})},maxBufferSize);return pendingRequests.set(dedupeKey,deduplicationHandler),pendingRequestsChannel.hasSubscribers&&pendingRequestsChannel.publish({size:pendingRequests.size,key:dedupeKey,type:"added"}),dispatch(opts2,deduplicationHandler)}}}});var require_sqlite_cache_store=__commonJS({"node_modules/.pnpm/undici@8.11.2/node_modules/undici/lib/cache/sqlite-cache-store.js"(exports,module){"use strict";var{Writable}=__require("node:stream"),{assertCacheKey,assertCacheValue}=require_cache(),DatabaseSync6,VERSION3=3,MAX_ENTRY_SIZE=2*1e3*1e3*1e3;module.exports=class{#maxEntrySize=MAX_ENTRY_SIZE;#maxCount=1/0;#db;#getValuesQuery;#updateValueQuery;#insertValueQuery;#deleteExpiredValuesQuery;#deleteByUrlQuery;#countEntriesQuery;#deleteOldValuesQuery;constructor(opts){
|
|
6770
6772
|
if(opts){if(typeof opts!="object")throw new TypeError("SqliteCacheStore options must be an object");if(opts.maxEntrySize!==void 0){if(typeof opts.maxEntrySize!="number"||!Number.isInteger(opts.maxEntrySize)||opts.maxEntrySize<0)throw new TypeError("SqliteCacheStore options.maxEntrySize must be a non-negative integer");if(opts.maxEntrySize>MAX_ENTRY_SIZE)throw new TypeError("SqliteCacheStore options.maxEntrySize must be less than 2gb");this.#maxEntrySize=opts.maxEntrySize}if(opts.maxCount!==void 0){
|
|
6771
|
-
if(typeof opts.maxCount!="number"||!Number.isInteger(opts.maxCount)||opts.maxCount<0)throw new TypeError("SqliteCacheStore options.maxCount must be a non-negative integer");this.#maxCount=opts.maxCount}}
|
|
6773
|
+
if(typeof opts.maxCount!="number"||!Number.isInteger(opts.maxCount)||opts.maxCount<0)throw new TypeError("SqliteCacheStore options.maxCount must be a non-negative integer");this.#maxCount=opts.maxCount}}DatabaseSync6||(DatabaseSync6=__require("node:sqlite").DatabaseSync),this.#db=new DatabaseSync6(opts?.location??":memory:"),this.#db.exec(`
|
|
6772
6774
|
PRAGMA journal_mode = WAL;
|
|
6773
6775
|
PRAGMA synchronous = NORMAL;
|
|
6774
6776
|
PRAGMA temp_store = memory;
|
|
@@ -7920,8 +7922,8 @@ nd Code default"},MODELS5={default:AGENT_DEFAULT2.id,options:[AGENT_DEFAULT2]},S
|
|
|
7920
7922
|
selectModel:{configId:"model",agentDefault:AGENT_DEFAULT2.id},modelVariants:!0,pickAuthMethod:()=>null,authFailure:"continue",isAuthenticated:env=>commandCodeSignedIn(env),classifyError:classifyCommandCodeError,describeAccountError:describeCommandCodeAccountError,accountErrorText:code=>code==="invalid_credentials"?void 0:{key:"chat.notice.commandCodeAccountRefused"},async configureSession({request:request2,sessionId,config:config3}){let modeId=config3.fullAuto?MODE_FULL:MODE_ASK;try{await request2(
|
|
7921
7923
|
"session/set_mode",{sessionId,modeId})}catch(error62){throw new Error(`Command Code rejected permission mode "${modeId}": ${error62.message}`)}},buildPromptText:turn=>turn.system?`${turn.system}
|
|
7922
7924
|
|
|
7923
|
-
${turn.text}`:turn.text},CommandCodeAgentDriver=createAcpDriver(SUPPORT3)}});import{DatabaseSync as
|
|
7924
|
-
trim())return!0;let db;try{return db=new
|
|
7925
|
+
${turn.text}`:turn.text},CommandCodeAgentDriver=createAcpDriver(SUPPORT3)}});import{DatabaseSync as DatabaseSync5}from"node:sqlite";import{join as join103}from"node:path";function kiroDataDir(env,platform=process.platform){let home2=userHome(env);return platform==="darwin"?join103(home2,"Library","Application Support","kiro-cli"):platform==="win32"?join103(env.LOCALAPPDATA?.trim()||join103(home2,"AppData","Local"),"kiro-cli"):join103(env.XDG_DATA_HOME?.trim()||join103(home2,".local","share"),"kiro-cli")}function kiroSignedIn(env,platform=process.platform){if(env[API_KEY_ENV2]?.
|
|
7926
|
+
trim())return!0;let db;try{return db=new DatabaseSync5(join103(kiroDataDir(env,platform),"data.sqlite3"),{readOnly:!0}),db.prepare("SELECT 1 FROM auth_kv WHERE key LIKE '%:token' AND length(value) > 0 LIMIT 1").get()!==void 0}catch{return!1}finally{db?.close()}}function resolveKiroModels(env,config3){return discoverAcpModels(env,config3.cli,SPAWN_ARGS3,DISCOVERY3)}function kiroUpdateFilter(){let hiddenTools=new Set;return update=>{let toolCallId=typeof update.toolCallId=="string"?update.toolCallId:
|
|
7925
7927
|
"";if(update._meta?.kiro?.toolId===CLOUD_CONFIG_TOOL)return toolCallId&&update.status!=="completed"&&update.status!=="failed"?hiddenTools.add(toolCallId):hiddenTools.delete(toolCallId),null;if(toolCallId&&hiddenTools.has(toolCallId))return(update.status==="completed"||update.status==="failed")&&hiddenTools.delete(toolCallId),null;let text13=update.sessionUpdate==="agent_message_chunk"?update.content?.text:void 0;if(typeof text13!="string"||!text13.includes(STEERING_ECHO))return update;let kept=text13.
|
|
7926
7928
|
slice(0,text13.indexOf(STEERING_ECHO)).trimEnd();return kept?{...update,content:{...update.content,text:kept}}:null}}function describeKiroAccountError(code){return code==="invalid_credentials"?LOGIN_NOTE4:"Kiro refused this request for the signed-in account. Check its Kiro plan and credits, then try again."}var AGENT_DEFAULT3,MODELS6,SPAWN_ARGS3,SIGN_IN4,API_KEY_ENV2,LOGIN_NOTE4,AUTH_METHODS,CLIENT_META,CLOUD_CONFIG_TOOL,STEERING_ECHO,DISCOVERY3,SUPPORT4,KiroAgentDriver,init_kiro=__esm({"server/\
|
|
7927
7929
|
drivers/acp/kiro.ts"(){"use strict";init_env_path();init_core3();init_custom_model_catalog();AGENT_DEFAULT3={id:"agent-default",label:"Kiro default"},MODELS6={default:AGENT_DEFAULT3.id,options:[AGENT_DEFAULT3]},SPAWN_ARGS3=["acp","--agent-engine=v3","--auth-method=cli"],SIGN_IN4="kiro-cli login",API_KEY_ENV2="KIRO_API_KEY",LOGIN_NOTE4=`Kiro is not signed in. Run ${SIGN_IN4} in a terminal, or set ${API_KEY_ENV2}, then check again.`,AUTH_METHODS=["aws-builder-id","aws-iam-identity-center","kiro-lo\
|
package/dist-server/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"type":"module","version":"0.3.
|
|
1
|
+
{"type":"module","version":"0.3.152"}
|
package/dist-server/pair-cli.js
CHANGED
|
@@ -4529,46 +4529,48 @@ void 0){let age=now-iat,max=validateInput("maxTokenAge option",typeof maxTokenAg
|
|
|
4529
4529
|
init_errors4()}});function isUsableJWK(jwk,entry,alg,kid){let{kty,key_ops,ext,kid:jwkKid,alg:jwkAlg,use,crv}=snapshotJwk(jwk),keyOps=Array.isArray(key_ops)?[...key_ops]:key_ops;return(ext===void 0||typeof ext=="boolean")&&(keyOps===void 0||Array.isArray(keyOps)&&keyOps.every((operation,index2)=>typeof operation=="string"&&keyOps.indexOf(operation)===index2)&&keyOps.includes("verify"))&&entry.kty.includes(kty)&&(kid===void 0||typeof kid=="string"&&kid===jwkKid)&&(jwkAlg===void 0?kty!=="AKP":alg===jwkAlg)&&(use===void 0||
|
|
4530
4530
|
use==="sig")&&(!entry.crv||crv===entry.crv)}async function importWithAlgCache(cache2,jwk,entry){let cached4=cache2.get(jwk)||cache2.set(jwk,{}).get(jwk),{alg}=entry;if(cached4[alg]===void 0){let key2=await jwkToKey(entry,{...jwk,alg,ext:!0});if(key2.type!=="public")throw new JWKSInvalid("JSON Web Key Set members must be public keys");cached4[alg]=key2}return cached4[alg]}function createLocalJWKSet(jwks){let snapshot;try{snapshot=structuredClone(jwks)}catch{}if(!isJwkSet(snapshot))throw new JWKSInvalid(
|
|
4531
4531
|
"JSON Web Key Set malformed");let cached4=new WeakMap;return Object.defineProperty(async(protectedHeader,token)=>{let{alg,kid}={...protectedHeader,...token?.header},entry=typeof alg=="string"?JWS[alg]:void 0;if(!entry||entry.secret)throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');let candidates=snapshot.keys.filter(jwk2=>isUsableJWK(jwk2,entry,alg,kid)),{0:jwk,length:length2}=candidates;if(!length2)throw new JWKSNoMatchingKey;if(length2!==1){let error62=new JWKSMultipleMatchingKeys;
|
|
4532
|
-
throw error62[Symbol.asyncIterator]=async function*(){for(let jwk2 of candidates)try{yield await importWithAlgCache(cached4,jwk2,entry)}catch{}},error62}return importWithAlgCache(cached4,jwk,entry)},"jwks",{value:()=>structuredClone(snapshot)})}var init_local=__esm({"node_modules/.pnpm/jose@6.2.10/node_modules/jose/dist/webapi/jwks/local.js"(){init_jwk_to_key();init_jws_algorithms();init_errors4();init_type_checks();init_jwk_metadata()}});var init_webapi=__esm({"node_modules/.pnpm/jose@6.2.10/node_modules/jose/dist/webapi/index.js"(){init_verify();init_local()}});import{createHash as createHash22,randomBytes as randomBytes7,randomUUID as randomUUID14,timingSafeEqual as timingSafeEqual2}from"node:crypto";import{chmodSync as chmodSync8,closeSync as closeSync16,lstatSync as lstatSync10,mkdirSync as mkdirSync32,openSync as openSync15,readFileSync as readFileSync40,rmSync as rmSync24,unlinkSync as unlinkSync9,writeFileSync as writeFileSync18}from"node:fs";import{createServer as createServer8}from"node:http";import{
|
|
4533
|
-
join as join77}from"node:path";import{setTimeout as delay}from"node:timers/promises";function object2(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("Invalid ChatGPT response.");return value}function string4(value,max=65536){return typeof value=="string"&&value.length>0&&value.length<=max}function privateDirectory(path3){if(mkdirSync32(path3,{recursive:!0,mode:448}),!lstatSync10(path3).isDirectory()||lstatSync10(
|
|
4534
|
-
|
|
4535
|
-
let
|
|
4536
|
-
|
|
4537
|
-
|
|
4538
|
-
|
|
4539
|
-
|
|
4540
|
-
|
|
4541
|
-
throw new Error("Saved ChatGPT
|
|
4542
|
-
|
|
4543
|
-
subject
|
|
4544
|
-
|
|
4545
|
-
|
|
4546
|
-
|
|
4547
|
-
|
|
4548
|
-
|
|
4549
|
-
|
|
4550
|
-
|
|
4551
|
-
|
|
4552
|
-
|
|
4553
|
-
|
|
4554
|
-
|
|
4555
|
-
|
|
4556
|
-
Bot"
|
|
4557
|
-
|
|
4558
|
-
|
|
4559
|
-
|
|
4560
|
-
|
|
4561
|
-
|
|
4562
|
-
this.
|
|
4563
|
-
|
|
4564
|
-
|
|
4565
|
-
|
|
4566
|
-
|
|
4567
|
-
"
|
|
4568
|
-
|
|
4569
|
-
|
|
4570
|
-
|
|
4571
|
-
|
|
4532
|
+
throw error62[Symbol.asyncIterator]=async function*(){for(let jwk2 of candidates)try{yield await importWithAlgCache(cached4,jwk2,entry)}catch{}},error62}return importWithAlgCache(cached4,jwk,entry)},"jwks",{value:()=>structuredClone(snapshot)})}var init_local=__esm({"node_modules/.pnpm/jose@6.2.10/node_modules/jose/dist/webapi/jwks/local.js"(){init_jwk_to_key();init_jws_algorithms();init_errors4();init_type_checks();init_jwk_metadata()}});var init_webapi=__esm({"node_modules/.pnpm/jose@6.2.10/node_modules/jose/dist/webapi/index.js"(){init_verify();init_local()}});import{createHash as createHash22,randomBytes as randomBytes7,randomUUID as randomUUID14,timingSafeEqual as timingSafeEqual2}from"node:crypto";import{chmodSync as chmodSync8,closeSync as closeSync16,lstatSync as lstatSync10,mkdirSync as mkdirSync32,openSync as openSync15,readFileSync as readFileSync40,rmSync as rmSync24,unlinkSync as unlinkSync9,writeFileSync as writeFileSync18}from"node:fs";import{createServer as createServer8}from"node:http";import{DatabaseSync as DatabaseSync4}from"node:sqlite";
|
|
4533
|
+
import{dirname as dirname35,isAbsolute as isAbsolute16,join as join77}from"node:path";import{setTimeout as delay}from"node:timers/promises";function object2(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("Invalid ChatGPT response.");return value}function string4(value,max=65536){return typeof value=="string"&&value.length>0&&value.length<=max}function privateDirectory(path3){if(mkdirSync32(path3,{recursive:!0,mode:448}),!lstatSync10(path3).isDirectory()||lstatSync10(
|
|
4534
|
+
path3).isSymbolicLink())throw new Error("ChatGPT credential storage must be a private directory.");chmodSync8(path3,448)}function readJson2(path3){try{let stat9=lstatSync10(path3);if(!stat9.isFile()||stat9.isSymbolicLink()||stat9.size>512e3)throw new Error("Invalid credential storage.");return chmodSync8(path3,384),JSON.parse(readFileSync40(path3,"utf8"))}catch(error62){if(error62.code==="ENOENT")return null;throw new Error("ChatGPT credential storage could not be read safely. Check its permissi\
|
|
4535
|
+
ons before signing in.")}}function recoverCredentialLock(path3){let guard=new DatabaseSync4(path3+".recovery.db");try{try{guard.exec("BEGIN IMMEDIATE")}catch(error62){if(error62.errcode===5)return!1;throw error62}let owner;try{owner=readFileSync40(path3,"utf8")}catch(error62){if(error62.code==="ENOENT")return!0;throw error62}if(!/^[1-9]\d{0,9}$/u.test(owner))return!1;try{process.kill(Number(owner),0)}catch(error62){if(error62.code==="ESRCH"){try{if(readFileSync40(path3,"utf8")!==owner)return!1;unlinkSync9(
|
|
4536
|
+
path3)}catch(changed2){if(changed2.code!=="ENOENT")throw changed2}return!0}}return!1}finally{guard.close()}}async function locked(directory,operation){let path3=join77(directory,".credentials.lock"),deadline=Date.now()+3e4,nextRecovery=0,fd;for(;;)try{fd=openSync15(path3,"wx",384);break}catch(error62){if(error62.code!=="EEXIST")throw new Error("ChatGPT credentials could not be locked safely.");if(Date.now()>=nextRecovery&&(nextRecovery=Date.now()+1e3,recoverCredentialLock(path3)))continue;if(Date.
|
|
4537
|
+
now()>=deadline)throw new Error("Another process is updating the ChatGPT sign-in. Please retry shortly.");await delay(50)}try{return writeFileSync18(fd,String(process.pid)),await operation()}finally{closeSync16(fd),unlinkSync9(path3)}}var ISSUER,RESOURCE,DIRECT_SCOPE,SCOPES,LIFETIME,TERMINAL_REFRESH,SIGN_IN,CONSENT,ChatGptPlanAuthController,init_chatgpt_plan_auth=__esm({"server/drivers/chatgpt-plan-auth.ts"(){"use strict";init_webapi();init_atomic();ISSUER="https://auth.openai.com",RESOURCE="htt\
|
|
4538
|
+
ps://api.openai.com/v1",DIRECT_SCOPE="chatgpt.tokens.use.direct",SCOPES=`openid profile email offline_access resource.invoke ${DIRECT_SCOPE}`,LIFETIME=15*6e4,TERMINAL_REFRESH=new Set(["invalid_grant","invalid_refresh_token","token_expired","refresh_token_expired","refresh_token_invalidated","refresh_token_reused"]),SIGN_IN="Continue with ChatGPT in Settings to use your ChatGPT plan.",CONSENT="ChatGPT plan usage is not enabled. Continue with ChatGPT in Settings and allow plan usage, or explicitly\
|
|
4539
|
+
choose another provider.";ChatGptPlanAuthController=class{options;issuer;resource;flow=null;disposed=!1;starting=null;retryClientId=null;refusedNow=new Set;constructor(options2){if(!isAbsolute16(options2.directory))throw new Error("ChatGPT credential storage must use an absolute path.");if(options2.testServerUrl){let url3=new URL(options2.testServerUrl);if(url3.protocol!=="http:"||url3.hostname!=="127.0.0.1"||url3.username||url3.password||url3.search||url3.hash||url3.pathname!=="/")throw new Error(
|
|
4540
|
+
"ChatGPT test endpoints must be a loopback origin.");this.issuer=url3.origin,this.resource=`${url3.origin}/v1`}else this.issuer=ISSUER,this.resource=RESOURCE;this.options=options2}prepare(){privateDirectory(dirname35(this.options.directory)),privateDirectory(this.options.directory)}read(){let raw=readJson2(join77(this.options.directory,"credentials.json"));if(raw===null)return null;let record12=object2(raw);if(!string4(record12.clientId,256)||record12.clientId==="dynamic_agent_client"||!string4(
|
|
4541
|
+
record12.subject,512)||!string4(record12.hostId,128)||record12.email!==void 0&&!string4(record12.email,320))throw new Error("Saved ChatGPT registration is invalid. Check credential storage before signing in.");if(record12.tokens!==void 0){let tokens2=object2(record12.tokens);if(!string4(tokens2.access)||typeof tokens2.refresh!="string"||tokens2.refresh.length>65536||!string4(tokens2.id)||!Array.isArray(tokens2.scopes)||!tokens2.scopes.every(scope=>string4(scope,256))||typeof tokens2.expiresAt!="\
|
|
4542
|
+
number"||!Number.isFinite(tokens2.expiresAt)||tokens2.scopes.includes(DIRECT_SCOPE)&&!tokens2.refresh||tokens2.earliestRefreshAt!==void 0&&(typeof tokens2.earliestRefreshAt!="number"||!Number.isFinite(tokens2.earliestRefreshAt)))throw new Error("Saved ChatGPT credentials are invalid. Continue with ChatGPT again.")}return record12}save(record12){writeFileAtomic(join77(this.options.directory,"credentials.json"),JSON.stringify(record12),{mode:384})}refusedPath(){return join77(this.options.directory,
|
|
4543
|
+
"refused-models.json")}savedRefused(subject){let raw=readJson2(this.refusedPath());if(raw===null)return[];let saved=object2(raw);return saved.subject===subject&&Array.isArray(saved.models)?saved.models.filter(slug2=>string4(slug2,256)):[]}refusedFor(subject){let saved=[];try{saved=this.savedRefused(subject)}catch{}return[...new Set([...saved,...this.refusedNow])]}clearRefused(){this.refusedNow.clear(),rmSync24(this.refusedPath(),{force:!0})}refusedModels(){try{let subject=this.read()?.subject;return subject?
|
|
4544
|
+
this.refusedFor(subject):[]}catch{return[]}}async refuseModel(slug2){this.disposed||!string4(slug2,256)||(this.refusedNow.add(slug2),this.prepare(),await locked(this.options.directory,async()=>{let subject=this.read()?.subject,models2=subject?this.savedRefused(subject):[];subject&&!models2.includes(slug2)&&writeFileAtomic(this.refusedPath(),JSON.stringify({subject,models:[...models2,slug2]}),{mode:384})}))}async hostId(){let parent=dirname35(this.options.directory);return locked(parent,async()=>{
|
|
4545
|
+
let path3=join77(parent,"host-id.json"),saved=readJson2(path3);if(saved!==null){let value2=object2(saved).hostId;if(!string4(value2)||!/^urn:uuid:[0-9a-f-]{36}$/i.test(value2))throw new Error("Saved ChatGPT host identity is invalid.");return value2}let value=`urn:uuid:${randomUUID14()}`;return writeFileAtomic(path3,JSON.stringify({hostId:value}),{mode:384}),value})}async request(url3,init={}){try{let response=await fetch(url3,{...init,redirect:"error",signal:init.signal?AbortSignal.any([init.signal,
|
|
4546
|
+
AbortSignal.timeout(15e3)]):AbortSignal.timeout(15e3)});if(Number(response.headers.get("content-length"))>1048576)throw new Error("Oversized response.");let reader=response.body?.getReader(),size=0,chunks=[];if(reader)for(;;){let{value,done}=await reader.read();if(done)break;if(size+=value.byteLength,size>1048576)throw await reader.cancel(),new Error("Oversized response.");chunks.push(value)}let text13=Buffer.concat(chunks).toString("utf8");return{response,body:text13?object2(JSON.parse(text13)):
|
|
4547
|
+
{}}}catch{throw new Error("Could not securely contact ChatGPT. Check your connection and try again; your saved account has not been removed.")}}async exchange(params,signal){return this.request(`${this.issuer}/api/accounts/oauth/token`,{method:"POST",body:params,signal})}tokenSet(body2,previous2){if(!string4(body2.access_token)||typeof body2.token_type!="string"||body2.token_type.toLowerCase()!=="bearer"||typeof body2.expires_in!="number"||!Number.isFinite(body2.expires_in)||body2.expires_in<=0||
|
|
4548
|
+
body2.expires_in>86400||body2.scope!==void 0&&typeof body2.scope!="string"||body2.id_token!==void 0&&!string4(body2.id_token))throw new Error("ChatGPT returned incomplete credentials. Continue with ChatGPT again.");let id2=string4(body2.id_token)?body2.id_token:previous2?.id;if(!id2)throw new Error("ChatGPT did not return a verifiable identity. Continue with ChatGPT again.");let scopes=typeof body2.scope=="string"?body2.scope.split(/\s+/).filter(Boolean):previous2?.scopes;if(!scopes)throw new Error(
|
|
4549
|
+
"ChatGPT did not confirm granted permissions. Continue with ChatGPT again.");if(scopes.includes(DIRECT_SCOPE)&&!string4(body2.refresh_token))throw new Error("ChatGPT did not provide renewable plan access. Continue with ChatGPT again.");return{access:body2.access_token,refresh:string4(body2.refresh_token)?body2.refresh_token:"",id:id2,scopes,expiresAt:Date.now()+body2.expires_in*1e3,...typeof body2.earliest_refresh_at=="number"&&Number.isFinite(body2.earliest_refresh_at)?{earliestRefreshAt:body2.
|
|
4550
|
+
earliest_refresh_at*1e3}:{}}}async identityKeys(signal){let{response,body:body2}=await this.request(`${this.issuer}/.well-known/jwks.json`,{signal});if(!response.ok)throw new Error("ChatGPT identity keys are unavailable. Try signing in again later.");try{if(!Array.isArray(body2.keys)||body2.keys.length===0)throw new Error("Empty identity keys.");return createLocalJWKSet(body2)}catch{throw new Error("ChatGPT identity keys could not be verified. Try signing in again later.")}}async identity(id2,clientId,keys,nonce){
|
|
4551
|
+
try{let{payload}=await jwtVerify(id2,keys,{issuer:this.issuer,audience:clientId,algorithms:["RS256","ES256"],requiredClaims:["sub","exp","iat"],clockTolerance:30});if(!string4(payload.sub,512)||typeof payload.iat!="number"||payload.iat>Date.now()/1e3+30||Array.isArray(payload.aud)&&payload.aud.length>1&&payload.azp!==clientId||nonce!==void 0&&payload.nonce!==nonce)throw new Error("Identity mismatch.");return{subject:payload.sub,...string4(payload.email,320)?{email:payload.email}:{}}}catch{throw new Error(
|
|
4552
|
+
"ChatGPT identity could not be verified. No account was replaced. Start sign-in again.")}}async start(){if(this.starting)return this.starting;this.starting=this.begin();try{return await this.starting}finally{this.starting=null}}async begin(){if(this.disposed)throw new Error("This provider was removed. Refresh Settings before signing in.");if(this.flow?.status.phase==="waiting")return{...this.flow.status,phase:"waiting"};this.prepare();let previous2=this.read(),clientId=previous2?.clientId??this.
|
|
4553
|
+
retryClientId,hostId=await this.hostId();if(previous2&&previous2.hostId!==hostId)throw new Error("This ChatGPT registration belongs to another host. Sign in using a new account entry on this host.");let state=randomBytes7(32).toString("base64url"),nonce=randomBytes7(32).toString("base64url"),verifier=randomBytes7(32).toString("base64url"),server=createServer8((request2,response)=>{response.setHeader("Cache-Control","no-store"),response.setHeader("Content-Type","text/plain; charset=utf-8"),response.
|
|
4554
|
+
setHeader("Referrer-Policy","no-referrer");let flow4=this.flow,callback;try{if(!flow4||request2.headers.host!==new URL(flow4.redirectUri).host||!request2.url?.startsWith("/"))throw new Error("Unexpected callback host.");if(callback=new URL(request2.url,flow4.redirectUri),callback.origin!==new URL(flow4.redirectUri).origin)throw new Error("Unexpected callback origin.")}catch{response.writeHead(400).end("Invalid sign-in callback. Return to Limix Bot and try again.");return}let actual=callback.searchParams.
|
|
4555
|
+
get("state")??"";if(request2.method!=="GET"||callback.pathname!=="/auth/callback"||!flow4||flow4.server!==server||flow4.consumed||flow4.status.phase!=="waiting"||Buffer.byteLength(actual)!==Buffer.byteLength(flow4.state)||!timingSafeEqual2(Buffer.from(actual),Buffer.from(flow4.state))||[...callback.searchParams.keys()].some(key2=>callback.searchParams.getAll(key2).length!==1)){response.writeHead(400).end("Invalid or expired sign-in. Return to Limix Bot and try again.");return}flow4.consumed=!0,response.
|
|
4556
|
+
end("Finishing sign-in. You can return to Limix Bot."),server.close(),this.complete(flow4,callback.searchParams)});if(await new Promise((resolve36,reject)=>{server.once("error",reject),server.listen(0,"127.0.0.1",resolve36)}),this.disposed)throw server.close(),new Error("This provider was removed.");let address2=server.address();if(!address2||typeof address2=="string")throw server.close(),new Error("ChatGPT sign-in listener could not start.");let redirectUri=`http://127.0.0.1:${address2.port}/au\
|
|
4557
|
+
th/callback`,url3=new URL(`${this.issuer}/api/accounts/authorize`);url3.search=new URLSearchParams({client_id:clientId??"dynamic_agent_client",ext_agent_host_id:hostId,...clientId?{}:{agent_name_hint:"Limix Bot"},...previous2?.email?{login_hint:previous2.email}:{},...previous2?.tokens&&!previous2.tokens.scopes.includes(DIRECT_SCOPE)?{prompt:"consent"}:{},response_type:"code",redirect_uri:redirectUri,scope:SCOPES,resource:this.resource,state,nonce,code_challenge_method:"S256",code_challenge:createHash22(
|
|
4558
|
+
"sha256").update(verifier).digest("base64url")}).toString();let status3={phase:"waiting",flowId:randomUUID14(),authorizationUrl:url3.href,expiresAt:new Date(Date.now()+LIFETIME).toISOString()},flow3={status:status3,state,nonce,verifier,redirectUri,previous:previous2,clientId,hostId,consumed:!1,server,abort:new AbortController,expiry:setTimeout(()=>this.finish(flow3,"expired","ChatGPT sign-in expired. Start again."),LIFETIME)};return flow3.expiry.unref(),this.flow=flow3,{...status3,phase:"waiting"}}finish(flow3,phase,message5){
|
|
4559
|
+
flow3.status.phase==="waiting"&&(clearTimeout(flow3.expiry),flow3.server.close(),flow3.abort.abort(),flow3.status={...flow3.status,phase,authorizationUrl:null,...message5?{message:message5}:{}})}async complete(flow3,params){try{if(params.has("error"))throw new Error("ChatGPT sign-in was not approved. You can try again in Settings.");let clientId=params.get("client_id")??flow3.clientId,code=params.get("code");if(!string4(clientId,256)||clientId==="dynamic_agent_client"||flow3.clientId&&flow3.clientId!==
|
|
4560
|
+
clientId||!string4(code,4096))throw new Error("ChatGPT registration was incomplete or did not match the selected account. Start sign-in again.");let keys=await this.identityKeys(flow3.abort.signal),{response,body:body2}=await this.exchange(new URLSearchParams({grant_type:"authorization_code",client_id:clientId,code,code_verifier:flow3.verifier,redirect_uri:flow3.redirectUri,resource:this.resource}),flow3.abort.signal);if(!response.ok)throw!flow3.previous&&body2.error==="invalid_grant"&&(this.retryClientId=
|
|
4561
|
+
clientId),new Error("ChatGPT could not finish this sign-in. Start again with a fresh authorization.");let tokens2=this.tokenSet(body2),identity=await this.identity(tokens2.id,clientId,keys,flow3.nonce);if(flow3.previous&&identity.subject!==flow3.previous.subject)throw new Error("ChatGPT returned a different account. Use a separate account entry; the saved account was not replaced.");await locked(this.options.directory,async()=>{if(!(this.disposed||flow3.status.phase!=="waiting"||flow3.abort.signal.
|
|
4562
|
+
aborted)){if(JSON.stringify(this.read())!==JSON.stringify(flow3.previous))throw new Error("The selected ChatGPT account changed during sign-in. Start again.");this.save({clientId,hostId:flow3.hostId,...identity,tokens:tokens2}),this.clearRefused(),this.retryClientId=null,this.finish(flow3,tokens2.scopes.includes(DIRECT_SCOPE)?"succeeded":"failed",tokens2.scopes.includes(DIRECT_SCOPE)?void 0:CONSENT)}}),flow3.status.phase==="succeeded"&&await this.options.onAuthenticated?.().catch(()=>{})}catch(error62){
|
|
4563
|
+
this.finish(flow3,"failed",error62 instanceof Error?error62.message:"ChatGPT sign-in could not finish. Try again.")}}async get(flowId){if(!flowId||this.flow?.status.flowId!==flowId)throw new Error("This sign-in is no longer available. Start again.");return{...this.flow.status}}async cancel(){await this.starting?.catch(()=>{}),this.flow&&this.finish(this.flow,"cancelled","ChatGPT sign-in cancelled.")}async dispose(){this.disposed=!0,await this.cancel(),this.flow=null}async snapshot(){let record12=this.
|
|
4564
|
+
read();return{authenticated:!!record12?.tokens?.scopes.includes(DIRECT_SCOPE),...record12?{account:{method:"login",...record12.email?{email:record12.email}:{},organization:`ChatGPT \xB7 ${record12.clientId.slice(-8)}`}}:{},...record12?.tokens?record12.tokens.scopes.includes(DIRECT_SCOPE)?{}:{reason:CONSENT}:{reason:SIGN_IN}}}async accessToken(){if(this.disposed)throw new Error("This ChatGPT provider was removed.");this.prepare();let cached4=this.read()?.tokens;return cached4?.scopes.includes(DIRECT_SCOPE)&&
|
|
4565
|
+
cached4.expiresAt>Date.now()+6e4?cached4.access:locked(this.options.directory,async()=>{if(this.disposed)throw new Error("This ChatGPT provider was removed.");let record12=this.read();if(!record12?.tokens)throw new Error(SIGN_IN);if(!record12.tokens.scopes.includes(DIRECT_SCOPE))throw new Error(CONSENT);if(record12.tokens.expiresAt>Date.now()+6e4)return record12.tokens.access;if((record12.tokens.earliestRefreshAt??0)>Date.now()){if(record12.tokens.expiresAt>Date.now())return record12.tokens.access;
|
|
4566
|
+
throw new Error("ChatGPT credentials cannot refresh yet. Please try again shortly.")}let keys=await this.identityKeys(),{response,body:body2}=await this.exchange(new URLSearchParams({grant_type:"refresh_token",client_id:record12.clientId,refresh_token:record12.tokens.refresh,resource:this.resource}));if(!response.ok){let code=typeof body2.error=="string"?body2.error:body2.error&&typeof body2.error=="object"?body2.error.code:void 0;throw typeof code=="string"&&TERMINAL_REFRESH.has(code)?(delete record12.
|
|
4567
|
+
tokens,this.save(record12),new Error(SIGN_IN)):code==="invalid_client"?new Error("ChatGPT did not accept this app registration. Check the integration configuration before trying again."):new Error("ChatGPT could not renew access right now. Try again later; your saved account has not been removed.")}let tokens2;try{if(tokens2=this.tokenSet(body2,record12.tokens),body2.id_token!==void 0&&(await this.identity(tokens2.id,record12.clientId,keys)).subject!==record12.subject)throw new Error("ChatGPT re\
|
|
4568
|
+
turned a different account during renewal.")}catch{throw delete record12.tokens,this.save(record12),new Error("ChatGPT renewal could not be verified. Continue with ChatGPT again in Settings.")}if(this.save({...record12,tokens:tokens2}),this.disposed)throw new Error("This ChatGPT provider was removed.");if(!tokens2.scopes.includes(DIRECT_SCOPE))throw new Error(CONSENT);return tokens2.access})}async models(){let record12=this.read();if(!record12?.tokens?.scopes.includes(DIRECT_SCOPE))return{default:"",
|
|
4569
|
+
options:[]};let refused=this.refusedFor(record12.subject),token=await this.accessToken(),{response,body:body2}=await this.request(`${this.resource}/models`,{headers:{Authorization:`Bearer ${token}`}});if(!response.ok)throw new Error(response.status===401||response.status===403?"ChatGPT did not authorize model access. Check this account's plan permissions in ChatGPT Settings.":"ChatGPT models are unavailable right now. Try refreshing later.");if(!Array.isArray(body2.models))throw new Error("ChatG\
|
|
4570
|
+
PT returned an invalid model catalog. No fallback models were selected.");let options2=[];for(let entry of body2.models){if(!entry||typeof entry!="object")continue;let row=entry;row.visibility!=="list"||!string4(row.slug,256)||/[\s\p{Cc}]/u.test(row.slug)||!string4(row.display_name,256)||options2.some(item=>item.id===row.slug)||refused.includes(row.slug)||options2.push({id:row.slug,label:row.display_name})}return{default:options2[0]?.id??"",options:options2}}async signOut(){if(this.disposed)throw new Error(
|
|
4571
|
+
"This provider was removed.");await this.cancel(),this.prepare(),await locked(this.options.directory,async()=>{let record12=this.read();if(!record12?.tokens)return;let revoked=!record12.tokens.refresh;try{if(!record12.tokens.refresh){delete record12.tokens,this.save(record12);return}let discovery=await this.request(`${this.issuer}/.well-known/openid-configuration`),endpoint=discovery.body.revocation_endpoint;if(discovery.response.ok&&discovery.body.issuer===this.issuer&&typeof endpoint=="string"&&
|
|
4572
|
+
new URL(endpoint).origin===this.issuer)for(let attempt=0;attempt<2&&!revoked;attempt++){try{let result2=await this.request(endpoint,{method:"POST",body:new URLSearchParams({token:record12.tokens.refresh,token_type_hint:"refresh_token",client_id:record12.clientId})});if(revoked=result2.response.status===200,result2.response.status<500)break}catch{}!revoked&&attempt===0&&await delay(250)}}catch{}if(delete record12.tokens,this.save(record12),this.clearRefused(),!revoked)throw Object.assign(new Error(
|
|
4573
|
+
"Signed out locally, but remote revocation was not confirmed. Disconnect Limix Bot in ChatGPT Settings \u2192 Usage to end access there."),{code:"chatgpt_revocation_unconfirmed"})})}}}});import{randomBytes as randomBytes8,timingSafeEqual as timingSafeEqual3}from"node:crypto";import{mkdtempSync as mkdtempSync9,rmSync as rmSync25}from"node:fs";import{createServer as createServer9}from"node:net";import{tmpdir as tmpdir12}from"node:os";import{join as join78}from"node:path";async function startChatGptTokenBridge(accessToken){let secret2=randomBytes8(32).toString("hex"),directory=process.platform==="win32"?void 0:mkdtempSync9(join78(tmpdir12(),"omb-auth-")),path3=directory?join78(directory,
|
|
4572
4574
|
"s"):`\\\\.\\pipe\\omb-auth-${randomBytes8(16).toString("hex")}`,connections=new Set,closed=!1,server=createServer9(socket=>{connections.add(socket),socket.on("close",()=>connections.delete(socket)),socket.on("error",()=>{});let input2="";socket.setTimeout(6e4,()=>socket.destroy()),socket.on("data",chunk=>{if(input2+=chunk.toString(),input2.length>128)return socket.destroy();if(!input2.endsWith(`
|
|
4573
4575
|
`))return;socket.removeAllListeners("data");let actual=Buffer.from(input2.trim()),expected=Buffer.from(secret2);if(actual.length!==expected.length||!timingSafeEqual3(actual,expected))return socket.destroy();accessToken().then(token=>{closed||socket.end(token)},()=>socket.destroy())})});try{await new Promise((resolve36,reject)=>{server.once("error",reject),server.listen(path3,resolve36)})}catch(error62){throw directory&&rmSync25(directory,{recursive:!0,force:!0}),error62}return{env:{OMB_CODEX_AUTH_SOCKET:path3,
|
|
4574
4576
|
OMB_CODEX_AUTH_SECRET:secret2},close(){if(!closed){closed=!0;for(let socket of connections)socket.destroy();server.close(),directory&&rmSync25(directory,{recursive:!0,force:!0})}}}}var init_chatgpt_plan_token_bridge=__esm({"server/drivers/chatgpt-plan-token-bridge.ts"(){"use strict"}});function chatgptPlanCodexArgs(renewing=!1){return["-c",'model_provider="openai_chatgpt_plan"',"-c",'model_providers.openai_chatgpt_plan.name="ChatGPT plan"',"-c",'model_providers.openai_chatgpt_plan.base_url="https://api.openai.com/v1"',...renewing?["-c",`model_providers.openai_chatgpt_plan.auth.command=${JSON.stringify(process.execPath)}`,"-c",`model_providers.openai_chatgpt_plan.auth.args=[${JSON.stringify(SPAWNED_PROXIES.chatgptPlanToken)}]`,"-c","model_providers.openai_chatgpt_plan.auth.refr\
|
|
@@ -6765,9 +6767,9 @@ bufferedBytes=0;try{waitingHandler.handler.onResponseError?.(waitingHandler.cont
|
|
|
6765
6767
|
isArray(skipHeaderNames))throw new TypeError(`expected opts.skipHeaderNames to be an array, got ${typeof skipHeaderNames}`);if(!Array.isArray(excludeHeaderNames))throw new TypeError(`expected opts.excludeHeaderNames to be an array, got ${typeof excludeHeaderNames}`);if(!Number.isFinite(maxBufferSize)||maxBufferSize<=0)throw new TypeError(`expected opts.maxBufferSize to be a positive finite number, got ${maxBufferSize}`);let skipHeaderNamesSet=new Set(skipHeaderNames.map(name=>name.toLowerCase())),
|
|
6766
6768
|
excludeHeaderNamesSet=new Set(excludeHeaderNames.map(name=>name.toLowerCase())),pendingRequests=new Map;return(dispatch,interceptorOrigin)=>(opts2,handler)=>{let requestOrigin=getInterceptorOrigin(opts2,interceptorOrigin);if(!requestOrigin||opts2.upgrade||methods.includes(opts2.method)===!1)return dispatch(opts2,handler);if(opts2={...opts2,headers:normalizeHeaders(opts2)},skipHeaderNamesSet.size>0){for(let headerName of Object.keys(opts2.headers))if(skipHeaderNamesSet.has(headerName.toLowerCase()))
|
|
6767
6769
|
return dispatch(opts2,handler)}let cacheKey2=makeCacheKey(opts2,requestOrigin),dedupeKey=makeDeduplicationKey(cacheKey2,excludeHeaderNamesSet),pendingHandler=pendingRequests.get(dedupeKey);if(pendingHandler)return pendingHandler.addWaitingHandler(handler)?!0:dispatch(opts2,handler);let deduplicationHandler=new DeduplicationHandler(handler,()=>{pendingRequests.delete(dedupeKey),pendingRequestsChannel.hasSubscribers&&pendingRequestsChannel.publish({size:pendingRequests.size,key:dedupeKey,type:"rem\
|
|
6768
|
-
oved"})},maxBufferSize);return pendingRequests.set(dedupeKey,deduplicationHandler),pendingRequestsChannel.hasSubscribers&&pendingRequestsChannel.publish({size:pendingRequests.size,key:dedupeKey,type:"added"}),dispatch(opts2,deduplicationHandler)}}}});var require_sqlite_cache_store=__commonJS({"node_modules/.pnpm/undici@8.11.2/node_modules/undici/lib/cache/sqlite-cache-store.js"(exports,module){"use strict";var{Writable}=__require("node:stream"),{assertCacheKey,assertCacheValue}=require_cache(),
|
|
6770
|
+
oved"})},maxBufferSize);return pendingRequests.set(dedupeKey,deduplicationHandler),pendingRequestsChannel.hasSubscribers&&pendingRequestsChannel.publish({size:pendingRequests.size,key:dedupeKey,type:"added"}),dispatch(opts2,deduplicationHandler)}}}});var require_sqlite_cache_store=__commonJS({"node_modules/.pnpm/undici@8.11.2/node_modules/undici/lib/cache/sqlite-cache-store.js"(exports,module){"use strict";var{Writable}=__require("node:stream"),{assertCacheKey,assertCacheValue}=require_cache(),DatabaseSync6,VERSION3=3,MAX_ENTRY_SIZE=2*1e3*1e3*1e3;module.exports=class{#maxEntrySize=MAX_ENTRY_SIZE;#maxCount=1/0;#db;#getValuesQuery;#updateValueQuery;#insertValueQuery;#deleteExpiredValuesQuery;#deleteByUrlQuery;#countEntriesQuery;#deleteOldValuesQuery;constructor(opts){
|
|
6769
6771
|
if(opts){if(typeof opts!="object")throw new TypeError("SqliteCacheStore options must be an object");if(opts.maxEntrySize!==void 0){if(typeof opts.maxEntrySize!="number"||!Number.isInteger(opts.maxEntrySize)||opts.maxEntrySize<0)throw new TypeError("SqliteCacheStore options.maxEntrySize must be a non-negative integer");if(opts.maxEntrySize>MAX_ENTRY_SIZE)throw new TypeError("SqliteCacheStore options.maxEntrySize must be less than 2gb");this.#maxEntrySize=opts.maxEntrySize}if(opts.maxCount!==void 0){
|
|
6770
|
-
if(typeof opts.maxCount!="number"||!Number.isInteger(opts.maxCount)||opts.maxCount<0)throw new TypeError("SqliteCacheStore options.maxCount must be a non-negative integer");this.#maxCount=opts.maxCount}}
|
|
6772
|
+
if(typeof opts.maxCount!="number"||!Number.isInteger(opts.maxCount)||opts.maxCount<0)throw new TypeError("SqliteCacheStore options.maxCount must be a non-negative integer");this.#maxCount=opts.maxCount}}DatabaseSync6||(DatabaseSync6=__require("node:sqlite").DatabaseSync),this.#db=new DatabaseSync6(opts?.location??":memory:"),this.#db.exec(`
|
|
6771
6773
|
PRAGMA journal_mode = WAL;
|
|
6772
6774
|
PRAGMA synchronous = NORMAL;
|
|
6773
6775
|
PRAGMA temp_store = memory;
|
|
@@ -7919,8 +7921,8 @@ nd Code default"},MODELS5={default:AGENT_DEFAULT2.id,options:[AGENT_DEFAULT2]},S
|
|
|
7919
7921
|
selectModel:{configId:"model",agentDefault:AGENT_DEFAULT2.id},modelVariants:!0,pickAuthMethod:()=>null,authFailure:"continue",isAuthenticated:env=>commandCodeSignedIn(env),classifyError:classifyCommandCodeError,describeAccountError:describeCommandCodeAccountError,accountErrorText:code=>code==="invalid_credentials"?void 0:{key:"chat.notice.commandCodeAccountRefused"},async configureSession({request:request2,sessionId,config:config3}){let modeId=config3.fullAuto?MODE_FULL:MODE_ASK;try{await request2(
|
|
7920
7922
|
"session/set_mode",{sessionId,modeId})}catch(error62){throw new Error(`Command Code rejected permission mode "${modeId}": ${error62.message}`)}},buildPromptText:turn=>turn.system?`${turn.system}
|
|
7921
7923
|
|
|
7922
|
-
${turn.text}`:turn.text},CommandCodeAgentDriver=createAcpDriver(SUPPORT3)}});import{DatabaseSync as
|
|
7923
|
-
trim())return!0;let db;try{return db=new
|
|
7924
|
+
${turn.text}`:turn.text},CommandCodeAgentDriver=createAcpDriver(SUPPORT3)}});import{DatabaseSync as DatabaseSync5}from"node:sqlite";import{join as join103}from"node:path";function kiroDataDir(env,platform=process.platform){let home2=userHome(env);return platform==="darwin"?join103(home2,"Library","Application Support","kiro-cli"):platform==="win32"?join103(env.LOCALAPPDATA?.trim()||join103(home2,"AppData","Local"),"kiro-cli"):join103(env.XDG_DATA_HOME?.trim()||join103(home2,".local","share"),"kiro-cli")}function kiroSignedIn(env,platform=process.platform){if(env[API_KEY_ENV2]?.
|
|
7925
|
+
trim())return!0;let db;try{return db=new DatabaseSync5(join103(kiroDataDir(env,platform),"data.sqlite3"),{readOnly:!0}),db.prepare("SELECT 1 FROM auth_kv WHERE key LIKE '%:token' AND length(value) > 0 LIMIT 1").get()!==void 0}catch{return!1}finally{db?.close()}}function resolveKiroModels(env,config3){return discoverAcpModels(env,config3.cli,SPAWN_ARGS3,DISCOVERY3)}function kiroUpdateFilter(){let hiddenTools=new Set;return update=>{let toolCallId=typeof update.toolCallId=="string"?update.toolCallId:
|
|
7924
7926
|
"";if(update._meta?.kiro?.toolId===CLOUD_CONFIG_TOOL)return toolCallId&&update.status!=="completed"&&update.status!=="failed"?hiddenTools.add(toolCallId):hiddenTools.delete(toolCallId),null;if(toolCallId&&hiddenTools.has(toolCallId))return(update.status==="completed"||update.status==="failed")&&hiddenTools.delete(toolCallId),null;let text13=update.sessionUpdate==="agent_message_chunk"?update.content?.text:void 0;if(typeof text13!="string"||!text13.includes(STEERING_ECHO))return update;let kept=text13.
|
|
7925
7927
|
slice(0,text13.indexOf(STEERING_ECHO)).trimEnd();return kept?{...update,content:{...update.content,text:kept}}:null}}function describeKiroAccountError(code){return code==="invalid_credentials"?LOGIN_NOTE4:"Kiro refused this request for the signed-in account. Check its Kiro plan and credits, then try again."}var AGENT_DEFAULT3,MODELS6,SPAWN_ARGS3,SIGN_IN4,API_KEY_ENV2,LOGIN_NOTE4,AUTH_METHODS,CLIENT_META,CLOUD_CONFIG_TOOL,STEERING_ECHO,DISCOVERY3,SUPPORT4,KiroAgentDriver,init_kiro=__esm({"server/\
|
|
7926
7928
|
drivers/acp/kiro.ts"(){"use strict";init_env_path();init_core3();init_custom_model_catalog();AGENT_DEFAULT3={id:"agent-default",label:"Kiro default"},MODELS6={default:AGENT_DEFAULT3.id,options:[AGENT_DEFAULT3]},SPAWN_ARGS3=["acp","--agent-engine=v3","--auth-method=cli"],SIGN_IN4="kiro-cli login",API_KEY_ENV2="KIRO_API_KEY",LOGIN_NOTE4=`Kiro is not signed in. Run ${SIGN_IN4} in a terminal, or set ${API_KEY_ENV2}, then check again.`,AUTH_METHODS=["aws-builder-id","aws-iam-identity-center","kiro-lo\
|