@cortexkit/opencode-openai-auth 1.9.1 → 1.9.2
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/bin.js +2 -2
- package/dist/{index-b79fxcrc.js → index-85w1x19b.js} +1 -1
- package/dist/{index-fqt90tbq.js → index-cb1kwn36.js} +18 -18
- package/dist/{index-hyjrm2vw.js → index-hpev556z.js} +1 -1
- package/dist/{index-mw7fqra8.js → index-qdy57ej9.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/v2/server.js +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{$e as k,Ze as w,_e as O}from"./index-6j3059fy.js";import{rf as h,wf as D}from"./index-hpb6k6st.js";import{Cf as j}from"./index-bvswyxpt.js";class g extends Error{operation;constructor(f){super(`a ${f} on a strict notification scope needs a session id`);this.name="RpcSessionRequiredError",this.operation=f}}function M(f){return typeof f==="string"&&f.length>0}var U=new Map;function y(f){let x=JSON.stringify([f.rpcRoot,f.directoryPrefix,f.registrationSessionId,...f.requireSession===!0?["strict"]:[]]),z=U.get(x);if(!z)z={queue:[],nextId:1,lastDrainAtBySession:new Map,lastDrainAtAny:0},U.set(x,z);return z}var m=100,t=3000;function i(f,x,z){if(f.requireSession===!0&&!M(z))throw new g("push");let H=y(f);if(H.queue.push({id:H.nextId++,type:"open-dialog",payload:x,sessionId:z}),H.queue.length>m)H.queue=H.queue.slice(-m)}function n(f,x=0,z){if(f.requireSession===!0&&!M(z))throw new g("drain");let H=y(f),Y=Date.now();if(H.lastDrainAtAny=Y,z!==void 0)H.lastDrainAtBySession.set(z,Y);let Z=f.sessionlessDrain==="broadcast-only",L=(B)=>z===void 0?!Z||B.sessionId===void 0:B.sessionId===void 0||B.sessionId===z;if(x>0)H.queue=H.queue.filter((B)=>{if(B.id>x)return!0;if(z===void 0)return!Z||B.sessionId!==void 0;return B.sessionId!==z});return H.queue.filter((B)=>B.id>x&&L(B))}function a(f,x){let z=Date.now(),H=y(f),Y=x!==void 0?H.lastDrainAtBySession.get(x)??0:f.sessionlessDrain==="broadcast-only"?H.lastDrainAtAny:0;return Y>0&&z-Y<t}import{randomBytes as v,timingSafeEqual as q}from"node:crypto";import{unlink as u}from"node:fs/promises";import{createServer as I}from"node:http";import{join as l}from"node:path";class N extends Error{status;constructor(f,x){if(!Number.isInteger(f)||f<400||f>499)throw RangeError(`RpcRequestError status must be 4xx, got ${f}`);super(x);this.name="RpcRequestError",this.status=f}}var E=1e6;class _ extends Error{declaredOversize;constructor(f){super("body too large");this.declaredOversize=f}}function p(f){return new Promise((x,z)=>{let H=(B=!1)=>{f.removeAllListeners("data"),f.on("data",()=>{}),f.resume(),z(new _(B))},Y=Number(f.headers["content-length"]);if(Number.isFinite(Y)&&Y>E){H(!0);return}let Z=[],L=0;f.on("data",(B)=>{if(L+=B.length,L>E){H();return}Z.push(B)}),f.on("end",()=>x(Buffer.concat(Z).toString("utf8"))),f.on("error",z)})}class S extends Error{}async function c(f,x){let z,H=new Promise((Y,Z)=>{z=setTimeout(()=>Z(new S("apply deadline exceeded")),x),z.unref?.()});f.catch(()=>{});try{return await Promise.race([f,H])}finally{clearTimeout(z)}}function d(f,x){if(!f?.startsWith("Bearer "))return!1;let z=Buffer.from(f.slice(7)),H=Buffer.from(x);return z.length===H.length&&q(z,H)}async function Bf(f){if(typeof f.drain==="function"===(typeof f.drainAsync==="function"))throw TypeError("exactly one of drain or drainAsync must be provided");let x=f.log??{warn(){},debug(){}},z=v(32).toString("hex"),H=f.timeoutMs??90000,Y=f.receiptTimeoutMs??2000,Z=!1,L=new Set,B=I((V,J)=>{V.setTimeout(H,()=>{V.socket.destroy()}),T(V,J)});B.on("connection",(V)=>{L.add(V),V.once("close",()=>L.delete(V))}),B.requestTimeout=Y,B.headersTimeout=Y;async function T(V,J){let G=(X,b,C={})=>{if(J.headersSent||J.writableEnded||J.destroyed)return;J.writeHead(X,{"content-type":"application/json",...C}),J.end(JSON.stringify(b))};try{let X=new URL(V.url??"/","http://127.0.0.1").pathname;if(V.method==="GET"&&X==="/health")return G(200,{ok:!0});if(V.method!=="POST"||!X.startsWith("/rpc/"))return G(404,{error:"not found"});if(!d(V.headers.authorization,z))return G(401,{error:"unauthorized"});let b=X.slice(5),C;try{C=await p(V)}catch($){if(!($ instanceof _))throw $;let P=V.socket;if(J.once("finish",()=>{P.end();let A=setTimeout(()=>P.destroy(),2000);if(A.unref(),V.once("end",()=>P.destroy()),P.once("close",()=>clearTimeout(A)),V.complete)P.destroy()}),!$.declaredOversize&&!V.complete){if(J.headersSent||J.writableEnded||J.destroyed)return;let A=JSON.stringify({error:"body too large"});J.writeHead(413,{"content-type":"application/json","content-length":Buffer.byteLength(A),connection:"close"}),J.write(A),V.once("end",()=>J.end());return}return G(413,{error:"body too large"},{connection:"close"})}let F;try{F=JSON.parse(C||"{}")}catch{return G(400,{error:"invalid json"})}if(b==="pending-notifications"){let $;try{if(f.parsePending)$=f.parsePending(F);else{if(!F||typeof F!=="object"||Array.isArray(F))throw Error("invalid params");let K=F;if(f.requireSession===!0&&!M(K.sessionId))return G(400,{error:"session required"});if("lastReceivedId"in K&&(typeof K.lastReceivedId!=="number"||!Number.isSafeInteger(K.lastReceivedId)||K.lastReceivedId<0)||"sessionId"in K&&typeof K.sessionId!=="string")throw Error("invalid params");$={lastReceivedId:Number(K.lastReceivedId??0),sessionId:typeof K.sessionId==="string"?K.sessionId:void 0}}}catch(K){if(K instanceof N)throw K;return G(400,{error:"invalid params"})}let{lastReceivedId:P,sessionId:A}=$;if(f.requireSession===!0&&!M(A))return G(400,{error:"session required"});if(A===void 0&&!Z)Z=!0,x.warn("rpc notification drain missing session id",{pid:process.pid});let W;if(f.drainAsync)try{W=await f.drainAsync(P,A)}catch(K){return x.warn("rpc notification drain failed",{pid:process.pid,error:K instanceof Error?K.message:String(K)}),G(500,{error:"drain failed"})}else W=f.drain?.(P,A);return G(200,{messages:W})}if(b==="apply"){let $=Promise.resolve(f.apply(F)),P=f.applyDeadlineMs===void 0?await $:await c($,f.applyDeadlineMs);return G(200,P)}return G(404,{error:"unknown method"})}catch(X){if(X instanceof N)return x.debug("rpc request refused",{pid:process.pid,status:X.status}),G(X.status,{error:X.message});if(X instanceof S)return x.warn("rpc apply deadline exceeded",{pid:process.pid,deadlineMs:f.applyDeadlineMs}),G(504,{error:"handler deadline exceeded"});x.warn("rpc request failed",{pid:process.pid,error:X instanceof Error?X.message:String(X)}),G(500,{error:"internal error"})}}let Q=await new Promise((V,J)=>{B.on("error",J),B.listen(0,"127.0.0.1",()=>{let G=B.address();if(G&&typeof G==="object")V(G.port);else J(Error("no port"))})});if(B.unref(),f.sweepRoot)try{await k(f.sweepRoot,f.dir,f.isManagedDir,x)}catch(V){x.warn("rpc state sweep failed",{pid:process.pid,error:V instanceof Error?V.message:String(V)})}try{await O(f.dir,{port:Q,token:z,pid:process.pid},{secureDir:f.secureDir}),x.debug("rpc server pid",{pid:process.pid,rpcPort:Q})}catch(V){throw await new Promise((J)=>B.close(()=>J())),V}return{port:Q,token:z,async stop(){await new Promise((G)=>{B.closeAllConnections?.(),B.close(()=>G());for(let X of L)X.destroy()});let V=l(f.dir,`port-${process.pid}.json`),J=await D(V).then((G)=>JSON.parse(G)).catch((G)=>{if(G instanceof h&&G.code!=="ENOENT")throw G;return});if(J?.port===Q&&J.token===z)await u(V).catch(()=>{})}}}async function Hf(f,x,z){let H=globalThis,Y=Symbol.for(f),Z=H[Y]??{servers:new Map,pending:new Map};H[Y]=Z;let{servers:L,pending:B}=Z,T=B.get(x)??Promise.resolve(),Q,V=T.catch(()=>{}).then(async()=>{let G=L.get(x);if(G){if(await G.stop(),L.get(x)===G)L.delete(x)}Q=await z(),L.set(x,Q)});B.set(x,V);try{await V}finally{if(B.get(x)===V)B.delete(x)}let J=Q;if(!J)throw Error("RPC server failed to start");return{server:J,release:async()=>{if(L.get(x)!==J)return;if(await J.stop(),L.get(x)===J)L.delete(x)}}}var R="1.9.
|
|
1
|
+
import{$e as k,Ze as w,_e as O}from"./index-6j3059fy.js";import{rf as h,wf as D}from"./index-hpb6k6st.js";import{Cf as j}from"./index-bvswyxpt.js";class g extends Error{operation;constructor(f){super(`a ${f} on a strict notification scope needs a session id`);this.name="RpcSessionRequiredError",this.operation=f}}function M(f){return typeof f==="string"&&f.length>0}var U=new Map;function y(f){let x=JSON.stringify([f.rpcRoot,f.directoryPrefix,f.registrationSessionId,...f.requireSession===!0?["strict"]:[]]),z=U.get(x);if(!z)z={queue:[],nextId:1,lastDrainAtBySession:new Map,lastDrainAtAny:0},U.set(x,z);return z}var m=100,t=3000;function i(f,x,z){if(f.requireSession===!0&&!M(z))throw new g("push");let H=y(f);if(H.queue.push({id:H.nextId++,type:"open-dialog",payload:x,sessionId:z}),H.queue.length>m)H.queue=H.queue.slice(-m)}function n(f,x=0,z){if(f.requireSession===!0&&!M(z))throw new g("drain");let H=y(f),Y=Date.now();if(H.lastDrainAtAny=Y,z!==void 0)H.lastDrainAtBySession.set(z,Y);let Z=f.sessionlessDrain==="broadcast-only",L=(B)=>z===void 0?!Z||B.sessionId===void 0:B.sessionId===void 0||B.sessionId===z;if(x>0)H.queue=H.queue.filter((B)=>{if(B.id>x)return!0;if(z===void 0)return!Z||B.sessionId!==void 0;return B.sessionId!==z});return H.queue.filter((B)=>B.id>x&&L(B))}function a(f,x){let z=Date.now(),H=y(f),Y=x!==void 0?H.lastDrainAtBySession.get(x)??0:f.sessionlessDrain==="broadcast-only"?H.lastDrainAtAny:0;return Y>0&&z-Y<t}import{randomBytes as v,timingSafeEqual as q}from"node:crypto";import{unlink as u}from"node:fs/promises";import{createServer as I}from"node:http";import{join as l}from"node:path";class N extends Error{status;constructor(f,x){if(!Number.isInteger(f)||f<400||f>499)throw RangeError(`RpcRequestError status must be 4xx, got ${f}`);super(x);this.name="RpcRequestError",this.status=f}}var E=1e6;class _ extends Error{declaredOversize;constructor(f){super("body too large");this.declaredOversize=f}}function p(f){return new Promise((x,z)=>{let H=(B=!1)=>{f.removeAllListeners("data"),f.on("data",()=>{}),f.resume(),z(new _(B))},Y=Number(f.headers["content-length"]);if(Number.isFinite(Y)&&Y>E){H(!0);return}let Z=[],L=0;f.on("data",(B)=>{if(L+=B.length,L>E){H();return}Z.push(B)}),f.on("end",()=>x(Buffer.concat(Z).toString("utf8"))),f.on("error",z)})}class S extends Error{}async function c(f,x){let z,H=new Promise((Y,Z)=>{z=setTimeout(()=>Z(new S("apply deadline exceeded")),x),z.unref?.()});f.catch(()=>{});try{return await Promise.race([f,H])}finally{clearTimeout(z)}}function d(f,x){if(!f?.startsWith("Bearer "))return!1;let z=Buffer.from(f.slice(7)),H=Buffer.from(x);return z.length===H.length&&q(z,H)}async function Bf(f){if(typeof f.drain==="function"===(typeof f.drainAsync==="function"))throw TypeError("exactly one of drain or drainAsync must be provided");let x=f.log??{warn(){},debug(){}},z=v(32).toString("hex"),H=f.timeoutMs??90000,Y=f.receiptTimeoutMs??2000,Z=!1,L=new Set,B=I((V,J)=>{V.setTimeout(H,()=>{V.socket.destroy()}),T(V,J)});B.on("connection",(V)=>{L.add(V),V.once("close",()=>L.delete(V))}),B.requestTimeout=Y,B.headersTimeout=Y;async function T(V,J){let G=(X,b,C={})=>{if(J.headersSent||J.writableEnded||J.destroyed)return;J.writeHead(X,{"content-type":"application/json",...C}),J.end(JSON.stringify(b))};try{let X=new URL(V.url??"/","http://127.0.0.1").pathname;if(V.method==="GET"&&X==="/health")return G(200,{ok:!0});if(V.method!=="POST"||!X.startsWith("/rpc/"))return G(404,{error:"not found"});if(!d(V.headers.authorization,z))return G(401,{error:"unauthorized"});let b=X.slice(5),C;try{C=await p(V)}catch($){if(!($ instanceof _))throw $;let P=V.socket;if(J.once("finish",()=>{P.end();let A=setTimeout(()=>P.destroy(),2000);if(A.unref(),V.once("end",()=>P.destroy()),P.once("close",()=>clearTimeout(A)),V.complete)P.destroy()}),!$.declaredOversize&&!V.complete){if(J.headersSent||J.writableEnded||J.destroyed)return;let A=JSON.stringify({error:"body too large"});J.writeHead(413,{"content-type":"application/json","content-length":Buffer.byteLength(A),connection:"close"}),J.write(A),V.once("end",()=>J.end());return}return G(413,{error:"body too large"},{connection:"close"})}let F;try{F=JSON.parse(C||"{}")}catch{return G(400,{error:"invalid json"})}if(b==="pending-notifications"){let $;try{if(f.parsePending)$=f.parsePending(F);else{if(!F||typeof F!=="object"||Array.isArray(F))throw Error("invalid params");let K=F;if(f.requireSession===!0&&!M(K.sessionId))return G(400,{error:"session required"});if("lastReceivedId"in K&&(typeof K.lastReceivedId!=="number"||!Number.isSafeInteger(K.lastReceivedId)||K.lastReceivedId<0)||"sessionId"in K&&typeof K.sessionId!=="string")throw Error("invalid params");$={lastReceivedId:Number(K.lastReceivedId??0),sessionId:typeof K.sessionId==="string"?K.sessionId:void 0}}}catch(K){if(K instanceof N)throw K;return G(400,{error:"invalid params"})}let{lastReceivedId:P,sessionId:A}=$;if(f.requireSession===!0&&!M(A))return G(400,{error:"session required"});if(A===void 0&&!Z)Z=!0,x.warn("rpc notification drain missing session id",{pid:process.pid});let W;if(f.drainAsync)try{W=await f.drainAsync(P,A)}catch(K){return x.warn("rpc notification drain failed",{pid:process.pid,error:K instanceof Error?K.message:String(K)}),G(500,{error:"drain failed"})}else W=f.drain?.(P,A);return G(200,{messages:W})}if(b==="apply"){let $=Promise.resolve(f.apply(F)),P=f.applyDeadlineMs===void 0?await $:await c($,f.applyDeadlineMs);return G(200,P)}return G(404,{error:"unknown method"})}catch(X){if(X instanceof N)return x.debug("rpc request refused",{pid:process.pid,status:X.status}),G(X.status,{error:X.message});if(X instanceof S)return x.warn("rpc apply deadline exceeded",{pid:process.pid,deadlineMs:f.applyDeadlineMs}),G(504,{error:"handler deadline exceeded"});x.warn("rpc request failed",{pid:process.pid,error:X instanceof Error?X.message:String(X)}),G(500,{error:"internal error"})}}let Q=await new Promise((V,J)=>{B.on("error",J),B.listen(0,"127.0.0.1",()=>{let G=B.address();if(G&&typeof G==="object")V(G.port);else J(Error("no port"))})});if(B.unref(),f.sweepRoot)try{await k(f.sweepRoot,f.dir,f.isManagedDir,x)}catch(V){x.warn("rpc state sweep failed",{pid:process.pid,error:V instanceof Error?V.message:String(V)})}try{await O(f.dir,{port:Q,token:z,pid:process.pid},{secureDir:f.secureDir}),x.debug("rpc server pid",{pid:process.pid,rpcPort:Q})}catch(V){throw await new Promise((J)=>B.close(()=>J())),V}return{port:Q,token:z,async stop(){await new Promise((G)=>{B.closeAllConnections?.(),B.close(()=>G());for(let X of L)X.destroy()});let V=l(f.dir,`port-${process.pid}.json`),J=await D(V).then((G)=>JSON.parse(G)).catch((G)=>{if(G instanceof h&&G.code!=="ENOENT")throw G;return});if(J?.port===Q&&J.token===z)await u(V).catch(()=>{})}}}async function Hf(f,x,z){let H=globalThis,Y=Symbol.for(f),Z=H[Y]??{servers:new Map,pending:new Map};H[Y]=Z;let{servers:L,pending:B}=Z,T=B.get(x)??Promise.resolve(),Q,V=T.catch(()=>{}).then(async()=>{let G=L.get(x);if(G){if(await G.stop(),L.get(x)===G)L.delete(x)}Q=await z(),L.set(x,Q)});B.set(x,V);try{await V}finally{if(B.get(x)===V)B.delete(x)}let J=Q;if(!J)throw Error("RPC server failed to start");return{server:J,release:async()=>{if(L.get(x)!==J)return;if(await J.stop(),L.get(x)===J)L.delete(x)}}}var R="1.9.2";function bf(f,x,z){let H={...x,version:R};return O(f,H,z)}var Cf=w(j);
|
|
2
2
|
export{i as Re,n as Se,a as Te,Bf as Ue,Hf as Ve,R as We,bf as Xe,Cf as Ye};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$a as w6,Ab as U9,Bb as O6,Cb as B3,Db as Y8,Ea as zX,Eb as t4,Fa as HX,Fb as LX,Ga as KX,Ha as UX,Ia as q6,Ib as h$,Ja as i8,Jb as J6,Ka as x1,La as JY,Ma as n1,Na as XY,Nb as v$,Oa as QY,Pa as GY,Pb as y$,Qa as $Y,Qb as a$,Ra as WY,Rb as t$,Sb as e$,Ta as IY,Tb as PG,Ua as bY,Va as S6,Wa as H3,Xa as K3,Ya as U3,Za as Z3,_a as V3,bb as v1,db as Q6,fb as w$,gb as h4,ja as D6,ka as uX,kb as LG,la as B$,lb as M6,ma as r,mb as I$,nb as b$,ob as G0,pa as M$,qb as VX,ra as $G,rb as uJ,sa as WG,sb as pJ,ta as A$,tb as BX,ua as T$,ub as k$,va as _G,vb as a4,wa as GX,wb as x$,xa as KY,xb as e6,ya as $X,yb as m9,za as WX,zb as K9}from"./index-fqt90tbq.js";import{$b as j1,Ac as H9,Bc as o$,Cc as r$,Dc as Z6,Ec as s$,Xb as g4,Zb as eX,ac as g$,dc as f$,hc as CG,ic as m$,jc as c$,kc as u$,pc as c9,qc as u9,rc as p$,sc as l$,vc as d$,wc as i$,xc as n$,zc as z9}from"./index-5sgqz46z.js";import{Be as C$,Ce as UG,De as I4,Ee as ZG,Fd as QX,Fe as VG,Ge as BG,Ld as c0,Mc as y1,Md as F$,Nd as w8,Oc as F6,Od as J8,Pd as D$,Rd as O$,Sd as s0,Uc as W9,Ud as _$,Xd as cJ,Yc as XG,Yd as C0,Zd as m6,_d as o8,ae as QG,be as S8,cd as mJ,ce as x4,de as I8,ed as U8,ee as X9,fd as N$,fe as T8,gd as M1,ge as V6,hd as s4,he as P$,id as j$,ie as q$,jd as rJ,je as z3,kd as sJ,ke as GG,ld as J1,le as B1,md as X1,me as r0,nd as a1,ne as r1,od as aJ,oe as HY,pd as tJ,qd as eJ,rd as YX,re as E$,sd as JX,se as E6,td as XX,te as S1,ud as n8,ue as I1,vd as X6,ve as zG,wd as f6,we as R8,xd as lQ,xe as R$,ye as HG,zd as tX,ze as KG}from"./index-6r27fz5a.js";import{Le as Q9}from"./index-mtf8pv2w.js";import{Re as vX,Se as yX,Te as gX,Ue as fG,Ve as L$,We as A1,Xe as mG,Ye as cG}from"./index-hyjrm2vw.js";import{df as AX,ff as J9,hf as H0,nf as h6,pf as ZX}from"./index-k1dfzavn.js";import{Af as MX,qf as L1,rf as Q8,uf as PX,vf as qX,wf as LY,xf as EX}from"./index-hpb6k6st.js";import{Cf as fX,Ef as S$}from"./index-bvswyxpt.js";import{Gf as gY}from"./index-2f9w48sc.js";import{createHash as EB,randomUUID as MB}from"node:crypto";import{statSync as AB}from"node:fs";import d4 from"node:os";import{readFile as IW}from"node:fs/promises";import{readFileSync as LW,statSync as NW}from"node:fs";import{homedir as jW,tmpdir as FW}from"node:os";import{join as u8}from"node:path";var DW="https://chatgpt.com/backend-api/codex/responses",bJ=536870912,OW=H0("config"),kJ=!1,_W="openai-auth.json",Y1={webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",dumpMaxBytes:"OPENCODE_OPENAI_AUTH_DUMP_MAX_BYTES",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function PW(){let Y=process.env[Y1.configDir]?.trim();if(Y)return Y;return u8(process.env.XDG_CONFIG_HOME||u8(jW(),".config"),"opencode")}function Y0(){return process.env[Y1.configFile]?.trim()||u8(PW(),_W)}function xJ(){try{let Y=JSON.parse(LW(Y0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function hJ(Y){let J=process.env[Y];if(J===void 0)return;let X=J.trim().toLowerCase();if(X==="1"||X==="true"||X==="yes"||X==="on")return!0;if(X===""||X==="0"||X==="false"||X==="no"||X==="off")return!1;return}function a6(Y,J,X){let Q=hJ(Y);if(Q!==void 0)return Q;if(typeof J==="boolean")return J;return X}function qW(Y){let J=process.env[Y1.dumpMaxBytes],X=J??Y;if(X===void 0)return bJ;let Q=J?.trim()?Number(J):X;if(typeof Q==="number"&&Number.isSafeInteger(Q)&&Q>=0)return Q;if(!kJ)kJ=!0,OW.warn("Invalid dumpMaxBytes; using the default 512 MiB cap",{env:Y1.dumpMaxBytes});return bJ}function vJ(Y){if(typeof Y.dump==="boolean")return Y.dump;if(Y.dump&&typeof Y.dump==="object")return Y.dump.enabled;return}var o1;function t6(){let Y=hJ(Y1.dump);if(Y!==void 0)return Y;let J=Y0(),X;try{X=NW(J)}catch{}if(o1?.path===J&&o1.mtimeMs===X?.mtimeMs&&o1.ctimeMs===X?.ctimeMs&&o1.size===X?.size)return o1.enabled;let Q=a6(Y1.dump,vJ(xJ()),!1);return o1={path:J,mtimeMs:X?.mtimeMs,ctimeMs:X?.ctimeMs,size:X?.size,enabled:Q},Q}function EW(){let Y=xJ();return{webSockets:a6(Y1.webSockets,Y.webSockets,!1),rawWebSocket:a6(Y1.rawWebSocket,Y.rawWebSocket,!1),responsesLite:a6(Y1.responsesLite,Y.responsesLite,!1),dump:a6(Y1.dump,vJ(Y),!1),dumpDir:process.env[Y1.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():u8(FW(),"opencode-openai-auth-dumps")),dumpMaxBytes:qW(Y.dumpMaxBytes),codexApiEndpoint:process.env[Y1.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():DW)}}var c8;function o0(){if(!c8)c8=EW();return c8}function yJ(){return c8=void 0,o1=void 0,o0()}import{readFileSync as MW}from"node:fs";var AW="The `main` account holds the login OpenCode signs in with (its login slot only points at it), so it cannot be removed. Sign in with another account through `opencode auth login` to replace it.";function TW(Y){return`The account-pool migration is moving OpenCode's login into \`${Y}\` right now, so it cannot be removed yet. Try again once the migration has finished.`}function _6(Y,J={}){return D6({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:F6,...J})}function zY(Y){try{let J=JSON.parse(MW(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return e6(J).migratedAt!==void 0}catch{return!1}}async function p8(Y,J){if(!zY(Y.configPath))return;let X=await J.read();return X.status==="ready"?X.rows:void 0}function l8(Y,J){if(Y===B1)return AW;if(e6(J.config).pending?.rowId===Y)return TW(Y);return}function RW(Y,J){return O6(Y,B1,J.legacyLocks).filter((X)=>X.name===Y8)}function E1(Y,J={}){return RW(Y,J)}var P6="This setup has no OpenAI login in its account store. Sign in for this setup with opencode auth login, or point OPENCODE_OPENAI_AUTH_FILE and OPENCODE_OPENAI_AUTH_STATE_FILE at the store that holds the login.";class s1 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function gJ(Y){let J=Y.storage,X=r1(J);if(!J||!X||c0(X))return;let Q=X,G=Y.now(),$=(J.refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!Q.access||!Q.expires||Q.expires-G<=$)&&!M1(Q.lastRefreshError,Q.refresh,G))try{Q=await Y.refreshAccount(Q,J)}catch(K){Y.warn?.("pool main row refresh failed",{error:K instanceof Error?K.message:String(K)})}let H=Q.access?.trim();if(!H)return;if(typeof Q.expires!=="number"||Q.expires<=Y.now())return;return{account:Q,token:H}}import{readFile as lJ}from"node:fs/promises";function d8(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function dJ(Y){let J=await cJ(Y.configPath),X=[];try{let G=JSON.parse(await lJ(Y.statePath,"utf8"));if(d8(G)){let $=G.accounts;if(d8($))X=Object.keys($)}}catch(G){if(G.code!=="ENOENT")throw G}return{rosterIds:J?[...J]:[],stateIds:X,orphanStateIds:J?X.filter((G)=>!J.has(G)):[]}}async function CW(Y){try{let J=JSON.parse(await lJ(Y.configPath,"utf8"));return d8(J)&&d8(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var fJ="Connect this host to the Claustrum vault (`opencode auth login` > Connect to the Claustrum vault, or the Vault section of `/openai`) if the vault holds the account, or sign in to the account again.";function iJ(Y){if(!Y)return;let J=Y.accounts.find((X)=>X.id==="main"&&s0(X));if(J)return J;if(!Y.mainAccountId)return;return Y.accounts.find((X)=>s0(X)&&X.accountId===Y.mainAccountId)}function wW(Y,J){let X=Y.lastRefreshError;return M1(X,Y.refresh,J)&&X!==void 0&&X.nextRetryAt!==void 0&&X.nextRetryAt-X.checkedAt>=mJ}function SW(Y){let J=[],X=[],Q=Y.now??Date.now(),G=iJ(Y.storage),$=!1;if(c0(Y.auth))J.push({code:"tombstoned-host-slot",message:`OpenCode's OpenAI slot holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${fJ}`});else if(r0(Y.auth)){if(!r1(Y.storage))J.push({code:"main-pool-row-missing",message:"The main account was moved into the account pool, but the pool has no usable `main` row."})}else if(!Y.auth)J.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),$=!0;else if(Y.auth.type!=="oauth")J.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),$=!0;else if(G&&(!Y.auth.refresh||G.refresh!==Y.auth.refresh))J.push({code:"main-refresh-not-in-store",message:"OpenCode's main credential does not match the copy in the account store."}),$=!0;if($&&G){let K={type:"restore-main-credential"};X.push(K);let U=J.find((V)=>V.code==="auth-slot-missing"||V.code==="auth-slot-not-oauth"||V.code==="main-refresh-not-in-store");if(U)U.repair=K}let W=Y.storage?.accounts??[];if(W.length===0)J.push({code:"no-accounts",message:"The account store has no accounts."});else if(!W.some((K)=>K.enabled!==!1))J.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let K of W){if(!s0(K)||!c0(K))continue;J.push({code:"tombstoned-account",accountId:K.id,message:`Account ${K.id} holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${fJ}`})}if(Y.retiredCustodyMode)J.push({code:"retired-custody-mode",message:"The config still selects the vault custody mode of an older version (`claustrum.mode`). It is ignored, and dropped at the next settings write; vault accounts are served once this host is connected to the Claustrum vault."});for(let K of W){if(!s0(K))continue;if(!wW(K,Q))continue;let U={type:"clear-refresh-backoff",accountId:K.id};X.push(U),J.push({code:"armed-non-transient-refresh-backoff",accountId:K.id,message:`Account ${K.id} has an armed non-transient refresh backoff.`,repair:U})}let H=[...Y.orphanStateIds??[]];if(H.length>0){let K={type:"prune-orphan-state-ids",ids:H};X.push(K),J.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${H.join(", ")}.`,repair:K})}return{findings:J,repairs:X}}function nJ(Y){let J=(X)=>{if(X.type==="restore-main-credential")return{label:"Copy the stored main credential back into OpenCode's slot",apply:async()=>{if(r0(await Y.readAuth()))return;let Q=iJ(await Y.loadAccounts(Y.paths));if(!Q)return;await Y.setMainAuth({refresh:Q.refresh,access:Q.access??"",expires:Q.expires??0})}};if(Y.migrated)return;if(X.type==="prune-orphan-state-ids")return{label:`Drop the state entries of ${X.ids.join(", ")}`,apply:async()=>{await Y.mutateAccounts((Q)=>Q,Y.paths)}};return{label:`Clear the refresh backoff of ${X.accountId}`,apply:async()=>{await Y.mutateAccounts((Q)=>{let G=Q.accounts.find(($)=>$.id===X.accountId&&s0($));if(G)G.lastRefreshError=void 0;return Q},Y.paths)}}};return[{id:"openai-auth",run:async()=>{let[X,Q,G,$]=await Promise.all([Y.loadAccounts(Y.paths),Y.readStoreIds(Y.paths),Y.readAuth(),CW(Y.paths)]),W=SW({auth:G.type==="missing"?void 0:G,storage:X,orphanStateIds:Q.orphanStateIds,retiredCustodyMode:$,now:Y.now()}),H=await D6({provider:"openai",quota:F6,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(H.status==="ready")for(let K of H.rows){if(K.disabledReason!==uJ)continue;W.findings.push({code:"slot-transfer-origin-unknown",accountId:K.id,message:`Account ${K.id} was preserved disabled after an interrupted transfer with an untagged placeholder; sole ownership could not be established. ${pJ}`})}return W.findings.map((K)=>{let U=K.repair?J(K.repair):void 0;return{code:K.code,message:K.message,...K.accountId!==void 0?{accountId:K.accountId}:{},...U?{repair:U}:{}}})}}]}var bW=ZX,oJ="OpenAI accounts",kW="ChatGPT accounts in the vault",xW="Uses the ChatGPT accounts in the Claustrum vault, with no sign-in. This works only while this host is connected to the vault and OpenCode has no OpenAI login stored; otherwise it fails and changes nothing.";async function hW(){let{redirectUri:Y}=await eJ(),J=await sJ(),X=rJ(crypto.getRandomValues(new Uint8Array(32)).buffer),Q=aJ(Y,J,X),G=YX(J,X);return{url:Q,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let $=await G;return{type:"success",refresh:$.refresh_token,access:$.access_token,expires:Date.now()+($.expires_in??3600)*1000,accountId:a1($)}}finally{tJ(X)}}}}async function vW(Y){let{deviceData:J,url:X,instructions:Q}=await JX(Y);return{url:X,instructions:Q,method:"auto",async callback(){try{let G=await XX(J,Y);return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:a1(G)}}catch{return{type:"failed"}}}}}function NX({client:Y,getAuth:J,getPaths:X=()=>G0(Y0()),fetchImpl:Q=fetch,packageVersion:G=A1,dependencies:$,onMainSlotWritten:W,vault:H}){let K={authorizeBrowser:$?.authorizeBrowser??hW,authorizeHeadless:$?.authorizeHeadless??(()=>vW(G)),beginAccountLogin:$?.beginAccountLogin??n8,loadAccounts:$?.loadAccounts??C0,mutateAccounts:$?.mutateAccounts??o8,readStoreIds:$?.readStoreIds??dJ,openBrowser:$?.openBrowser??bW,now:$?.now??Date.now,openAccountPool:$?.openAccountPool??_6,migrationBlockers:$?.migrationBlockers??(async()=>{let j=await M6({currentVersion:G});return j.open?[]:j.blockers.map((C)=>({pid:C.pid,version:C.version}))}),...$?.terminal?{terminal:$.terminal}:{},...$?.vaultWait?{vaultWait:$.vaultWait}:{}},U=async()=>await J?.().catch(()=>{return})??{type:"missing"},V=async()=>{if(H&&await H.authority()!=="local")return!0;if((await U()).type!=="missing")return!0;let j=X(),C=K.openAccountPool(j);if((await C.read()).status==="ready")return HX(C);return((await K.loadAccounts(j))?.accounts.length??0)>0},O=async(j)=>{if(await BX(X().configPath,async()=>{if(H&&await H.authority()!=="local")return!1;if(r0(await U()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...j}}),!0}))await W?.().catch(()=>{})},L=(j)=>({begin:async({headless:C,signal:u})=>{if(H&&await H.authority()!=="local")throw Error(q6);let E=await K.beginAccountLogin({version:G,headless:C,...u?{signal:u}:{}});return{url:E.url,instructions:E.instructions,completion:E.completion.then(async(h)=>{if(H&&await H.authority()!=="local")throw Error(q6);let y=await j.read(),n=y.status==="ready"?y.rows.find((B0)=>B0.id===B1)?.identity:void 0;if(h.accountId&&n&&h.accountId===n)throw Error("that account is already the OpenCode main credential");return{id:h.id,credential:{type:"oauth",refresh:h.refresh,...h.access!==void 0?{access:h.access}:{},...h.expires!==void 0?{expires:h.expires}:{}},...h.accountId!==void 0?{identity:h.accountId}:{},...h.label!==void 0?{label:h.label}:{}}})}},openBrowser:(C)=>K.openBrowser(C)}),B=async(j)=>{if(H&&await H.authority()!=="local")throw Error(q6);let C=j.credential;if(C?.type!=="oauth"||!C.access)throw Error("no usable access token for a quota check");let u=await J8({accessToken:C.access,fetchImpl:Q,now:K.now,...j.identity?{accountId:j.identity}:{},accountKey:j.id});return E6(u,K.now(),!0)},D=(j)=>nJ({paths:X(),migrated:j,readAuth:U,loadAccounts:K.loadAccounts,readStoreIds:K.readStoreIds,mutateAccounts:K.mutateAccounts,setMainAuth:O,now:K.now}),P=(j,C)=>({title:oJ,store:JY(C,{rowLocks:(u)=>O6(j,u)}),...K.terminal?{terminal:K.terminal}:{},login:L(C),protect:(u,E)=>l8(u,E),extraLocks:E1(j),pollQuota:B,doctor:D(!0),status:async()=>{let u=await H?.status();if(H&&await H.authority()!=="local"&&u)return[KY(H.host,H.name,u.enrollment)];return[`Routing: ${(await K.loadAccounts(j))?.routing?.mode??"main-first"}`,...H?[KY(H.host,H.name,(await H.status()).enrollment)]:[]]},...H?{extraActions:[M(H)]}:{}}),M=(j)=>{let C=j.enrolled();return{id:C?"vault-disconnect":"vault-connect",label:C?"Disconnect from the Claustrum vault":"Connect to the Claustrum vault",hint:"serve OpenAI accounts held in the vault",run:async(u)=>{let E=await j.authority();if(C){if(E!=="local")await j.disconnect();u.print("Disconnected from the Claustrum vault.");return}if(E!=="local"){u.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}u.print(`Asking the Claustrum vault to enroll ${j.name}…`);let h,y=await j.waitForApproval({...K.vaultWait,onPending:(n)=>{let V0=n.state==="pending"?n.requestId??n.retryCode??"":n.state;if(V0===h)return;h=V0;for(let B0 of GX(j.name,n))u.print(B0);u.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});u.print($X(j,y).text)}}},w=async()=>{let j=await K.migrationBlockers();return zX({title:oJ,status:["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. Account management opens after the move.",...j.length>0?["These processes still hold the move back:",...j.map((C)=>` ${C.pid==="unknown"?"processes that could not be read":`pid ${C.pid}`}: version ${C.version}`)]:[]],actions:[WX({checks:D(!1)})],...K.terminal?{terminal:K.terminal}:{}})},b=async(j)=>{let C=X(),u=K.openAccountPool(C);if(H&&await H.authority()!=="local")return i8(P(C,u),H);if(await p8(C,u)===void 0)return w();let E=P(C,u);return H?i8(E,H):KX(E)},k=(j)=>async()=>{if(H&&await H.authority()!=="local")throw Error(q6);let C=await j();if(C.method!=="auto")return C;return{...C,callback:async()=>{let u=await C.callback();if(H&&await H.authority()!=="local")return{type:"failed"};return u}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:UX({hasCredential:V,openMenu:b,login:k(()=>K.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:k(()=>K.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...H?.enrolled()?[{label:kW,type:"oauth",authorize:async()=>({url:"",instructions:xW,method:"auto",callback:async()=>{if(await QX(H.paths,H.name)!=="vault")return{type:"failed"};try{let j=JSON.parse(await IW(LX(),"utf8"));if(!j||typeof j!=="object"||Array.isArray(j)||Object.hasOwn(j,"openai"))return{type:"failed"}}catch(j){if(j.code!=="ENOENT")return{type:"failed"}}return{...VX,type:"success"}}})}]:[]]}var UY=["type","model","instructions","previous_response_id","input","tools","tool_choice","parallel_tool_calls","reasoning","store","stream","include","prompt_cache_key","text","generate","client_metadata"];function t1(Y){let J={};for(let X of UY)if(X in Y)J[X]=Y[X];for(let X of Object.keys(Y))if(!(X in J))J[X]=Y[X];return J}import{createHash as Jz}from"node:crypto";import{createHash as yW,randomBytes as jX}from"node:crypto";import{chmod as gW,lstat as FX,mkdir as fW,open as mW,readdir as TX,rename as cW,unlink as NY,writeFile as uW}from"node:fs/promises";import{join as r8,resolve as ZY}from"node:path";var pW=100,VY="session-unknown",lW=300000,dW=60000,iW=600000,nW=/\.(body|meta|request|response)\.json$/,oW=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+-\d{6,}-[a-zA-Z0-9._-]+$/,rW=/\.[a-f0-9]{24}\.partial$/;function RX(Y){let J=Y.replace(nW,"");if(J===Y||!oW.test(J))return;return J}function sW(Y){let J=Y.replace(rW,"");return J!==Y&&RX(J)!==void 0}async function DX(Y){let{dir:J,maxBytes:X}=Y,Q=Y.now??Date.now(),G=Y.minAgeMs??dW,$=Y.partialStaleMs??iW,W={removed:0,freedBytes:0};if(!(X>0))return W;try{if(L1)await PX(J,"directory");if((await FX(J)).isSymbolicLink())return W;let H=new Set((Y.protectedPaths??[]).map((M)=>ZY(M))),K=await TX(J,{withFileTypes:!0}),U=[];await Promise.all(K.map(async(M)=>{if(!M.isFile())return;let w=sW(M.name),b=w?void 0:RX(M.name);if(!w&&b===void 0)return;let k=r8(J,M.name);try{let j=await FX(k);if(!j.isFile())return;U.push({path:k,size:j.size,mtimeMs:j.mtimeMs,group:b})}catch{}}));let V=U.reduce((M,w)=>M+w.size,0),O=0,L=0,B=async(M)=>{try{await NY(M.path),V-=M.size,L+=M.size,O+=1}catch{}};for(let M of U){if(M.group!==void 0)continue;if(H.has(ZY(M.path)))continue;if(Q-M.mtimeMs<$)continue;await B(M)}let D=new Map;for(let M of U){if(M.group===void 0)continue;let w=D.get(M.group)??{files:[],newest:0};w.files.push(M),w.newest=Math.max(w.newest,M.mtimeMs),D.set(M.group,w)}let P=[...D.entries()].sort(([M,w],[b,k])=>w.newest-k.newest||M.localeCompare(b));for(let[,M]of P){if(V<=X)break;if(Q-M.newest<G)continue;if(M.files.some((w)=>H.has(ZY(w.path))))continue;for(let w of M.files)await B(w)}if(O>0)Y.logger?.debug("removed old dump files",{removed:O,freedBytes:L});return{removed:O,freedBytes:L}}catch(H){if(H instanceof Q8&&H.code==="ERR_PRIVATE_FILES_SECURITY")throw H;return W}}async function aW(Y,J,X){if(L1)return MX(Y,J,{stagePath:`${Y}.${X?X():jX(12).toString("hex")}.partial`});for(let Q=0;;Q+=1){let G=`${Y}.${X?X():jX(12).toString("hex")}.partial`,$=!1,W;try{W=await mW(G,"wx",384),$=!0,await W.writeFile(J,"utf8"),await W.chmod(384),await W.close(),W=void 0,await cW(G,Y);return}catch(H){if(await W?.close().catch(()=>{}),$)await NY(G).catch(()=>{});if(H.code==="EEXIST"&&Q===0)continue;throw H}}}function BY(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function X8(Y,J){let X=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!X)return J;return X.slice(0,80)}function OX(Y){return yW("sha256").update(Y).digest("hex")}function tW(Y){return Y.toLowerCase().replace(/[-_]/g,"")}function _X(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function eW(Y,J){if(Y===void 0)return null;if(Y===J)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:J.length};let X=0;while(X<Y.length&&X<J.length&&Y[X]===J[X])X++;let Q=Y.length-1,G=J.length-1;while(Q>=X&&G>=X&&Y[Q]===J[G])Q--,G--;return{changed:!0,firstByte:X,lastPreviousByte:Q,lastCurrentByte:G,changedPreviousBytes:Q-X+1,changedCurrentBytes:G-X+1,previousBytes:Y.length,currentBytes:J.length}}var Yz=0;function CX(Y){let J=Y.enabled===!0,X=Y.pid??process.pid,Q=Y.now??Date.now,G=Y.logger,$=new Set((Y.secretKeys??[]).map(tW)),W=AX({extraSecretKeys:(E)=>$.has(E),extraValuePatterns:[...Y.secretPatterns??[]]}),H=new Set(Y.schemaKeys??["tools"]),K=new Map,U=()=>typeof Y.dir==="function"?Y.dir():Y.dir;function V(E){let h=W.redact({[E]:null})[E];return h===null?void 0:h}function O(E){if(Array.isArray(E))return E.map(O);if(_X(E)){let h={};for(let[y,n]of Object.entries(E)){let V0=V(y);if(H.has(y))h[y]=W.redactStrings(n);else if(V0!==void 0)h[y]=V0;else h[y]=O(n)}return h}return W.redactStrings(E)}function L(E){let h;try{h=JSON.parse(E)}catch{return{text:W.redactStrings(E),parsed:void 0}}let y=O(h),n=JSON.stringify(y);return{text:JSON.stringify(h)===n?E:n,parsed:_X(y)?y:void 0}}async function B(E,h,y,n){let V0=`-${X8(h,VY)}-${X8(y,"channel")}`,B0;try{B0=await TX(E)}catch{return}let l=B0.filter((t)=>t.endsWith(".meta.json")&&t.includes(V0)).sort().reverse();for(let t of l)try{if(JSON.parse(await LY(r8(E,t),L1))?.baselineKey!==n)continue;return await LY(r8(E,t.replace(/\.meta\.json$/,".body.json")),L1)}catch(L0){if(L0 instanceof Q8&&(L1||L0.code==="ERR_PRIVATE_FILES_SECURITY"))throw L0}return}function D(E,h){if(!K.has(E))while(K.size>=pW){let y=K.keys().next().value;if(y===void 0)break;K.delete(y)}K.set(E,h)}async function P(E){if(!J)return;let h=++Yz,y=E.session?.trim()||VY,n=U(),V0=new Date(Q()).toISOString(),B0=[V0.replace(/[:.]/g,"-"),String(X),String(h).padStart(6,"0"),X8(y,VY),X8(E.channel,"channel"),...E.phase?[X8(E.phase,"phase")]:[]].join("-"),l=r8(n,B0),t={body:`${l}.body.json`,metadata:`${l}.meta.json`,request:`${l}.request.json`},L0=OX(`${E.channel}\x00${y}`);try{if(L1)await qX(n);else await fW(n,{recursive:!0,mode:448}),await gW(n,448);let v=K.get(L0),x0=v===void 0?void 0:"memory";if(v===void 0){if(v=await B(n,y,E.channel,L0),v!==void 0)x0="disk"}let R0=L(E.bodyText),U0={id:B0,createdAt:V0,pid:X,session:BY(y),channel:E.channel,...E.phase?{phase:E.phase}:{},accountId:E.accountId,status:E.status,error:E.error===void 0?void 0:W.redactStrings(E.error),baselineKey:L0,bodyBytes:Buffer.byteLength(E.bodyText,"utf8"),bodyHash:OX(E.bodyText),diff:eW(v,R0.text),baselineSource:x0,body:R0.parsed?{parseable:!0,...Y.summarize?.(R0.parsed)}:{parseable:!1},...E.meta?{extra:O(E.meta)}:{},files:t},s=O({url:E.url,method:E.method,accountId:E.accountId,headers:E.headers===void 0?void 0:Object.fromEntries(new Headers(E.headers).entries())}),E0=(i,g)=>L1?EX(i,g):uW(i,g,{encoding:"utf8",mode:384,flag:"wx"}),d=[[t.body,R0.text],[t.metadata,`${JSON.stringify(U0,null,2)}
|
|
1
|
+
import{$a as w6,Ab as U9,Bb as O6,Cb as B3,Db as Y8,Ea as zX,Eb as t4,Fa as HX,Fb as LX,Ga as KX,Ha as UX,Ia as q6,Ib as h$,Ja as i8,Jb as J6,Ka as x1,La as JY,Ma as n1,Na as XY,Nb as v$,Oa as QY,Pa as GY,Pb as y$,Qa as $Y,Qb as a$,Ra as WY,Rb as t$,Sb as e$,Ta as IY,Tb as PG,Ua as bY,Va as S6,Wa as H3,Xa as K3,Ya as U3,Za as Z3,_a as V3,bb as v1,db as Q6,fb as w$,gb as h4,ja as D6,ka as uX,kb as LG,la as B$,lb as M6,ma as r,mb as I$,nb as b$,ob as G0,pa as M$,qb as VX,ra as $G,rb as uJ,sa as WG,sb as pJ,ta as A$,tb as BX,ua as T$,ub as k$,va as _G,vb as a4,wa as GX,wb as x$,xa as KY,xb as e6,ya as $X,yb as m9,za as WX,zb as K9}from"./index-cb1kwn36.js";import{$b as j1,Ac as H9,Bc as o$,Cc as r$,Dc as Z6,Ec as s$,Xb as g4,Zb as eX,ac as g$,dc as f$,hc as CG,ic as m$,jc as c$,kc as u$,pc as c9,qc as u9,rc as p$,sc as l$,vc as d$,wc as i$,xc as n$,zc as z9}from"./index-5sgqz46z.js";import{Be as C$,Ce as UG,De as I4,Ee as ZG,Fd as QX,Fe as VG,Ge as BG,Ld as c0,Mc as y1,Md as F$,Nd as w8,Oc as F6,Od as J8,Pd as D$,Rd as O$,Sd as s0,Uc as W9,Ud as _$,Xd as cJ,Yc as XG,Yd as C0,Zd as m6,_d as o8,ae as QG,be as S8,cd as mJ,ce as x4,de as I8,ed as U8,ee as X9,fd as N$,fe as T8,gd as M1,ge as V6,hd as s4,he as P$,id as j$,ie as q$,jd as rJ,je as z3,kd as sJ,ke as GG,ld as J1,le as B1,md as X1,me as r0,nd as a1,ne as r1,od as aJ,oe as HY,pd as tJ,qd as eJ,rd as YX,re as E$,sd as JX,se as E6,td as XX,te as S1,ud as n8,ue as I1,vd as X6,ve as zG,wd as f6,we as R8,xd as lQ,xe as R$,ye as HG,zd as tX,ze as KG}from"./index-6r27fz5a.js";import{Le as Q9}from"./index-mtf8pv2w.js";import{Re as vX,Se as yX,Te as gX,Ue as fG,Ve as L$,We as A1,Xe as mG,Ye as cG}from"./index-hpev556z.js";import{df as AX,ff as J9,hf as H0,nf as h6,pf as ZX}from"./index-k1dfzavn.js";import{Af as MX,qf as L1,rf as Q8,uf as PX,vf as qX,wf as LY,xf as EX}from"./index-hpb6k6st.js";import{Cf as fX,Ef as S$}from"./index-bvswyxpt.js";import{Gf as gY}from"./index-2f9w48sc.js";import{createHash as EB,randomUUID as MB}from"node:crypto";import{statSync as AB}from"node:fs";import d4 from"node:os";import{readFile as IW}from"node:fs/promises";import{readFileSync as LW,statSync as NW}from"node:fs";import{homedir as jW,tmpdir as FW}from"node:os";import{join as u8}from"node:path";var DW="https://chatgpt.com/backend-api/codex/responses",bJ=536870912,OW=H0("config"),kJ=!1,_W="openai-auth.json",Y1={webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",dumpMaxBytes:"OPENCODE_OPENAI_AUTH_DUMP_MAX_BYTES",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function PW(){let Y=process.env[Y1.configDir]?.trim();if(Y)return Y;return u8(process.env.XDG_CONFIG_HOME||u8(jW(),".config"),"opencode")}function Y0(){return process.env[Y1.configFile]?.trim()||u8(PW(),_W)}function xJ(){try{let Y=JSON.parse(LW(Y0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function hJ(Y){let J=process.env[Y];if(J===void 0)return;let X=J.trim().toLowerCase();if(X==="1"||X==="true"||X==="yes"||X==="on")return!0;if(X===""||X==="0"||X==="false"||X==="no"||X==="off")return!1;return}function a6(Y,J,X){let Q=hJ(Y);if(Q!==void 0)return Q;if(typeof J==="boolean")return J;return X}function qW(Y){let J=process.env[Y1.dumpMaxBytes],X=J??Y;if(X===void 0)return bJ;let Q=J?.trim()?Number(J):X;if(typeof Q==="number"&&Number.isSafeInteger(Q)&&Q>=0)return Q;if(!kJ)kJ=!0,OW.warn("Invalid dumpMaxBytes; using the default 512 MiB cap",{env:Y1.dumpMaxBytes});return bJ}function vJ(Y){if(typeof Y.dump==="boolean")return Y.dump;if(Y.dump&&typeof Y.dump==="object")return Y.dump.enabled;return}var o1;function t6(){let Y=hJ(Y1.dump);if(Y!==void 0)return Y;let J=Y0(),X;try{X=NW(J)}catch{}if(o1?.path===J&&o1.mtimeMs===X?.mtimeMs&&o1.ctimeMs===X?.ctimeMs&&o1.size===X?.size)return o1.enabled;let Q=a6(Y1.dump,vJ(xJ()),!1);return o1={path:J,mtimeMs:X?.mtimeMs,ctimeMs:X?.ctimeMs,size:X?.size,enabled:Q},Q}function EW(){let Y=xJ();return{webSockets:a6(Y1.webSockets,Y.webSockets,!1),rawWebSocket:a6(Y1.rawWebSocket,Y.rawWebSocket,!1),responsesLite:a6(Y1.responsesLite,Y.responsesLite,!1),dump:a6(Y1.dump,vJ(Y),!1),dumpDir:process.env[Y1.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():u8(FW(),"opencode-openai-auth-dumps")),dumpMaxBytes:qW(Y.dumpMaxBytes),codexApiEndpoint:process.env[Y1.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():DW)}}var c8;function o0(){if(!c8)c8=EW();return c8}function yJ(){return c8=void 0,o1=void 0,o0()}import{readFileSync as MW}from"node:fs";var AW="The `main` account holds the login OpenCode signs in with (its login slot only points at it), so it cannot be removed. Sign in with another account through `opencode auth login` to replace it.";function TW(Y){return`The account-pool migration is moving OpenCode's login into \`${Y}\` right now, so it cannot be removed yet. Try again once the migration has finished.`}function _6(Y,J={}){return D6({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:F6,...J})}function zY(Y){try{let J=JSON.parse(MW(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return e6(J).migratedAt!==void 0}catch{return!1}}async function p8(Y,J){if(!zY(Y.configPath))return;let X=await J.read();return X.status==="ready"?X.rows:void 0}function l8(Y,J){if(Y===B1)return AW;if(e6(J.config).pending?.rowId===Y)return TW(Y);return}function RW(Y,J){return O6(Y,B1,J.legacyLocks).filter((X)=>X.name===Y8)}function E1(Y,J={}){return RW(Y,J)}var P6="This setup has no OpenAI login in its account store. Sign in for this setup with opencode auth login, or point OPENCODE_OPENAI_AUTH_FILE and OPENCODE_OPENAI_AUTH_STATE_FILE at the store that holds the login.";class s1 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function gJ(Y){let J=Y.storage,X=r1(J);if(!J||!X||c0(X))return;let Q=X,G=Y.now(),$=(J.refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!Q.access||!Q.expires||Q.expires-G<=$)&&!M1(Q.lastRefreshError,Q.refresh,G))try{Q=await Y.refreshAccount(Q,J)}catch(K){Y.warn?.("pool main row refresh failed",{error:K instanceof Error?K.message:String(K)})}let H=Q.access?.trim();if(!H)return;if(typeof Q.expires!=="number"||Q.expires<=Y.now())return;return{account:Q,token:H}}import{readFile as lJ}from"node:fs/promises";function d8(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function dJ(Y){let J=await cJ(Y.configPath),X=[];try{let G=JSON.parse(await lJ(Y.statePath,"utf8"));if(d8(G)){let $=G.accounts;if(d8($))X=Object.keys($)}}catch(G){if(G.code!=="ENOENT")throw G}return{rosterIds:J?[...J]:[],stateIds:X,orphanStateIds:J?X.filter((G)=>!J.has(G)):[]}}async function CW(Y){try{let J=JSON.parse(await lJ(Y.configPath,"utf8"));return d8(J)&&d8(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var fJ="Connect this host to the Claustrum vault (`opencode auth login` > Connect to the Claustrum vault, or the Vault section of `/openai`) if the vault holds the account, or sign in to the account again.";function iJ(Y){if(!Y)return;let J=Y.accounts.find((X)=>X.id==="main"&&s0(X));if(J)return J;if(!Y.mainAccountId)return;return Y.accounts.find((X)=>s0(X)&&X.accountId===Y.mainAccountId)}function wW(Y,J){let X=Y.lastRefreshError;return M1(X,Y.refresh,J)&&X!==void 0&&X.nextRetryAt!==void 0&&X.nextRetryAt-X.checkedAt>=mJ}function SW(Y){let J=[],X=[],Q=Y.now??Date.now(),G=iJ(Y.storage),$=!1;if(c0(Y.auth))J.push({code:"tombstoned-host-slot",message:`OpenCode's OpenAI slot holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${fJ}`});else if(r0(Y.auth)){if(!r1(Y.storage))J.push({code:"main-pool-row-missing",message:"The main account was moved into the account pool, but the pool has no usable `main` row."})}else if(!Y.auth)J.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),$=!0;else if(Y.auth.type!=="oauth")J.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),$=!0;else if(G&&(!Y.auth.refresh||G.refresh!==Y.auth.refresh))J.push({code:"main-refresh-not-in-store",message:"OpenCode's main credential does not match the copy in the account store."}),$=!0;if($&&G){let K={type:"restore-main-credential"};X.push(K);let U=J.find((V)=>V.code==="auth-slot-missing"||V.code==="auth-slot-not-oauth"||V.code==="main-refresh-not-in-store");if(U)U.repair=K}let W=Y.storage?.accounts??[];if(W.length===0)J.push({code:"no-accounts",message:"The account store has no accounts."});else if(!W.some((K)=>K.enabled!==!1))J.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let K of W){if(!s0(K)||!c0(K))continue;J.push({code:"tombstoned-account",accountId:K.id,message:`Account ${K.id} holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${fJ}`})}if(Y.retiredCustodyMode)J.push({code:"retired-custody-mode",message:"The config still selects the vault custody mode of an older version (`claustrum.mode`). It is ignored, and dropped at the next settings write; vault accounts are served once this host is connected to the Claustrum vault."});for(let K of W){if(!s0(K))continue;if(!wW(K,Q))continue;let U={type:"clear-refresh-backoff",accountId:K.id};X.push(U),J.push({code:"armed-non-transient-refresh-backoff",accountId:K.id,message:`Account ${K.id} has an armed non-transient refresh backoff.`,repair:U})}let H=[...Y.orphanStateIds??[]];if(H.length>0){let K={type:"prune-orphan-state-ids",ids:H};X.push(K),J.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${H.join(", ")}.`,repair:K})}return{findings:J,repairs:X}}function nJ(Y){let J=(X)=>{if(X.type==="restore-main-credential")return{label:"Copy the stored main credential back into OpenCode's slot",apply:async()=>{if(r0(await Y.readAuth()))return;let Q=iJ(await Y.loadAccounts(Y.paths));if(!Q)return;await Y.setMainAuth({refresh:Q.refresh,access:Q.access??"",expires:Q.expires??0})}};if(Y.migrated)return;if(X.type==="prune-orphan-state-ids")return{label:`Drop the state entries of ${X.ids.join(", ")}`,apply:async()=>{await Y.mutateAccounts((Q)=>Q,Y.paths)}};return{label:`Clear the refresh backoff of ${X.accountId}`,apply:async()=>{await Y.mutateAccounts((Q)=>{let G=Q.accounts.find(($)=>$.id===X.accountId&&s0($));if(G)G.lastRefreshError=void 0;return Q},Y.paths)}}};return[{id:"openai-auth",run:async()=>{let[X,Q,G,$]=await Promise.all([Y.loadAccounts(Y.paths),Y.readStoreIds(Y.paths),Y.readAuth(),CW(Y.paths)]),W=SW({auth:G.type==="missing"?void 0:G,storage:X,orphanStateIds:Q.orphanStateIds,retiredCustodyMode:$,now:Y.now()}),H=await D6({provider:"openai",quota:F6,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(H.status==="ready")for(let K of H.rows){if(K.disabledReason!==uJ)continue;W.findings.push({code:"slot-transfer-origin-unknown",accountId:K.id,message:`Account ${K.id} was preserved disabled after an interrupted transfer with an untagged placeholder; sole ownership could not be established. ${pJ}`})}return W.findings.map((K)=>{let U=K.repair?J(K.repair):void 0;return{code:K.code,message:K.message,...K.accountId!==void 0?{accountId:K.accountId}:{},...U?{repair:U}:{}}})}}]}var bW=ZX,oJ="OpenAI accounts",kW="ChatGPT accounts in the vault",xW="Uses the ChatGPT accounts in the Claustrum vault, with no sign-in. This works only while this host is connected to the vault and OpenCode has no OpenAI login stored; otherwise it fails and changes nothing.";async function hW(){let{redirectUri:Y}=await eJ(),J=await sJ(),X=rJ(crypto.getRandomValues(new Uint8Array(32)).buffer),Q=aJ(Y,J,X),G=YX(J,X);return{url:Q,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let $=await G;return{type:"success",refresh:$.refresh_token,access:$.access_token,expires:Date.now()+($.expires_in??3600)*1000,accountId:a1($)}}finally{tJ(X)}}}}async function vW(Y){let{deviceData:J,url:X,instructions:Q}=await JX(Y);return{url:X,instructions:Q,method:"auto",async callback(){try{let G=await XX(J,Y);return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:a1(G)}}catch{return{type:"failed"}}}}}function NX({client:Y,getAuth:J,getPaths:X=()=>G0(Y0()),fetchImpl:Q=fetch,packageVersion:G=A1,dependencies:$,onMainSlotWritten:W,vault:H}){let K={authorizeBrowser:$?.authorizeBrowser??hW,authorizeHeadless:$?.authorizeHeadless??(()=>vW(G)),beginAccountLogin:$?.beginAccountLogin??n8,loadAccounts:$?.loadAccounts??C0,mutateAccounts:$?.mutateAccounts??o8,readStoreIds:$?.readStoreIds??dJ,openBrowser:$?.openBrowser??bW,now:$?.now??Date.now,openAccountPool:$?.openAccountPool??_6,migrationBlockers:$?.migrationBlockers??(async()=>{let j=await M6({currentVersion:G});return j.open?[]:j.blockers.map((C)=>({pid:C.pid,version:C.version}))}),...$?.terminal?{terminal:$.terminal}:{},...$?.vaultWait?{vaultWait:$.vaultWait}:{}},U=async()=>await J?.().catch(()=>{return})??{type:"missing"},V=async()=>{if(H&&await H.authority()!=="local")return!0;if((await U()).type!=="missing")return!0;let j=X(),C=K.openAccountPool(j);if((await C.read()).status==="ready")return HX(C);return((await K.loadAccounts(j))?.accounts.length??0)>0},O=async(j)=>{if(await BX(X().configPath,async()=>{if(H&&await H.authority()!=="local")return!1;if(r0(await U()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...j}}),!0}))await W?.().catch(()=>{})},L=(j)=>({begin:async({headless:C,signal:u})=>{if(H&&await H.authority()!=="local")throw Error(q6);let E=await K.beginAccountLogin({version:G,headless:C,...u?{signal:u}:{}});return{url:E.url,instructions:E.instructions,completion:E.completion.then(async(h)=>{if(H&&await H.authority()!=="local")throw Error(q6);let y=await j.read(),n=y.status==="ready"?y.rows.find((B0)=>B0.id===B1)?.identity:void 0;if(h.accountId&&n&&h.accountId===n)throw Error("that account is already the OpenCode main credential");return{id:h.id,credential:{type:"oauth",refresh:h.refresh,...h.access!==void 0?{access:h.access}:{},...h.expires!==void 0?{expires:h.expires}:{}},...h.accountId!==void 0?{identity:h.accountId}:{},...h.label!==void 0?{label:h.label}:{}}})}},openBrowser:(C)=>K.openBrowser(C)}),B=async(j)=>{if(H&&await H.authority()!=="local")throw Error(q6);let C=j.credential;if(C?.type!=="oauth"||!C.access)throw Error("no usable access token for a quota check");let u=await J8({accessToken:C.access,fetchImpl:Q,now:K.now,...j.identity?{accountId:j.identity}:{},accountKey:j.id});return E6(u,K.now(),!0)},D=(j)=>nJ({paths:X(),migrated:j,readAuth:U,loadAccounts:K.loadAccounts,readStoreIds:K.readStoreIds,mutateAccounts:K.mutateAccounts,setMainAuth:O,now:K.now}),P=(j,C)=>({title:oJ,store:JY(C,{rowLocks:(u)=>O6(j,u)}),...K.terminal?{terminal:K.terminal}:{},login:L(C),protect:(u,E)=>l8(u,E),extraLocks:E1(j),pollQuota:B,doctor:D(!0),status:async()=>{let u=await H?.status();if(H&&await H.authority()!=="local"&&u)return[KY(H.host,H.name,u.enrollment)];return[`Routing: ${(await K.loadAccounts(j))?.routing?.mode??"main-first"}`,...H?[KY(H.host,H.name,(await H.status()).enrollment)]:[]]},...H?{extraActions:[M(H)]}:{}}),M=(j)=>{let C=j.enrolled();return{id:C?"vault-disconnect":"vault-connect",label:C?"Disconnect from the Claustrum vault":"Connect to the Claustrum vault",hint:"serve OpenAI accounts held in the vault",run:async(u)=>{let E=await j.authority();if(C){if(E!=="local")await j.disconnect();u.print("Disconnected from the Claustrum vault.");return}if(E!=="local"){u.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}u.print(`Asking the Claustrum vault to enroll ${j.name}…`);let h,y=await j.waitForApproval({...K.vaultWait,onPending:(n)=>{let V0=n.state==="pending"?n.requestId??n.retryCode??"":n.state;if(V0===h)return;h=V0;for(let B0 of GX(j.name,n))u.print(B0);u.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});u.print($X(j,y).text)}}},w=async()=>{let j=await K.migrationBlockers();return zX({title:oJ,status:["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. Account management opens after the move.",...j.length>0?["These processes still hold the move back:",...j.map((C)=>` ${C.pid==="unknown"?"processes that could not be read":`pid ${C.pid}`}: version ${C.version}`)]:[]],actions:[WX({checks:D(!1)})],...K.terminal?{terminal:K.terminal}:{}})},b=async(j)=>{let C=X(),u=K.openAccountPool(C);if(H&&await H.authority()!=="local")return i8(P(C,u),H);if(await p8(C,u)===void 0)return w();let E=P(C,u);return H?i8(E,H):KX(E)},k=(j)=>async()=>{if(H&&await H.authority()!=="local")throw Error(q6);let C=await j();if(C.method!=="auto")return C;return{...C,callback:async()=>{let u=await C.callback();if(H&&await H.authority()!=="local")return{type:"failed"};return u}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:UX({hasCredential:V,openMenu:b,login:k(()=>K.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:k(()=>K.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...H?.enrolled()?[{label:kW,type:"oauth",authorize:async()=>({url:"",instructions:xW,method:"auto",callback:async()=>{if(await QX(H.paths,H.name)!=="vault")return{type:"failed"};try{let j=JSON.parse(await IW(LX(),"utf8"));if(!j||typeof j!=="object"||Array.isArray(j)||Object.hasOwn(j,"openai"))return{type:"failed"}}catch(j){if(j.code!=="ENOENT")return{type:"failed"}}return{...VX,type:"success"}}})}]:[]]}var UY=["type","model","instructions","previous_response_id","input","tools","tool_choice","parallel_tool_calls","reasoning","store","stream","include","prompt_cache_key","text","generate","client_metadata"];function t1(Y){let J={};for(let X of UY)if(X in Y)J[X]=Y[X];for(let X of Object.keys(Y))if(!(X in J))J[X]=Y[X];return J}import{createHash as Jz}from"node:crypto";import{createHash as yW,randomBytes as jX}from"node:crypto";import{chmod as gW,lstat as FX,mkdir as fW,open as mW,readdir as TX,rename as cW,unlink as NY,writeFile as uW}from"node:fs/promises";import{join as r8,resolve as ZY}from"node:path";var pW=100,VY="session-unknown",lW=300000,dW=60000,iW=600000,nW=/\.(body|meta|request|response)\.json$/,oW=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+-\d{6,}-[a-zA-Z0-9._-]+$/,rW=/\.[a-f0-9]{24}\.partial$/;function RX(Y){let J=Y.replace(nW,"");if(J===Y||!oW.test(J))return;return J}function sW(Y){let J=Y.replace(rW,"");return J!==Y&&RX(J)!==void 0}async function DX(Y){let{dir:J,maxBytes:X}=Y,Q=Y.now??Date.now(),G=Y.minAgeMs??dW,$=Y.partialStaleMs??iW,W={removed:0,freedBytes:0};if(!(X>0))return W;try{if(L1)await PX(J,"directory");if((await FX(J)).isSymbolicLink())return W;let H=new Set((Y.protectedPaths??[]).map((M)=>ZY(M))),K=await TX(J,{withFileTypes:!0}),U=[];await Promise.all(K.map(async(M)=>{if(!M.isFile())return;let w=sW(M.name),b=w?void 0:RX(M.name);if(!w&&b===void 0)return;let k=r8(J,M.name);try{let j=await FX(k);if(!j.isFile())return;U.push({path:k,size:j.size,mtimeMs:j.mtimeMs,group:b})}catch{}}));let V=U.reduce((M,w)=>M+w.size,0),O=0,L=0,B=async(M)=>{try{await NY(M.path),V-=M.size,L+=M.size,O+=1}catch{}};for(let M of U){if(M.group!==void 0)continue;if(H.has(ZY(M.path)))continue;if(Q-M.mtimeMs<$)continue;await B(M)}let D=new Map;for(let M of U){if(M.group===void 0)continue;let w=D.get(M.group)??{files:[],newest:0};w.files.push(M),w.newest=Math.max(w.newest,M.mtimeMs),D.set(M.group,w)}let P=[...D.entries()].sort(([M,w],[b,k])=>w.newest-k.newest||M.localeCompare(b));for(let[,M]of P){if(V<=X)break;if(Q-M.newest<G)continue;if(M.files.some((w)=>H.has(ZY(w.path))))continue;for(let w of M.files)await B(w)}if(O>0)Y.logger?.debug("removed old dump files",{removed:O,freedBytes:L});return{removed:O,freedBytes:L}}catch(H){if(H instanceof Q8&&H.code==="ERR_PRIVATE_FILES_SECURITY")throw H;return W}}async function aW(Y,J,X){if(L1)return MX(Y,J,{stagePath:`${Y}.${X?X():jX(12).toString("hex")}.partial`});for(let Q=0;;Q+=1){let G=`${Y}.${X?X():jX(12).toString("hex")}.partial`,$=!1,W;try{W=await mW(G,"wx",384),$=!0,await W.writeFile(J,"utf8"),await W.chmod(384),await W.close(),W=void 0,await cW(G,Y);return}catch(H){if(await W?.close().catch(()=>{}),$)await NY(G).catch(()=>{});if(H.code==="EEXIST"&&Q===0)continue;throw H}}}function BY(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function X8(Y,J){let X=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!X)return J;return X.slice(0,80)}function OX(Y){return yW("sha256").update(Y).digest("hex")}function tW(Y){return Y.toLowerCase().replace(/[-_]/g,"")}function _X(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function eW(Y,J){if(Y===void 0)return null;if(Y===J)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:J.length};let X=0;while(X<Y.length&&X<J.length&&Y[X]===J[X])X++;let Q=Y.length-1,G=J.length-1;while(Q>=X&&G>=X&&Y[Q]===J[G])Q--,G--;return{changed:!0,firstByte:X,lastPreviousByte:Q,lastCurrentByte:G,changedPreviousBytes:Q-X+1,changedCurrentBytes:G-X+1,previousBytes:Y.length,currentBytes:J.length}}var Yz=0;function CX(Y){let J=Y.enabled===!0,X=Y.pid??process.pid,Q=Y.now??Date.now,G=Y.logger,$=new Set((Y.secretKeys??[]).map(tW)),W=AX({extraSecretKeys:(E)=>$.has(E),extraValuePatterns:[...Y.secretPatterns??[]]}),H=new Set(Y.schemaKeys??["tools"]),K=new Map,U=()=>typeof Y.dir==="function"?Y.dir():Y.dir;function V(E){let h=W.redact({[E]:null})[E];return h===null?void 0:h}function O(E){if(Array.isArray(E))return E.map(O);if(_X(E)){let h={};for(let[y,n]of Object.entries(E)){let V0=V(y);if(H.has(y))h[y]=W.redactStrings(n);else if(V0!==void 0)h[y]=V0;else h[y]=O(n)}return h}return W.redactStrings(E)}function L(E){let h;try{h=JSON.parse(E)}catch{return{text:W.redactStrings(E),parsed:void 0}}let y=O(h),n=JSON.stringify(y);return{text:JSON.stringify(h)===n?E:n,parsed:_X(y)?y:void 0}}async function B(E,h,y,n){let V0=`-${X8(h,VY)}-${X8(y,"channel")}`,B0;try{B0=await TX(E)}catch{return}let l=B0.filter((t)=>t.endsWith(".meta.json")&&t.includes(V0)).sort().reverse();for(let t of l)try{if(JSON.parse(await LY(r8(E,t),L1))?.baselineKey!==n)continue;return await LY(r8(E,t.replace(/\.meta\.json$/,".body.json")),L1)}catch(L0){if(L0 instanceof Q8&&(L1||L0.code==="ERR_PRIVATE_FILES_SECURITY"))throw L0}return}function D(E,h){if(!K.has(E))while(K.size>=pW){let y=K.keys().next().value;if(y===void 0)break;K.delete(y)}K.set(E,h)}async function P(E){if(!J)return;let h=++Yz,y=E.session?.trim()||VY,n=U(),V0=new Date(Q()).toISOString(),B0=[V0.replace(/[:.]/g,"-"),String(X),String(h).padStart(6,"0"),X8(y,VY),X8(E.channel,"channel"),...E.phase?[X8(E.phase,"phase")]:[]].join("-"),l=r8(n,B0),t={body:`${l}.body.json`,metadata:`${l}.meta.json`,request:`${l}.request.json`},L0=OX(`${E.channel}\x00${y}`);try{if(L1)await qX(n);else await fW(n,{recursive:!0,mode:448}),await gW(n,448);let v=K.get(L0),x0=v===void 0?void 0:"memory";if(v===void 0){if(v=await B(n,y,E.channel,L0),v!==void 0)x0="disk"}let R0=L(E.bodyText),U0={id:B0,createdAt:V0,pid:X,session:BY(y),channel:E.channel,...E.phase?{phase:E.phase}:{},accountId:E.accountId,status:E.status,error:E.error===void 0?void 0:W.redactStrings(E.error),baselineKey:L0,bodyBytes:Buffer.byteLength(E.bodyText,"utf8"),bodyHash:OX(E.bodyText),diff:eW(v,R0.text),baselineSource:x0,body:R0.parsed?{parseable:!0,...Y.summarize?.(R0.parsed)}:{parseable:!1},...E.meta?{extra:O(E.meta)}:{},files:t},s=O({url:E.url,method:E.method,accountId:E.accountId,headers:E.headers===void 0?void 0:Object.fromEntries(new Headers(E.headers).entries())}),E0=(i,g)=>L1?EX(i,g):uW(i,g,{encoding:"utf8",mode:384,flag:"wx"}),d=[[t.body,R0.text],[t.metadata,`${JSON.stringify(U0,null,2)}
|
|
2
2
|
`],[t.request,`${JSON.stringify(s,null,2)}
|
|
3
3
|
`]],S=await Promise.allSettled(d.map(([i,g])=>E0(i,g))),p=S.find((i)=>i.status==="rejected");if(p){if(Y.cleanupFailedDumps)await M(d,S);throw p.reason}return D(L0,R0.text),G?.debug("dumped request",{id:B0,session:BY(y),body:t.body}),C(n,Object.values(t)),{id:B0,files:t,responseFile:`${l}.response.json`}}catch(v){if(v instanceof Q8&&(L1||v.code==="ERR_PRIVATE_FILES_SECURITY"))throw v;G?.warn("request dump failed",{session:BY(y),error:v instanceof Error?v.message:String(v)});return}}async function M(E,h){await Promise.all(E.map(async([y],n)=>{let V0=h[n];if(V0?.status==="rejected"&&V0.reason?.code==="EEXIST")return;await NY(y).catch(()=>{})}))}let w=Y.maxBytes??0,b=Y.sweepIntervalMs??lW,k=0;function j(E,h){return{dir:E,maxBytes:w,protectedPaths:h,now:Q(),minAgeMs:Y.sweepMinAgeMs,partialStaleMs:Y.partialStaleMs,logger:G}}function C(E,h){if(!(w>0))return;let y=Q();if(y-k<b)return;k=y,DX(j(E,h))}async function u(E,h){if(!E)return;let y=O({status:h.status,requestId:h.requestId,usage:h.usage,...h.fields,complete:h.complete??!0});try{return await aW(E.responseFile,`${JSON.stringify(y,null,2)}
|
|
4
4
|
`,Y.stageName),E.responseFile}catch(n){if(n instanceof Q8&&(L1||n.code==="ERR_PRIVATE_FILES_SECURITY"))throw n;G?.warn("response dump failed",{id:E.id,error:n instanceof Error?n.message:String(n)});return}}return{isEnabled:()=>J,setEnabled:(E)=>{J=E},dump:P,dumpResponse:u,sweep:(E)=>DX(j(U(),E))}}var wX=H0("dump"),h1="x-cortexkit-openai-auth-dump-session",Xz=["chatgpt-account-id","email","org_name","organization_name"],Qz=["tools"];function jY(Y){return Jz("sha256").update(JSON.stringify(Y)).digest("hex")}function Gz(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function $z(Y){let J=Array.isArray(Y.input)?Y.input:[],X=Array.isArray(Y.tools)?Y.tools:[],Q=Y.client_metadata!=null&&typeof Y.client_metadata==="object"&&!Array.isArray(Y.client_metadata)?Y.client_metadata:void 0;return{model:typeof Y.model==="string"?Y.model:void 0,stream:Y.stream,generate:Y.generate,store:Y.store,previousResponseID:typeof Y.previous_response_id==="string"?Y.previous_response_id:void 0,promptCacheKey:typeof Y.prompt_cache_key==="string"?Y.prompt_cache_key:void 0,reasoning:Y.reasoning,inputCount:J.length,inputHash:jY(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:jY(J[0]),toolsCount:X.length,toolTypes:X.map(Gz),toolsHash:jY(X),clientMetadataKeys:Q?Object.keys(Q).sort():[]}}var FY;function SX(){return FY=o0().dumpMaxBytes,CX({dir:()=>o0().dumpDir,maxBytes:FY,logger:wX,secretKeys:Xz,schemaKeys:Qz,summarize:$z})}var s8=SX();async function A6(Y){if(!t6()){s8.setEnabled(!1);return}if(o0().dumpMaxBytes!==FY)s8=SX();s8.setEnabled(!0);let J=typeof Y.bodyText==="function"?Y.bodyText():Y.bodyText;await s8.dump({session:Y.sessionID,channel:Y.transport,phase:Y.phase,bodyText:J,accountId:Y.accountId,url:Y.url,method:Y.method,headers:Y.headers,status:Y.status,error:Y.error})}async function e1(Y){if(!t6())return;wX.debug("diagnostic",Y)}function T6(Y){return JSON.stringify(DY(Y))??"undefined"}function DY(Y){if(Array.isArray(Y))return Y.map(DY);if(!r(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((J)=>[J,DY(Y[J])]))}var Wz=512,zz=2097152;function OY(Y,J){if(typeof Y==="function"||typeof J==="function")return!1;if(J!==null&&typeof J==="object"&&Object.hasOwn(J,"toJSON")&&typeof J.toJSON==="function")return!1;if(Y===J)return!0;if(Array.isArray(Y))return Array.isArray(J)&&Y.length===J.length&&Y.every(($,W)=>OY($,J[W]));if(Y===null||J===null||typeof Y!=="object"||typeof J!=="object"||Array.isArray(J))return!1;let X=Y,Q=J,G=Object.keys(X);return G.length===Object.keys(Q).length&&G.every(($)=>Object.prototype.propertyIsEnumerable.call(Q,$)&&OY(X[$],Q[$]))}function Y6(Y,J){let X=[],Q=[],G=0;for(let $=0;$<Y.length;$++){let W=J?.texts[$],H=W!==void 0&&OY(J?.snapshots[$],Y[$]),K=H?W:T6(Y[$]);X.push(K),Q.push(H?J?.snapshots[$]:K==="undefined"?void 0:JSON.parse(K)),G+=K.length}return{texts:X,snapshots:Q,retainable:Y.length<=Wz&&G<=zz}}function G8(Y){return Y.retainable?Y:void 0}function $8(Y,J){if(Y.texts.length>J.texts.length)return;for(let X=0;X<Y.texts.length;X++)if(Y.texts[X]!==J.texts[X])return;return Y.texts.length}var IX=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol","gpt-6.1-terra"]),Hz="terminal_resize_reflow",a8="0.159.0",bX=`codex_exec/${a8} (Debian 12.0.0; aarch64) unknown (codex_exec; ${a8})`,Kz="seccomp",R6="x-openai-auth-agent";function Uz(Y){if(typeof Y!=="string")return;try{let J=JSON.parse(Y);return typeof J==="object"&&J!==null&&!Array.isArray(J)?J:void 0}catch{return}}function W8(Y,J){return r(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===J}function Zz(Y,J,X){if(!Y.input)return J.length>0;let Q=Y.canonicalInput??Y6(Y.input);if($8(Q,X)===void 0)return!0;return J.slice(Y.input.length).some(($)=>W8($,"user")||W8($,"developer"))}function Vz(Y,J,X){let Q=Array.isArray(J?.input)?J.input:void 0,G=Q?Y6(Q,Y.canonicalInput):void 0;if(Q&&G&&(Zz(Y,Q,G)||!Y.turnID))Y.turnID=(X?.uuid??J6)(),Y.turnStartedAt=(X?.now??Date.now)();else if(!Y.turnStartedAt)Y.turnStartedAt=(X?.now??Date.now)();if(Q&&G)Y.input=Q.slice(),Y.canonicalInput=G8(G)}function kX(Y){let J=Y.headers.get(R6);if(Y.headers.delete(R6),!Y.metadata)return{init:Y.init};let X=Uz(Y.init?.body),Q=Y.runtime?.now??Date.now;if(!Y.skipTurnUpdate){if(!Y.websocket)Vz(Y.metadata,X,Y.runtime);else if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Q();if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Q()}let G=JSON.stringify({session_id:Y.metadata.threadID,thread_id:Y.metadata.threadID,thread_source:"user",turn_id:Y.metadata.turnID,sandbox:Kz,turn_started_at_unix_ms:Y.metadata.turnStartedAt,request_kind:"turn",window_id:Y.metadata.windowID});if(Y.headers.set("originator","codex_exec"),Y.websocket)Y.headers.delete("accept"),Y.headers.delete("content-type");else Y.headers.set("accept","text/event-stream");if(Y.headers.set("session-id",Y.metadata.threadID),Y.headers.delete("x-session-id"),Y.headers.delete("x-session-affinity"),Y.headers.set("thread-id",Y.metadata.threadID),Y.headers.set("x-codex-window-id",Y.metadata.windowID),Y.headers.set("x-client-request-id",Y.metadata.threadID),Y.headers.set("x-codex-beta-features",Hz),Y.headers.set("x-codex-turn-metadata",G),Y.headers.set("user-agent",bX),Y.headers.set("version",a8),Y.dumpSessionID)Y.headers.set(h1,Y.dumpSessionID);let $=X;if(!$)return{init:Y.init};let W=Y.responsesLite&&typeof $.model==="string"&&IX.has($.model);if(W&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if($.prompt_cache_key=Y.metadata.threadID,$.parallel_tool_calls??=!0,Array.isArray($.tools))$.tools=$.tools.map(Bz);if(Y.applyEffort?.($,Y.metadata,J),W)Y.rewriteLite($);let H={...typeof $.client_metadata==="object"&&$.client_metadata!==null?$.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(H["x-codex-turn-metadata"]=G,H["x-codex-ws-stream-request-start-ms"]=String(Q()),W)H.ws_request_header_x_openai_internal_codex_responses_lite="true"}return $.client_metadata=H,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(t1($))}}}function Bz(Y){if(!r(Y)||Y.type!=="function")return Y;let J=r(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:K,...U}=Y.parameters;return U})():Y.parameters,{type:X,name:Q,description:G,strict:$,parameters:W,...H}=Y;return{type:X,name:Q,description:G,strict:$??!1,parameters:J,...H}}import{lstat as xX,opendir as Lz}from"node:fs/promises";import{join as Nz}from"node:path";async function hX(Y){try{if(!(await xX(Y)).isDirectory())return;let J=0,X=!1,Q=[],G=async($)=>{try{let W=await xX(Nz(Y,$));if(W.isFile())J+=W.size}catch(W){if(W.code!=="ENOENT")X=!0}};for await(let $ of await Lz(Y)){if(!$.isFile())continue;if(Q.push(G($.name)),Q.length===32)await Promise.all(Q),Q=[]}return await Promise.all(Q),X?void 0:J}catch(J){return J.code==="ENOENT"?0:void 0}}function _Y(Y){let J=["B","KiB","MiB","GiB","TiB","PiB"],X=0,Q=Y;while(Q>=1024&&X<J.length-1)Q/=1024,X++;return`${Number(Q.toFixed(1))} ${J[X]}`}var PY={rpcRoot:"openai-auth",directoryPrefix:fX,registrationSessionId:"process"},t8=new Map;function xN(Y,J){if(J?.aborted)return Promise.resolve(!1);if(qY(Y))return Promise.resolve(!0);return new Promise((X)=>{let Q=(H)=>{if(clearTimeout($),J?.removeEventListener("abort",G),W.delete(Q),W.size===0)t8.delete(Y);X(H)},G=()=>Q(!1),$=setTimeout(()=>Q(!1),2000),W=t8.get(Y)??new Set;t8.set(Y,W),W.add(Q),J?.addEventListener("abort",G,{once:!0})})}function e8(Y,J){vX(PY,Y,J)}function mX(Y=0,J){let X=yX(PY,Y,J);if(J!==void 0)for(let Q of t8.get(J)??[])Q(!0);return X}function qY(Y){return gX(PY,Y)}var Y9=H0("commands");function C6(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}function EY(Y){return`${String(Y.startHour).padStart(2,"0")}-${String(Y.endHour).padStart(2,"0")}`}function jz(Y){let J=/^(\d{1,2})-(\d{1,2})$/.exec(Y.trim());if(!J)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let X=Number(J[1]),Q=Number(J[2]);if(X>23||Q>23||X===Q)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:X,endHour:Q}}var Fz="Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.\n\nBefore enabling sustain with Magic Context, set a non-expiring `cache_ttl` for models used by main sessions; elapsed-time cold-cache assumptions are no longer valid.";function Dz(Y){let J=(X)=>n1(Y.store(),E1(C6(Y)),(Q)=>{let G={...Q.cacheKeep??{}};X(G),Q.cacheKeep=G});return{title:"Cache",build:async()=>{let X=Y.cacheKeepManager;if(!X)return{lines:["Keep-warm unavailable"]};let Q=X9(await Y.loadAccounts(C6(Y))),G=Q?.enabled===!0,$=Q?.subagents===!0,W=X.status(),H=W.window?EY(W.window):"always (no window)";return{lines:[`Keep-warm ${G?"on":"off"} · ${W.tracked===0?"no sessions":`${W.tracked} session${W.tracked===1?"":"s"}`}`,`Timer ${W.running?"armed":"idle"} · subagents ${$?"on":"off"} · sustain ${W.sustain?"on":"off"}`,`Window ${H}`,...Y.cacheKeepNotice?[Y.cacheKeepNotice]:[],`TTL ${Math.round(W.ttlMs/1000)}s · lead ${Math.round(W.leadMs/1000)}s · idle cap ${Math.round(W.maxIdleWarmMs/60000)}min (subagents ${Math.round(W.maxSubagentIdleMs/60000)}min)`],items:W.targets.map((K)=>({id:K.sessionKey,label:K.sessionKey,group:"Sessions",detail:[K.accountId??"main",`expires in ${Math.ceil((K.cacheExpiresAt-W.generatedAt)/1000)}s`,...K.lastWarmedAt?[`last warm ${Math.ceil((W.generatedAt-K.lastWarmedAt)/1000)}s ago`]:[],...K.backoffUntil&&K.backoffUntil>W.generatedAt?[`backoff ${Math.ceil((K.backoffUntil-W.generatedAt)/1000)}s`]:[]].join(" · ")})),actions:[{id:"enabled",label:G?"Turn keep-warm off":"Turn keep-warm on",knobs:[{kind:"toggle",id:"enabled",label:"Keep-warm",value:!G}],run:async({values:K})=>{let U=K.enabled===!0;if(await J((V)=>{V.enabled=U}),Y.setCacheKeepEnabled?.(U),U)X.start();else X.stop();return Y9.info(U?"cachekeep enabled":"cachekeep disabled"),U?`Keep-warm is on. TTL ${Math.round(W.ttlMs/1000)}s, idle cap ${Math.round(W.maxIdleWarmMs/60000)}min.`:"Keep-warm is off."}},{id:"subagents",label:$?"Stop warming subagent sessions":"Warm subagent sessions too",knobs:[{kind:"toggle",id:"subagents",label:"Subagent warming",value:!$}],run:async({values:K})=>{let U=K.subagents===!0;return await J((V)=>{V.subagents=U}),Y.setCacheKeepSubagents?.(U),`Subagent warming is ${U?"on":"off"}.`}},{id:"sustain",label:W.sustain?"Stop sustaining main sessions":"Sustain main sessions past the idle cap",knobs:[{kind:"toggle",id:"sustain",label:"Sustain",value:!W.sustain}],run:async({values:K})=>{let U=K.sustain===!0;return await J((V)=>{V.sustain=U}),Y.setCacheKeepSustain?.(U),U?Fz:"Main-agent sessions again stop warming at the configured idle cap."}},{id:"window",label:"Set the warm window",description:"Warm only between these local hours, e.g. 9-18 or 22-6. Leave it empty to warm at any hour.",knobs:[{kind:"text",id:"window",label:"Window (HH-HH)",placeholder:"9-18",...W.window?{value:EY(W.window)}:{}}],run:async({values:K})=>{let U=K.window;if(typeof U!=="string"||U.trim()==="")return await J((B)=>{delete B.startHour,delete B.endHour}),Y.setCacheKeepWindow?.(void 0),"Warm window cleared: keep-warm warms at any hour (within idle caps).";let V=jz(U);if(!V.ok)return{ok:!1,text:`Invalid window: ${V.reason}`};let{startHour:O,endHour:L}=V;return await J((B)=>{B.startHour=O,B.endHour=L}),Y.setCacheKeepWindow?.({startHour:O,endHour:L}),`Warming limited to ${EY(V)} local hours.`}}]}}}}var cX=["error","warn","info","debug","trace"];function Oz(Y){return{title:"Diagnostics",build:async()=>{let J=o0(),X=t6(),G=(await Y.loadAccounts(C6(Y)))?.logging?.level??"info",$=X?await hX(J.dumpDir):void 0,W=$===void 0?"size unavailable":_Y($),H=J.dumpMaxBytes===0?"no cap":`${_Y(J.dumpMaxBytes)} cap`,K=Y.layoutNotice?.();return{lines:[X?`Dumps on (${W} / ${H})`:"Dumps off",`Dump directory: ${J.dumpDir}`,`Log level: ${G}`,...K?[K]:[]],actions:[{id:"dump",label:X?"Turn request dumps off":"Turn request dumps on",knobs:[{kind:"toggle",id:"enabled",label:"Request dumps",value:!X}],run:async({values:U})=>{let V=U.enabled===!0;await n1(Y.store(),E1(C6(Y)),(L)=>{L.dump={...L.dump??{},enabled:V}});let O=yJ();return Y9.info(V?"request dump enabled":"request dump disabled"),V?`Request dumps are on, written to ${O.dumpDir}.
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as x,J as f,K as g,L as h,M as i,N as j,O as k,P as l,Q as m,R as n,S as o,T as p,U as q,V as r,W as s,X as t,Y as u,Z as v,_ as w,aa as y,ba as z,ca as A,da as B,ea as C,fa as D,ga as E,ha as F,ia as G,j as c,k as d,l as e}from"./index-
|
|
1
|
+
import{$ as x,J as f,K as g,L as h,M as i,N as j,O as k,P as l,Q as m,R as n,S as o,T as p,U as q,V as r,W as s,X as t,Y as u,Z as v,_ as w,aa as y,ba as z,ca as A,da as B,ea as C,fa as D,ga as E,ha as F,ia as G,j as c,k as d,l as e}from"./index-qdy57ej9.js";import"./index-cb1kwn36.js";import"./index-5sgqz46z.js";import{ld as a,md as b}from"./index-6r27fz5a.js";import"./index-mtf8pv2w.js";import"./index-hpev556z.js";import"./index-6j3059fy.js";import"./index-k1dfzavn.js";import"./index-hpb6k6st.js";import"./index-bvswyxpt.js";import"./index-2f9w48sc.js";export{D as rewriteResponsesLiteBody,B as resolveSidebarSessionId,s as poolResetTarget,a as parseJwtClaims,y as mergePushedQuotaMetadata,l as getMainRefreshLockName,x as findCachekeepFallbackAccount,b as extractAccountIdFromClaims,G as default,t as createResetTargetResolver,j as codexOAuthModelVariantSource,h as codexOAuthModelListed,i as codexOAuthModelLimit,A as buildSidebarState,z as buildSidebarMachineState,u as buildResetRedemptionDeps,p as __resetBootQuotaSeedForTest,v as __menuContextForTest,o as __bootQuotaSeedPromiseForTest,r as ResetTargetResolutionError,c as RESPONSES_LITE_MODELS,w as POOL_MIGRATION_ENABLED,F as OpenAIAuthPlugin,C as MID_CONVERSATION_EFFORT_MODELS,m as MAIN_REFRESH_LOCK_TTL_MS,n as MAIN_REFRESH_LEASE_TTL_MS,k as EMPTY_BEARER_MESSAGE,g as DISALLOWED_MODELS,E as CodexAuthPlugin,d as CODEX_VERSION,e as CODEX_USER_AGENT,q as AuthPersistError,f as ALLOWED_MODELS};
|
package/dist/rpc/port-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Xe as b,Ye as c}from"../index-
|
|
1
|
+
import{Xe as b,Ye as c}from"../index-hpev556z.js";import{af as a}from"../index-6j3059fy.js";import"../index-hpb6k6st.js";import"../index-bvswyxpt.js";import"../index-2f9w48sc.js";export{b as writePortFile,c as isOpenaiRpcStateDir,a as discoverPortFile};
|
package/dist/v2/server.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{c as S0}from"../index-
|
|
1
|
+
import{c as S0}from"../index-85w1x19b.js";import{A as E0,B as o2,C as l$,D as u$,E as rZ,F as tZ,G as x0,H as KZ,I as TZ,L as bZ,M as kZ,N as DZ,V as vZ,W as hZ,_ as q0,d as H0,e as yZ,ea as G$,f as B1,fa as Q$,g as S2,h as e2,i as Q1,ia as b0,k as J$,l as z$,m as $$,n as c2,o as NZ,p as w1,q as FZ,r as xZ,s as qZ,t as $1,u as r$,v as t$,w as P0,x as M0,y as g1,z as C0}from"../index-qdy57ej9.js";import{Ab as _0,Bb as EZ,Jb as R2,Kb as GZ,La as MZ,Lb as QZ,Mb as b1,Nb as YZ,Ob as XZ,Qb as O0,Rb as R0,Sa as t2,Sb as A0,ab as Y1,bb as V0,cb as U0,db as W0,eb as w2,gb as h$,hb as a2,ib as m$,jb as g$,lb as F0,mb as zZ,ob as K0,pa as B0,pb as CZ,ta as x$,ua as q$,yb as T0,zb as L0}from"../index-cb1kwn36.js";import{ac as iZ,pc as aZ,qc as nZ,sc as oZ,wc as sZ}from"../index-5sgqz46z.js";import{Be as y$,Ce as f$,De as A1,Ee as I$,Fd as _Z,Fe as v$,Ld as PZ,Mc as P$,Nd as j0,Od as fZ,Pd as O$,Yd as q2,Zd as m2,ce as R$,ee as s$,fe as A$,ld as s2,le as G1,md as r2,nd as X0,se as IZ,te as y2,ud as m1,ue as S$,vd as M$,ve as b$,wd as C$,we as k$,xd as E$,ye as D$,ze as w$}from"../index-6r27fz5a.js";import"../index-mtf8pv2w.js";import{Ve as WZ,We as N0}from"../index-hpev556z.js";import"../index-6j3059fy.js";import{ff as Y0,hf as L2}from"../index-k1dfzavn.js";import"../index-hpb6k6st.js";import{Ef as HZ}from"../index-bvswyxpt.js";import{If as j1,Jf as Q0}from"../index-2f9w48sc.js";import{AsyncLocalStorage as b4}from"node:async_hooks";import{randomUUID as k4}from"node:crypto";class Y2 extends Error{kind;providerID;sessionID;requestKind;constructor($){super($.message??`${$.providerID} ${$.requestKind} request refused (${$.kind})`);this.name="OpenCode2AuthError",this.kind=$.kind,this.providerID=$.providerID,this.sessionID=$.sessionID,this.requestKind=$.requestKind}}function K2($){return`common-auth-placeholder.${$}`}function o1($){let Z=K2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function k2($,Z){if($?.type!=="oauth")return!1;let J=Z===void 0?void 0:K2(Z),G=(Q)=>J===void 0?Q.startsWith("common-auth-placeholder."):Q===J;return G($.access)&&G($.refresh)}var s1="No browser sign-in: this connects the plugin to the accounts in its vault.";async function N1($,Z){let J=Z.now??Date.now,{integrationID:G}=Z,Q=(V)=>o1({integrationID:G,methodID:V,now:J()}),Y=async(V,N)=>{return await Z.onLogin(V,{integrationID:G,methodID:N}),Q(N)},F=(V)=>async(N)=>{let B=V.method.id,H=await V.authorize(N),T={url:H.url,instructions:H.instructions,...H.expiresAt===void 0?{}:{expiresAt:H.expiresAt}};if(H.mode==="auto")return{...T,mode:"auto",callback:H.callback.then((C)=>Y(C,B))};let q=H.callback;return{...T,mode:"code",callback:async(C)=>Y(await q(C),B)}};return $.integration.transform((V)=>{let N=Z.label===void 0?{}:{label:()=>Z.label};for(let T of Z.methods)V.method.update({integrationID:G,method:T.method,authorize:F(T),refresh:async(q)=>{if(!k2(q,G))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return Q(q.methodID)},...N});let B=Z.vault;if(B===void 0)return;let H=B.method.id;V.method.update({integrationID:G,method:B.method,authorize:async()=>({url:"",instructions:B.instructions??s1,mode:"auto",callback:Promise.resolve().then(()=>B.activate({integrationID:G,methodID:H})).then(()=>Q(H))}),refresh:async(T)=>{if(!k2(T,G)||T.methodID!==H)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return Q(H)},...N})})}function w0($){let Z=[],J;for(let G of $.split(/\r?\n/))if(G.startsWith("data:"))Z.push(G.slice(5).replace(/^ /,""));else if(G.startsWith("event:"))J=G.slice(6).trim();if(Z.length===0)return;return J===void 0?{data:Z.join(`
|
|
2
2
|
`)}:{event:J,data:Z.join(`
|
|
3
3
|
`)}}function F1($,Z){let J=new TextDecoder,G="",Q=(F)=>{let V=w0(F);if(!V)return;try{$(V)}catch(N){Z(N)}},Y=()=>{for(;;){let F=/\r?\n\r?\n/.exec(G);if(!F)return;let V=G.slice(0,F.index);G=G.slice(F.index+F[0].length),Q(V)}};return new TransformStream({transform(F,V){V.enqueue(F),G+=J.decode(F,{stream:!0}),Y()},flush(){if(G+=J.decode(),Y(),G.trim()!=="")Q(G);G=""}})}var r1=512,t1=1200000,A2="x-common-auth-attempt",O2=($,Z)=>JSON.stringify([$,Z]),N2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function y0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function f0($,Z){let J=$.getReader();return new ReadableStream({async pull(G){let Q;try{Q=await J.read()}catch(Y){Z({reason:"failed",message:Y instanceof Error?Y.message:String(Y)}),G.error(Y);return}if(Q.done)Z(),G.close();else G.enqueue(Q.value)},async cancel(G){Z({reason:"cancelled",...G===void 0?{}:{message:String(G)}}),await J.cancel(G)}})}function u2($,Z){for(let[J,G]of Object.entries(Z)){let Q=J.toLowerCase();for(let Y of Object.keys($))if(Y.toLowerCase()===Q)delete $[Y];if(G!==null)$[J]=G}}function I0($,Z){for(let[J,G]of Object.entries(Z))if(G===null)$.delete(J);else $.set(J,G)}async function K1($,Z,J={}){let{providerID:G}=Z,Q=J.gateOnPlaceholder,Y=(z)=>Q===void 0||Q.credential(z)===K2(G),F=J.logger,V=Math.max(1,J.maxRecords??r1),N=[...J.hostCredentials??[K2(G)],...Q?[K2(G)]:[]].filter((z)=>z!==""),B=new Map,H=new WeakMap,T=new Map,q=0,C=new Set,D=new Map,d=new Map,O=(z)=>{let j=d.get(z);return j?.ownedSeen===!0&&j.foreignSeen},I=(z,j)=>{D.set(z,j);let U=d.get(z)??{ownedSeen:!1,foreignSeen:!1};if(j)U.ownedSeen=!0;else U.foreignSeen=!0;d.set(z,U)},B2=(z,j)=>{let U=Q?.refuseMisplaced,P=U?[...j].filter(([,k])=>k.includes(K2(G))):[],W=Y(j)&&(!U||P.length>0);if(U){if(P.length>0&&(P.length!==1||!W))throw I(z.sessionID,!1),new Y2({kind:"placement-refused",providerID:G,sessionID:z.sessionID,requestKind:z.kind,message:U(P[0]?.[0]??"")})}return I(z.sessionID,W),W},J2=!1,w=!1,l=new Map,_2=0,Z2=!1,i=new Map,X=(z,j)=>{try{F?.warn(z,j)}catch{}},K=(z)=>z instanceof Error?z.message:String(z),M=new Map,L=(z,j)=>{let U=(M.get(z)??Promise.resolve()).then(j),P=U.then(()=>{},()=>{});return M.set(z,P),P.then(()=>{if(M.get(z)===P)M.delete(z)}),U},h=(z,j)=>{let U=M.get(z);return U?U.then(()=>h(z,j)):j()},R=async(z)=>{try{await Z.dropChoice?.({...z.input,accountId:z.accountId})}catch(j){X("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:z.input.sessionID,error:K(j)})}},S=async(z)=>{try{await Z.dropSameAccountRetry?.({...z.input,accountId:z.accountId})}catch(j){X("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:z.input.sessionID,error:K(j)})}},v=async(z)=>{if(z.next)await R(z.next);if(z.sameAccount)await S(z.sameAccount)},A=(z)=>{let j=T.get(z);if(T.delete(z),j)L(j.sessionID,()=>v(j))},f=async(z,j)=>{let U=l.get(z);if(!U||U.size===0)return;await Promise.all([...U].map(async(P)=>{try{await P(j)}catch(W){X("opencode2 auth listener threw; the request is unaffected",{event:z,error:K(W)})}}))},n=async(z,j)=>{try{await Z.onAttemptEnd?.(z,j)}catch(U){X("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:z.attemptId,error:K(U)})}},u=(z,j)=>{if(z.ended||!z.attempt)return;let U={...z.status===void 0?{}:{status:z.status},outputStarted:z.outputStarted,...z.limit?{limit:z.limit.signal}:{},...j?{error:j}:{}};if(j)z.endError=j;z.ended=n(z.attempt,U)},o=(z,j)=>u(z,{reason:"abandoned",message:j}),s=(z)=>[...B.values()].filter((j)=>j.key===z),e=(z)=>s(z).at(-1),p=(z)=>{if(B.delete(z.id),T.get(z.key)?.attemptId===z.id||!s(z.key).length)A(z.key)},x=(z)=>{B.set(z.id,z);while(B.size>V){let j=B.values().next().value;if(j===void 0)break;o(j,"dropped to keep the record bound"),p(j)}},G2=(z)=>z.accountId===void 0?void 0:{...z.scope,accountId:z.accountId},g=(z,j)=>new Y2({kind:"no-account",providerID:G,sessionID:z.sessionID,requestKind:z.kind,...j===void 0?{}:{message:j}}),m=(z)=>{i.get(z)?.clear(),i.delete(z)},$2=async(z,j)=>{let U=()=>g(z,`${G} ${z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(Z2)throw U();let P=i.get(z.sessionID);if(!P)P=new Set,i.set(z.sessionID,P);let W={};P.add(W);let k=()=>{if(!P.has(W))throw U()};try{return await j(k)}finally{if(P.delete(W),P.size===0&&i.get(z.sessionID)===P)i.delete(z.sessionID)}},X2=(z,j)=>{for(let[U,P]of j)if(N.some((W)=>P.includes(W)))throw new Y2({kind:"host-credential-on-wire",providerID:G,sessionID:z.sessionID,requestKind:z.kind,message:`${G} ${z.kind} request still carries the host's placeholder credential in ${U}; the adapter's account headers must replace it`})},_=(z)=>{for(let j of s(z))if(j.ended||!j.attempt)p(j);else if(j.transport==="ws"||j.judged)o(j,"a newer attempt of its session and kind began"),p(j)},b=async(z,j,U,P)=>{let W=O2(z.sessionID,z.kind),{input:k,accountId:E,sameAccountRetry:y}=await h(z.sessionID,async()=>{U();let r=T.get(W);T.delete(W);let z2=r?.accountId??e(W)?.accountId;_(W);let t=r?.next,Q2=r?.sameAccount,a=Q2!==void 0&&Q2.input.modelID===z.modelID&&Q2.input.agent===z.agent,U2=t!==void 0&&t.input.modelID===z.modelID&&t.input.agent===z.agent,W2={...z,phase:"request",...z2===void 0?{}:{previousAccountId:z2},...r?.rerouteFrom?{rerouteFrom:r.rerouteFrom}:{}};if(t&&!U2)await L(z.sessionID,()=>R(t)),U();if(Q2&&!a)await L(z.sessionID,()=>S(Q2)),U();let H2=a?Q2.accountId:U2?t.accountId:await Z.chooseAccount(W2);return{input:W2,accountId:typeof H2==="string"?H2:void 0,sameAccountRetry:a}});U();let c={},V2;if(E!==void 0){let r=await Z.accountHeaders({...z,accountId:E});if(U(),y0(r))c=r.headers,V2=r.attempt;else c=r}let g2=`attempt-${++_2}`,E2={id:g2,key:W,scope:z,accountId:E,headers:c,attempt:E===void 0?void 0:{...z,accountId:E,attemptId:g2,transport:P,data:V2},...P===void 0?{}:{transport:P},outputStarted:!1,sameAccountRetry:y};if(x(E2),E2.attempt)f("select",{...z,accountId:E2.attempt.accountId,hook:j,...k.previousAccountId===void 0?{}:{previousAccountId:k.previousAccountId},...k.rerouteFrom===void 0?{}:{rerouteFrom:k.rerouteFrom},handle:E2.attempt});return E2},j2=async(z,j,U,P,W)=>{let k=O2(z.sessionID,z.kind),E=P===void 0?void 0:B.get(P);if(E?.key!==k)E=void 0;if(!E){if(E=e(k),s(k).filter((c)=>c.transport===void 0&&!c.ended).length>1&&!w)w=!0,X("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:z.sessionID,kind:z.kind})}if(!E||E.transport!==void 0||E.ended)E=await b(z,j,W,U);else if(E.transport=U,E.attempt)E.attempt.transport=U;if(U==="ws"){for(let y of s(k))if(y!==E&&y.transport==="ws")o(y,"a newer attempt of its session and kind went out over WebSocket")}return E},b2=async(z,j)=>{try{return await j()}catch(U){throw u(z,{reason:"failed",message:K(U)}),U}},u1=(z,j)=>{let U=s(O2(z,j)).filter((P)=>P.transport==="ws").at(-1);return U?.attempt!==void 0&&!U.ended?U:void 0},U1=(z,j,U)=>{let P=G2(z);if(!P||!z.attempt||z.limit)return;z.limit={signal:j,delivered:f("limit",{...P,via:U,limit:j,outputStarted:z.outputStarted,handle:z.attempt})}},p1=(z,j,U,P)=>{let W=G2(z);if(!W||!z.attempt)return;f("quota",{...W,transport:j,...P===void 0?{}:{status:P},quota:U,handle:z.attempt})},c1=(z,j,U,P)=>{let W=z.attempt;if(!W)return;let k=Z.inspectEvent?.(P===void 0?{transport:j,data:U,attempt:W}:{transport:j,data:U,event:P,attempt:W});if(!k)return;if(k.quota!==void 0)p1(z,j,k.quota);if(k.outputStarted)z.outputStarted=!0;if(k.limit)U1(z,k.limit,j);if(k.error!==void 0)u(z,{reason:"failed",message:k.error});else if(k.done)u(z)},k0=(z,j)=>{let U=z.attempt;if(!U||j.accountId===z.accountId)return;if(U.reboundFrom??=U.accountId,U.accountId=j.accountId,"data"in j)U.data=j.data;z.accountId=j.accountId},D0=(z)=>!z.attempt||z.endError!==void 0||z.status!==void 0&&z.status>=400,d1=(z)=>{let j=[...B.values()].filter((y)=>y.scope.sessionID===z),U=j.filter((y)=>y.limit&&!y.rerouted).at(-1);if(U)return U;let P=j.filter((y)=>y.scope.kind==="primary"),W=P.length>0?P:j;if(W.length<=1)return W[0];let k=W.filter((y)=>!y.judged&&D0(y)).at(-1);if(k)return k;let E=W.filter((y)=>y.attempt&&!y.ended);if(E.length>1)return"ambiguous";return E[0]??W.at(-1)},C2={providerID:G},P2=[];P2.push(await $.session.hook("model.request",(z)=>{if(Q)return;return $2(N2(z),async(j)=>{let U=await b(N2(z),"model.request",j);if(j(),U.accountId===void 0)throw g(U.scope);u2(z.headers,{...U.headers,[A2]:U.id})})},C2)),P2.push(await $.session.hook("http.request",(z)=>{if(Q){if(!B2(N2(z),z.request.headers))return}return $2(N2(z),async(j)=>{let U=z.request.headers.get(A2)??void 0,P=Q?await b(N2(z),"http.request",j,"http"):await j2(N2(z),"http.request","http",U,j);j();let W=G2(P),k=P.attempt;if(!W||!k)throw g(P.scope);await b2(P,async()=>{let E=z.request;if(Z.rewriteRequest){if(U!==void 0){let V2=new Headers(E.headers);V2.delete(A2),E=new Request(E,{headers:V2})}E=await Z.rewriteRequest({...W,request:E,attempt:k})??E,j()}let y=new Headers(E.headers);y.delete(A2),I0(y,P.headers),X2(P.scope,y.entries());let c=new Request(E,{headers:y});H.set(c,P),z.request=c})})},C2)),P2.push(await $.session.hook("http.response",async(z)=>{let j=H.get(z.request);if(!j){if(Q)return;if(!J2)J2=!0,X("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:z.sessionID,kind:z.kind});return}let U=z.response;if(Z.answeredBy&&j.attempt){let y=j.attempt,c=await b2(j,async()=>Z.answeredBy?.({request:z.request,response:U,attempt:y}));if(c)k0(j,c)}let P=G2(j),W=j.attempt;if(!P||!W)return;j.status=U.status;let k=Z.quotaFromHeaders?.(U.headers,U.status,W);if(k!==void 0)p1(j,"http",k,U.status);if(!U.ok&&Z.limitFromResponse){let y=await Z.limitFromResponse({status:U.status,headers:U.headers,body:()=>U.clone().text(),attempt:W});if(y)U1(j,y,"http")}if(!U.ok||!U.body)u(j);let E=U;if(U.body&&(Z.inspectEvent||Z.onAttemptEnd)){let y=U.body;if(Z.inspectEvent)y=y.pipeThrough(F1((c)=>c1(j,"http",c.data,c.event),(c)=>X("opencode2 auth event inspection threw",{error:K(c)})));E=new Response(f0(y,(c)=>u(j,c)),{status:U.status,statusText:U.statusText,headers:U.headers})}if(Z.rewriteResponse)E=await Z.rewriteResponse({...P,request:z.request,response:E,attempt:W})??E;if(E!==U)z.response=E},C2)),P2.push(await $.session.hook("experimental.ws.handshake",(z)=>{if(Q){let j=O2(z.sessionID,z.kind);if(C.delete(j),!B2(N2(z),new Headers(z.headers)))return}return $2(N2(z),async(j)=>{let U;for(let E of Object.keys(z.headers)){if(E.toLowerCase()!==A2)continue;U??=z.headers[E],delete z.headers[E]}let P=Q?await b(N2(z),"experimental.ws.handshake",j,"ws"):await j2(N2(z),"experimental.ws.handshake","ws",U,j);j();let W=G2(P),k=P.attempt;if(!W||!k)throw g(P.scope);await b2(P,async()=>{if(!Q?.refuseMisplaced)u2(z.headers,P.headers);let E=Z.rewriteHandshakeURL?.({...W,url:z.url,attempt:k});if(E!==void 0)z.url=E;if(Q?.refuseMisplaced)u2(z.headers,P.headers);if(X2(P.scope,Object.entries(z.headers)),Q)C.add(P.key)})})},C2));let i1=Z.rewriteWebSocketFrame?.bind(Z);if(i1)P2.push(await $.session.hook("experimental.ws.send",async(z)=>{let j=N2(z);if(Q&&!C.has(O2(j.sessionID,j.kind)))return;let U=u1(j.sessionID,j.kind),P=await i1({...j,attempt:U?.attempt,frame:z.frame});if(P!==void 0)z.frame=P},C2));P2.push(await $.session.hook("experimental.ws.receive",(z)=>{if(Q&&!C.has(O2(z.sessionID,z.kind)))return;let j=u1(z.sessionID,z.kind);if(!j)return;try{c1(j,"ws",z.frame)}catch(U){X("opencode2 auth frame inspection threw",{error:K(U)})}},C2)),P2.push(await $.session.hook("retry",async(z)=>{if(Q&&D.get(z.sessionID)!==!0)return;let j=z.decision,U=()=>f("retry",{sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:j,decision:j});if(O(z.sessionID)&&!Z.retrySameAccount){await U();return}let P=d1(z.sessionID);if(!P)return;if(P==="ambiguous"){await f("retry",{sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:j,decision:j});return}let W=P;await $2(W.scope,async(k)=>{let E=k,y=Z.retrySameAccount?.bind(Z),c=W.attempt;if(y&&c&&!W.outputStarted&&!W.sameAccountRetry){if(W.ended)await W.ended;if(W.limit)await W.limit.delivered;let r=await L(W.scope.sessionID,async()=>{E();let z2=c.accountId,t=()=>B.has(W.id)&&W.accountId===z2&&d1(z.sessionID)===W&&!W.outputStarted&&(!Q||D.get(z.sessionID)===!0);if(!t()||W.sameAccountRetry)return!1;W.sameAccountRetry=!0;let Q2={...W.scope,accountId:z2,error:z.error,attempt:z.attempt,...W.limit?{limit:W.limit.signal}:{}},a;try{a=await y(Q2)}catch(H2){X("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:z.sessionID,error:K(H2)})}if(!a)return E(),!1;let U2={accountId:a.accountId,input:Q2};try{E()}catch(H2){throw await S(U2),H2}if(!t()||a.accountId!==z2)return await S(U2),!1;let W2=T.get(W.key);if(T.delete(W.key),W2)await v(W2);try{E()}catch(H2){throw await S(U2),H2}if(!t())return await S(U2),!1;return T.set(W.key,{attemptId:W.id,sessionID:W.scope.sessionID,order:++q,accountId:z2,sameAccount:U2}),W.judged=!0,z.decision={retry:!0,delay:0},!0});if(E(),r){await f("retry",{sessionID:z.sessionID,accountId:W.accountId,kind:W.scope.kind,attempt:z.attempt,reason:"same-account",hostDecision:j,decision:z.decision,handle:W.attempt});return}}if(O(z.sessionID)){await U();return}W.judged=!0;let V2=W.attempt;if(V2&&!W.outputStarted){if(!W.limit){let r=Z.limitFromError?.(z.error,V2);if(r)U1(W,r,"error")}if(W.ended)await W.ended;if(W.limit)await W.limit.delivered}E();let{decision:g2,reason:E2}=await L(W.scope.sessionID,async()=>{if(E(),O(z.sessionID))return{decision:j,reason:"host-decides"};let r=T.get(W.key);if(T.delete(W.key),r)await v(r);if(E(),O(z.sessionID))return{decision:j,reason:"host-decides"};let z2=j,t,Q2,a;if(W.accountId===void 0||!V2)z2={retry:!1},t="no-account";else if(W.outputStarted)z2={retry:!1},t="output-started";else if(W.limit){let U2={accountId:W.accountId,limit:W.limit.signal},W2,H2={...W.scope,phase:"retry",previousAccountId:W.accountId,rerouteFrom:U2};try{W2=await Z.chooseAccount(H2)}catch(H1){X("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:W.scope.sessionID,error:K(H1)})}let M2=typeof W2==="object"?W2.hold:void 0,l2=typeof W2==="string"?W2:M2?W.accountId:void 0;if(l2!==void 0)a={accountId:l2,input:H2};try{E()}catch(H1){if(a)await R(a);throw H1}if(O(z.sessionID)){if(a)await R(a);return{decision:j,reason:"host-decides"}}if(M2&&Number.isFinite(M2.delayMs)&&M2.delayMs>=0)z2={retry:!0,delay:Math.min(M2.delayMs,t1)},t="hold";else if(!M2&&l2!==void 0&&l2!==W.accountId)W.rerouted=!0,Q2=U2,z2={retry:!0,delay:0},t="reroute";else{if(M2&&a)await R(a),a=void 0;t="host-decides-last-account"}}else t="host-decides";if(z.decision=z2,z2.retry&&W.accountId!==void 0&&B.has(W.id))T.set(W.key,{attemptId:W.id,sessionID:W.scope.sessionID,order:++q,accountId:W.accountId,...Q2===void 0?{}:{rerouteFrom:Q2},...a===void 0?{}:{next:a}});else if(a)await R(a);return{decision:z2,reason:t}});E(),await f("retry",{sessionID:z.sessionID,...W.accountId===void 0?{}:{accountId:W.accountId},kind:W.scope.kind,attempt:z.attempt,reason:E2,hostDecision:j,decision:g2,...V2===void 0?{}:{handle:V2}})})},C2));let a1=(z)=>{if(m(z),D.delete(z),!d.get(z)?.foreignSeen)d.delete(z);for(let j of C)if(JSON.parse(j)[0]===z)C.delete(j);for(let j of[...B.values()]){if(j.scope.sessionID!==z)continue;o(j,"its session was forgotten"),B.delete(j.id)}for(let[j,U]of T)if(U.sessionID===z)A(j)},W1=new AbortController,n1=$.event;if(n1)(async()=>{try{for await(let z of n1.subscribe({signal:W1.signal}))if(z.type==="session.deleted")a1(z.data.sessionID);else if(z.type==="session.status"&&z.data.status.type==="idle"){let j=z.data.sessionID,U=++q;L(j,async()=>{for(let[P,W]of T)if(W.sessionID===j&&W.order<U)T.delete(P),await v(W)})}}catch(z){if(!W1.signal.aborted)X("opencode2 auth stopped listening for session deletion",{error:K(z)})}})();return{on(z,j){let U=l.get(z);if(!U)U=new Set,l.set(z,U);let P=j;return U.add(P),()=>{U.delete(P)}},accountFor(z,j){return e(O2(z,j))?.accountId},forgetSession:a1,get size(){return B.size},async dispose(){if(Z2)return;Z2=!0;for(let z of i.keys())m(z);W1.abort();for(let z of B.values())o(z,"the installation was disposed");B.clear();for(let z of T.keys())A(z);C.clear(),D.clear(),d.clear(),l.clear(),await Promise.all(M.values()),await Promise.all(P2.map(async(z)=>{try{await z.dispose()}catch(j){X("opencode2 auth hook did not dispose cleanly",{error:K(j)})}}))}}}import{createHash as v0}from"node:crypto";var h0=1024,m0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),e1=($)=>$$($,"user"),g0=($)=>m0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function l0($){return v0("sha256").update(JSON.stringify($)).digest("hex")}class x2{runtime;maxSessions;#$=new Map;constructor($,Z=h0){this.runtime=$;this.maxSessions=Z}advance($,Z,J=this.runtime){let G=this.#$.get($),Q=Array.isArray(Z.input)?Z.input:[],Y=Q.filter(e1),F=Q.findLastIndex(e1),V=F<0?void 0:l0(Q[F]),N=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,B,H,T;if(N)B=Y.length>0,H=V??G?.fingerprint,T=G?.userCount===void 0?void 0:G.userCount+Y.length;else{H=V,T=Y.length;let C=F>=0&&F>Q.findLastIndex(g0),D=G!==void 0&&!G.completed&&G.fingerprint===H&&G.userCount===T;B=C&&!D}let q=B||!G?{turnID:(J?.uuid??R2)(),turnStartedAt:(J?.now??Date.now)()}:{turnID:G.turnID,turnStartedAt:G.turnStartedAt};return this.#Z($,{...q,completed:!1,fingerprint:H,userCount:T}),q}completed($){let Z=this.#$.get($);if(Z)this.#Z($,{...Z,completed:!0})}get($){return this.#$.get($)}forget($){this.#$.delete($)}#Z($,Z){this.#$.delete($),this.#$.set($,Z);while(this.#$.size>this.maxSessions){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function T1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var Z$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function u0(){let $=globalThis;return $[Z$]??=crypto.randomUUID(),$[Z$]}class D2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,J){this.runtime=$;this.store=J;this.installationID=Z??u0(),this.sessions=J?.sessions??new Map,this.frameTurns=J?.frameTurns??new x2}get($){let Z=this.runtime?.uuid??R2;if(this.store)return this.store.get($,Z);let J=this.sessions.get($);if(!J){let G=Z();J={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,J)}return J}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(p2(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var L1={version:J$,"user-agent":z$,originator:"codex_exec"};var p0=1024,c0=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,d2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),Y$=($)=>d2($)&&($.type==="message"||("role"in $))&&$.role==="user",X$=($)=>d2($)&&$.type==="configuration_update";class _1{http;#$=new Map;constructor($=new D2){this.http=$}apply($,Z,J){if(Z.kind!=="primary")return!1;let G=typeof $.model==="string"?$.model:"";if(!G$.has(G))return!1;if(c0.test(G))return!1;let Q=d2($.reasoning)?$.reasoning:void 0,Y=typeof Q?.effort==="string"?Q.effort:void 0;if(!Y)return!1;let F=this.#$.get(Z.sessionID);if(F===void 0)return this.#Z(Z.sessionID,Y),!1;if(Y===F)return!1;let V=Array.isArray($.input)?$.input:void 0;if(!V||V.length===0)return!1;let N=V.findLastIndex(Y$);if(N<0){if(J==="http")return!1;return $.reasoning={...Q,effort:F},!0}if($.reasoning={...Q,effort:F},!X$(V[N-1]))V.splice(N,0,{type:"configuration_update",reasoning:{effort:Y}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>p0){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function p2($){try{let Z=JSON.parse($);return d2(Z)?Z:void 0}catch{return}}async function j$($,Z,J,G,Q=J.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Y=await $.clone().text(),F=p2(Y);if(F)delete F.max_output_tokens;let V=new Headers($.headers),N=c2({rewriteLite:Q$,init:{body:F?JSON.stringify(F):$.body===null?void 0:Y},headers:V,metadata:Q.get(Z.sessionID),installationID:Q.installationID,runtime:Q.runtime,websocket:!1,responsesLite:G,applyEffort:(B)=>{J.apply(B,Z,"http")}});return new Request($,{headers:V,body:N.init?.body})}function B$($,Z,J,G){let Q=G.sessions.get($.sessionID),Y=G.frameTurns.get($.sessionID);if(!Q||!Y)return;let F=T1(Q,Y),V=new Headers({"content-type":"application/json"});for(let B of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let H=J.get(B);if(H!==null)V.set(B,H)}c2({init:{body:$.bodyText},headers:V,metadata:F,installationID:G.installationID,runtime:G.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let N=new URL(Z);if(N.protocol==="wss:")N.protocol="https:";if(N.protocol==="ws:")N.protocol="http:";return new Request(N,{method:"POST",headers:V,body:$.bodyText})}function d0($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let J=Z.findIndex((G,Q)=>JSON.stringify(G)!==JSON.stringify($[Q]));return J>=0&&X$(Z[J])&&Y$(Z[J+1])&&JSON.stringify(Z.slice(J+1))===JSON.stringify($.slice(J))}function V$($,Z,J){let G=p2($);if(G?.type!=="response.create")return;let Q=J.http.advanceFrame(Z.sessionID,G),Y=J.http.get(Z.sessionID);delete G.max_output_tokens;let F=c2({rewriteLite:()=>{},init:{body:JSON.stringify(G)},headers:new Headers,metadata:T1(Y,Q),installationID:J.http.installationID,runtime:J.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(N)=>{J.apply(N,Z,"ws")}}),V=p2(String(F.init?.body));if(!V)return;if(!d0(G.input,V.input)){if("input"in G)V.input=G.input;else delete V.input;return JSON.stringify(V)}return String(F.init?.body)}function i0($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function P1($,Z){let J=new URL($);if(J.origin!=="https://api.openai.com"&&J.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(J.pathname))return $;let G=new URL(`${i0(Z)}/responses`);if(G.search=J.search,J.protocol==="ws:"||J.protocol==="wss:")G.protocol=G.protocol==="https:"?"wss:":"ws:";return G.href}import{resolve as M1}from"node:path";var U$=Symbol.for("@cortexkit/openai-auth/opencode2-rate-limits/v1"),W$=globalThis,C1=W$[U$]??new Map;W$[U$]=C1;function H$($){let Z=C1.get($);if(!Z)Z=new Map,C1.set($,Z);return Z}function N$($){return H$(JSON.stringify(["pool",M1($.configPath),M1($.statePath)]))}function F$($){return H$(JSON.stringify(["vault",M1($)]))}import{resolve as K$}from"node:path";var a0=1024;class i2{accounts=new Map;limit;constructor($=a0){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let J=this.accounts.keys().next().value;if(J===void 0)break;this.accounts.delete(J)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var T$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),L$=globalThis,E1=L$[T$]??new Map;L$[T$]=E1;function O1($){let Z=JSON.stringify([K$($.configPath),K$($.statePath)]),J=E1.get(Z);if(!J)J=new i2,E1.set(Z,J);return J}var F2="openai",n0=60000,R1=1,o0="request refused: no account with a usable credential",T2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function s0($){let Z=T2($)?$.counters:void 0,J=T2(Z)?Z.resetCredits:void 0,G=T2(J)?J.value:void 0;return typeof G==="number"&&Number.isFinite(G)?G:void 0}function n2($){try{return JSON.parse($)}catch{return}}function _$($){let Z=s2($);return Z?r2(Z):void 0}var r0=new Set(["usage_limit_reached","rate_limit_exceeded"]);function x1($,Z,J){return{reason:$.window,...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function t0($,Z){let J=o2($);if(J){let Y=typeof $.status==="number"?$.status:void 0;return x1(J,Z,Y)}if($.type!=="response.failed"||!T2($.response))return;let G=$.response.failed;if(T2(G)&&typeof G.rate_limit_reached_type==="string")return{reason:G.rate_limit_reached_type};let Q=$.response.error;if(T2(Q)){let Y=typeof Q.code==="string"?Q.code:typeof Q.type==="string"?Q.type:void 0;if(Y&&r0.has(Y))return{reason:Y}}return}function e0($,Z){let J=n2($);if(!T2(J))return;let G=typeof J.type==="string"?J.type:void 0;if(G==="codex.rate_limits")return{quota:{snapshot:E$(J),complete:!0}};let Q=t0(J,Z);if(Q)return{limit:Q};if(G===void 0||G==="error")return;return l$(G)?void 0:{outputStarted:!0}}function $4($){let Z=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:M$($),complete:C$($)}}function Z4($){let Z=$.get("retry-after");if(Z===null)return;let J=Number(Z);return Number.isFinite(J)&&J>=0?J*1000:void 0}function p$($){let Z=new WeakMap,J=new WeakSet,{source:G,pins:Q}=$,Y=$.now??Date.now,F=$.log,V=$.vault,N=new _1($.codex),B=new Map,H=new Map,T=(X)=>`${X.sessionID}\x00${X.kind}\x00${X.accountId}`,q=V?.paths?.rosterPath,C=q?F$(q):new Map,D=$.sessionAccounts??new i2,d=new y$,O=(X,K,M)=>{let L=M?[]:u$(G.peek().rows,X,K,V?.identities()??new Set),h=(V?.routes()??[]).filter((R)=>R.kind==="oauth"&&R$(y2(R.quota),X,K));return[...L.map((R)=>({id:R.id,...R.identity!==void 0?{identity:R.identity}:{},quota:R.quota,row:R})),...h.map((R)=>({id:R.id,...R.identity!==void 0?{identity:R.identity}:{},quota:R.quota}))]},I=(X,K,M)=>{let L=k$(X,K,M),h=X.map((A)=>({id:A.id,kind:"oauth",...P$(A.quota)?{quota:A.quota}:{}})),R=X.flatMap((A)=>A.row?[A.row]:[]),S=new Set(X.filter((A)=>!A.row).map((A)=>A.id)),v=G.rateLimitMarks(R);for(let A of S){let f=C.get(A);if(f===void 0)continue;if(f<=M)C.delete(A);else v.set(A,f)}return{rows:h,now:M,rateLimitMarks:v,refreshBackoff:G.refreshBackoffFor(R),killswitch:L,requestPull:(A)=>S.has(A)?V?.requestReading(A):G.requestReading(A)}},B2=(X,K,M,L,h)=>{let R=f$({...X,placement:D$(K),mainId:h});if(R.kind==="block"){F?.debug("pool admission refused the request",{reason:R.block.reason});return}let S=R.order.filter((v)=>!M.has(v));if(L!==void 0&&S.includes(L))return L;return S[0]},J2=(X,K,M,L,h,R,S,v)=>{let A=new Map(K.map((x)=>[x.id,x.quota])),f={requestBytes:R1,reservePercent:(x)=>A$(M,x===S$?void 0:x),resetCredits:(x)=>s0(A.get(x))},n=A1(X),u=(x,G2)=>t2(S,{sessionId:L,requestBytes:R1,validPinnedAccountIds:X.rows.map((g)=>g.id).filter((g)=>!n.excluded.has(g)),excludeAccountIds:x,quotaCheckedAtByAccount:Object.fromEntries(X.rows.map((g)=>[g.id,n.projections.get(g.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(K.map((g)=>[g.id,g.identity])),select:(g)=>v?{accountId:v,source:"mode-fallback",quotaCheckedAt:n.projections.get(v)?.checkedAt}:I$(X,f,new Set(x),g),persist:G2},(g,m)=>S.set(g,m)),o=[...h],s=u(o,R);if(!s)return;let e=s.accountId,p=v$(X,f,e);if(p.kind==="none")return;if(p.kind==="move"){let x=u([...o,e],R);if(x)return x.accountId;return p.reason==="killswitch"?void 0:e}if(p.kind==="detour")return u([...o,e],!1)?.accountId;return e},_2={providerID:F2,dropChoice(X){let K=T(X);H.get(K)?.drop(),H.delete(K),B.delete(K)},chooseAccount:async(X)=>{let K=await V?.authority(),M=await $.storage(),L=K!==void 0&&K!=="local",h=()=>{throw new Y2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:e2})};if(L)await $.awaitVaultRoster?.();else{if(!(await G.current()).active){if(await $.slotPlaceholderWithoutMain?.())h();F?.warn("the account pool does not serve requests yet; refusing the request",{kind:X.kind});return}await G.prepareTokens(G.peek().rows,M)}let R=Y(),S=O(M,R,L),v=w$(I(S.filter((m)=>m.id!==X.rerouteFrom?.accountId),M,R));if(v)await v,R=Y(),S=O(M,R,L);let A=new Map(S.map((m)=>[m.id,m])),f=I(S,M,R),n=new Set(X.rerouteFrom?[X.rerouteFrom.accountId]:[]),u=M?.routing?.mode??"main-first",o=X.kind==="primary",s=new Set,e,p,x,G2=!1,g=(m)=>{let $2=A1(f).projections.get(m)?.checkedAt,X2=A.get(m)?.identity;return Q.reserve(X.sessionID,{accountId:m,inputBytes:R1,...$2!==void 0?{quotaCheckedAt:$2}:{},...X2!==void 0?{wireIdentity:X2}:{}})};try{for(;;){let m=new Set([...n,...s]);x=void 0,e=void 0;let $2=u!=="sticky-balanced";if(u==="sticky-balanced"){let _=new Map(Q.placementSnapshot(X.sessionID)),b=_.get(X.sessionID);if($2=b===void 0,x=J2(f,S,M,X.sessionID,m,o&&s.size===0,_),x!==void 0&&_.get(X.sessionID)!==b)e=_.get(X.sessionID)}if(x??=B2(f,u,m,o?void 0:D.activeAccount(X.sessionID),L?u==="sticky-balanced"?null:b$(V?.routes()??[]):void 0),x===void 0||s.has(x)){if(n.size>0){let _=new Map(f.rateLimitMarks);for(let b of n)_.delete(b);f={...f,rateLimitMarks:_},n.clear();continue}if(f.rateLimitMarks.size>0){f={...f,rateLimitMarks:new Map};continue}x=void 0;break}if(o&&u==="sticky-balanced")p=g(x);if(!G2){G2=!0;let _=await h$({vaultMode:L,fresh:$2,sessionId:X.sessionID,request:{modelId:X.modelID,kind:X.kind,retry:X.phase==="retry"||X.rerouteFrom!==void 0},routes:V?.routes()??[],routing:f,eligibleIds:S.filter((b)=>!m.has(b.id)).map((b)=>b.id)});if(_&&_!==x){if(p)Q.rollback(p);if(p=void 0,u==="sticky-balanced"){let b=new Map(Q.placementSnapshot(X.sessionID));x=J2(f,S,M,X.sessionID,m,o,b,_)??x,e=b.get(X.sessionID)??e}else x=_;if(o&&u==="sticky-balanced")p=g(x)}}let X2=A.get(x)?.row;if(X2){if(G.usableToken(X2)!==void 0)break;F?.debug("pool row holds no usable token; choosing again",{accountId:x})}else{if(!V)break;let _=await V.authorize(x);if(_){B.set(T({...X,accountId:x}),_);break}F?.debug("the vault refused to serve an account; choosing again",{accountId:x})}if(p)Q.rollback(p);p=void 0,s.add(x)}if(x===void 0&&!L&&S.length===0&&await $.slotPlaceholderWithoutMain?.())h();if(x===void 0&&L&&V&&(S.length===0||s.size>0)){let m=s.size>0?"vault-refused":q$(V);throw F?.warn("vault mode: no vault account can serve; refusing the request",{cause:m}),new Y2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:x$(m,V.name)})}if(x!==void 0){let m=x,$2=p,X2=e,_=()=>{if($2)Q.finish($2,X2);if(o)D.record(X.sessionID,m),$.onRoute?.(X.sessionID,m,u)};if(X.phase==="retry")H.set(T({...X,accountId:x}),{commit:_,drop:()=>{if($2)Q.rollback($2)}}),p=void 0;else _();let b=F?.info;d.served(f,x,F&&b?{info:(j2,b2)=>b.call(F,j2,b2)}:void 0)}return F?.debug("pool account chosen",{kind:X.kind,accountId:x,mode:u,...X.rerouteFrom?{rerouteFrom:X.rerouteFrom.accountId}:{}}),x}finally{if(p)Q.rollback(p)}},accountHeaders:async(X)=>{let{accountId:K}=X,M=T(X),L=H.get(M);H.delete(M);let h=()=>{L?.commit()};try{let R=()=>new Y2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:o0}),S=V&&await V.authority()!=="local"?void 0:G.peek().rows.find((f)=>f.id===K);if(!S&&V){let f=T(X),n=B.get(f)??await V.authorize(K);if(B.delete(f),!n)throw F?.warn("the vault refused to serve an account; refusing the request",{accountId:K}),R();return h(),{headers:{...L1,"session-id":X.sessionID,authorization:`Bearer ${n.accessToken}`,"chatgpt-account-id":n.accountIdentity??_$(n.accessToken)??null},attempt:{kind:"vault",routeId:K,receipt:n}}}let v=S?G.usableToken(S):void 0;if(!S||!v)throw F?.warn("pool row holds no usable token; refusing the request",{accountId:K}),R();let A=S.identity??_$(v);return h(),{headers:{...L1,"session-id":X.sessionID,authorization:`Bearer ${v}`,"chatgpt-account-id":A??null},attempt:{kind:"pool",token:v,credentialEpoch:S.credentialEpoch}}}finally{L?.drop()}},async rewriteRequest({request:X,sessionID:K,kind:M}){let L=$.codexEndpoint?P1(X.url,$.codexEndpoint()):X.url,h=L===X.url?X:new Request(L,X);return await j$(h,{sessionID:K,kind:M},N,$.responsesLite?.()??!1)??h},rewriteHandshakeURL:({url:X})=>$.codexEndpoint?P1(X,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:X,sessionID:K,kind:M})=>V$(X,{sessionID:K,kind:M},N),quotaFromHeaders:(X,K,M)=>{if(M.data?.kind==="vault"&&w2()&&K>=200&&K<300)Z.set(M,{status:K,headers:X});return $4(X)},async limitFromResponse({status:X,headers:K,body:M,attempt:L}){if(X<400)return;let h=n2(await M().catch(()=>"")),R=o2({...T2(h)?h:{},status:X});if(L.data?.kind==="vault"&&w2())a2(L.sessionID,L.data.receipt,{status:X,headers:K,body:h,limit:R,quota:V?.routes().find((f)=>f.id===L.accountId)?.quota,now:Y()});if(!R)return;let S=Y(),v=x1(R,S,X);if(v.retryAfterMs!==void 0)return v;let A=Z4(K);return A===void 0?v:{...v,retryAfterMs:A}},inspectEvent:({data:X,transport:K,attempt:M})=>{if(M.data?.kind==="vault"&&w2()&&(g$(X)||K==="ws"&&X.includes('"response.completed"'))){let L=n2(X);if(m$(L))J.add(M);if(K==="ws"&&T2(L)&&L.type==="response.completed")a2(M.sessionID,M.data.receipt,{status:200,headers:new Headers,failed:J.has(M)})}return e0(X,Y())},limitFromError(X){let K=n2(X.message),M=o2({...T2(K)?K:{},...X.status!==void 0?{status:X.status}:{}})??(X.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return M?x1(M,Y(),X.status):void 0},async onAttemptEnd(X,K){let M=X.data,L=M?.kind==="vault"&&w2()?Z.get(X):void 0;if(Z.delete(X),M?.kind==="vault"&&L&&!K.error&&!K.limit)a2(X.sessionID,M.receipt,{...L,failed:J.has(X)});if(M?.kind!=="vault"||K.status!==401)return;F?.warn("a vault account answered 401; reporting it to the vault",{accountId:X.accountId}),await V?.reportFailure(M.receipt,401)}},Z2=(X,K,M)=>{let L=M.data;if(L?.kind==="vault"){V?.recordSnapshot(X,K.snapshot,K.complete,L.receipt);return}if(L?.kind!=="pool")return;if(G.peek().rows.find((R)=>R.id===X)?.credentialEpoch!==L.credentialEpoch){F?.debug("quota reading dropped: the row holds another credential",{accountId:X});return}G.recordSnapshot(X,K.snapshot,L.token,K.complete)},i=(X,K,M)=>{let L=Y(),h=M.data?.kind==="vault",R=h?V?.routes().find((A)=>A.id===X)?.quota:G.peek().rows.find((A)=>A.id===X)?.quota,S=O$(y2(R),K.reason,L,n0,K.retryAfterMs!==void 0?L+K.retryAfterMs:void 0);if(!h){G.markRateLimited(X,S);return}let v=C.get(X);if(v===void 0||v<S)C.set(X,S)};return{adapter:_2,attach(X){X.on("quota",(K)=>Z2(K.accountId,K.quota,K.handle)),X.on("limit",(K)=>{i(K.accountId,K.limit,K.handle),F?.debug("pool row refused the request",{accountId:K.accountId,via:K.via,reason:K.limit.reason,outputStarted:K.outputStarted})})},forgetSession(X){Q.forget(X),D.forget(X),N.forget(X)},activeAccount:(X)=>D.activeAccount(X)}}import{resolve as o$}from"node:path";import{Buffer as J4}from"node:buffer";import{resolve as c$}from"node:path";function f2($){return J4.byteLength(JSON.stringify($))}function z4($){return $.reduce((Z,J)=>Z+f2(J),0)}function q1($,Z){return 2+$+Math.max(0,Z-1)}function G4($){let{head:Z,pending:J}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+q1(Z.inputBytes,Z.input.length)+1:0)+(J?20+q1(J.inputBytes,J.input.length)+10+q1(J.outputBytes,J.output.length)+(J.responseID===void 0?0:14+J.responseIDBytes)+1:0)}function d$($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class i${enabled;caps=$1;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$)this.entries.clear(),this.bytes=0}send($,Z){if(!this.enabled)return;let J=d$(Z);if(J?.type!=="response.create")return;if(!Array.isArray(J.input)){this.forget($);return}let G=J.previous_response_id,Q=this.entries.get($),Y=Q?.head;if(G&&G!==Y?.responseID){this.forget($);return}let{type:F,previous_response_id:V,input:N,...B}=J;this.keep($,{fields:G&&Q?Q.fields:B,fieldsBytes:G&&Q?Q.fieldsBytes:f2(B),...G&&Y?{head:Y}:{},pending:{input:N,inputBytes:z4(N),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,J){if(!this.enabled||!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed"))return;let G=this.entries.get($);if(!G?.pending)return;let Q=d$(Z);if(!Q)return;let Y=G.pending,F=Q.response;if(Q.type==="response.created"&&typeof F?.id==="string")Y.responseID=F.id,Y.responseIDBytes=f2(F.id),this.keep($,G);else if(Q.type==="response.output_item.done"&&Q.item){if(typeof Q.response_id==="string"&&Y.responseID!==void 0&&Q.response_id!==Y.responseID)return;Y.output.push(Q.item),Y.outputBytes+=f2(Q.item),this.keep($,G)}else if(Q.type==="response.completed"&&typeof F?.id==="string"){if(F.id===G.head?.responseID||Y.responseID!==void 0&&F.id!==Y.responseID)return;let V={responseID:F.id,responseIDBytes:Y.responseID===F.id?Y.responseIDBytes:f2(F.id),input:[...G.head?.input??[],...Y.input,...Y.output],inputBytes:(G.head?.inputBytes??0)+Y.inputBytes+Y.outputBytes},N={...G,head:V,pending:void 0};if(!this.keep($,N))return;J?.({sessionID:$,responseID:V.responseID,bodyText:this.body(G.fields,V)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let J=G4(Z);if(this.forget($),J>this.caps.maxBytes)return!1;Z.bytes=J,this.entries.set($,Z),this.bytes+=J;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let G=this.entries.keys().next().value;if(G===void 0)break;this.forget(G)}return this.entries.has($)}}var a$=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),n$=globalThis,S1=n$[a$]??new Map;n$[a$]=S1;function Z1($){let Z=JSON.stringify([c$($.configPath),c$($.statePath)]),J=S1.get(Z);if(!J)J=new i$,S1.set(Z,J);return J}var Q4=5000,Y4=["accept","originator","session-id","thread-id","user-agent","version","x-client-request-id","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-openai-internal-codex-responses-lite","x-opencode-parent-session-id","x-parent-session-id"],X4=["x-opencode-parent-session-id","x-parent-session-id"];function e$($){let Z=s$($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:r$($?{...$,cachekeep:Z}:$)}}var $Z=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),ZZ=globalThis,I2=ZZ[$Z]??new Map;ZZ[$Z]=I2;function j4($,Z){let J=[],G=()=>J.at(-1)?.location,Q=()=>{let N=G();if(!N)throw Error("no location holds keep-warm");return N},Y=(N,B)=>{V.remove(N),G()?.log?.debug(`cachekeep dropped target (${B})`,{sessionKey:N})},F=async(N)=>{if(N.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let B=N.accountId??"main",H=Q(),T=await H.source.accessFor(B,await H.storage());if(!T)throw Error(`pool row ${B} has no usable token`);return{token:T.token,identity:T.row.identity}},V=t$({...$1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(N,B)=>Q().fetch(N,B),logger:{debug:(N,B)=>G()?.log?.debug(N,B),warn:(N,B)=>G()?.log?.warn(N,B)},getWindow:()=>G()?.settings().window,getSustain:()=>G()?.settings().sustain===!0,resolveLocal:F,vault:{owns:(N)=>G()?.vault.owns(N)===!0,authority:()=>Q().vault.authority(),send:async(N,B,H)=>{let T=Q();if(await T.vault.authority()!=="vault")return;return T.vault.send(N,B,H)}},activeAccount:(N)=>{if(N===void 0)throw Error("target has no session");let B=G(),H=B?.settings();if(!B||!H?.enabled){Y(N,"keep-warm is off");return}if(!H.subagents&&V.status().targets.some((q)=>q.sessionKey===N&&q.isSubagent)){Y(N,"subagent warming is off");return}let T=B.accounts.activeAccount(N);if(T===void 0){Y(N,"no account recorded for the session");return}return T},verifyCredential:({target:N,mode:B,identity:H})=>{if(N.meta.credentialMode!==B)throw Error(`a target captured in ${N.meta.credentialMode??"an unknown"} mode is not warmed with a ${B} credential`);if(H!==N.meta.chatgptAccountId)throw Y(N.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:V,settings:Z,holders:J,joinTimeoutMs:$.joinTimeoutMs??Q4}}function B4($){try{let Z=JSON.parse($),J=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(J?.role!=="user")return!1;return(typeof J.content==="string"?J.content:Array.isArray(J.content)?J.content.map((Q)=>typeof Q?.text==="string"?Q.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function V4($){let Z={};for(let J of Y4){let G=$.get(J);if(G)Z[J]=G}return Z}function JZ($,Z,J){let G=JSON.stringify([o$($.configPath),o$($.statePath)]),Q=I2.get(G);if(!Q)Q=j4(J,Z.settings()),I2.set(G,Q);let Y=Q,F=Z1($);F.setEnabled(Y.settings.enabled);let V={location:{...Z,settings:()=>Y.settings}};Y.holders.push(V);let N=!1,B=async(H)=>{try{let T=V.location.settings();if(N||!T.enabled)return;if(H.kind!=="primary"){if(H.kind==="generate"&&B4(await H.request.clone().text())){if(N)return;Y.manager.remove(H.sessionID)}return}let q=H.attempt.data,C=q?.kind==="pool"?"local":q?.kind==="vault"?"vault":void 0;if(!C)return;let D=H.request.headers,d=X4.some((B2)=>D.has(B2))||Z.parentOf!==void 0&&await Z.parentOf(H.sessionID)!==void 0;if(d&&!T.subagents)return;let O=await H.request.clone().text();if(N)return;let I=D.get("chatgpt-account-id")??void 0;Y.manager.track({sessionKey:H.sessionID,bodyText:O,accountId:H.attempt.accountId,isSubagent:d,meta:{replayHeaders:V4(D),...I?{chatgptAccountId:I}:{},routingSessionId:H.sessionID,url:H.request.url,credentialMode:C}})}catch(T){Z.log?.warn("cachekeep capture failed",{error:T instanceof Error?T.message:String(T)})}};return{manager:Y.manager,configure:(H)=>{Object.assign(Y.settings,H),F.setEnabled(Y.settings.enabled)},capture:B,forget:(H)=>Y.manager.remove(H),async release(){if(N)return;N=!0;let H=Y.holders.indexOf(V);if(H>=0)Y.holders.splice(H,1);if(Y.holders.length>0)return;if(I2.get(G)===Y)I2.delete(G);Y.manager.stop();let T;try{await Promise.race([Y.manager.tick().catch(()=>{}),new Promise((q)=>{T=setTimeout(q,Y.joinTimeoutMs),T.unref?.()})])}finally{clearTimeout(T)}}}}import{mkdirSync as U4}from"node:fs";import{dirname as W4,resolve as H4}from"node:path";function N4(){return zZ("opencode2")}var F4=2000;class jZ{path;options;sessions;frameTurns=new x2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Q=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=YZ($,Z.uuid??R2)}get($,Z=R2){let J=this.sessions.get($);if(!J){let G=Z();J={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,J),this.#Z.delete($),this.#z.delete($),this.#$.add($),this.#Y()}return J}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#z.add($);this.#Y()}#Y(){if(this.#J)return;this.#J=setTimeout(()=>{this.#J=void 0,this.save()},this.options.saveDelayMs??F4),this.#J.unref?.()}save(){if(clearTimeout(this.#J),this.#J=void 0,!this.#Q)this.#Q=!0,this.#G=this.#G.then(()=>{return this.#Q=!1,this.#j()});return this.#G}settled(){return this.#J?this.save():this.#G}#X(){if(this.#z.size===0)return;let $;try{$=b1(this.path)}catch{$=new Map}for(let Z of this.#z)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#z.clear()}async#j(){if(this.#X(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((G)=>{let Q=this.sessions.get(G);return Q?[[G,Q]]:[]}),Z=[...this.#Z],J=null;try{if(U4(W4(this.path),{recursive:!0}),J=await this.#B(),!J)return;let G;try{G=b1(this.path)}catch{G=new Map}await this.options.afterRead?.();let Q=!1;for(let Y of Z)if(G.delete(Y))Q=!0;for(let[Y,F]of $){if(G.get(Y)===F.threadID)continue;G.set(Y,F.threadID),Q=!0}if(Q)XZ(this.path,G)}catch{return}finally{await J?.release().catch(()=>{})}for(let[G,Q]of $)if(this.sessions.get(G)===Q)this.#$.delete(G);for(let G of Z)if(!this.sessions.has(G))this.#Z.delete(G)}#B(){return QZ(this.path,this.options.lockWaitMs??GZ)}}var BZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),VZ=globalThis,J1=VZ[BZ]??new Map;VZ[BZ]=J1;function K4($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.sessions instanceof Map&&typeof Z.get==="function"&&typeof Z.delete==="function"&&typeof Z.save==="function"&&typeof Z.settled==="function"&&(Z.frameTurns===void 0||Z.frameTurns!==null&&typeof Z.frameTurns.advance==="function"&&typeof Z.frameTurns.get==="function"&&typeof Z.frameTurns.completed==="function"&&typeof Z.frameTurns.forget==="function")}function UZ($=N4()){let Z=H4($),J=J1,G=J1.get(Z),Q=J1;if(G!==void 0&&!K4(G))J.compatible??=new Map,Q=J.compatible;let Y=Q.get(Z);if(!Y)Y=new jZ(Z),Q.set(Z,Y);let F=Y;return F.frameTurns??=new x2,Y}var k1=Symbol.for("cortexkit.openai-auth.v2.commands"),T4=L2("v2-command");function z1($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.closed instanceof AbortController&&typeof Z.menu?.open==="function"&&typeof Z.menu?.apply==="function"&&typeof Z.session?.get==="function"&&(Z.registration===void 0||Z.registration!==null&&typeof Z.registration.dispose==="function")}function D1($){T4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function L4(){let $=globalThis;return $[k1]??={locations:new Map},$[k1].locations??=new Map,$[k1]}async function LZ($,Z){let J=L4(),G=$.location.directory,Q={menu:Z,session:$.session,closed:new AbortController},Y=await HZ(G),F=await WZ(KZ,Y.dir,()=>TZ({...Y,drain:FZ,apply:(T)=>{let q=J.locations.get(G);if(!z1(q))throw Error("The OpenAI menu location was closed");return q.menu.apply(T)}})),V=J.locations.get(G);if(J.locations.set(G,Q),z1(V))V.closed.abort(),await V.registration?.dispose();let N={name:"openai",description:"OpenAI account menu",async execute(T){let q=[...J.locations.values()].find(z1)?.session;if(!q)return D1("no live location");let C=await q.get({sessionID:T.sessionID}),D=J.locations.get(C.location.directory);if(!z1(D))return D1("location closed");let d=await NZ(T.sessionID,D.closed.signal);if(!d||J.locations.get(C.location.directory)!==D){if(!d&&!D.closed.signal.aborted)w1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},T.sessionID);return D1(D.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let O=await D.menu.open(T.sessionID);w1(O,T.sessionID)}};J.command??=N,J.command.execute=N.execute;let B=J.command;try{Q.registration=await $.command.transform((T)=>{T.add(B)})}catch(T){if(Q.closed.abort(),J.locations.get(G)===Q)J.locations.delete(G);throw await F.release(),T}let H=!1;return async()=>{if(H)return;if(H=!0,Q.closed.abort(),J.locations.get(G)===Q)J.locations.delete(G);await F.release(),await Q.registration?.dispose()}}var _4="openai-auth-pool-browser",P4="openai-auth-pool-headless",M4="openai-auth-vault",C4="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Run /openai → Vault → Connect and approve the request before trying again.";async function v2($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function OZ($){return{method:{id:M4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await _Z($.paths,$.name)!=="vault")throw Error(C4)}}}function RZ($){let Z=(J,G,Q)=>({method:{id:J,type:"oauth",label:G},async authorize(){if($.vault)await v2($.vault);let Y=await $.beginLogin({version:$.version,headless:Q});return{url:Y.url,instructions:Y.instructions,mode:"auto",callback:Y.completion}}});return[Z(_4,"ChatGPT (openai-auth pool, browser)",!1),Z(P4,"ChatGPT (openai-auth pool, headless)",!0)]}function y1($){let Z=(J)=>typeof J==="string"?J:"";return k2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===CZ||PZ($)}function E4($){if($.accountId)return $.accountId;let Z=$.access?s2($.access):void 0;return Z?r2(Z):void 0}async function AZ($,Z,J,G={}){if(G.vault)await v2(G.vault);if(y1(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Q=MZ($,{rowLocks:(C)=>EZ(Z,C)}),Y=await Q.read();if(Y.status!=="ready")throw Error(`the account pool cannot be read (${Y.status}); the login was not stored`);let F={type:"oauth",refresh:J.refresh,...J.access!==void 0?{access:J.access}:{},...J.expires!==void 0?{expires:J.expires}:{}},V=E4(J);if(G.vault)await v2(G.vault);let N=V!==void 0?{identity:V}:{};if(G.origin==="import"){let C=Y.rows.find((D)=>V!==void 0&&D.identity===V||D.credential?.type==="oauth"&&D.credential.refresh===J.refresh);if(C)return{id:C.id,operation:"kept"}}let B=Y.rows.filter((C)=>C.type==="oauth"&&!C.invalid),H=V?B.find((C)=>C.identity===V):void 0,T=Y.rows.find((C)=>C.id===G1);if(H)return{id:(await Q.replace(H.id,F,N)).id,operation:"replaced"};if(!T){let C=await Q.add({id:G1,credential:F,...N,...J.label!==void 0?{label:J.label}:{}});return{id:C.id,operation:C.outcome==="added-disabled"?"added-disabled":"added"}}if(!T.invalid&&!T.credential)return{id:(await Q.replace(G1,F,N)).id,operation:"replaced"};let q=await Q.add({id:J.id,credential:F,...N,...J.label!==void 0?{label:J.label}:{}});return{id:q.id,operation:q.outcome==="added-disabled"?"added-disabled":q.outcome==="rotated"?"replaced":"added"}}function O4($){let Z=$.itemId!==void 0;switch($.sectionId){case"accounts":return Z?["enable","disable","remove","move"].includes($.actionId):$.actionId==="add";case"routing":return!Z&&["order","mode"].includes($.actionId);case"quota":return $.actionId==="check";case"limits":return Z?$.actionId==="floors":$.actionId==="killswitch";case"session":return!Z&&$.actionId==="clear-pin";case"vault":return Z?["enable","disable"].includes($.actionId):["connect","disconnect"].includes($.actionId);case"diagnostics":return!Z&&["logging","dump"].includes($.actionId);case"cache":return!Z&&["enabled","subagents","sustain","window"].includes($.actionId);case"reset":return Z&&["preview","spend","retry"].includes($.actionId);default:return!1}}function SZ($){let Z={...$,allowAction:O4,unavailableSections:[]};return{open:(J)=>xZ(Z,J),apply:(J)=>{let G=J!==null&&typeof J==="object"?J:{},Q=G.values&&typeof G.values==="object"&&!Array.isArray(G.values)?Object.fromEntries(Object.entries(G.values).filter(([,Y])=>Y===null||["string","number","boolean"].includes(typeof Y))):void 0;return qZ(Z,{command:"openai",sectionId:typeof G.sectionId==="string"?G.sectionId:"",actionId:typeof G.actionId==="string"?G.actionId:"",...Q?{values:Q}:{},...G.confirmed===!0?{confirmed:!0}:{},...typeof G.itemId==="string"?{itemId:G.itemId}:{},...typeof G.sessionId==="string"?{sessionId:G.sessionId}:{}})}}}function R4($,Z){if(!bZ($.modelID??$.id)){$.enabled=!1;return}let J=kZ($.id);if(J)$.limit={...J};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((G)=>[G.id,G])).values()]}function wZ($){return $.model.transform((Z)=>{let J=Z.list(F2);for(let G of J){let Q=DZ(String(G.id)),Y=Q?J.find((F)=>String(F.id)===Q):void 0;Z.update(F2,String(G.id),(F)=>R4(F,Y?.variants?.map((V)=>({...V,id:String(V.id)}))))}})}class f1{log;pending=new Map;requests=new Map;writing=new Set;constructor($){this.log=$}async safely($){let Z=(async()=>{try{await $()}catch{this.log.warn("request dump failed")}})();this.writing.add(Z);try{await Z}finally{this.writing.delete(Z)}}async captureHttp($,Z){if(!yZ())return;await this.safely(async()=>{let J={sessionID:Z.sessionID,accountId:Z.accountId,transport:"http",phase:"http",url:$.url,method:$.method,headers:new Headers($.headers),bodyText:await $.clone().text()};if(this.pending.set($,{attemptId:Z.attemptId,input:J}),this.requests.set(Z.attemptId,$),this.pending.size>512){let G=this.pending.keys().next().value;if(G)this.take(G)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let J=this.take($);if(J)await this.safely(()=>Q1({...J,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let J=this.requests.get($.attemptId),G=J&&this.take(J);if(!G)return;let{reason:Q,message:Y}=Z.error,F=Y?`${Q}: ${Y}`:Q;await this.safely(()=>Q1({...G,error:Y1(F,J?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>Q1({sessionID:Z.sessionID,accountId:Z.accountId,transport:"websocket",phase:"observed",bodyText:$}))}clear(){this.pending.clear(),this.requests.clear()}async settle(){await Promise.all(this.writing)}}class I1{counts=new Map;record($,Z){let J=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof J==="number"&&Number.isFinite(J)?J:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function mZ($){return async(Z)=>{let J=Z.credential;if(J.type!=="oauth"||!J.access)throw Error("the row holds no access token to poll with");let G=await fZ({accessToken:J.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,G),IZ(G,$.now(),!0)}}function gZ($){let{source:Z,counts:J,now:G}=$,Q=async(B)=>{let H=await Z.rowAccess(B,await $.storage());if(!H?.row)throw new vZ("unknown_account",`${B==="main"?"Main":"Fallback"} account ${B} was not found.`);return hZ(B,H)},Y=async(B)=>{if($.authority&&await $.authority()!=="local")return{account:B,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[H]=await Z.pollRows(await $.storage(),{ids:[B]});if(!H)return{account:B,ok:!1,error:"targeted quota refresh returned no result"};return{account:H.id,ok:H.ok,...H.error!==void 0?{error:H.error}:{}}},F=(B)=>Z.peek().rows.find((H)=>H.id===B),V=(B)=>{let H=F(B);if(!H)return null;let T=y2(H.quota)??{},q=J.applicable(H),C=Math.max(0,...[T.primary?.checkedAt,T.secondary?.checkedAt].filter((D)=>typeof D==="number"));return{quota:{...T,...q!==void 0?{resetCreditsApplicable:q}:{}},checkedAt:C,refreshAfter:C,...H.identity!==void 0?{accountId:H.identity}:{}}};return{resolveResetTarget:Q,refreshResetTargetQuota:Y,quotaManager:{isRateLimited:(B)=>{let H=F(B);if(!H)return!1;let T=Z.rateLimitMarks([H]).get(H.id);return T!==void 0&&T>G()},getMain:()=>V("main"),getFallback:(B)=>V(B)}}}import{resolve as lZ}from"node:path";var A4=1024;class v1{pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=A4){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.reservations.delete($),this.pins.delete($);for(let Z of this.listeners)Z($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}snapshot(){return new Map(this.pins)}placementSnapshot($){let Z=new Map(this.pins);for(let J of this.reservations.values())if(J.sessionId!==$)Z.set(J.sessionId,J.pin);return Z}reserve($,Z){let J={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,J),J}rollback($){if(this.reservations.get($.sessionId)===$)this.reservations.delete($.sessionId)}finish($,Z){if(this.reservations.get($.sessionId)!==$)return;if(this.rollback($),Z&&this.pins.get($.sessionId)===$.previous)this.set($.sessionId,Z)}get size(){return this.pins.size}set($,Z){this.reservations.delete($),this.pins.delete($),this.pins.set($,Z);for(let J of this.listeners)J($,Z);while(this.pins.size>this.limit){let J=this.pins.keys().next().value;if(J===void 0)break;this.forget(J)}}place($){return t2(this.placementSnapshot($.sessionId),$,(Z,J)=>this.set(Z,J))}}var uZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),pZ=globalThis,X1=pZ[uZ]??new Map;pZ[uZ]=X1;function x4($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.get==="function"&&typeof Z.forget==="function"&&typeof Z.subscribe==="function"&&typeof Z.snapshot==="function"&&typeof Z.place==="function"&&typeof Z.placementSnapshot==="function"&&typeof Z.reserve==="function"&&typeof Z.rollback==="function"&&typeof Z.finish==="function"}function cZ($){let Z=JSON.stringify([lZ($.configPath),lZ($.statePath)]),J=X1,G=X1.get(Z);if(G!==void 0&&!x4(G)){let Y=X1;Y.compatibleV1??=new Map,J=Y.compatibleV1}let Q=J.get(Z);if(!Q)Q=new v1,J.set(Z,Q);return Q}import{statSync as q4}from"node:fs";import{resolve as S4}from"node:path";function eZ($){return $.map((Z)=>{try{let J=q4(Z);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}function h1($){return eZ([$.vault.paths.tokenPath,$.vault.paths.statePath])}function dZ($){return eZ([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+h1($)}class $0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:dZ($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),J=this.subscriptions.get($.pins);if(!J){let G=new Set;J={producers:G,stop:$.pins.subscribe((Q,Y)=>{let F=G.values().next().value;if(F)this.publish(F,{sessionId:Q,pin:Y,accountId:Y?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,J)}return J.producers.add($),this.timer??=setInterval(()=>{for(let G of this.producers){let Q={stamp:dZ(G),roster:G.vault.snapshot()},Y=this.observations.get(G);if(Q.stamp!==Y?.stamp||Q.roster!==Y?.roster)this.observations.set(G,Q),this.publish(G)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),J.producers.delete($),!J.producers.size)J.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;let G=await $.vault.authority()!=="local",Q=h1($),Y=()=>this.producers.has($)&&$.vault.enrolled()===G&&h1($)===Q,F=await(G?m2($.paths):q2($.paths)),V=G?rZ($.vault.snapshot()?.rows,new Set($.vault.routes().map((H)=>H.id)),F,Date.now()):tZ((await $.source.sidebarView()).rows,F,Date.now()),N={canWrite:Y,vaultMode:G};if(await aZ(V,this.file,N),!Y()||!Z)return;let B=V.vaultAccounts??V.fallbacks;if(Z.accountId===void 0){await oZ(Z.sessionId,B,this.file,N);return}if(Z.pin){let H=Date.now();await sZ({sessionId:Z.sessionId,assignment:{accountId:Z.pin.accountId,wireAccountId:Z.pin.wireIdentity,inputBytes:Z.pin.inputBytes??0,quotaCheckedAt:Z.pin.quotaCheckedAt,assignedAt:H,lastSeenAt:H},validPinnedAccountIds:[...G?[]:["main"],...B.filter((T)=>T.enabled).map((T)=>T.id)]},this.file,N)}await nZ({sessionId:Z.sessionId,activeId:Z.accountId,route:Z.route??V.route,updatedAt:Date.now()},B,this.file,N)}).catch(()=>{L2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var Z0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),J0=globalThis,h2=J0[Z0]??new Map;J0[Z0]=h2;function z0($,Z=iZ(),J=2000){let G=S4(Z),Q=h2.get(G);if(!Q)Q=new $0(G,J),h2.set(G,Q);let Y=Q,F=Y.add($),V=!1;for(let[N,B]of $.pins.snapshot())Y.publish($,{sessionId:N,pin:B,accountId:B.accountId,route:"sticky-balanced"});return{publish:()=>Y.publish($),route:(N,B,H)=>{Y.publish($,{sessionId:N,accountId:B,route:H})},async release(){if(V)return;if(V=!0,F(),await Y.settled(),Y.empty&&h2.get(G)===Y)h2.delete(G)}}}var V1="cortexkit-openai-auth",D4=5000;async function G0($,Z,J,G=new D2,Q,Y,F){let V=new f1(J),N=new b4,B=new Map,H=new Map,T=(O)=>{H.delete(O);for(let I of B.keys())if(I.startsWith(`${O}:`))B.delete(I)},q=(O)=>{F?.(O.sessionID),Y?.send(O.sessionID,O.frame)},D=await K1({session:{hook:(O,I,B2)=>$.session.hook(O,async(J2)=>{let w=O==="http.request"?J2:void 0,l=O==="experimental.ws.handshake"?J2:void 0,Z2=(w?w.request.headers:l?new Headers(l.headers):void 0)?.get("authorization")===`Bearer ${K2(Z.providerID)}`,i={};if(l)B.delete(`${l.sessionID}:${l.kind}`);try{await N.run(i,()=>I(J2))}catch(X){if(Z2&&!(X instanceof Y2))throw V0(X);throw X}if(w&&Z2&&i.attempt){let X=w.request.headers.get("thread-id");if(X)w.request.headers.set("session-id",X)}if(w&&Z2&&i.attempt)await V.captureHttp(w.request,i.attempt);if(w&&Z2&&i.attempt)await Q?.({sessionID:w.sessionID,kind:w.kind,request:w.request,attempt:i.attempt});if(l&&Z2&&i.attempt)l.headers["session-id"]=G.get(l.sessionID).threadID;if(O==="experimental.ws.send"){let X=J2,K=B.get(`${X.sessionID}:${X.kind}`);if(K)await V.frame(X.frame,K.attempt);if(K&&X.kind==="primary")q(X)}if(w||l){let X=w??l;if(!X)return;let M=(w?w.request.headers:new Headers(X.headers)).get("authorization")?.replace(/^Bearer /,"");if(Z2&&M)H.set(X.sessionID,M);else H.delete(X.sessionID);if(l){let L=`${l.sessionID}:${l.kind}`;if(Z2&&M&&i.attempt)B.set(L,{bearer:M,attempt:i.attempt,url:l.url,headers:new Headers(Object.entries(l.headers).filter(([h])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(h.toLowerCase())))});else B.delete(L)}if(H.size>512){let L=H.keys().next().value;if(L)H.delete(L)}if(B.size>512){let L=B.keys().next().value;if(L)B.delete(L)}}else if(O==="experimental.ws.receive"){let X=J2,K=B.get(`${X.sessionID}:${X.kind}`);if(K){if(G.frameReceived(X.sessionID,X.frame),X.kind==="primary"){let M;if(Y?.receive(X.sessionID,X.frame,(L)=>{M=L}),M)try{let L=B$(M,K.url,K.headers,G);if(L)await Q?.({sessionID:X.sessionID,kind:"primary",request:L,attempt:K.attempt})}catch(L){J.warn("cachekeep WebSocket capture failed",{error:L instanceof Error?L.message:String(L)})}}X.frame=U0(X.frame,K.bearer)}}else if(O==="retry"){let X=J2,K=H.get(X.sessionID);if(K)Object.assign(X.error,{message:Y1(X.error.message,K)})}},B2)},event:{subscribe:(O)=>async function*(){for await(let I of $.event.subscribe(O)){if(I.type==="session.deleted")T(I.data.sessionID);yield I}}()}},{...Z,rewriteRequest:async(O)=>{let I=N.getStore();if(I)I.attempt=O.attempt;return Z.rewriteRequest?.(O)},rewriteHandshakeURL:(O)=>{let I=N.getStore();if(I)I.attempt=O.attempt;return Z.rewriteHandshakeURL?.(O)},onAttemptEnd:async(O,I)=>{await V.end(O,I),await Z.onAttemptEnd?.(O,I)},rewriteResponse:async(O)=>{await V.response(O.request,O.response.status);let I=await Z.rewriteResponse?.(O)??O.response;return W0(I,O.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(O)=>{let I=O.get("authorization");return I?.startsWith("Bearer ")?I.slice(7):void 0}},logger:{warn:(O,I)=>J.warn(O,{data:I})}}),d=D.dispose;return{...D,dispose:async()=>{H.clear(),B.clear(),await d(),await V.settle(),V.clear()}}}function l1($={}){return{id:V1,setup:(Z)=>w4(Z,$)}}async function w4($,Z={}){let g=[];try{let J=L2("opencode2");let G=L2("quota");let Q=Z.version??N0;await A0({version:Q,...Z.runtimeLayout});let Y=Z.paths??(()=>K0(H0()));let F=await m2(Y());let V=F?.logging?.level;if(V&&typeof V==="string")Y0(V);let N=Z.fetch??fetch;let B=Z.now??Date.now;let H=Z.poolMigration??q0;if(!H&&!S2(Y().configPath)){J.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let _=(j2)=>{throw new Y2({kind:"no-account",providerID:F2,sessionID:j2.sessionID,requestKind:j2.kind,message:e2})},b=await G0($,{providerID:F2,chooseAccount:_,accountHeaders:_},J);return()=>b.dispose()}let T=Z.vault?.firstRosterWaitMs??M0;let q=x0({host:"opencode",stateDir:Z.vault?.stateDir??B0(Y().statePath),reservedRouteIds:()=>w.peek().rows.map((_)=>_.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>N},Y());let C=q.vault;let D=async()=>await C.authority()==="local"?q2(Y()):m2(Y());let d=!1;let O=!1;const I=j1(g,{[Symbol.dispose](){if(!d)q.release()}},0);await C.authority();let B2=q.firstRoster;let J2=new I1;let w=new C0({paths:Y,rateLimitMarks:N$(Y()),refreshProvider:async(_)=>{let b=await j0({refreshToken:_.refresh,fetchImpl:N,now:B}),j2=X0({id_token:"",access_token:b.access,refresh_token:b.refresh});return{...b,...j2?{identity:j2}:{}}},pullQuota:mZ({fetchImpl:N,now:B,counts:J2,logger:G}),now:B,vaultIdentities:()=>C.identities(),vaultMode:()=>C.enrolled(),vaultAuthority:()=>C.authority(),vaultFirstRoster:B2,vaultFirstRosterBackgroundWaitMs:T,log:L2("pool")});if(await C.authority()==="local")await w.load();let l=Z.heartbeat===!1?void 0:await O0({version:Q,logger:L2("heartbeat")});let _2=Z.fence??(()=>F0({currentVersion:Q}));let Z2=Z.slot??S0();let i=async()=>T0(Y(),await Z2.get({path:{id:"openai"}}));let X=!1;let K=H?E0({paths:Y,slot:Z2,version:Q,fence:_2,runDeps:{vaultServes:()=>C.serves()},paused:async()=>await C.authority()!=="local",migrate:async(_)=>{let b=await L0(_);if(X=b.status==="refused",!O)await w.load();return b},adopt:async(_)=>{if(O)return{status:"retry",reason:"unsettled"};if(!await g1(B2,T))return{status:"retry",reason:"vault-roster-pending"};if(O)return{status:"retry",reason:"unsettled"};let b=await _0(_);if(!O)await w.load();return b}}):void 0;K?.start();q.start();let M=cZ(Y());let L=z0({paths:Y(),source:w,pins:M,vault:C},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const h=j1(g,{[Symbol.dispose](){if(!d)L.release()}},0);L.publish();let R=Z.codex??new D2(void 0,void 0,UZ());let S=e$(F);let v=Z1(Y());let A=JZ(Y(),{source:w,storage:D,vault:C,accounts:O1(Y()),settings:()=>S,parentOf:async(_)=>(await $.session.get({sessionID:_}))?.parentID??void 0,fetch:N,log:L2("cachekeep")},{now:B,codexResponsesUrl:B1().codexApiEndpoint,...Z.cacheKeep});const f=j1(g,{[Symbol.dispose](){if(!d)A.release()}},0);let n=p$({codex:R,onRoute:L.route,source:w,slotPlaceholderWithoutMain:i,storage:D,pins:M,sessionAccounts:O1(Y()),vault:C,awaitVaultRoster:async()=>{await g1(C.awaitRequestRoster(),P0)},responsesLite:()=>B1().responsesLite,codexEndpoint:()=>B1().codexApiEndpoint,now:B,log:J});let u=await G0($,n.adapter,J,R,(_)=>A.capture(_),v,(_)=>A.forget(_));n.attach(u);let o=async(_)=>{if(await v2(C),S2(Y().configPath))return;if(await K?.idle(),S2(Y().configPath))return;if(X&&!y1(_)&&(await _2()).open){await w.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let s=async(_)=>{await o(_);let b=await AZ(w.poolStore(),Y(),_,{vault:C});if(!S2(Y().configPath))await K?.requestAdoption();await w.load(),J.info("ChatGPT login stored in the account pool",b)};let e=await N1($,{integrationID:F2,methods:RZ({beginLogin:Z.beginLogin??m1,version:Q,vault:C}),onLogin:(_)=>s(_),label:"ChatGPT (openai-auth account pool)",vault:OZ(C)});let p=await wZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let x=$.command&&$.location?await LZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??SZ({...gZ({source:w,storage:D,counts:J2,now:B,authority:()=>C.authority()}),fetchImpl:N,now:B,randomUUID:k4,accountStoragePath:Y().configPath,accountStatePath:Y().statePath,packageVersion:Q,layoutNotice:R0,loadAccounts:q2,store:()=>w.poolStore(),migration:async()=>{if(S2(Y().configPath))return{migrated:!0};let _=await _2();return{migrated:!1,blockers:_.open?[]:_.blockers}},beginAccountLogin:Z.beginLogin??m1,refreshAllQuota:async()=>(await w.pollRows(await q2(Y()))).map((_)=>({..._,account:_.id})),getStickyRouting:async(_)=>M.get(_),cacheKeepManager:A.manager,setCacheKeepEnabled:(_)=>A.configure({enabled:_}),setCacheKeepSubagents:(_)=>A.configure({subagents:_}),setCacheKeepSustain:(_)=>A.configure({sustain:_}),setCacheKeepWindow:(_)=>A.configure({window:_}),afterWrite:()=>w.load(),refreshSidebar:()=>L.publish(),clearStickyRouting:async(_)=>{let b=M.get(_)!==void 0;return M.forget(_),b},vault:C})):void 0;let G2=new AbortController;(async()=>{try{for await(let _ of $.event.subscribe({signal:G2.signal}))if(_.type==="session.deleted")n.forgetSession(_.data.sessionID),A.forget(_.data.sessionID),v.forget(_.data.sessionID)}catch(_){if(!G2.signal.aborted)J.warn("stopped listening for session deletion",{error:_ instanceof Error?_.message:String(_)})}})();d=!0;return async()=>{O=!0,G2.abort();let _=A.release();await x?.(),K?.dispose(),await w.dispose(),await L.release(),await Promise.allSettled([u.dispose(),e.dispose(),p.dispose()]);let b;try{await Promise.race([Promise.all([K?.idle(),w.settled(),R.store?.settled(),_]),new Promise((j2)=>{b=setTimeout(j2,D4),b.unref?.()})])}finally{clearTimeout(b),q.release(),await l?.release()}}}catch(m){var $2=m,X2=1}finally{Q0(g,$2,X2)}}var y4=l1(),j7={id:V1,setup:y4.setup,server:b0.server};export{j7 as default,l1 as createOpenAIAuthPlugin,V1 as OPENAI_AUTH_PLUGIN_ID};
|