@cortexkit/opencode-openai-auth 1.9.5 → 1.9.6

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/v2/server.js CHANGED
@@ -1,3 +1,3 @@
1
- import{c as g0}from"../index-4gnwkw3a.js";import{A as w0,B as Z1,C as o$,D as s$,E as Q0,F as Y0,G as v0,H as OZ,I as AZ,L as hZ,M as gZ,N as mZ,V as dZ,W as iZ,_ as h0,d as C0,e as uZ,ea as U$,f as F1,fa as H$,g as I2,h as Q1,i as W1,ia as m0,k as V$,l as W$,m as j$,n as r2,o as EZ,p as l1,q as CZ,r as IZ,s as fZ,t as Y1,u as QZ,v as YZ,w as b0,x as D0,y as n1,z as k0}from"../index-8rj2xddq.js";import{Ab as q0,Bb as S0,Cb as DZ,Kb as D2,Lb as UZ,Ma as SZ,Mb as HZ,Nb as h1,Ob as NZ,Pb as FZ,Rb as y0,Sb as I0,Ta as G1,Tb as f0,bb as U1,cb as P0,db as M0,eb as E0,fb as h2,hb as i$,ib as $1,jb as a$,kb as n$,mb as A0,nb as WZ,pa as _0,pb as R0,qb as bZ,ta as I$,ua as f$,zb as x0}from"../index-h3vtzckv.js";import{bc as $0,qc as Z0,rc as J0,tc as z0,xc as G0}from"../index-7qxa018z.js";import{Ae as l$,Ce as u$,De as p$,Ee as y1,Fe as c$,Gd as xZ,Ge as d$,Md as qZ,Nc as q$,Od as L0,Pd as pZ,Qd as k$,Zd as y2,_d as d2,de as w$,fe as GZ,ge as y$,md as J1,me as V1,nd as z1,od as T0,te as cZ,ue as m2,vd as a1,ve as v$,wd as S$,we as h$,xd as b$,xe as g$,yd as D$,ze as m$}from"../index-1nrre3d8.js";import"../index-41yn5c02.js";import{We as PZ,Xe as O0}from"../index-f1cqptqa.js";import"../index-npj40h62.js";import{gf as K0,if as M2}from"../index-s2vrkdj4.js";import"../index-mcy24ej8.js";import{Gf as MZ}from"../index-y4j7y8b8.js";import{Kf as N1,Lf as F0}from"../index-cf0mrvqj.js";import{AsyncLocalStorage as l4}from"node:async_hooks";import{randomUUID as u4}from"node:crypto";class V2 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 P2($){return`common-auth-placeholder.${$}`}function G$($){let Z=P2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function f2($,Z){if($?.type!=="oauth")return!1;let z=Z===void 0?void 0:P2(Z),G=(Y)=>z===void 0?Y.startsWith("common-auth-placeholder."):Y===z;return G($.access)&&G($.refresh)}var Q$="No browser sign-in: this connects the plugin to the accounts in its vault.";async function M1($,Z){let z=Z.now??Date.now,{integrationID:G}=Z,Y=(U)=>G$({integrationID:G,methodID:U,now:z()}),Q=async(U,H)=>{return await Z.onLogin(U,{integrationID:G,methodID:H}),Y(H)},K=(U)=>async(H)=>{let N=U.method.id,V=await U.authorize(H),P={url:V.url,instructions:V.instructions,...V.expiresAt===void 0?{}:{expiresAt:V.expiresAt}};if(V.mode==="auto")return{...P,mode:"auto",callback:V.callback.then((E)=>Q(E,N))};let C=V.callback;return{...P,mode:"code",callback:async(E)=>Q(await C(E),N)}};return $.integration.transform((U)=>{let H=Z.label===void 0?{}:{label:()=>Z.label};for(let P of Z.methods)U.method.update({integrationID:G,method:P.method,authorize:K(P),refresh:async(C)=>{if(!f2(C,G))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return Y(C.methodID)},...H});let N=Z.vault;if(N===void 0)return;let V=N.method.id;U.method.update({integrationID:G,method:N.method,authorize:async()=>({url:"",instructions:N.instructions??Q$,mode:"auto",callback:Promise.resolve().then(()=>N.activate({integrationID:G,methodID:V})).then(()=>Y(V))}),refresh:async(P)=>{if(!f2(P,G)||P.methodID!==V)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return Y(V)},...H})})}function c0($){let Z=[],z;for(let G of $.split(/\r?\n/))if(G.startsWith("data:"))Z.push(G.slice(5).replace(/^ /,""));else if(G.startsWith("event:"))z=G.slice(6).trim();if(Z.length===0)return;return z===void 0?{data:Z.join(`
1
+ import{c as l0}from"../index-tcaef7wq.js";import{A as I0,B as X1,C as r$,D as t$,E as X0,F as j0,G as g0,H as RZ,I as xZ,L as mZ,M as lZ,N as uZ,V as aZ,W as nZ,_ as m0,d as A0,e as cZ,ea as L$,f as M1,fa as P$,g as v2,h as W1,i as T1,ia as u0,k as T$,l as _$,m as F$,n as z1,o as OZ,p as s1,q as AZ,r as vZ,s as hZ,t as U1,u as XZ,v as jZ,w as k0,x as w0,y as z$,z as y0}from"../index-5xs8nfcx.js";import{Ab as b0,Bb as D0,Cb as wZ,Kb as k2,Lb as NZ,Ma as DZ,Mb as FZ,Nb as a1,Ob as KZ,Pb as TZ,Rb as f0,Sb as v0,Ta as V1,Tb as h0,bb as _1,cb as E0,db as C0,eb as O0,fb as p2,hb as n$,ib as Y1,jb as o$,kb as s$,mb as x0,nb as HZ,pa as M0,pb as S0,qb as kZ,ta as l$,ua as u$,zb as q0}from"../index-qn927h9w.js";import{bc as J0,qc as z0,rc as G0,tc as Q0,xc as Y0}from"../index-se7mn1wg.js";import{Ae as d$,Ce as i$,De as l1,Ee as u1,Fe as a$,Gd as qZ,Ge as p1,Md as bZ,Nc as y$,Od as P0,Pd as dZ,Qd as h$,Zd as f2,_d as s2,de as g$,fe as YZ,ge as m$,md as j1,me as K1,nd as B1,od as L0,te as iZ,ue as d2,vd as J$,ve as p$,wd as I$,we as g1,xd as f$,xe as c$,yd as v$,ze as m1}from"../index-jqqeynjm.js";import"../index-t52k32ab.js";import{We as EZ,Xe as R0}from"../index-3mmdgz6r.js";import"../index-7bv7pgy8.js";import{gf as _0,if as R2}from"../index-x8qjasc7.js";import"../index-1kbr03m0.js";import{Gf as CZ}from"../index-y4j7y8b8.js";import{Kf as P1,Lf as T0}from"../index-cf0mrvqj.js";import{AsyncLocalStorage as p4}from"node:async_hooks";import{randomUUID as c4}from"node:crypto";class F2 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 A2($){return`common-auth-placeholder.${$}`}function U$($){let Z=A2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function m2($,Z){if($?.type!=="oauth")return!1;let z=Z===void 0?void 0:A2(Z),G=(X)=>z===void 0?X.startsWith("common-auth-placeholder."):X===z;return G($.access)&&G($.refresh)}var H$="No browser sign-in: this connects the plugin to the accounts in its vault.";async function R1($,Z){let z=Z.now??Date.now,{integrationID:G}=Z,X=(W)=>U$({integrationID:G,methodID:W,now:z()}),Y=async(W,H)=>{return await Z.onLogin(W,{integrationID:G,methodID:H}),X(H)},F=(W)=>async(H)=>{let N=W.method.id,V=await W.authorize(H),P={url:V.url,instructions:V.instructions,...V.expiresAt===void 0?{}:{expiresAt:V.expiresAt}};if(V.mode==="auto")return{...P,mode:"auto",callback:V.callback.then((E)=>Y(E,N))};let C=V.callback;return{...P,mode:"code",callback:async(E)=>Y(await C(E),N)}};return $.integration.transform((W)=>{let H=Z.label===void 0?{}:{label:()=>Z.label};for(let P of Z.methods)W.method.update({integrationID:G,method:P.method,authorize:F(P),refresh:async(C)=>{if(!m2(C,G))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return X(C.methodID)},...H});let N=Z.vault;if(N===void 0)return;let V=N.method.id;W.method.update({integrationID:G,method:N.method,authorize:async()=>({url:"",instructions:N.instructions??H$,mode:"auto",callback:Promise.resolve().then(()=>N.activate({integrationID:G,methodID:V})).then(()=>X(V))}),refresh:async(P)=>{if(!m2(P,G)||P.methodID!==V)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return X(V)},...H})})}function i0($){let Z=[],z;for(let G of $.split(/\r?\n/))if(G.startsWith("data:"))Z.push(G.slice(5).replace(/^ /,""));else if(G.startsWith("event:"))z=G.slice(6).trim();if(Z.length===0)return;return z===void 0?{data:Z.join(`
2
2
  `)}:{event:z,data:Z.join(`
3
- `)}}function E1($,Z){let z=new TextDecoder,G="",Y=(K)=>{let U=c0(K);if(!U)return;try{$(U)}catch(H){Z(H)}},Q=()=>{for(;;){let K=/\r?\n\r?\n/.exec(G);if(!K)return;let U=G.slice(0,K.index);G=G.slice(K.index+K[0].length),Y(U)}};return new TransformStream({transform(K,U){U.enqueue(K),G+=z.decode(K,{stream:!0}),Q()},flush(){if(G+=z.decode(),Q(),G.trim()!=="")Y(G);G=""}})}var Y$=512,C1=3621000,k2="x-common-auth-attempt",b2=($,Z)=>JSON.stringify([$,Z]),N2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function d0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function i0($,Z){let z=$.getReader();return new ReadableStream({async pull(G){let Y;try{Y=await z.read()}catch(Q){Z({reason:"failed",message:Q instanceof Error?Q.message:String(Q)}),G.error(Q);return}if(Y.done)Z(),G.close();else G.enqueue(Y.value)},async cancel(G){Z({reason:"cancelled",...G===void 0?{}:{message:String(G)}}),await z.cancel(G)}})}function o2($,Z){for(let[z,G]of Object.entries(Z)){let Y=z.toLowerCase();for(let Q of Object.keys($))if(Q.toLowerCase()===Y)delete $[Q];if(G!==null)$[z]=G}}function a0($,Z){for(let[z,G]of Object.entries(Z))if(G===null)$.delete(z);else $.set(z,G)}async function O1($,Z,z={}){let{providerID:G}=Z,Y=z.gateOnPlaceholder,Q=(J)=>Y===void 0||Y.credential(J)===P2(G),K=z.logger,U=Math.max(1,z.maxRecords??Y$),H=z.hostRetryLimit??10,N=[...z.hostCredentials??[P2(G)],...Y?[P2(G)]:[]].filter((J)=>J!==""),V=new Map,P=new WeakMap,C=new Map,E=0,w=new Set,n=new Map,O=new Map,D=(J)=>{let j=O.get(J);return j?.ownedSeen===!0&&j.foreignSeen},U2=(J,j)=>{n.set(J,j);let W=O.get(J)??{ownedSeen:!1,foreignSeen:!1};if(j)W.ownedSeen=!0;else W.foreignSeen=!0;O.set(J,W)},G2=(J,j)=>{let W=Y?.refuseMisplaced,M=W?[...j].filter(([,b])=>b.includes(P2(G))):[],B=Q(j)&&(!W||M.length>0);if(W){if(M.length>0&&(M.length!==1||!B))throw U2(J.sessionID,!1),new V2({kind:"placement-refused",providerID:G,sessionID:J.sessionID,requestKind:J.kind,message:W(M[0]?.[0]??"")})}return U2(J.sessionID,B),B},I=!1,i=!1,H2=new Map,X2=0,$2=!1,X=new Map,F=(J,j)=>{try{K?.warn(J,j)}catch{}},T=(J)=>J instanceof Error?J.message:String(J),L=(J)=>J.excluded.clear(),g=(J)=>J.excluded.size===0?{}:{excluded:[...J.excluded]},x=(J,j,W)=>{if(!z.enforceRequestExclusion||J===void 0||!W.excluded.has(J))return!1;return F("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:j.sessionID,kind:j.kind,phase:j.phase,accountId:J}),!0},k=new Map,f=(J,j)=>{let W=(k.get(J)??Promise.resolve()).then(j),M=W.then(()=>{},()=>{});return k.set(J,M),M.then(()=>{if(k.get(J)===M)k.delete(J)}),W},S=(J,j)=>{let W=k.get(J);return W?W.then(()=>S(J,j)):j()},y=async(J)=>{try{await Z.dropChoice?.({...J.input,accountId:J.accountId})}catch(j){F("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:J.input.sessionID,error:T(j)})}},u=async(J)=>{try{await Z.dropSameAccountRetry?.({...J.input,accountId:J.accountId})}catch(j){F("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:J.input.sessionID,error:T(j)})}},a=async(J)=>{if(J.next)await y(J.next);if(J.sameAccount)await u(J.sameAccount)},J2=(J)=>{let j=C.get(J);if(C.delete(J),j)f(j.sessionID,()=>a(j))},r=async(J,j)=>{let W=H2.get(J);if(!W||W.size===0)return;await Promise.all([...W].map(async(M)=>{try{await M(j)}catch(B){F("opencode2 auth listener threw; the request is unaffected",{event:J,error:T(B)})}}))},Q2=async(J,j)=>{try{await Z.onAttemptEnd?.(J,j)}catch(W){F("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:J.attemptId,error:T(W)})}},p=(J,j)=>{if(J.ended||!J.attempt)return;let W={...J.status===void 0?{}:{status:J.status},outputStarted:J.outputStarted,...J.limit?{limit:J.limit.signal}:{},...j?{error:j}:{}};if(j)J.endError=j;if(j?.reason==="cancelled"||!j&&!J.limit&&(J.status===void 0||J.status<400))L(J.request);J.ended=Q2(J.attempt,W)},A=(J,j)=>p(J,{reason:"abandoned",message:j}),z2=(J)=>[...V.values()].filter((j)=>j.key===J),c=(J)=>z2(J).at(-1),m=(J)=>{if(V.delete(J.id),C.get(J.key)?.attemptId===J.id||!z2(J.key).length)J2(J.key)},j2=(J)=>{V.set(J.id,J);while(V.size>U){let j=V.values().next().value;if(j===void 0)break;A(j,"dropped to keep the record bound"),m(j)}},Y2=(J)=>J.accountId===void 0?void 0:{...J.scope,accountId:J.accountId},_=(J,j)=>new V2({kind:"no-account",providerID:G,sessionID:J.sessionID,requestKind:J.kind,...j===void 0?{}:{message:j}}),v=(J)=>{X.get(J)?.clear(),X.delete(J)},B2=async(J,j)=>{let W=()=>_(J,`${G} ${J.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if($2)throw W();let M=X.get(J.sessionID);if(!M)M=new Set,X.set(J.sessionID,M);let B={};M.add(B);let b=()=>{if(!M.has(B))throw W()};try{return await j(b)}finally{if(M.delete(B),M.size===0&&X.get(J.sessionID)===M)X.delete(J.sessionID)}},i2=(J,j)=>{for(let[W,M]of j)if(N.some((B)=>M.includes(B)))throw new V2({kind:"host-credential-on-wire",providerID:G,sessionID:J.sessionID,requestKind:J.kind,message:`${G} ${J.kind} request still carries the host's placeholder credential in ${W}; the adapter's account headers must replace it`})},l0=(J)=>{for(let j of z2(J))if(j.ended||!j.attempt)m(j);else if(j.transport==="ws"||j.judged)A(j,"a newer attempt of its session and kind began"),m(j)},a2=async(J,j,W,M)=>{let B=b2(J.sessionID,J.kind),{input:b,accountId:R,sameAccountRetry:q,request:o}=await S(J.sessionID,async()=>{W();let d=C.get(B);C.delete(B);let s=z2(B);if(d&&s.some((_2)=>_2.id!==d.attemptId&&_2.attempt&&!_2.ended))F("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:J.sessionID,kind:J.kind});if(!d){let _2=new Set(s.filter((W2)=>W2.attempt&&!W2.ended).map((W2)=>W2.request));for(let W2 of s)if(!_2.has(W2.request))L(W2.request)}let t=d?.request??{excluded:new Set},C2=d?.accountId??c(B)?.accountId;l0(B);let h=d?.next,e=d?.sameAccount,T2=e!==void 0&&e.input.modelID===J.modelID&&e.input.agent===J.agent,l=h!==void 0&&h.input.modelID===J.modelID&&h.input.agent===J.agent,O2=d?.wake,x2={...J,phase:"request",...g(t),...C2===void 0?{}:{previousAccountId:C2},...d?.rerouteFrom?{rerouteFrom:d.rerouteFrom}:{},...O2===void 0?{}:{wake:O2,hostAttempt:h?.input.hostAttempt}};if(h&&(!l||O2!==void 0))await f(J.sessionID,()=>y(h)),W();if(e&&!T2)await f(J.sessionID,()=>u(e)),W();let Z2=T2?e.accountId:l&&O2===void 0?h.accountId:await Z.chooseAccount(x2),L2=typeof Z2==="string"?Z2:void 0;if(x(L2,x2,t)){let _2=L2;if(T2&&e)await f(J.sessionID,()=>u(e));else if(_2!==void 0)await f(J.sessionID,()=>y(l&&h?h:{accountId:_2,input:x2}));L2=void 0,W()}return{input:x2,accountId:L2,sameAccountRetry:T2,request:t}});W();let E2={},R2;if(R!==void 0){let d=await Z.accountHeaders({...J,accountId:R});if(W(),d0(d))E2=d.headers,R2=d.attempt;else E2=d}let n2=`attempt-${++X2}`,S2={id:n2,key:B,scope:J,request:o,accountId:R,headers:E2,attempt:R===void 0?void 0:{...J,accountId:R,attemptId:n2,transport:M,data:R2},...M===void 0?{}:{transport:M},outputStarted:!1,sameAccountRetry:q};if(j2(S2),S2.attempt)r("select",{...J,accountId:S2.attempt.accountId,hook:j,...b.previousAccountId===void 0?{}:{previousAccountId:b.previousAccountId},...b.rerouteFrom===void 0?{}:{rerouteFrom:b.rerouteFrom},handle:S2.attempt});return S2},s1=async(J,j,W,M,B)=>{let b=b2(J.sessionID,J.kind),R=M===void 0?void 0:V.get(M);if(R?.key!==b)R=void 0;if(!R){if(R=c(b),z2(b).filter((o)=>o.transport===void 0&&!o.ended).length>1&&!i)i=!0,F("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:J.sessionID,kind:J.kind})}if(!R||R.transport!==void 0||R.ended)R=await a2(J,j,B,W);else if(R.transport=W,R.attempt)R.attempt.transport=W;if(W==="ws"){for(let q of z2(b))if(q!==R&&q.transport==="ws")A(q,"a newer attempt of its session and kind went out over WebSocket")}return R},T1=async(J,j)=>{try{return await j()}catch(W){throw p(J,{reason:"failed",message:T(W)}),W}},r1=(J,j)=>{let W=z2(b2(J,j)).filter((M)=>M.transport==="ws").at(-1);return W?.attempt!==void 0&&!W.ended?W:void 0},L1=(J,j,W)=>{let M=Y2(J);if(!M||!J.attempt||J.limit)return;J.limit={signal:j,delivered:r("limit",{...M,via:W,limit:j,outputStarted:J.outputStarted,handle:J.attempt})}},t1=(J,j,W,M)=>{let B=Y2(J);if(!B||!J.attempt)return;r("quota",{...B,transport:j,...M===void 0?{}:{status:M},quota:W,handle:J.attempt})},e1=(J,j,W,M)=>{let B=J.attempt;if(!B)return;let b=Z.inspectEvent?.(M===void 0?{transport:j,data:W,attempt:B}:{transport:j,data:W,event:M,attempt:B});if(!b)return;if(b.quota!==void 0)t1(J,j,b.quota);if(b.outputStarted)J.outputStarted=!0;if(b.hostRetry==="veto")J.hostRetry="veto";if(b.limit)L1(J,b.limit,j);if(b.error!==void 0)p(J,{reason:"failed",message:b.error});else if(b.done)p(J)},u0=(J,j)=>{let W=J.attempt;if(!W||j.accountId===J.accountId)return;if(W.reboundFrom??=W.accountId,W.accountId=j.accountId,"data"in j)W.data=j.data;J.accountId=j.accountId},p0=(J)=>!J.attempt||J.endError!==void 0||J.status!==void 0&&J.status>=400,$$=(J)=>{let j=[...V.values()].filter((q)=>q.scope.sessionID===J),W=j.filter((q)=>q.limit&&!q.rerouted).at(-1);if(W)return W;let M=j.filter((q)=>q.scope.kind==="primary"),B=M.length>0?M:j;if(B.length<=1)return B[0];let b=B.filter((q)=>!q.judged&&p0(q)).at(-1);if(b)return b;let R=B.filter((q)=>q.attempt&&!q.ended);if(R.length>1)return"ambiguous";return R[0]??B.at(-1)},q2={providerID:G},A2=[];A2.push(await $.session.hook("model.request",(J)=>{if(Y)return;return B2(N2(J),async(j)=>{let W=await a2(N2(J),"model.request",j);if(j(),W.accountId===void 0)throw _(W.scope);o2(J.headers,{...W.headers,[k2]:W.id})})},q2)),A2.push(await $.session.hook("http.request",(J)=>{if(Y){if(!G2(N2(J),J.request.headers))return}return B2(N2(J),async(j)=>{let W=J.request.headers.get(k2)??void 0,M=Y?await a2(N2(J),"http.request",j,"http"):await s1(N2(J),"http.request","http",W,j);j();let B=Y2(M),b=M.attempt;if(!B||!b)throw _(M.scope);await T1(M,async()=>{let R=J.request;if(Z.rewriteRequest){if(W!==void 0){let E2=new Headers(R.headers);E2.delete(k2),R=new Request(R,{headers:E2})}R=await Z.rewriteRequest({...B,request:R,attempt:b})??R,j()}let q=new Headers(R.headers);q.delete(k2),a0(q,M.headers),i2(M.scope,q.entries());let o=new Request(R,{headers:q});P.set(o,M),J.request=o})})},q2)),A2.push(await $.session.hook("http.response",async(J)=>{let j=P.get(J.request);if(!j){if(Y)return;if(!I)I=!0,F("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:J.sessionID,kind:J.kind});return}let W=J.response;if(Z.answeredBy&&j.attempt){let q=j.attempt,o=await T1(j,async()=>Z.answeredBy?.({request:J.request,response:W,attempt:q}));if(o)u0(j,o)}let M=Y2(j),B=j.attempt;if(!M||!B)return;j.status=W.status;let b=Z.quotaFromHeaders?.(W.headers,W.status,B);if(b!==void 0)t1(j,"http",b,W.status);if(!W.ok&&Z.limitFromResponse){let q=await Z.limitFromResponse({status:W.status,headers:W.headers,body:()=>W.clone().text(),attempt:B});if(q)L1(j,q,"http")}if(!W.ok||!W.body)p(j);let R=W;if(W.body&&(Z.inspectEvent||Z.onAttemptEnd)){let q=W.body;if(Z.inspectEvent)q=q.pipeThrough(E1((o)=>e1(j,"http",o.data,o.event),(o)=>F("opencode2 auth event inspection threw",{error:T(o)})));R=new Response(i0(q,(o)=>p(j,o)),{status:W.status,statusText:W.statusText,headers:W.headers})}if(Z.rewriteResponse)R=await Z.rewriteResponse({...M,request:J.request,response:R,attempt:B})??R;if(Z.responseRetry){if(await Z.responseRetry({...M,request:J.request,response:R,attempt:B})==="veto")j.hostRetry="veto"}if(R!==W)J.response=R},q2)),A2.push(await $.session.hook("experimental.ws.handshake",(J)=>{if(Y){let j=b2(J.sessionID,J.kind);if(w.delete(j),!G2(N2(J),new Headers(J.headers)))return}return B2(N2(J),async(j)=>{let W;for(let R of Object.keys(J.headers)){if(R.toLowerCase()!==k2)continue;W??=J.headers[R],delete J.headers[R]}let M=Y?await a2(N2(J),"experimental.ws.handshake",j,"ws"):await s1(N2(J),"experimental.ws.handshake","ws",W,j);j();let B=Y2(M),b=M.attempt;if(!B||!b)throw _(M.scope);await T1(M,async()=>{if(!Y?.refuseMisplaced)o2(J.headers,M.headers);let R=Z.rewriteHandshakeURL?.({...B,url:J.url,attempt:b});if(R!==void 0)J.url=R;if(Y?.refuseMisplaced)o2(J.headers,M.headers);if(i2(M.scope,Object.entries(J.headers)),Y)w.add(M.key)})})},q2));let Z$=Z.rewriteWebSocketFrame?.bind(Z);if(Z$)A2.push(await $.session.hook("experimental.ws.send",async(J)=>{let j=N2(J);if(Y&&!w.has(b2(j.sessionID,j.kind)))return;let W=r1(j.sessionID,j.kind),M=await Z$({...j,attempt:W?.attempt,frame:J.frame});if(M!==void 0)J.frame=M},q2));A2.push(await $.session.hook("experimental.ws.receive",(J)=>{if(Y&&!w.has(b2(J.sessionID,J.kind)))return;let j=r1(J.sessionID,J.kind);if(!j)return;try{e1(j,"ws",J.frame)}catch(W){F("opencode2 auth frame inspection threw",{error:T(W)})}},q2)),A2.push(await $.session.hook("retry",async(J)=>{if(Y&&n.get(J.sessionID)!==!0)return;let j=J.decision,W=()=>r("retry",{sessionID:J.sessionID,attempt:J.attempt,reason:"host-decides",hostDecision:j,decision:j});if(D(J.sessionID)&&!Z.retrySameAccount){await W();return}let M=$$(J.sessionID);if(!M)return;if(M==="ambiguous"){await r("retry",{sessionID:J.sessionID,attempt:J.attempt,reason:"host-decides",hostDecision:j,decision:j});return}let B=M,b=()=>B.hostRetry==="veto";await B2(B.scope,async(R)=>{let q=R,o=Z.retrySameAccount?.bind(Z),E2=B.attempt;if(o&&E2&&!B.outputStarted&&(!b()||D(J.sessionID))&&!B.sameAccountRetry){if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;let d=await f(B.scope.sessionID,async()=>{q();let s=E2.accountId,t=()=>V.has(B.id)&&B.accountId===s&&$$(J.sessionID)===B&&!B.outputStarted&&(!b()||D(J.sessionID))&&(!Y||n.get(J.sessionID)===!0);if(!t()||B.sameAccountRetry)return!1;B.sameAccountRetry=!0;let C2={...B.scope,accountId:s,error:J.error,attempt:J.attempt,...B.limit?{limit:B.limit.signal}:{}},h;try{h=await o(C2)}catch(l){F("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:J.sessionID,error:T(l)})}if(!h)return q(),!1;let e={accountId:h.accountId,input:C2};try{q()}catch(l){throw await u(e),l}if(!t()||h.accountId!==s)return await u(e),!1;let T2=C.get(B.key);if(C.delete(B.key),T2)await a(T2);try{q()}catch(l){throw await u(e),l}if(!t())return await u(e),!1;return C.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++E,accountId:s,sameAccount:e}),B.judged=!0,J.decision={retry:!0,delay:0},!0});if(q(),d){await r("retry",{sessionID:J.sessionID,accountId:B.accountId,kind:B.scope.kind,attempt:J.attempt,reason:"same-account",hostDecision:j,decision:J.decision,handle:B.attempt});return}}if(D(J.sessionID)){await W();return}B.judged=!0;let R2=B.attempt;if(R2&&!B.outputStarted){if(!B.limit){let d=Z.limitFromError?.(J.error,R2);if(d)L1(B,d,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered}q();let{decision:n2,reason:S2}=await f(B.scope.sessionID,async()=>{if(q(),D(J.sessionID))return{decision:j,reason:"host-decides"};let d=C.get(B.key);if(C.delete(B.key),d)await a(d);if(q(),D(J.sessionID))return{decision:j,reason:"host-decides"};let s=j,t,C2,h,e;if(B.accountId===void 0||!R2)s={retry:!1},t="no-account";else if(B.outputStarted)s={retry:!1},t="output-started";else if(b())s={retry:!1},t="adapter-veto";else if(B.limit){let T2={accountId:B.accountId,limit:B.limit.signal},l,O2={...B.scope,phase:"retry",...g(B.request),hostAttempt:J.attempt,previousAccountId:B.accountId,rerouteFrom:T2};try{l=await Z.chooseAccount(O2)}catch(P1){F("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:B.scope.sessionID,error:T(P1)})}let x2=typeof l==="string"?l:typeof l==="object"&&("hold"in l)?B.accountId:void 0;if(x(x2,O2,B.request)){if(x2!==void 0)await y({accountId:x2,input:O2});l=void 0}let Z2=typeof l==="object"&&"hold"in l?l.hold:void 0,L2=typeof l==="object"&&"waitThenReselect"in l?l.waitThenReselect:void 0,_2=typeof l==="object"&&"hostRetry"in l?l.hostRetry:void 0,W2=typeof l==="string"?l:Z2?B.accountId:void 0;if(W2!==void 0)h={accountId:W2,input:O2};try{q()}catch(P1){if(h)await y(h);throw P1}if(D(J.sessionID)){if(h)await y(h);return{decision:j,reason:"host-decides"}}if(b()||_2==="veto"){if(h)await y(h);if(h=void 0,q(),D(J.sessionID))return{decision:j,reason:"host-decides"};B.hostRetry="veto",s={retry:!1},t="adapter-veto"}else if(!(H-J.attempt>=1)){if(h)await y(h);h=void 0,t="host-decides-last-account"}else if(L2&&Number.isFinite(L2.delayMs)&&L2.delayMs>=0&&L2.delayMs<=C1)s={retry:!0,delay:Math.ceil(L2.delayMs)},t="wait-then-reselect";else if(Z2&&Number.isFinite(Z2.delayMs)&&Z2.delayMs>=0&&Z2.delayMs<=C1){if(s={retry:!0,delay:Math.ceil(Z2.delayMs)},Z2.target!==void 0)e={target:Z2.target,...Z2.checkpoint===void 0?{}:{checkpoint:Z2.checkpoint},...Z2.kind===void 0?{}:{kind:Z2.kind}};t="hold"}else if(!Z2&&W2!==void 0&&W2!==B.accountId)B.rerouted=!0,B.request.excluded.add(B.accountId),C2=T2,s={retry:!0,delay:0},t="reroute";else{if(Z2&&h)await y(h),h=void 0;t="host-decides-last-account"}}else t="host-decides";if(J.decision=s,s.retry&&B.accountId!==void 0&&V.has(B.id))C.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++E,accountId:B.accountId,...C2===void 0?{}:{rerouteFrom:C2},...h===void 0?{}:{next:h},...e===void 0?{}:{wake:e}});else if(h)await y(h);if(!s.retry)L(B.request);return{decision:s,reason:t}});q(),await r("retry",{sessionID:J.sessionID,...B.accountId===void 0?{}:{accountId:B.accountId},kind:B.scope.kind,attempt:J.attempt,reason:S2,hostDecision:j,decision:n2,...R2===void 0?{}:{handle:R2}})})},q2));let J$=(J)=>{if(v(J),n.delete(J),!O.get(J)?.foreignSeen)O.delete(J);for(let j of w)if(JSON.parse(j)[0]===J)w.delete(j);for(let j of[...V.values()]){if(j.scope.sessionID!==J)continue;A(j,"its session was forgotten"),L(j.request),V.delete(j.id)}for(let[j,W]of C)if(W.sessionID===J)J2(j)},_1=new AbortController,z$=$.event;if(z$)(async()=>{try{for await(let J of z$.subscribe({signal:_1.signal}))if(J.type==="session.deleted")J$(J.data.sessionID);else if(J.type==="session.status"&&J.data.status.type==="idle"){let j=J.data.sessionID,W=++E;f(j,async()=>{for(let[M,B]of C)if(B.sessionID===j&&B.order<W)C.delete(M),L(B.request),await a(B)})}}catch(J){if(!_1.signal.aborted)F("opencode2 auth stopped listening for session deletion",{error:T(J)})}})();return{on(J,j){let W=H2.get(J);if(!W)W=new Set,H2.set(J,W);let M=j;return W.add(M),()=>{W.delete(M)}},accountFor(J,j){return c(b2(J,j))?.accountId},forgetSession:J$,get size(){return V.size},async dispose(){if($2)return;$2=!0;for(let J of X.keys())v(J);_1.abort();for(let J of V.values())A(J,"the installation was disposed");V.clear();for(let J of C.keys())J2(J);w.clear(),n.clear(),O.clear(),H2.clear(),await Promise.all(k.values()),await Promise.all(A2.map(async(J)=>{try{await J.dispose()}catch(j){F("opencode2 auth hook did not dispose cleanly",{error:T(j)})}}))}}}import{createHash as n0}from"node:crypto";var o0=1024,s0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),X$=($)=>j$($,"user"),r0=($)=>s0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function t0($){return n0("sha256").update(JSON.stringify($)).digest("hex")}class w2{runtime;maxSessions;#$=new Map;constructor($,Z=o0){this.runtime=$;this.maxSessions=Z}advance($,Z,z=this.runtime){let G=this.#$.get($),Y=Array.isArray(Z.input)?Z.input:[],Q=Y.filter(X$),K=Y.findLastIndex(X$),U=K<0?void 0:t0(Y[K]),H=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,N,V,P;if(H)N=Q.length>0,V=U??G?.fingerprint,P=G?.userCount===void 0?void 0:G.userCount+Q.length;else{V=U,P=Q.length;let E=K>=0&&K>Y.findLastIndex(r0),w=G!==void 0&&!G.completed&&G.fingerprint===V&&G.userCount===P;N=E&&!w}let C=N||!G?{turnID:(z?.uuid??D2)(),turnStartedAt:(z?.now??Date.now)()}:{turnID:G.turnID,turnStartedAt:G.turnStartedAt};return this.#Z($,{...C,completed:!1,fingerprint:V,userCount:P}),C}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 z=this.#$.keys().next().value;if(z===void 0)break;this.#$.delete(z)}}}function A1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var B$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function e0(){let $=globalThis;return $[B$]??=crypto.randomUUID(),$[B$]}class v2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,z){this.runtime=$;this.store=z;this.installationID=Z??e0(),this.sessions=z?.sessions??new Map,this.frameTurns=z?.frameTurns??new w2}get($){let Z=this.runtime?.uuid??D2;if(this.store)return this.store.get($,Z);let z=this.sessions.get($);if(!z){let G=Z();z={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,z)}return z}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(s2(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var R1={version:V$,"user-agent":W$,originator:"codex_exec"};var $4=1024,Z4=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,t2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),N$=($)=>t2($)&&($.type==="message"||("role"in $))&&$.role==="user",F$=($)=>t2($)&&$.type==="configuration_update";class x1{http;#$=new Map;constructor($=new v2){this.http=$}apply($,Z,z){if(Z.kind!=="primary")return!1;let G=typeof $.model==="string"?$.model:"";if(!U$.has(G))return!1;if(Z4.test(G))return!1;let Y=t2($.reasoning)?$.reasoning:void 0,Q=typeof Y?.effort==="string"?Y.effort:void 0;if(!Q)return!1;let K=this.#$.get(Z.sessionID);if(K===void 0)return this.#Z(Z.sessionID,Q),!1;if(Q===K)return!1;let U=Array.isArray($.input)?$.input:void 0;if(!U||U.length===0)return!1;let H=U.findLastIndex(N$);if(H<0){if(z==="http")return!1;return $.reasoning={...Y,effort:K},!0}if($.reasoning={...Y,effort:K},!F$(U[H-1]))U.splice(H,0,{type:"configuration_update",reasoning:{effort:Q}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>$4){let z=this.#$.keys().next().value;if(z===void 0)break;this.#$.delete(z)}}}function s2($){try{let Z=JSON.parse($);return t2(Z)?Z:void 0}catch{return}}async function K$($,Z,z,G,Y=z.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Q=await $.clone().text(),K=s2(Q);if(K)delete K.max_output_tokens;let U=new Headers($.headers),H=r2({rewriteLite:H$,init:{body:K?JSON.stringify(K):$.body===null?void 0:Q},headers:U,metadata:Y.get(Z.sessionID),installationID:Y.installationID,runtime:Y.runtime,websocket:!1,responsesLite:G,applyEffort:(N)=>{z.apply(N,Z,"http")}});return new Request($,{headers:U,body:H.init?.body})}function T$($,Z,z,G){let Y=G.sessions.get($.sessionID),Q=G.frameTurns.get($.sessionID);if(!Y||!Q)return;let K=A1(Y,Q),U=new Headers({"content-type":"application/json"});for(let N of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let V=z.get(N);if(V!==null)U.set(N,V)}r2({init:{body:$.bodyText},headers:U,metadata:K,installationID:G.installationID,runtime:G.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let H=new URL(Z);if(H.protocol==="wss:")H.protocol="https:";if(H.protocol==="ws:")H.protocol="http:";return new Request(H,{method:"POST",headers:U,body:$.bodyText})}function J4($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let z=Z.findIndex((G,Y)=>JSON.stringify(G)!==JSON.stringify($[Y]));return z>=0&&F$(Z[z])&&N$(Z[z+1])&&JSON.stringify(Z.slice(z+1))===JSON.stringify($.slice(z))}function L$($,Z,z){let G=s2($);if(G?.type!=="response.create")return;let Y=z.http.advanceFrame(Z.sessionID,G),Q=z.http.get(Z.sessionID);delete G.max_output_tokens;let K=r2({rewriteLite:()=>{},init:{body:JSON.stringify(G)},headers:new Headers,metadata:A1(Q,Y),installationID:z.http.installationID,runtime:z.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(H)=>{z.apply(H,Z,"ws")}}),U=s2(String(K.init?.body));if(!U)return;if(!J4(G.input,U.input)){if("input"in G)U.input=G.input;else delete U.input;return JSON.stringify(U)}return String(K.init?.body)}function z4($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function q1($,Z){let z=new URL($);if(z.origin!=="https://api.openai.com"&&z.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(z.pathname))return $;let G=new URL(`${z4(Z)}/responses`);if(G.search=z.search,z.protocol==="ws:"||z.protocol==="wss:")G.protocol=G.protocol==="https:"?"wss:":"ws:";return G.href}import{resolve as S1}from"node:path";var _$=Symbol.for("@cortexkit/openai-auth/opencode2-rate-limits/v1"),P$=globalThis,b1=P$[_$]??new Map;P$[_$]=b1;function M$($){let Z=b1.get($);if(!Z)Z=new Map,b1.set($,Z);return Z}function E$($){return M$(JSON.stringify(["pool",S1($.configPath),S1($.statePath)]))}function C$($){return M$(JSON.stringify(["vault",S1($)]))}import{resolve as O$}from"node:path";var G4=1024;class e2{accounts=new Map;limit;constructor($=G4){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let z=this.accounts.keys().next().value;if(z===void 0)break;this.accounts.delete(z)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var A$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),R$=globalThis,D1=R$[A$]??new Map;R$[A$]=D1;function k1($){let Z=JSON.stringify([O$($.configPath),O$($.statePath)]),z=D1.get(Z);if(!z)z=new e2,D1.set(Z,z);return z}var F2="openai",Q4=60000,w1=1,Y4="request refused: no account with a usable credential",K2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function X4($){let Z=K2($)?$.counters:void 0,z=K2(Z)?Z.resetCredits:void 0,G=K2(z)?z.value:void 0;return typeof G==="number"&&Number.isFinite(G)?G:void 0}function g2($){try{return JSON.parse($)}catch{return}}function x$($){let Z=J1($);return Z?z1(Z):void 0}var j4=new Set(["usage_limit_reached","rate_limit_exceeded"]);function I1($,Z,z){return{reason:$.window,...z!==void 0?{status:z}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function B4($,Z){let z=Z1($);if(z){let Q=typeof $.status==="number"?$.status:void 0;return I1(z,Z,Q)}if($.type!=="response.failed"||!K2($.response))return;let G=$.response.failed;if(K2(G)&&typeof G.rate_limit_reached_type==="string")return{reason:G.rate_limit_reached_type};let Y=$.response.error;if(K2(Y)){let Q=typeof Y.code==="string"?Y.code:typeof Y.type==="string"?Y.type:void 0;if(Q&&j4.has(Q))return{reason:Q}}return}function V4($,Z){let z=g2($);if(!K2(z))return;let G=typeof z.type==="string"?z.type:void 0;if(G==="codex.rate_limits")return{quota:{snapshot:D$(z),complete:!0}};let Y=B4(z,Z);if(Y)return{limit:Y};if(G===void 0||G==="error")return;return o$(G)?void 0:{outputStarted:!0}}function W4($){let Z=!1;for(let z of $.keys())if(z.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:S$($),complete:b$($)}}function U4($){let Z=$.get("retry-after");if(Z===null)return;let z=Number(Z);return Number.isFinite(z)&&z>=0?z*1000:void 0}function r$($){let Z=new WeakMap,z=new WeakSet,{source:G,pins:Y}=$,Q=$.now??Date.now,K=$.log,U=$.vault,H=new x1($.codex),N=new Map,V=new Map,P=(X)=>`${X.sessionID}\x00${X.kind}\x00${X.accountId}`,C=U?.paths?.rosterPath,E=C?C$(C):new Map,w=$.sessionAccounts??new e2,n=new u$,O=(X,F,T)=>{let L=T?[]:s$(G.peek().rows,X,F,U?.identities()??new Set),g=(U?.routes()??[]).filter((x)=>x.kind==="oauth"&&w$(m2(x.quota),X,F));return[...L.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota,row:x})),...g.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota}))]},D=(X,F,T)=>{let L=g$(X,F,T),g=X.map((S)=>({id:S.id,kind:"oauth",...q$(S.quota)?{quota:S.quota}:{}})),x=X.flatMap((S)=>S.row?[S.row]:[]),k=new Set(X.filter((S)=>!S.row).map((S)=>S.id)),f=G.rateLimitMarks(x);for(let S of k){let y=E.get(S);if(y===void 0)continue;if(y<=T)E.delete(S);else f.set(S,y)}return{rows:g,now:T,rateLimitMarks:f,refreshBackoff:G.refreshBackoffFor(x),killswitch:L,requestPull:(S)=>k.has(S)?U?.requestReading(S):G.requestReading(S)}},U2=(X,F,T,L,g)=>{let x=p$({...X,placement:m$(F),mainId:g});if(x.kind==="block"){K?.debug("pool admission refused the request",{reason:x.block.reason});return}let k=x.order.filter((f)=>!T.has(f));if(L!==void 0&&k.includes(L))return L;return k[0]},G2=(X,F,T,L,g,x,k,f)=>{let S=new Map(F.map((A)=>[A.id,A.quota])),y={requestBytes:w1,reservePercent:(A)=>y$(T,A===v$?void 0:A),resetCredits:(A)=>X4(S.get(A))},u=y1(X),a=(A,z2)=>G1(k,{sessionId:L,requestBytes:w1,validPinnedAccountIds:X.rows.map((c)=>c.id).filter((c)=>!u.excluded.has(c)),excludeAccountIds:A,quotaCheckedAtByAccount:Object.fromEntries(X.rows.map((c)=>[c.id,u.projections.get(c.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(F.map((c)=>[c.id,c.identity])),select:(c)=>f?{accountId:f,source:"mode-fallback",quotaCheckedAt:u.projections.get(f)?.checkedAt}:c$(X,y,new Set(A),c),persist:z2},(c,m)=>k.set(c,m)),J2=[...g],r=a(J2,x);if(!r)return;let Q2=r.accountId,p=d$(X,y,Q2);if(p.kind==="none")return;if(p.kind==="move"){let A=a([...J2,Q2],x);if(A)return A.accountId;return p.reason==="killswitch"?void 0:Q2}if(p.kind==="detour")return a([...J2,Q2],!1)?.accountId;return Q2},H2={providerID:F2,dropChoice(X){let F=P(X);V.get(F)?.drop(),V.delete(F),N.delete(F)},chooseAccount:async(X)=>{let F=await U?.authority(),T=await $.storage(),L=F!==void 0&&F!=="local",g=()=>{throw new V2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:Q1})};if(L)await $.awaitVaultRoster?.();else{if(!(await G.current()).active){if(await $.slotPlaceholderWithoutMain?.())g();K?.warn("the account pool does not serve requests yet; refusing the request",{kind:X.kind});return}await G.prepareTokens(G.peek().rows,T)}let x=Q(),k=O(T,x,L),f=l$(D(k.filter((m)=>m.id!==X.rerouteFrom?.accountId),T,x));if(f)await f,x=Q(),k=O(T,x,L);let S=new Map(k.map((m)=>[m.id,m])),y=D(k,T,x),u=new Set(X.rerouteFrom?[X.rerouteFrom.accountId]:[]),a=T?.routing?.mode??"main-first",J2=X.kind==="primary",r=new Set,Q2,p,A,z2=!1,c=(m)=>{let j2=y1(y).projections.get(m)?.checkedAt,Y2=S.get(m)?.identity;return Y.reserve(X.sessionID,{accountId:m,inputBytes:w1,...j2!==void 0?{quotaCheckedAt:j2}:{},...Y2!==void 0?{wireIdentity:Y2}:{}})};try{for(;;){let m=new Set([...u,...r]);A=void 0,Q2=void 0;let j2=a!=="sticky-balanced";if(a==="sticky-balanced"){let _=new Map(Y.placementSnapshot(X.sessionID)),v=_.get(X.sessionID);if(j2=v===void 0,A=G2(y,k,T,X.sessionID,m,J2&&r.size===0,_),A!==void 0&&_.get(X.sessionID)!==v)Q2=_.get(X.sessionID)}if(A??=U2(y,a,m,J2?void 0:w.activeAccount(X.sessionID),L?a==="sticky-balanced"?null:h$(U?.routes()??[]):void 0),A===void 0||r.has(A)){if(u.size>0){let _=new Map(y.rateLimitMarks);for(let v of u)_.delete(v);y={...y,rateLimitMarks:_},u.clear();continue}if(y.rateLimitMarks.size>0){y={...y,rateLimitMarks:new Map};continue}A=void 0;break}if(J2&&a==="sticky-balanced")p=c(A);if(!z2){z2=!0;let _=await i$({vaultMode:L,fresh:j2,sessionId:X.sessionID,request:{modelId:X.modelID,kind:X.kind,retry:X.phase==="retry"||X.rerouteFrom!==void 0},routes:U?.routes()??[],routing:y,eligibleIds:k.filter((v)=>!m.has(v.id)).map((v)=>v.id)});if(_&&_!==A){if(p)Y.rollback(p);if(p=void 0,a==="sticky-balanced"){let v=new Map(Y.placementSnapshot(X.sessionID));A=G2(y,k,T,X.sessionID,m,J2,v,_)??A,Q2=v.get(X.sessionID)??Q2}else A=_;if(J2&&a==="sticky-balanced")p=c(A)}}let Y2=S.get(A)?.row;if(Y2){if(G.usableToken(Y2)!==void 0)break;K?.debug("pool row holds no usable token; choosing again",{accountId:A})}else{if(!U)break;let _=await U.authorize(A);if(_){N.set(P({...X,accountId:A}),_);break}K?.debug("the vault refused to serve an account; choosing again",{accountId:A})}if(p)Y.rollback(p);p=void 0,r.add(A)}if(A===void 0&&!L&&k.length===0&&await $.slotPlaceholderWithoutMain?.())g();if(A===void 0&&L&&U&&(k.length===0||r.size>0)){let m=r.size>0?"vault-refused":f$(U);throw K?.warn("vault mode: no vault account can serve; refusing the request",{cause:m}),new V2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:I$(m,U.name)})}if(A!==void 0){let m=A,j2=p,Y2=Q2,_=()=>{if(j2)Y.finish(j2,Y2);if(J2)w.record(X.sessionID,m),$.onRoute?.(X.sessionID,m,a)};if(X.phase==="retry")V.set(P({...X,accountId:A}),{commit:_,drop:()=>{if(j2)Y.rollback(j2)}}),p=void 0;else _();let v=K?.info;n.served(y,A,K&&v?{info:(B2,i2)=>v.call(K,B2,i2)}:void 0)}return K?.debug("pool account chosen",{kind:X.kind,accountId:A,mode:a,...X.rerouteFrom?{rerouteFrom:X.rerouteFrom.accountId}:{}}),A}finally{if(p)Y.rollback(p)}},accountHeaders:async(X)=>{let{accountId:F}=X,T=P(X),L=V.get(T);V.delete(T);let g=()=>{L?.commit()};try{let x=()=>new V2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:Y4}),k=U&&await U.authority()!=="local"?void 0:G.peek().rows.find((y)=>y.id===F);if(!k&&U){let y=P(X),u=N.get(y)??await U.authorize(F);if(N.delete(y),!u)throw K?.warn("the vault refused to serve an account; refusing the request",{accountId:F}),x();return g(),{headers:{...R1,"session-id":X.sessionID,authorization:`Bearer ${u.accessToken}`,"chatgpt-account-id":u.accountIdentity??x$(u.accessToken)??null},attempt:{kind:"vault",routeId:F,receipt:u}}}let f=k?G.usableToken(k):void 0;if(!k||!f)throw K?.warn("pool row holds no usable token; refusing the request",{accountId:F}),x();let S=k.identity??x$(f);return g(),{headers:{...R1,"session-id":X.sessionID,authorization:`Bearer ${f}`,"chatgpt-account-id":S??null},attempt:{kind:"pool",token:f,credentialEpoch:k.credentialEpoch}}}finally{L?.drop()}},async rewriteRequest({request:X,sessionID:F,kind:T}){let L=$.codexEndpoint?q1(X.url,$.codexEndpoint()):X.url,g=L===X.url?X:new Request(L,X);return await K$(g,{sessionID:F,kind:T},H,$.responsesLite?.()??!1)??g},rewriteHandshakeURL:({url:X})=>$.codexEndpoint?q1(X,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:X,sessionID:F,kind:T})=>L$(X,{sessionID:F,kind:T},H),quotaFromHeaders:(X,F,T)=>{if(T.data?.kind==="vault")U?.reportUsage(T.data.routeId,{headers:X},T.data.receipt);if(T.data?.kind==="vault"&&h2()&&F>=200&&F<300)Z.set(T,{status:F,headers:X});return W4(X)},async limitFromResponse({status:X,headers:F,body:T,attempt:L}){if(X<400)return;let g=g2(await T().catch(()=>"")),x=Z1({...K2(g)?g:{},status:X});if(L.data?.kind==="vault"&&h2())$1(L.sessionID,L.data.receipt,{status:X,headers:F,body:g,limit:x,quota:U?.routes().find((y)=>y.id===L.accountId)?.quota,now:Q()});if(!x)return;let k=Q(),f=I1(x,k,X);if(f.retryAfterMs!==void 0)return f;let S=U4(F);return S===void 0?f:{...f,retryAfterMs:S}},inspectEvent:({data:X,transport:F,attempt:T})=>{if(T.data?.kind==="vault"&&X.includes("codex.rate_limits")){let L=g2(X);if(K2(L)&&L.type==="codex.rate_limits")U?.reportUsage(T.data.routeId,{frame:L},T.data.receipt)}if(T.data?.kind==="vault"&&h2()&&(n$(X)||F==="ws"&&X.includes('"response.completed"'))){let L=g2(X);if(a$(L))z.add(T);if(F==="ws"&&K2(L)&&L.type==="response.completed")$1(T.sessionID,T.data.receipt,{status:200,headers:new Headers,failed:z.has(T)})}return V4(X,Q())},limitFromError(X){let F=g2(X.message),T=Z1({...K2(F)?F:{},...X.status!==void 0?{status:X.status}:{}})??(X.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return T?I1(T,Q(),X.status):void 0},async onAttemptEnd(X,F){let T=X.data,L=T?.kind==="vault"&&h2()?Z.get(X):void 0;if(Z.delete(X),T?.kind==="vault"&&L&&!F.error&&!F.limit)$1(X.sessionID,T.receipt,{...L,failed:z.has(X)});if(T?.kind!=="vault"||F.status!==401)return;K?.warn("a vault account answered 401; reporting it to the vault",{accountId:X.accountId}),await U?.reportFailure(T.receipt,401)}},X2=(X,F,T)=>{let L=T.data;if(L?.kind==="vault"){U?.recordSnapshot(X,F.snapshot,F.complete,L.receipt);return}if(L?.kind!=="pool")return;if(G.peek().rows.find((x)=>x.id===X)?.credentialEpoch!==L.credentialEpoch){K?.debug("quota reading dropped: the row holds another credential",{accountId:X});return}G.recordSnapshot(X,F.snapshot,L.token,F.complete)},$2=(X,F,T)=>{let L=Q(),g=T.data?.kind==="vault",x=g?U?.routes().find((S)=>S.id===X)?.quota:G.peek().rows.find((S)=>S.id===X)?.quota,k=k$(m2(x),F.reason,L,Q4,F.retryAfterMs!==void 0?L+F.retryAfterMs:void 0);if(!g){G.markRateLimited(X,k);return}let f=E.get(X);if(f===void 0||f<k)E.set(X,k)};return{adapter:H2,attach(X){X.on("quota",(F)=>X2(F.accountId,F.quota,F.handle)),X.on("limit",(F)=>{$2(F.accountId,F.limit,F.handle),K?.debug("pool row refused the request",{accountId:F.accountId,via:F.via,reason:F.limit.reason,outputStarted:F.outputStarted})})},forgetSession(X){Y.forget(X),w.forget(X),H.forget(X)},activeAccount:(X)=>w.activeAccount(X)}}import{resolve as zZ}from"node:path";import{Buffer as H4}from"node:buffer";import{resolve as t$}from"node:path";function l2($){return H4.byteLength(JSON.stringify($))}function N4($){return $.reduce((Z,z)=>Z+l2(z),0)}function f1($,Z){return 2+$+Math.max(0,Z-1)}function F4($){let{head:Z,pending:z}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+f1(Z.inputBytes,Z.input.length)+1:0)+(z?20+f1(z.inputBytes,z.input.length)+10+f1(z.outputBytes,z.output.length)+(z.responseID===void 0?0:14+z.responseIDBytes)+1:0)}function e$($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class $Z{enabled;caps=Y1;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 z=e$(Z);if(z?.type!=="response.create")return;if(!Array.isArray(z.input)){this.forget($);return}let G=z.previous_response_id,Y=this.entries.get($),Q=Y?.head;if(G&&G!==Q?.responseID){this.forget($);return}let{type:K,previous_response_id:U,input:H,...N}=z;this.keep($,{fields:G&&Y?Y.fields:N,fieldsBytes:G&&Y?Y.fieldsBytes:l2(N),...G&&Q?{head:Q}:{},pending:{input:H,inputBytes:N4(H),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,z){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 Y=e$(Z);if(!Y)return;let Q=G.pending,K=Y.response;if(Y.type==="response.created"&&typeof K?.id==="string")Q.responseID=K.id,Q.responseIDBytes=l2(K.id),this.keep($,G);else if(Y.type==="response.output_item.done"&&Y.item){if(typeof Y.response_id==="string"&&Q.responseID!==void 0&&Y.response_id!==Q.responseID)return;Q.output.push(Y.item),Q.outputBytes+=l2(Y.item),this.keep($,G)}else if(Y.type==="response.completed"&&typeof K?.id==="string"){if(K.id===G.head?.responseID||Q.responseID!==void 0&&K.id!==Q.responseID)return;let U={responseID:K.id,responseIDBytes:Q.responseID===K.id?Q.responseIDBytes:l2(K.id),input:[...G.head?.input??[],...Q.input,...Q.output],inputBytes:(G.head?.inputBytes??0)+Q.inputBytes+Q.outputBytes},H={...G,head:U,pending:void 0};if(!this.keep($,H))return;z?.({sessionID:$,responseID:U.responseID,bodyText:this.body(G.fields,U)})}}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 z=F4(Z);if(this.forget($),z>this.caps.maxBytes)return!1;Z.bytes=z,this.entries.set($,Z),this.bytes+=z;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 ZZ=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),JZ=globalThis,v1=JZ[ZZ]??new Map;JZ[ZZ]=v1;function X1($){let Z=JSON.stringify([t$($.configPath),t$($.statePath)]),z=v1.get(Z);if(!z)z=new $Z,v1.set(Z,z);return z}var K4=5000,T4=["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"],L4=["x-opencode-parent-session-id","x-parent-session-id"];function XZ($){let Z=GZ($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:QZ($?{...$,cachekeep:Z}:$)}}var jZ=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),BZ=globalThis,u2=BZ[jZ]??new Map;BZ[jZ]=u2;function _4($,Z){let z=[],G=()=>z.at(-1)?.location,Y=()=>{let H=G();if(!H)throw Error("no location holds keep-warm");return H},Q=(H,N)=>{U.remove(H),G()?.log?.debug(`cachekeep dropped target (${N})`,{sessionKey:H})},K=async(H)=>{if(H.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let N=H.accountId??"main",V=Y(),P=await V.source.accessFor(N,await V.storage());if(!P)throw Error(`pool row ${N} has no usable token`);return{token:P.token,identity:P.row.identity}},U=YZ({...Y1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(H,N)=>Y().fetch(H,N),logger:{debug:(H,N)=>G()?.log?.debug(H,N),warn:(H,N)=>G()?.log?.warn(H,N)},getWindow:()=>G()?.settings().window,getSustain:()=>G()?.settings().sustain===!0,resolveLocal:K,vault:{owns:(H)=>G()?.vault.owns(H)===!0,authority:()=>Y().vault.authority(),reportUsage:(...H)=>G()?.vault.reportUsage(...H),send:async(H,N,V)=>{let P=Y();if(await P.vault.authority()!=="vault")return;return P.vault.send(H,N,V)}},activeAccount:(H)=>{if(H===void 0)throw Error("target has no session");let N=G(),V=N?.settings();if(!N||!V?.enabled){Q(H,"keep-warm is off");return}if(!V.subagents&&U.status().targets.some((C)=>C.sessionKey===H&&C.isSubagent)){Q(H,"subagent warming is off");return}let P=N.accounts.activeAccount(H);if(P===void 0){Q(H,"no account recorded for the session");return}return P},verifyCredential:({target:H,mode:N,identity:V})=>{if(H.meta.credentialMode!==N)throw Error(`a target captured in ${H.meta.credentialMode??"an unknown"} mode is not warmed with a ${N} credential`);if(V!==H.meta.chatgptAccountId)throw Q(H.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:U,settings:Z,holders:z,joinTimeoutMs:$.joinTimeoutMs??K4}}function P4($){try{let Z=JSON.parse($),z=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(z?.role!=="user")return!1;return(typeof z.content==="string"?z.content:Array.isArray(z.content)?z.content.map((Y)=>typeof Y?.text==="string"?Y.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function M4($){let Z={};for(let z of T4){let G=$.get(z);if(G)Z[z]=G}return Z}function VZ($,Z,z){let G=JSON.stringify([zZ($.configPath),zZ($.statePath)]),Y=u2.get(G);if(!Y)Y=_4(z,Z.settings()),u2.set(G,Y);let Q=Y,K=X1($);K.setEnabled(Q.settings.enabled);let U={location:{...Z,settings:()=>Q.settings}};Q.holders.push(U);let H=!1,N=async(V)=>{try{let P=U.location.settings();if(H||!P.enabled)return;if(V.kind!=="primary"){if(V.kind==="generate"&&P4(await V.request.clone().text())){if(H)return;Q.manager.remove(V.sessionID)}return}let C=V.attempt.data,E=C?.kind==="pool"?"local":C?.kind==="vault"?"vault":void 0;if(!E)return;let w=V.request.headers,n=L4.some((U2)=>w.has(U2))||Z.parentOf!==void 0&&await Z.parentOf(V.sessionID)!==void 0;if(n&&!P.subagents)return;let O=await V.request.clone().text();if(H)return;let D=w.get("chatgpt-account-id")??void 0;Q.manager.track({sessionKey:V.sessionID,bodyText:O,accountId:V.attempt.accountId,isSubagent:n,meta:{replayHeaders:M4(w),...D?{chatgptAccountId:D}:{},routingSessionId:V.sessionID,url:V.request.url,credentialMode:E}})}catch(P){Z.log?.warn("cachekeep capture failed",{error:P instanceof Error?P.message:String(P)})}};return{manager:Q.manager,configure:(V)=>{Object.assign(Q.settings,V),K.setEnabled(Q.settings.enabled)},capture:N,forget:(V)=>Q.manager.remove(V),async release(){if(H)return;H=!0;let V=Q.holders.indexOf(U);if(V>=0)Q.holders.splice(V,1);if(Q.holders.length>0)return;if(u2.get(G)===Q)u2.delete(G);Q.manager.stop();let P;try{await Promise.race([Q.manager.tick().catch(()=>{}),new Promise((C)=>{P=setTimeout(C,Q.joinTimeoutMs),P.unref?.()})])}finally{clearTimeout(P)}}}}import{mkdirSync as E4}from"node:fs";import{dirname as C4,resolve as O4}from"node:path";function A4(){return WZ("opencode2")}var R4=2000;class KZ{path;options;sessions;frameTurns=new w2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Q=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=NZ($,Z.uuid??D2)}get($,Z=D2){let z=this.sessions.get($);if(!z){let G=Z();z={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,z),this.#Z.delete($),this.#z.delete($),this.#$.add($),this.#Y()}return z}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??R4),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{$=h1(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 Y=this.sessions.get(G);return Y?[[G,Y]]:[]}),Z=[...this.#Z],z=null;try{if(E4(C4(this.path),{recursive:!0}),z=await this.#B(),!z)return;let G;try{G=h1(this.path)}catch{G=new Map}await this.options.afterRead?.();let Y=!1;for(let Q of Z)if(G.delete(Q))Y=!0;for(let[Q,K]of $){if(G.get(Q)===K.threadID)continue;G.set(Q,K.threadID),Y=!0}if(Y)FZ(this.path,G)}catch{return}finally{await z?.release().catch(()=>{})}for(let[G,Y]of $)if(this.sessions.get(G)===Y)this.#$.delete(G);for(let G of Z)if(!this.sessions.has(G))this.#Z.delete(G)}#B(){return HZ(this.path,this.options.lockWaitMs??UZ)}}var TZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),LZ=globalThis,j1=LZ[TZ]??new Map;LZ[TZ]=j1;function x4($){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 _Z($=A4()){let Z=O4($),z=j1,G=j1.get(Z),Y=j1;if(G!==void 0&&!x4(G))z.compatible??=new Map,Y=z.compatible;let Q=Y.get(Z);if(!Q)Q=new KZ(Z),Y.set(Z,Q);let K=Q;return K.frameTurns??=new w2,Q}var g1=Symbol.for("cortexkit.openai-auth.v2.commands"),q4=M2("v2-command");function B1($){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 m1($){q4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function S4(){let $=globalThis;return $[g1]??={locations:new Map},$[g1].locations??=new Map,$[g1]}async function RZ($,Z){let z=S4(),G=$.location.directory,Y={menu:Z,session:$.session,closed:new AbortController},Q=await MZ(G),K=await PZ(OZ,Q.dir,()=>AZ({...Q,drain:CZ,apply:(P)=>{let C=z.locations.get(G);if(!B1(C))throw Error("The OpenAI menu location was closed");return C.menu.apply(P)}})),U=z.locations.get(G);if(z.locations.set(G,Y),B1(U))U.closed.abort(),await U.registration?.dispose();let H={name:"openai",description:"OpenAI account menu",async execute(P){let C=[...z.locations.values()].find(B1)?.session;if(!C)return m1("no live location");let E=await C.get({sessionID:P.sessionID}),w=z.locations.get(E.location.directory);if(!B1(w))return m1("location closed");let n=await EZ(P.sessionID,w.closed.signal);if(!n||z.locations.get(E.location.directory)!==w){if(!n&&!w.closed.signal.aborted)l1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},P.sessionID);return m1(w.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let O=await w.menu.open(P.sessionID);l1(O,P.sessionID)}};z.command??=H,z.command.execute=H.execute;let N=z.command;try{Y.registration=await $.command.transform((P)=>{P.add(N)})}catch(P){if(Y.closed.abort(),z.locations.get(G)===Y)z.locations.delete(G);throw await K.release(),P}let V=!1;return async()=>{if(V)return;if(V=!0,Y.closed.abort(),z.locations.get(G)===Y)z.locations.delete(G);await K.release(),await Y.registration?.dispose()}}var b4="openai-auth-pool-browser",D4="openai-auth-pool-headless",k4="openai-auth-vault",w4="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 p2($){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 kZ($){return{method:{id:k4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await xZ($.paths,$.name)!=="vault")throw Error(w4)}}}function wZ($){let Z=(z,G,Y)=>({method:{id:z,type:"oauth",label:G},async authorize(){if($.vault)await p2($.vault);let Q=await $.beginLogin({version:$.version,headless:Y});return{url:Q.url,instructions:Q.instructions,mode:"auto",callback:Q.completion}}});return[Z(b4,"ChatGPT (openai-auth pool, browser)",!1),Z(D4,"ChatGPT (openai-auth pool, headless)",!0)]}function u1($){let Z=(z)=>typeof z==="string"?z:"";return f2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===bZ||qZ($)}function y4($){if($.accountId)return $.accountId;let Z=$.access?J1($.access):void 0;return Z?z1(Z):void 0}async function yZ($,Z,z,G={}){if(G.vault)await p2(G.vault);if(u1(z))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Y=SZ($,{rowLocks:(E)=>DZ(Z,E)}),Q=await Y.read();if(Q.status!=="ready")throw Error(`the account pool cannot be read (${Q.status}); the login was not stored`);let K={type:"oauth",refresh:z.refresh,...z.access!==void 0?{access:z.access}:{},...z.expires!==void 0?{expires:z.expires}:{}},U=y4(z);if(G.vault)await p2(G.vault);let H=U!==void 0?{identity:U}:{};if(G.origin==="import"){let E=Q.rows.find((w)=>U!==void 0&&w.identity===U||w.credential?.type==="oauth"&&w.credential.refresh===z.refresh);if(E)return{id:E.id,operation:"kept"}}let N=Q.rows.filter((E)=>E.type==="oauth"&&!E.invalid),V=U?N.find((E)=>E.identity===U):void 0,P=Q.rows.find((E)=>E.id===V1);if(V)return{id:(await Y.replace(V.id,K,H)).id,operation:"replaced"};if(!P){let E=await Y.add({id:V1,credential:K,...H,...z.label!==void 0?{label:z.label}:{}});return{id:E.id,operation:E.outcome==="added-disabled"?"added-disabled":"added"}}if(!P.invalid&&!P.credential)return{id:(await Y.replace(V1,K,H)).id,operation:"replaced"};let C=await Y.add({id:z.id,credential:K,...H,...z.label!==void 0?{label:z.label}:{}});return{id:C.id,operation:C.outcome==="added-disabled"?"added-disabled":C.outcome==="rotated"?"replaced":"added"}}function I4($){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 vZ($){let Z={...$,allowAction:I4,unavailableSections:[]};return{open:(z)=>IZ(Z,z),apply:(z)=>{let G=z!==null&&typeof z==="object"?z:{},Y=G.values&&typeof G.values==="object"&&!Array.isArray(G.values)?Object.fromEntries(Object.entries(G.values).filter(([,Q])=>Q===null||["string","number","boolean"].includes(typeof Q))):void 0;return fZ(Z,{command:"openai",sectionId:typeof G.sectionId==="string"?G.sectionId:"",actionId:typeof G.actionId==="string"?G.actionId:"",...Y?{values:Y}:{},...G.confirmed===!0?{confirmed:!0}:{},...typeof G.itemId==="string"?{itemId:G.itemId}:{},...typeof G.sessionId==="string"?{sessionId:G.sessionId}:{}})}}}function f4($,Z){if(!hZ($.modelID??$.id)){$.enabled=!1;return}let z=gZ($.id);if(z)$.limit={...z};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((G)=>[G.id,G])).values()]}function lZ($){return $.model.transform((Z)=>{let z=Z.list(F2);for(let G of z){let Y=mZ(String(G.id)),Q=Y?z.find((K)=>String(K.id)===Y):void 0;Z.update(F2,String(G.id),(K)=>f4(K,Q?.variants?.map((U)=>({...U,id:String(U.id)}))))}})}class p1{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(!uZ())return;await this.safely(async()=>{let z={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:z}),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 z=this.take($);if(z)await this.safely(()=>W1({...z,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let z=this.requests.get($.attemptId),G=z&&this.take(z);if(!G)return;let{reason:Y,message:Q}=Z.error,K=Q?`${Y}: ${Q}`:Y;await this.safely(()=>W1({...G,error:U1(K,z?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>W1({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 c1{counts=new Map;record($,Z){let z=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof z==="number"&&Number.isFinite(z)?z:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function aZ($){return async(Z)=>{let z=Z.credential;if(z.type!=="oauth"||!z.access)throw Error("the row holds no access token to poll with");let G=await pZ({accessToken:z.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,G),cZ(G,$.now(),!0)}}function nZ($){let{source:Z,counts:z,now:G}=$,Y=async(N)=>{let V=await Z.rowAccess(N,await $.storage());if(!V?.row)throw new dZ("unknown_account",`${N==="main"?"Main":"Fallback"} account ${N} was not found.`);return iZ(N,V)},Q=async(N)=>{if($.authority&&await $.authority()!=="local")return{account:N,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[V]=await Z.pollRows(await $.storage(),{ids:[N]});if(!V)return{account:N,ok:!1,error:"targeted quota refresh returned no result"};return{account:V.id,ok:V.ok,...V.error!==void 0?{error:V.error}:{}}},K=(N)=>Z.peek().rows.find((V)=>V.id===N),U=(N)=>{let V=K(N);if(!V)return null;let P=m2(V.quota)??{},C=z.applicable(V),E=Math.max(0,...[P.primary?.checkedAt,P.secondary?.checkedAt].filter((w)=>typeof w==="number"));return{quota:{...P,...C!==void 0?{resetCreditsApplicable:C}:{}},checkedAt:E,refreshAfter:E,...V.identity!==void 0?{accountId:V.identity}:{}}};return{resolveResetTarget:Y,refreshResetTargetQuota:Q,quotaManager:{isRateLimited:(N)=>{let V=K(N);if(!V)return!1;let P=Z.rateLimitMarks([V]).get(V.id);return P!==void 0&&P>G()},getMain:()=>U("main"),getFallback:(N)=>U(N)}}}import{resolve as oZ}from"node:path";var v4=1024;class d1{pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=v4){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 z of this.reservations.values())if(z.sessionId!==$)Z.set(z.sessionId,z.pin);return Z}reserve($,Z){let z={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,z),z}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 z of this.listeners)z($,Z);while(this.pins.size>this.limit){let z=this.pins.keys().next().value;if(z===void 0)break;this.forget(z)}}place($){return G1(this.placementSnapshot($.sessionId),$,(Z,z)=>this.set(Z,z))}}var sZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),rZ=globalThis,H1=rZ[sZ]??new Map;rZ[sZ]=H1;function h4($){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 tZ($){let Z=JSON.stringify([oZ($.configPath),oZ($.statePath)]),z=H1,G=H1.get(Z);if(G!==void 0&&!h4(G)){let Q=H1;Q.compatibleV1??=new Map,z=Q.compatibleV1}let Y=z.get(Z);if(!Y)Y=new d1,z.set(Z,Y);return Y}import{statSync as g4}from"node:fs";import{resolve as m4}from"node:path";function X0($){return $.map((Z)=>{try{let z=g4(Z);return`${z.ino}:${z.size}:${z.mtimeMs}:${z.ctimeMs}`}catch{return"?"}}).join("|")}function i1($){return X0([$.vault.paths.tokenPath,$.vault.paths.statePath])}function eZ($){return X0([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+i1($)}class j0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;protocol=V0;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:eZ($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),z=this.subscriptions.get($.pins);if(!z){let G=new Set;z={producers:G,stop:$.pins.subscribe((Y,Q)=>{let K=G.values().next().value;if(K)this.publish(K,{sessionId:Y,pin:Q,accountId:Q?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,z)}return z.producers.add($),this.timer??=setInterval(()=>{for(let G of this.producers){let Y={stamp:eZ(G),roster:G.vault.snapshot()},Q=this.observations.get(G);if(Y.stamp!==Q?.stamp||Y.roster!==Q?.roster)this.observations.set(G,Y),this.publish(G)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),z.producers.delete($),!z.producers.size)z.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;await($.write??B0)(this.file,$,Z,()=>this.producers.has($))}).catch(()=>{M2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var B0=async($,Z,z,G)=>{let Q=await Z.vault.authority()!=="local",K=i1(Z),U=()=>G()&&Z.vault.enrolled()===Q&&i1(Z)===K,H=await(Q?d2(Z.paths):y2(Z.paths)),N=Q?Q0(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((C)=>C.id)),H,Date.now()):Y0((await Z.source.sidebarView()).rows,H,Date.now()),V={canWrite:U,vaultMode:Q};if(await Z0(N,$,V),!U()||!z)return;let P=N.vaultAccounts??N.fallbacks;if(z.accountId===void 0){await z0(z.sessionId,P,$,V);return}if(z.pin){let C=Date.now();await G0({sessionId:z.sessionId,assignment:{accountId:z.pin.accountId,wireAccountId:z.pin.wireIdentity,inputBytes:z.pin.inputBytes??0,quotaCheckedAt:z.pin.quotaCheckedAt,assignedAt:C,lastSeenAt:C},validPinnedAccountIds:[...Q?[]:["main"],...P.filter((E)=>E.enabled).map((E)=>E.id)]},$,V)}await J0({sessionId:z.sessionId,activeId:z.accountId,route:z.route??N.route,updatedAt:Date.now()},P,$,V)},V0=2,W0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),U0=globalThis,c2=U0[W0]??new Map;U0[W0]=c2;function H0($,Z=$0(),z=2000){let G=m4(Z),Y=c2.get(G);if(Y?.protocol!==V0)Y=new j0(G,z),c2.set(G,Y);let Q=Y;$={...$,write:$.write??B0};let K=Q.add($),U=!1;for(let[H,N]of $.pins.snapshot())Q.publish($,{sessionId:H,pin:N,accountId:N.accountId,route:"sticky-balanced"});return{publish:()=>Q.publish($),route:(H,N,V)=>{Q.publish($,{sessionId:H,accountId:N,route:V})},async release(){if(U)return;if(U=!0,K(),await Q.settled(),Q.empty&&c2.get(G)===Q)c2.delete(G)}}}var K1="cortexkit-openai-auth",p4=5000;async function N0($,Z,z,G=new v2,Y,Q,K){let U=new p1(z),H=new l4,N=new Map,V=new Map,P=(O)=>{V.delete(O);for(let D of N.keys())if(D.startsWith(`${O}:`))N.delete(D)},C=(O)=>{K?.(O.sessionID),Q?.send(O.sessionID,O.frame)},w=await O1({session:{hook:(O,D,U2)=>$.session.hook(O,async(G2)=>{let I=O==="http.request"?G2:void 0,i=O==="experimental.ws.handshake"?G2:void 0,X2=(I?I.request.headers:i?new Headers(i.headers):void 0)?.get("authorization")===`Bearer ${P2(Z.providerID)}`,$2={};if(i)N.delete(`${i.sessionID}:${i.kind}`);try{await H.run($2,()=>D(G2))}catch(X){if(X2&&!(X instanceof V2))throw P0(X);throw X}if(I&&X2&&$2.attempt){let X=I.request.headers.get("thread-id");if(X)I.request.headers.set("session-id",X)}if(I&&X2&&$2.attempt)await U.captureHttp(I.request,$2.attempt);if(I&&X2&&$2.attempt)await Y?.({sessionID:I.sessionID,kind:I.kind,request:I.request,attempt:$2.attempt});if(i&&X2&&$2.attempt)i.headers["session-id"]=G.get(i.sessionID).threadID;if(O==="experimental.ws.send"){let X=G2,F=N.get(`${X.sessionID}:${X.kind}`);if(F)await U.frame(X.frame,F.attempt);if(F&&X.kind==="primary")C(X)}if(I||i){let X=I??i;if(!X)return;let T=(I?I.request.headers:new Headers(X.headers)).get("authorization")?.replace(/^Bearer /,"");if(X2&&T)V.set(X.sessionID,T);else V.delete(X.sessionID);if(i){let L=`${i.sessionID}:${i.kind}`;if(X2&&T&&$2.attempt)N.set(L,{bearer:T,attempt:$2.attempt,url:i.url,headers:new Headers(Object.entries(i.headers).filter(([g])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(g.toLowerCase())))});else N.delete(L)}if(V.size>512){let L=V.keys().next().value;if(L)V.delete(L)}if(N.size>512){let L=N.keys().next().value;if(L)N.delete(L)}}else if(O==="experimental.ws.receive"){let X=G2,F=N.get(`${X.sessionID}:${X.kind}`);if(F){if(G.frameReceived(X.sessionID,X.frame),X.kind==="primary"){let T;if(Q?.receive(X.sessionID,X.frame,(L)=>{T=L}),T)try{let L=T$(T,F.url,F.headers,G);if(L)await Y?.({sessionID:X.sessionID,kind:"primary",request:L,attempt:F.attempt})}catch(L){z.warn("cachekeep WebSocket capture failed",{error:L instanceof Error?L.message:String(L)})}}X.frame=M0(X.frame,F.bearer)}}else if(O==="retry"){let X=G2,F=V.get(X.sessionID);if(F)Object.assign(X.error,{message:U1(X.error.message,F)})}},U2)},event:{subscribe:(O)=>async function*(){for await(let D of $.event.subscribe(O)){if(D.type==="session.deleted")P(D.data.sessionID);yield D}}()}},{...Z,rewriteRequest:async(O)=>{let D=H.getStore();if(D)D.attempt=O.attempt;return Z.rewriteRequest?.(O)},rewriteHandshakeURL:(O)=>{let D=H.getStore();if(D)D.attempt=O.attempt;return Z.rewriteHandshakeURL?.(O)},onAttemptEnd:async(O,D)=>{await U.end(O,D),await Z.onAttemptEnd?.(O,D)},rewriteResponse:async(O)=>{await U.response(O.request,O.response.status);let D=await Z.rewriteResponse?.(O)??O.response;return E0(D,O.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(O)=>{let D=O.get("authorization");return D?.startsWith("Bearer ")?D.slice(7):void 0}},logger:{warn:(O,D)=>z.warn(O,{data:D})}}),n=w.dispose;return{...w,dispose:async()=>{V.clear(),N.clear(),await n(),await U.settle(),U.clear()}}}function o1($={}){return{id:K1,setup:(Z)=>c4(Z,$)}}async function c4($,Z={}){let c=[];try{let z=M2("opencode2");let G=M2("quota");let Y=Z.version??O0;await f0({version:Y,...Z.runtimeLayout});let Q=Z.paths??(()=>R0(C0()));let K=await d2(Q());let U=K?.logging?.level;if(U&&typeof U==="string")K0(U);let H=Z.fetch??fetch;let N=Z.now??Date.now;let V=Z.poolMigration??h0;if(!V&&!I2(Q().configPath)){z.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 _=(B2)=>{throw new V2({kind:"no-account",providerID:F2,sessionID:B2.sessionID,requestKind:B2.kind,message:Q1})},v=await N0($,{providerID:F2,chooseAccount:_,accountHeaders:_},z);return()=>v.dispose()}let P=Z.vault?.firstRosterWaitMs??D0;let C=v0({host:"opencode",stateDir:Z.vault?.stateDir??_0(Q().statePath),reservedRouteIds:()=>I.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:()=>H},Q());let E=C.vault;let w=async()=>await E.authority()==="local"?y2(Q()):d2(Q());let n=!1;let O=!1;const D=N1(c,{[Symbol.dispose](){if(!n)C.release()}},0);await E.authority();let U2=C.firstRoster;let G2=new c1;let I=new k0({paths:Q,rateLimitMarks:E$(Q()),refreshProvider:async(_)=>{let v=await L0({refreshToken:_.refresh,fetchImpl:H,now:N}),B2=T0({id_token:"",access_token:v.access,refresh_token:v.refresh});return{...v,...B2?{identity:B2}:{}}},pullQuota:aZ({fetchImpl:H,now:N,counts:G2,logger:G}),now:N,vaultIdentities:()=>E.identities(),vaultMode:()=>E.enrolled(),vaultAuthority:()=>E.authority(),vaultFirstRoster:U2,vaultFirstRosterBackgroundWaitMs:P,log:M2("pool")});if(await E.authority()==="local")await I.load();let i=Z.heartbeat===!1?void 0:await y0({version:Y,logger:M2("heartbeat")});let H2=Z.fence??(()=>A0({currentVersion:Y}));let X2=Z.slot??g0();let $2=async()=>x0(Q(),await X2.get({path:{id:"openai"}}));let X=!1;let F=V?w0({paths:Q,slot:X2,version:Y,fence:H2,runDeps:{vaultServes:()=>E.serves()},paused:async()=>await E.authority()!=="local",migrate:async(_)=>{let v=await q0(_);if(X=v.status==="refused",!O)await I.load();return v},adopt:async(_)=>{if(O)return{status:"retry",reason:"unsettled"};if(!await n1(U2,P))return{status:"retry",reason:"vault-roster-pending"};if(O)return{status:"retry",reason:"unsettled"};let v=await S0(_);if(!O)await I.load();return v}}):void 0;F?.start();C.start();let T=tZ(Q());let L=H0({paths:Q(),source:I,pins:T,vault:E},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const g=N1(c,{[Symbol.dispose](){if(!n)L.release()}},0);L.publish();let x=Z.codex??new v2(void 0,void 0,_Z());let k=XZ(K);let f=X1(Q());let S=VZ(Q(),{source:I,storage:w,vault:E,accounts:k1(Q()),settings:()=>k,parentOf:async(_)=>(await $.session.get({sessionID:_}))?.parentID??void 0,fetch:H,log:M2("cachekeep")},{now:N,codexResponsesUrl:F1().codexApiEndpoint,...Z.cacheKeep});const y=N1(c,{[Symbol.dispose](){if(!n)S.release()}},0);let u=r$({codex:x,onRoute:L.route,source:I,slotPlaceholderWithoutMain:$2,storage:w,pins:T,sessionAccounts:k1(Q()),vault:E,awaitVaultRoster:async()=>{await n1(E.awaitRequestRoster(),b0)},responsesLite:()=>F1().responsesLite,codexEndpoint:()=>F1().codexApiEndpoint,now:N,log:z});let a=await N0($,u.adapter,z,x,(_)=>S.capture(_),f,(_)=>S.forget(_));u.attach(a);let J2=async(_)=>{if(await p2(E),I2(Q().configPath))return;if(await F?.idle(),I2(Q().configPath))return;if(X&&!u1(_)&&(await H2()).open){await I.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 r=async(_)=>{await J2(_);let v=await yZ(I.poolStore(),Q(),_,{vault:E});if(!I2(Q().configPath))await F?.requestAdoption();await I.load(),z.info("ChatGPT login stored in the account pool",v)};let Q2=await M1($,{integrationID:F2,methods:wZ({beginLogin:Z.beginLogin??a1,version:Y,vault:E}),onLogin:(_)=>r(_),label:"ChatGPT (openai-auth account pool)",vault:kZ(E)});let p=await lZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let A=$.command&&$.location?await RZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??vZ({...nZ({source:I,storage:w,counts:G2,now:N,authority:()=>E.authority()}),fetchImpl:H,now:N,randomUUID:u4,accountStoragePath:Q().configPath,accountStatePath:Q().statePath,packageVersion:Y,layoutNotice:I0,loadAccounts:y2,store:()=>I.poolStore(),migration:async()=>{if(I2(Q().configPath))return{migrated:!0};let _=await H2();return{migrated:!1,blockers:_.open?[]:_.blockers}},beginAccountLogin:Z.beginLogin??a1,refreshAllQuota:async()=>(await I.pollRows(await y2(Q()))).map((_)=>({..._,account:_.id})),getStickyRouting:async(_)=>T.get(_),cacheKeepManager:S.manager,setCacheKeepEnabled:(_)=>S.configure({enabled:_}),setCacheKeepSubagents:(_)=>S.configure({subagents:_}),setCacheKeepSustain:(_)=>S.configure({sustain:_}),setCacheKeepWindow:(_)=>S.configure({window:_}),afterWrite:()=>I.load(),refreshSidebar:()=>L.publish(),clearStickyRouting:async(_)=>{let v=T.get(_)!==void 0;return T.forget(_),v},vault:E})):void 0;let z2=new AbortController;(async()=>{try{for await(let _ of $.event.subscribe({signal:z2.signal}))if(_.type==="session.deleted")u.forgetSession(_.data.sessionID),S.forget(_.data.sessionID),f.forget(_.data.sessionID)}catch(_){if(!z2.signal.aborted)z.warn("stopped listening for session deletion",{error:_ instanceof Error?_.message:String(_)})}})();n=!0;return async()=>{O=!0,z2.abort();let _=S.release();await A?.(),F?.dispose(),await I.dispose(),await L.release(),await Promise.allSettled([a.dispose(),Q2.dispose(),p.dispose()]);let v;try{await Promise.race([Promise.all([F?.idle(),I.settled(),x.store?.settled(),_]),new Promise((B2)=>{v=setTimeout(B2,p4),v.unref?.()})])}finally{clearTimeout(v),C.release(),await i?.release()}}}catch(m){var j2=m,Y2=1}finally{F0(c,j2,Y2)}}var d4=o1(),_7={id:K1,setup:d4.setup,server:m0.server};export{_7 as default,o1 as createOpenAIAuthPlugin,K1 as OPENAI_AUTH_PLUGIN_ID};
3
+ `)}}function x1($,Z){let z=new TextDecoder,G="",X=(F)=>{let W=i0(F);if(!W)return;try{$(W)}catch(H){Z(H)}},Y=()=>{for(;;){let F=/\r?\n\r?\n/.exec(G);if(!F)return;let W=G.slice(0,F.index);G=G.slice(F.index+F[0].length),X(W)}};return new TransformStream({transform(F,W){W.enqueue(F),G+=z.decode(F,{stream:!0}),Y()},flush(){if(G+=z.decode(),Y(),G.trim()!=="")X(G);G=""}})}var Z1=512,S1=3621000,y2="x-common-auth-attempt",D2=($,Z)=>JSON.stringify([$,Z]),M2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function a0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function n0($,Z){let z=$.getReader();return new ReadableStream({async pull(G){let X;try{X=await z.read()}catch(Y){Z({reason:"failed",message:Y instanceof Error?Y.message:String(Y)}),G.error(Y);return}if(X.done)Z(),G.close();else G.enqueue(X.value)},async cancel(G){Z({reason:"cancelled",...G===void 0?{}:{message:String(G)}}),await z.cancel(G)}})}function $1($,Z){for(let[z,G]of Object.entries(Z)){let X=z.toLowerCase();for(let Y of Object.keys($))if(Y.toLowerCase()===X)delete $[Y];if(G!==null)$[z]=G}}function o0($,Z){for(let[z,G]of Object.entries(Z))if(G===null)$.delete(z);else $.set(z,G)}async function q1($,Z,z={}){let{providerID:G}=Z,X=z.gateOnPlaceholder,Y=(J)=>X===void 0||X.credential(J)===A2(G),F=z.logger,W=Math.max(1,z.maxRecords??Z1),H=z.hostRetryLimit??10,N=[...z.hostCredentials??[A2(G)],...X?[A2(G)]:[]].filter((J)=>J!==""),V=new Map,P=new WeakMap,C=new Map,E=0,h=new Set,a=new Map,A=new Map,k=(J)=>{let j=A.get(J);return j?.ownedSeen===!0&&j.foreignSeen},W2=(J,j)=>{a.set(J,j);let U=A.get(J)??{ownedSeen:!1,foreignSeen:!1};if(j)U.ownedSeen=!0;else U.foreignSeen=!0;A.set(J,U)},X2=(J,j)=>{let U=X?.refuseMisplaced,L=U?[...j].filter(([,I])=>I.includes(A2(G))):[],B=Y(j)&&(!U||L.length>0);if(U){if(L.length>0&&(L.length!==1||!B))throw W2(J.sessionID,!1),new F2({kind:"placement-refused",providerID:G,sessionID:J.sessionID,requestKind:J.kind,message:U(L[0]?.[0]??"")})}return W2(J.sessionID,B),B},v=!1,n=!1,K2=new Map,U2=0,j2=!1,b=new Map,g=(J,j)=>{try{F?.warn(J,j)}catch{}},p=(J)=>J instanceof Error?J.message:String(J),Q=(J)=>J.excluded.clear(),K=(J)=>J.excluded.size===0?{}:{excluded:[...J.excluded]},_=(J,j,U)=>{if(!z.enforceRequestExclusion||J===void 0||!U.excluded.has(J))return!1;return g("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:j.sessionID,kind:j.kind,phase:j.phase,accountId:J}),!0},M=new Map,D=(J,j)=>{let U=(M.get(J)??Promise.resolve()).then(j),L=U.then(()=>{},()=>{});return M.set(J,L),L.then(()=>{if(M.get(J)===L)M.delete(J)}),U},O=(J,j)=>{let U=M.get(J);return U?U.then(()=>O(J,j)):j()},R=async(J)=>{try{await Z.dropChoice?.({...J.input,accountId:J.accountId})}catch(j){g("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:J.input.sessionID,error:p(j)})}},f=async(J)=>{try{await Z.dropSameAccountRetry?.({...J.input,accountId:J.accountId})}catch(j){g("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:J.input.sessionID,error:p(j)})}},q=async(J)=>{if(J.next)await R(J.next);if(J.sameAccount)await f(J.sameAccount)},w=(J)=>{let j=C.get(J);if(C.delete(J),j)D(j.sessionID,()=>q(j))},y=async(J,j)=>{let U=K2.get(J);if(!U||U.size===0)return;await Promise.all([...U].map(async(L)=>{try{await L(j)}catch(B){g("opencode2 auth listener threw; the request is unaffected",{event:J,error:p(B)})}}))},J2=async(J,j)=>{try{await Z.onAttemptEnd?.(J,j)}catch(U){g("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:J.attemptId,error:p(U)})}},G2=(J,j)=>{if(J.ended||!J.attempt)return;let U={...J.status===void 0?{}:{status:J.status},outputStarted:J.outputStarted,...J.limit?{limit:J.limit.signal}:{},...j?{error:j}:{}};if(j)J.endError=j;if(j?.reason==="cancelled"||!j&&!J.limit&&(J.status===void 0||J.status<400))Q(J.request);J.ended=J2(J.attempt,U)},e=(J,j)=>G2(J,{reason:"abandoned",message:j}),s=(J)=>[...V.values()].filter((j)=>j.key===J),c=(J)=>s(J).at(-1),m=(J)=>{if(V.delete(J.id),C.get(J.key)?.attemptId===J.id||!s(J.key).length)w(J.key)},$2=(J)=>{V.set(J.id,J);while(V.size>W){let j=V.values().next().value;if(j===void 0)break;e(j,"dropped to keep the record bound"),m(j)}},T2=(J)=>J.accountId===void 0?void 0:{...J.scope,accountId:J.accountId},T=(J,j)=>new F2({kind:"no-account",providerID:G,sessionID:J.sessionID,requestKind:J.kind,...j===void 0?{}:{message:j}}),l=(J)=>{b.get(J)?.clear(),b.delete(J)},Z2=async(J,j)=>{let U=()=>T(J,`${G} ${J.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(j2)throw U();let L=b.get(J.sessionID);if(!L)L=new Set,b.set(J.sessionID,L);let B={};L.add(B);let I=()=>{if(!L.has(B))throw U()};try{return await j(I)}finally{if(L.delete(B),L.size===0&&b.get(J.sessionID)===L)b.delete(J.sessionID)}},t=(J,j)=>{for(let[U,L]of j)if(N.some((B)=>L.includes(B)))throw new F2({kind:"host-credential-on-wire",providerID:G,sessionID:J.sessionID,requestKind:J.kind,message:`${G} ${J.kind} request still carries the host's placeholder credential in ${U}; the adapter's account headers must replace it`})},B2=(J)=>{for(let j of s(J))if(j.ended||!j.attempt)m(j);else if(j.transport==="ws"||j.judged)e(j,"a newer attempt of its session and kind began"),m(j)},w2=async(J,j,U,L)=>{let B=D2(J.sessionID,J.kind),{input:I,accountId:x,sameAccountRetry:S,request:r}=await O(J.sessionID,async()=>{U();let Q2=C.get(B);C.delete(B);let g2=s(B);if(Q2&&g2.some((o)=>o.id!==Q2.attemptId&&o.attempt&&!o.ended))g("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:J.sessionID,kind:J.kind});if(!Q2){let o=new Set(g2.filter((N2)=>N2.attempt&&!N2.ended).map((N2)=>N2.request));for(let N2 of g2)if(!o.has(N2.request))Q(N2.request)}let V2=Q2?.request??{excluded:new Set},z2=Q2?.accountId??c(B)?.accountId;B2(B);let i=Q2?.next,Y2=Q2?.sameAccount,u=Y2!==void 0&&Y2.input.modelID===J.modelID&&Y2.input.agent===J.agent,H2=i!==void 0&&i.input.modelID===J.modelID&&i.input.agent===J.agent,O2=Q2?.wake,d={...J,phase:"request",...K(V2),...z2===void 0?{}:{previousAccountId:z2},...Q2?.rerouteFrom?{rerouteFrom:Q2.rerouteFrom}:{},...O2===void 0?{}:{wake:O2,hostAttempt:i?.input.hostAttempt}};if(i&&(!H2||O2!==void 0))await D(J.sessionID,()=>R(i)),U();if(Y2&&!u)await D(J.sessionID,()=>f(Y2)),U();if(Y2?.continuation&&(!u||k(J.sessionID))){if(u)await D(J.sessionID,()=>f(Y2));throw T(J)}let b2=u?Y2.accountId:H2&&O2===void 0?i.accountId:await Z.chooseAccount(d),S2=typeof b2==="string"?b2:void 0;if(_(S2,d,V2)){let o=S2;if(u&&Y2)await D(J.sessionID,()=>f(Y2));else if(o!==void 0)await D(J.sessionID,()=>R(H2&&i?i:{accountId:o,input:d}));S2=void 0,U()}return{input:d,accountId:S2,sameAccountRetry:u,request:V2}});U();let _2={},L2;if(x!==void 0){let Q2=await Z.accountHeaders({...J,accountId:x});if(U(),a0(Q2))_2=Q2.headers,L2=Q2.attempt;else _2=Q2}let h2=`attempt-${++U2}`,P2={id:h2,key:B,scope:J,request:r,accountId:x,headers:_2,attempt:x===void 0?void 0:{...J,accountId:x,attemptId:h2,transport:L,data:L2},...L===void 0?{}:{transport:L},outputStarted:!1,sameAccountRetry:S};if($2(P2),P2.attempt)y("select",{...J,accountId:P2.attempt.accountId,hook:j,...I.previousAccountId===void 0?{}:{previousAccountId:I.previousAccountId},...I.rerouteFrom===void 0?{}:{rerouteFrom:I.rerouteFrom},handle:P2.attempt});return P2},r2=async(J,j,U,L,B)=>{let I=D2(J.sessionID,J.kind),x=L===void 0?void 0:V.get(L);if(x?.key!==I)x=void 0;if(!x){if(x=c(I),s(I).filter((r)=>r.transport===void 0&&!r.ended).length>1&&!n)n=!0,g("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:J.sessionID,kind:J.kind})}if(!x||x.transport!==void 0||x.ended)x=await w2(J,j,B,U);else if(x.transport=U,x.attempt)x.attempt.transport=U;if(U==="ws"){for(let S of s(I))if(S!==x&&S.transport==="ws")e(S,"a newer attempt of its session and kind went out over WebSocket")}return x},C1=async(J,j)=>{try{return await j()}catch(U){throw G2(J,{reason:"failed",message:p(U)}),U}},Q$=(J,j)=>{let U=s(D2(J,j)).filter((L)=>L.transport==="ws").at(-1);return U?.attempt!==void 0&&!U.ended?U:void 0},t2=(J,j,U)=>{let L=T2(J);if(!L||!J.attempt||J.limit)return;J.limit={signal:j,delivered:y("limit",{...L,via:U,limit:j,outputStarted:J.outputStarted,handle:J.attempt})}},Y$=(J,j,U,L)=>{let B=T2(J);if(!B||!J.attempt)return;y("quota",{...B,transport:j,...L===void 0?{}:{status:L},quota:U,handle:J.attempt})},X$=(J,j,U,L)=>{let B=J.attempt;if(!B)return;let I=Z.inspectEvent?.(L===void 0?{transport:j,data:U,attempt:B}:{transport:j,data:U,event:L,attempt:B});if(!I)return;if(I.quota!==void 0)Y$(J,j,I.quota);if(I.outputStarted)J.outputStarted=!0;if(I.hostRetry==="veto")J.hostRetry="veto";if(I.limit)t2(J,I.limit,j);if(I.error!==void 0)G2(J,{reason:"failed",message:I.error});else if(I.done)G2(J)},p0=(J,j)=>{let U=J.attempt;if(!U||j.accountId===J.accountId)return;if(U.reboundFrom??=U.accountId,U.accountId=j.accountId,"data"in j)U.data=j.data;J.accountId=j.accountId},c0=(J)=>!J.attempt||J.endError!==void 0||J.status!==void 0&&J.status>=400,j$=(J)=>{let j=[...V.values()].filter((S)=>S.scope.sessionID===J),U=j.filter((S)=>S.limit&&!S.rerouted).at(-1);if(U)return U;let L=j.filter((S)=>S.scope.kind==="primary"),B=L.length>0?L:j;if(B.length<=1)return B[0];let I=B.filter((S)=>!S.judged&&c0(S)).at(-1);if(I)return I;let x=B.filter((S)=>S.attempt&&!S.ended);if(x.length>1)return"ambiguous";return x[0]??B.at(-1)},q2={providerID:G},x2=[];x2.push(await $.session.hook("model.request",(J)=>{if(X)return;return Z2(M2(J),async(j)=>{let U=await w2(M2(J),"model.request",j);if(j(),U.accountId===void 0)throw T(U.scope);$1(J.headers,{...U.headers,[y2]:U.id})})},q2)),x2.push(await $.session.hook("http.request",(J)=>{if(X){if(!X2(M2(J),J.request.headers))return}return Z2(M2(J),async(j)=>{let U=J.request.headers.get(y2)??void 0,L=X?await w2(M2(J),"http.request",j,"http"):await r2(M2(J),"http.request","http",U,j);j();let B=T2(L),I=L.attempt;if(!B||!I)throw T(L.scope);await C1(L,async()=>{let x=J.request;if(Z.rewriteRequest){if(U!==void 0){let _2=new Headers(x.headers);_2.delete(y2),x=new Request(x,{headers:_2})}x=await Z.rewriteRequest({...B,request:x,attempt:I})??x,j()}let S=new Headers(x.headers);S.delete(y2),o0(S,L.headers),t(L.scope,S.entries());let r=new Request(x,{headers:S});P.set(r,L),J.request=r})})},q2)),x2.push(await $.session.hook("http.response",async(J)=>{let j=P.get(J.request);if(!j){if(X)return;if(!v)v=!0,g("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:J.sessionID,kind:J.kind});return}let U=J.response;if(Z.answeredBy&&j.attempt){let S=j.attempt,r=await C1(j,async()=>Z.answeredBy?.({request:J.request,response:U,attempt:S}));if(r)p0(j,r)}let L=T2(j),B=j.attempt;if(!L||!B)return;j.status=U.status;let I=Z.quotaFromHeaders?.(U.headers,U.status,B);if(I!==void 0)Y$(j,"http",I,U.status);if(!U.ok&&Z.limitFromResponse){let S=await Z.limitFromResponse({status:U.status,headers:U.headers,body:()=>U.clone().text(),attempt:B});if(S)t2(j,S,"http")}if(!U.ok||!U.body)G2(j);let x=U;if(U.body&&(Z.inspectEvent||Z.onAttemptEnd)){let S=U.body;if(Z.inspectEvent)S=S.pipeThrough(x1((r)=>X$(j,"http",r.data,r.event),(r)=>g("opencode2 auth event inspection threw",{error:p(r)})));x=new Response(n0(S,(r)=>{if(r?.reason==="failed")j.httpReadFailed=!0;G2(j,r)}),{status:U.status,statusText:U.statusText,headers:U.headers})}if(Z.rewriteResponse)x=await Z.rewriteResponse({...L,request:J.request,response:x,attempt:B})??x;if(Z.responseRetry){if(await Z.responseRetry({...L,request:J.request,response:x,attempt:B})==="veto")j.hostRetry="veto"}if(x!==U)J.response=x},q2)),x2.push(await $.session.hook("experimental.ws.handshake",(J)=>{if(X){let j=D2(J.sessionID,J.kind);if(h.delete(j),!X2(M2(J),new Headers(J.headers)))return}return Z2(M2(J),async(j)=>{let U;for(let x of Object.keys(J.headers)){if(x.toLowerCase()!==y2)continue;U??=J.headers[x],delete J.headers[x]}let L=X?await w2(M2(J),"experimental.ws.handshake",j,"ws"):await r2(M2(J),"experimental.ws.handshake","ws",U,j);j();let B=T2(L),I=L.attempt;if(!B||!I)throw T(L.scope);await C1(L,async()=>{if(!X?.refuseMisplaced)$1(J.headers,L.headers);let x=Z.rewriteHandshakeURL?.({...B,url:J.url,attempt:I});if(x!==void 0)J.url=x;if(X?.refuseMisplaced)$1(J.headers,L.headers);if(t(L.scope,Object.entries(J.headers)),X)h.add(L.key)})})},q2));let B$=Z.rewriteWebSocketFrame?.bind(Z);if(B$)x2.push(await $.session.hook("experimental.ws.send",async(J)=>{let j=M2(J);if(X&&!h.has(D2(j.sessionID,j.kind)))return;let U=Q$(j.sessionID,j.kind),L=await B$({...j,attempt:U?.attempt,frame:J.frame});if(L!==void 0)J.frame=L},q2));x2.push(await $.session.hook("experimental.ws.receive",(J)=>{if(X&&!h.has(D2(J.sessionID,J.kind)))return;let j=Q$(J.sessionID,J.kind);if(!j)return;try{X$(j,"ws",J.frame)}catch(U){g("opencode2 auth frame inspection threw",{error:p(U)})}},q2)),x2.push(await $.session.hook("retry",async(J)=>{if(X&&a.get(J.sessionID)!==!0)return;let j=J.decision,U=()=>y("retry",{sessionID:J.sessionID,attempt:J.attempt,reason:"host-decides",hostDecision:j,decision:j});if(k(J.sessionID)&&!Z.retrySameAccount){await U();return}let L=j$(J.sessionID);if(!L)return;if(L==="ambiguous"){await y("retry",{sessionID:J.sessionID,attempt:J.attempt,reason:"host-decides",hostDecision:j,decision:j});return}let B=L,I=()=>B.hostRetry==="veto";await Z2(B.scope,async(x)=>{let S=x,r=Z.retrySameAccount?.bind(Z),_2=B.attempt,L2=B.outputStarted;if(L2&&B.httpReadFailed&&r&&_2&&!k(J.sessionID)){if(!B.limit){let V2=Z.limitFromError?.(J.error,_2);if(V2)t2(B,V2,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;S()}let h2=()=>B.httpReadFailed===!0&&J.error.type==="provider.transport"&&j.retry&&H-J.attempt>=1&&!B.limit&&!(B.status!==void 0&&B.status>=400)&&!(J.error.status!==void 0&&J.error.status>=400)&&!_2?.reboundFrom&&!I()&&!k(J.sessionID);if(r&&_2&&(!L2||h2())&&(!I()||k(J.sessionID))&&!B.sameAccountRetry){if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;let V2=await D(B.scope.sessionID,async()=>{S();let z2=_2.accountId,i=()=>V.has(B.id)&&B.accountId===z2&&j$(J.sessionID)===B&&B.outputStarted===L2&&(!L2||h2())&&(!I()||k(J.sessionID))&&(!X||a.get(J.sessionID)===!0);if(!i()||B.sameAccountRetry)return!1;B.sameAccountRetry=!0;let Y2={...B.scope,accountId:z2,error:J.error,attempt:J.attempt,...B.limit?{limit:B.limit.signal}:{},...L2?{continuation:"interrupted-read"}:{}},u;try{u=await r(Y2)}catch(d){g("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:J.sessionID,error:p(d)})}if(!u)return S(),!1;let H2={accountId:u.accountId,input:Y2,...L2?{continuation:!0}:{}};try{S()}catch(d){throw await f(H2),d}if(!i()||u.accountId!==z2)return await f(H2),!1;let O2=C.get(B.key);if(C.delete(B.key),O2)await q(O2);try{S()}catch(d){throw await f(H2),d}if(!i())return await f(H2),!1;return C.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++E,accountId:z2,sameAccount:H2}),B.judged=!0,J.decision=L2?j:{retry:!0,delay:0},!0});if(S(),V2){await y("retry",{sessionID:J.sessionID,accountId:B.accountId,kind:B.scope.kind,attempt:J.attempt,reason:L2?"continue-same-account":"same-account",hostDecision:j,decision:J.decision,handle:B.attempt});return}}if(k(J.sessionID)){await U();return}B.judged=!0;let P2=B.attempt;if(P2&&!B.outputStarted){if(!B.limit){let V2=Z.limitFromError?.(J.error,P2);if(V2)t2(B,V2,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered}S();let{decision:Q2,reason:g2}=await D(B.scope.sessionID,async()=>{if(S(),k(J.sessionID))return{decision:j,reason:"host-decides"};let V2=C.get(B.key);if(C.delete(B.key),V2)await q(V2);if(S(),k(J.sessionID))return{decision:j,reason:"host-decides"};let z2=j,i,Y2,u,H2;if(B.accountId===void 0||!P2)z2={retry:!1},i="no-account";else if(B.outputStarted)z2={retry:!1},i="output-started";else if(I())z2={retry:!1},i="adapter-veto";else if(B.limit){let O2={accountId:B.accountId,limit:B.limit.signal},d,b2={...B.scope,phase:"retry",...K(B.request),hostAttempt:J.attempt,previousAccountId:B.accountId,rerouteFrom:O2};try{d=await Z.chooseAccount(b2)}catch(A1){g("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:B.scope.sessionID,error:p(A1)})}let S2=typeof d==="string"?d:typeof d==="object"&&("hold"in d)?B.accountId:void 0;if(_(S2,b2,B.request)){if(S2!==void 0)await R({accountId:S2,input:b2});d=void 0}let o=typeof d==="object"&&"hold"in d?d.hold:void 0,N2=typeof d==="object"&&"waitThenReselect"in d?d.waitThenReselect:void 0,d0=typeof d==="object"&&"hostRetry"in d?d.hostRetry:void 0,e2=typeof d==="string"?d:o?B.accountId:void 0;if(e2!==void 0)u={accountId:e2,input:b2};try{S()}catch(A1){if(u)await R(u);throw A1}if(k(J.sessionID)){if(u)await R(u);return{decision:j,reason:"host-decides"}}if(I()||d0==="veto"){if(u)await R(u);if(u=void 0,S(),k(J.sessionID))return{decision:j,reason:"host-decides"};B.hostRetry="veto",z2={retry:!1},i="adapter-veto"}else if(!(H-J.attempt>=1)){if(u)await R(u);u=void 0,i="host-decides-last-account"}else if(N2&&Number.isFinite(N2.delayMs)&&N2.delayMs>=0&&N2.delayMs<=S1)z2={retry:!0,delay:Math.ceil(N2.delayMs)},i="wait-then-reselect";else if(o&&Number.isFinite(o.delayMs)&&o.delayMs>=0&&o.delayMs<=S1){if(z2={retry:!0,delay:Math.ceil(o.delayMs)},o.target!==void 0)H2={target:o.target,...o.checkpoint===void 0?{}:{checkpoint:o.checkpoint},...o.kind===void 0?{}:{kind:o.kind}};i="hold"}else if(!o&&e2!==void 0&&e2!==B.accountId)B.rerouted=!0,B.request.excluded.add(B.accountId),Y2=O2,z2={retry:!0,delay:0},i="reroute";else{if(o&&u)await R(u),u=void 0;i="host-decides-last-account"}}else i="host-decides";if(J.decision=z2,z2.retry&&B.accountId!==void 0&&V.has(B.id))C.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++E,accountId:B.accountId,...Y2===void 0?{}:{rerouteFrom:Y2},...u===void 0?{}:{next:u},...H2===void 0?{}:{wake:H2}});else if(u)await R(u);if(!z2.retry)Q(B.request);return{decision:z2,reason:i}});S(),await y("retry",{sessionID:J.sessionID,...B.accountId===void 0?{}:{accountId:B.accountId},kind:B.scope.kind,attempt:J.attempt,reason:g2,hostDecision:j,decision:Q2,...P2===void 0?{}:{handle:P2}})})},q2));let V$=(J)=>{if(l(J),a.delete(J),!A.get(J)?.foreignSeen)A.delete(J);for(let j of h)if(JSON.parse(j)[0]===J)h.delete(j);for(let j of[...V.values()]){if(j.scope.sessionID!==J)continue;e(j,"its session was forgotten"),Q(j.request),V.delete(j.id)}for(let[j,U]of C)if(U.sessionID===J)w(j)},O1=new AbortController,W$=$.event;if(W$)(async()=>{try{for await(let J of W$.subscribe({signal:O1.signal}))if(J.type==="session.deleted")V$(J.data.sessionID);else if(J.type==="session.status"&&J.data.status.type==="idle"){let j=J.data.sessionID,U=++E;D(j,async()=>{for(let[L,B]of C)if(B.sessionID===j&&B.order<U)C.delete(L),Q(B.request),await q(B)})}}catch(J){if(!O1.signal.aborted)g("opencode2 auth stopped listening for session deletion",{error:p(J)})}})();return{on(J,j){let U=K2.get(J);if(!U)U=new Set,K2.set(J,U);let L=j;return U.add(L),()=>{U.delete(L)}},accountFor(J,j){return c(D2(J,j))?.accountId},forgetSession:V$,get size(){return V.size},async dispose(){if(j2)return;j2=!0;for(let J of b.keys())l(J);O1.abort();for(let J of V.values())e(J,"the installation was disposed");V.clear();for(let J of C.keys())w(J);h.clear(),a.clear(),A.clear(),K2.clear(),await Promise.all(M.values()),await Promise.all(x2.map(async(J)=>{try{await J.dispose()}catch(j){g("opencode2 auth hook did not dispose cleanly",{error:p(j)})}}))}}}import{createHash as s0}from"node:crypto";var r0=1024,t0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),N$=($)=>F$($,"user"),e0=($)=>t0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function $4($){return s0("sha256").update(JSON.stringify($)).digest("hex")}class I2{runtime;maxSessions;#$=new Map;constructor($,Z=r0){this.runtime=$;this.maxSessions=Z}advance($,Z,z=this.runtime){let G=this.#$.get($),X=Array.isArray(Z.input)?Z.input:[],Y=X.filter(N$),F=X.findLastIndex(N$),W=F<0?void 0:$4(X[F]),H=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,N,V,P;if(H)N=Y.length>0,V=W??G?.fingerprint,P=G?.userCount===void 0?void 0:G.userCount+Y.length;else{V=W,P=Y.length;let E=F>=0&&F>X.findLastIndex(e0),h=G!==void 0&&!G.completed&&G.fingerprint===V&&G.userCount===P;N=E&&!h}let C=N||!G?{turnID:(z?.uuid??k2)(),turnStartedAt:(z?.now??Date.now)()}:{turnID:G.turnID,turnStartedAt:G.turnStartedAt};return this.#Z($,{...C,completed:!1,fingerprint:V,userCount:P}),C}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 z=this.#$.keys().next().value;if(z===void 0)break;this.#$.delete(z)}}}function b1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var K$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function Z4(){let $=globalThis;return $[K$]??=crypto.randomUUID(),$[K$]}class l2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,z){this.runtime=$;this.store=z;this.installationID=Z??Z4(),this.sessions=z?.sessions??new Map,this.frameTurns=z?.frameTurns??new I2}get($){let Z=this.runtime?.uuid??k2;if(this.store)return this.store.get($,Z);let z=this.sessions.get($);if(!z){let G=Z();z={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,z)}return z}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(J1(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var D1={version:T$,"user-agent":_$,originator:"codex_exec"};var J4=1024,z4=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,G1=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),M$=($)=>G1($)&&($.type==="message"||("role"in $))&&$.role==="user",E$=($)=>G1($)&&$.type==="configuration_update";class k1{http;#$=new Map;constructor($=new l2){this.http=$}apply($,Z,z){if(Z.kind!=="primary")return!1;let G=typeof $.model==="string"?$.model:"";if(!L$.has(G))return!1;if(z4.test(G))return!1;let X=G1($.reasoning)?$.reasoning:void 0,Y=typeof X?.effort==="string"?X.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 W=Array.isArray($.input)?$.input:void 0;if(!W||W.length===0)return!1;let H=W.findLastIndex(M$);if(H<0){if(z==="http")return!1;return $.reasoning={...X,effort:F},!0}if($.reasoning={...X,effort:F},!E$(W[H-1]))W.splice(H,0,{type:"configuration_update",reasoning:{effort:Y}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>J4){let z=this.#$.keys().next().value;if(z===void 0)break;this.#$.delete(z)}}}function J1($){try{let Z=JSON.parse($);return G1(Z)?Z:void 0}catch{return}}async function C$($,Z,z,G,X=z.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Y=await $.clone().text(),F=J1(Y);if(F)delete F.max_output_tokens;let W=new Headers($.headers),H=z1({rewriteLite:P$,init:{body:F?JSON.stringify(F):$.body===null?void 0:Y},headers:W,metadata:X.get(Z.sessionID),installationID:X.installationID,runtime:X.runtime,websocket:!1,responsesLite:G,applyEffort:(N)=>{z.apply(N,Z,"http")}});return new Request($,{headers:W,body:H.init?.body})}function O$($,Z,z,G){let X=G.sessions.get($.sessionID),Y=G.frameTurns.get($.sessionID);if(!X||!Y)return;let F=b1(X,Y),W=new Headers({"content-type":"application/json"});for(let N of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let V=z.get(N);if(V!==null)W.set(N,V)}z1({init:{body:$.bodyText},headers:W,metadata:F,installationID:G.installationID,runtime:G.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let H=new URL(Z);if(H.protocol==="wss:")H.protocol="https:";if(H.protocol==="ws:")H.protocol="http:";return new Request(H,{method:"POST",headers:W,body:$.bodyText})}function G4($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let z=Z.findIndex((G,X)=>JSON.stringify(G)!==JSON.stringify($[X]));return z>=0&&E$(Z[z])&&M$(Z[z+1])&&JSON.stringify(Z.slice(z+1))===JSON.stringify($.slice(z))}function A$($,Z,z){let G=J1($);if(G?.type!=="response.create")return;let X=z.http.advanceFrame(Z.sessionID,G),Y=z.http.get(Z.sessionID);delete G.max_output_tokens;let F=z1({rewriteLite:()=>{},init:{body:JSON.stringify(G)},headers:new Headers,metadata:b1(Y,X),installationID:z.http.installationID,runtime:z.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(H)=>{z.apply(H,Z,"ws")}}),W=J1(String(F.init?.body));if(!W)return;if(!G4(G.input,W.input)){if("input"in G)W.input=G.input;else delete W.input;return JSON.stringify(W)}return String(F.init?.body)}function Q4($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function w1($,Z){let z=new URL($);if(z.origin!=="https://api.openai.com"&&z.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(z.pathname))return $;let G=new URL(`${Q4(Z)}/responses`);if(G.search=z.search,z.protocol==="ws:"||z.protocol==="wss:")G.protocol=G.protocol==="https:"?"wss:":"ws:";return G.href}import{resolve as y1}from"node:path";var R$=Symbol.for("@cortexkit/openai-auth/opencode2-rate-limits/v1"),x$=globalThis,I1=x$[R$]??new Map;x$[R$]=I1;function S$($){let Z=I1.get($);if(!Z)Z=new Map,I1.set($,Z);return Z}function q$($){return S$(JSON.stringify(["pool",y1($.configPath),y1($.statePath)]))}function b$($){return S$(JSON.stringify(["vault",y1($)]))}import{resolve as D$}from"node:path";var Y4=1024;class Q1{accounts=new Map;limit;constructor($=Y4){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let z=this.accounts.keys().next().value;if(z===void 0)break;this.accounts.delete(z)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var k$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),w$=globalThis,f1=w$[k$]??new Map;w$[k$]=f1;function v1($){let Z=JSON.stringify([D$($.configPath),D$($.statePath)]),z=f1.get(Z);if(!z)z=new Q1,f1.set(Z,z);return z}var E2="openai",X4=60000,h1=1,j4="request refused: no account with a usable credential",C2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function B4($){let Z=C2($)?$.counters:void 0,z=C2(Z)?Z.resetCredits:void 0,G=C2(z)?z.value:void 0;return typeof G==="number"&&Number.isFinite(G)?G:void 0}function c2($){try{return JSON.parse($)}catch{return}}function u2($){let Z=j1($);return Z?B1(Z):void 0}var V4=new Set(["usage_limit_reached","rate_limit_exceeded"]);function c1($,Z,z){return{reason:$.window,...z!==void 0?{status:z}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function W4($,Z){let z=X1($);if(z){let Y=typeof $.status==="number"?$.status:void 0;return c1(z,Z,Y)}if($.type!=="response.failed"||!C2($.response))return;let G=$.response.failed;if(C2(G)&&typeof G.rate_limit_reached_type==="string")return{reason:G.rate_limit_reached_type};let X=$.response.error;if(C2(X)){let Y=typeof X.code==="string"?X.code:typeof X.type==="string"?X.type:void 0;if(Y&&V4.has(Y))return{reason:Y}}return}function U4($,Z){let z=c2($);if(!C2(z))return;let G=typeof z.type==="string"?z.type:void 0;if(G==="codex.rate_limits")return{quota:{snapshot:v$(z),complete:!0}};let X=W4(z,Z);if(X)return{limit:X};if(G===void 0||G==="error")return;return r$(G)?void 0:{outputStarted:!0}}function H4($){let Z=!1;for(let z of $.keys())if(z.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:I$($),complete:f$($)}}function N4($){let Z=$.get("retry-after");if(Z===null)return;let z=Number(Z);return Number.isFinite(z)&&z>=0?z*1000:void 0}function e$($){let Z=new WeakMap,z=new WeakSet,{source:G,pins:X}=$,Y=$.now??Date.now,F=$.log,W=$.vault,H=new k1($.codex),N=new Map,V=new Map,P=(Q)=>`${Q.sessionID}\x00${Q.kind}`,C=new Map,E=(Q)=>`${Q.sessionID}\x00${Q.kind}\x00${Q.accountId}`,h=W?.paths?.rosterPath,a=h?b$(h):new Map,A=$.sessionAccounts??new Q1,k=new i$,W2=(Q,K,_)=>{let M=_?[]:t$(G.peek().rows,Q,K,W?.identities()??new Set),D=(W?.routes()??[]).filter((O)=>O.kind==="oauth"&&g$(d2(O.quota),Q,K));return[...M.map((O)=>({id:O.id,...O.identity!==void 0?{identity:O.identity}:{},quota:O.quota,row:O})),...D.map((O)=>({id:O.id,...O.identity!==void 0?{identity:O.identity}:{},quota:O.quota}))]},X2=(Q,K,_)=>{let M=c$(Q,K,_),D=Q.map((q)=>({id:q.id,kind:"oauth",...y$(q.quota)?{quota:q.quota}:{}})),O=Q.flatMap((q)=>q.row?[q.row]:[]),R=new Set(Q.filter((q)=>!q.row).map((q)=>q.id)),f=G.rateLimitMarks(O);for(let q of R){let w=a.get(q);if(w===void 0)continue;if(w<=_)a.delete(q);else f.set(q,w)}return{rows:D,now:_,rateLimitMarks:f,refreshBackoff:G.refreshBackoffFor(O),killswitch:M,requestPull:(q)=>R.has(q)?W?.requestReading(q):G.requestReading(q)}},v=(Q,K,_,M,D)=>{let O=l1({...Q,placement:m1(K),mainId:D});if(O.kind==="block"){F?.debug("pool admission refused the request",{reason:O.block.reason});return}let R=O.order.filter((f)=>!_.has(f));if(M!==void 0&&R.includes(M))return M;return R[0]},n=(Q,K)=>{let _=new Map(Q.map((M)=>[M.id,M.quota]));return{requestBytes:h1,reservePercent:(M)=>m$(K,M===p$?void 0:M),resetCredits:(M)=>B4(_.get(M))}},K2=(Q,K,_,M,D,O,R,f)=>{let q=n(K,_),w=u1(Q),y=(c,m)=>V1(R,{sessionId:M,requestBytes:h1,validPinnedAccountIds:Q.rows.map(($2)=>$2.id).filter(($2)=>!w.excluded.has($2)),excludeAccountIds:c,quotaCheckedAtByAccount:Object.fromEntries(Q.rows.map(($2)=>[$2.id,w.projections.get($2.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(K.map(($2)=>[$2.id,$2.identity])),select:($2)=>f?{accountId:f,source:"mode-fallback",quotaCheckedAt:w.projections.get(f)?.checkedAt}:a$(Q,q,new Set(c),$2),persist:m},($2,T2)=>R.set($2,T2)),J2=[...D],G2=y(J2,O);if(!G2)return;let e=G2.accountId,s=p1(Q,q,e);if(s.kind==="none")return;if(s.kind==="move"){let c=y([...J2,e],O);if(c)return c.accountId;return s.reason==="killswitch"?void 0:e}if(s.kind==="detour")return y([...J2,e],!1)?.accountId;return e},b={providerID:E2,async retrySameAccount(Q){if(Q.continuation!=="interrupted-read")return;let K=V.get(P(Q));if(V.delete(P(Q)),!K||K.accountId!==Q.accountId||K.modelID!==Q.modelID||K.agent!==Q.agent||Q.limit)return;let _=W!==void 0&&await W.authority()!=="local",M=await $.storage();if(!_&&!(await G.current()).active)return;let D=Y(),O=W2(M,D,_),R=O.find((y)=>y.id===Q.accountId);if(!R)return;let f=X2(O,M,D),q=M?.routing?.mode??"main-first";if(q==="sticky-balanced"){let y=p1(f,n(O,M),Q.accountId);if(y.kind!=="serve"&&y.kind!=="last-path")return}else{let y=l1({...f,placement:m1(q),..._?{mainId:g1(W?.routes()??[])}:{}});if(y.kind==="block"||!y.order.includes(Q.accountId))return}let w=K.data;if(R.row){if(w?.kind!=="pool")return;let y=G.usableToken(R.row),J2=R.row.identity??(y&&u2(y));if(!y||!w.identity||J2!==w.identity)return}else{if(w?.kind!=="vault"||!W)return;let y=await W.authorize(Q.accountId);if(!y||y.credentialId!==w.credentialId||y.accountIdentity!==w.accountIdentity||(y.accountIdentity??u2(y.accessToken))!==w.wireIdentity||R.identity!==void 0&&R.identity!==w.wireIdentity)return}return{accountId:Q.accountId}},dropSameAccountRetry(){},dropChoice(Q){let K=E(Q);C.get(K)?.drop(),C.delete(K),N.delete(K)},chooseAccount:async(Q)=>{let K=await W?.authority(),_=await $.storage(),M=K!==void 0&&K!=="local",D=()=>{throw new F2({kind:"no-account",providerID:E2,sessionID:Q.sessionID,requestKind:Q.kind,message:W1})};if(M)await $.awaitVaultRoster?.();else{if(!(await G.current()).active){if(await $.slotPlaceholderWithoutMain?.())D();F?.warn("the account pool does not serve requests yet; refusing the request",{kind:Q.kind});return}await G.prepareTokens(G.peek().rows,_)}let O=Y(),R=W2(_,O,M),f=d$(X2(R.filter((T)=>T.id!==Q.rerouteFrom?.accountId),_,O));if(f)await f,O=Y(),R=W2(_,O,M);let q=new Map(R.map((T)=>[T.id,T])),w=X2(R,_,O),y=new Set(Q.rerouteFrom?[Q.rerouteFrom.accountId]:[]),J2=_?.routing?.mode??"main-first",G2=Q.kind==="primary",e=new Set,s,c,m,$2=!1,T2=(T)=>{let l=u1(w).projections.get(T)?.checkedAt,Z2=q.get(T)?.identity;return X.reserve(Q.sessionID,{accountId:T,inputBytes:h1,...l!==void 0?{quotaCheckedAt:l}:{},...Z2!==void 0?{wireIdentity:Z2}:{}})};try{for(;;){let T=new Set([...y,...e]);m=void 0,s=void 0;let l=J2!=="sticky-balanced";if(J2==="sticky-balanced"){let t=new Map(X.placementSnapshot(Q.sessionID)),B2=t.get(Q.sessionID);if(l=B2===void 0,m=K2(w,R,_,Q.sessionID,T,G2&&e.size===0,t),m!==void 0&&t.get(Q.sessionID)!==B2)s=t.get(Q.sessionID)}if(m??=v(w,J2,T,G2?void 0:A.activeAccount(Q.sessionID),M?J2==="sticky-balanced"?null:g1(W?.routes()??[]):void 0),m===void 0||e.has(m)){if(y.size>0){let t=new Map(w.rateLimitMarks);for(let B2 of y)t.delete(B2);w={...w,rateLimitMarks:t},y.clear();continue}if(w.rateLimitMarks.size>0){w={...w,rateLimitMarks:new Map};continue}m=void 0;break}if(G2&&J2==="sticky-balanced")c=T2(m);if(!$2){$2=!0;let t=await n$({vaultMode:M,fresh:l,sessionId:Q.sessionID,request:{modelId:Q.modelID,kind:Q.kind,retry:Q.phase==="retry"||Q.rerouteFrom!==void 0},routes:W?.routes()??[],routing:w,eligibleIds:R.filter((B2)=>!T.has(B2.id)).map((B2)=>B2.id)});if(t&&t!==m){if(c)X.rollback(c);if(c=void 0,J2==="sticky-balanced"){let B2=new Map(X.placementSnapshot(Q.sessionID));m=K2(w,R,_,Q.sessionID,T,G2,B2,t)??m,s=B2.get(Q.sessionID)??s}else m=t;if(G2&&J2==="sticky-balanced")c=T2(m)}}let Z2=q.get(m)?.row;if(Z2){if(G.usableToken(Z2)!==void 0)break;F?.debug("pool row holds no usable token; choosing again",{accountId:m})}else{if(!W)break;let t=await W.authorize(m);if(t){N.set(E({...Q,accountId:m}),t);break}F?.debug("the vault refused to serve an account; choosing again",{accountId:m})}if(c)X.rollback(c);c=void 0,e.add(m)}if(m===void 0&&!M&&R.length===0&&await $.slotPlaceholderWithoutMain?.())D();if(m===void 0&&M&&W&&(R.length===0||e.size>0)){let T=e.size>0?"vault-refused":u$(W);throw F?.warn("vault mode: no vault account can serve; refusing the request",{cause:T}),new F2({kind:"no-account",providerID:E2,sessionID:Q.sessionID,requestKind:Q.kind,message:l$(T,W.name)})}if(m!==void 0){let T=m,l=c,Z2=s,t=()=>{if(l)X.finish(l,Z2);if(G2)A.record(Q.sessionID,T),$.onRoute?.(Q.sessionID,T,J2)};if(Q.phase==="retry")C.set(E({...Q,accountId:m}),{commit:t,drop:()=>{if(l)X.rollback(l)}}),c=void 0;else t();let B2=F?.info;k.served(w,m,F&&B2?{info:(w2,r2)=>B2.call(F,w2,r2)}:void 0)}return F?.debug("pool account chosen",{kind:Q.kind,accountId:m,mode:J2,...Q.rerouteFrom?{rerouteFrom:Q.rerouteFrom.accountId}:{}}),m}finally{if(c)X.rollback(c)}},accountHeaders:async(Q)=>{let{accountId:K}=Q;V.delete(P(Q));let _=E(Q),M=C.get(_);C.delete(_);let D=()=>{M?.commit()};try{let O=()=>new F2({kind:"no-account",providerID:E2,sessionID:Q.sessionID,requestKind:Q.kind,message:j4}),R=W&&await W.authority()!=="local"?void 0:G.peek().rows.find((w)=>w.id===K);if(!R&&W){let w=E(Q),y=N.get(w)??await W.authorize(K);if(N.delete(w),!y)throw F?.warn("the vault refused to serve an account; refusing the request",{accountId:K}),O();return D(),{headers:{...D1,"session-id":Q.sessionID,authorization:`Bearer ${y.accessToken}`,"chatgpt-account-id":y.accountIdentity??u2(y.accessToken)??null},attempt:{kind:"vault",routeId:K,receipt:y}}}let f=R?G.usableToken(R):void 0;if(!R||!f)throw F?.warn("pool row holds no usable token; refusing the request",{accountId:K}),O();let q=R.identity??u2(f);return D(),{headers:{...D1,"session-id":Q.sessionID,authorization:`Bearer ${f}`,"chatgpt-account-id":q??null},attempt:{kind:"pool",token:f,credentialEpoch:R.credentialEpoch,...q!==void 0?{identity:q}:{}}}}finally{M?.drop()}},async rewriteRequest({request:Q,sessionID:K,kind:_}){let M=$.codexEndpoint?w1(Q.url,$.codexEndpoint()):Q.url,D=M===Q.url?Q:new Request(M,Q);return await C$(D,{sessionID:K,kind:_},H,$.responsesLite?.()??!1)??D},rewriteHandshakeURL:({url:Q})=>$.codexEndpoint?w1(Q,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:Q,sessionID:K,kind:_})=>A$(Q,{sessionID:K,kind:_},H),quotaFromHeaders:(Q,K,_)=>{if(_.data?.kind==="vault")W?.reportUsage(_.data.routeId,{headers:Q},_.data.receipt);if(_.data?.kind==="vault"&&p2()&&K>=200&&K<300)Z.set(_,{status:K,headers:Q});return H4(Q)},async limitFromResponse({status:Q,headers:K,body:_,attempt:M}){if(Q<400)return;let D=c2(await _().catch(()=>"")),O=X1({...C2(D)?D:{},status:Q});if(M.data?.kind==="vault"&&p2())Y1(M.sessionID,M.data.receipt,{status:Q,headers:K,body:D,limit:O,quota:W?.routes().find((w)=>w.id===M.accountId)?.quota,now:Y()});if(!O)return;let R=Y(),f=c1(O,R,Q);if(f.retryAfterMs!==void 0)return f;let q=N4(K);return q===void 0?f:{...f,retryAfterMs:q}},inspectEvent:({data:Q,transport:K,attempt:_})=>{if(_.data?.kind==="vault"&&Q.includes("codex.rate_limits")){let M=c2(Q);if(C2(M)&&M.type==="codex.rate_limits")W?.reportUsage(_.data.routeId,{frame:M},_.data.receipt)}if(_.data?.kind==="vault"&&p2()&&(s$(Q)||K==="ws"&&Q.includes('"response.completed"'))){let M=c2(Q);if(o$(M))z.add(_);if(K==="ws"&&C2(M)&&M.type==="response.completed")Y1(_.sessionID,_.data.receipt,{status:200,headers:new Headers,failed:z.has(_)})}return U4(Q,Y())},limitFromError(Q){let K=c2(Q.message),_=X1({...C2(K)?K:{},...Q.status!==void 0?{status:Q.status}:{}})??(Q.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return _?c1(_,Y(),Q.status):void 0},async onAttemptEnd(Q,K){let _=Q.data;if(_&&K.outputStarted&&K.error?.reason==="failed"){if(V.set(P(Q),{accountId:Q.accountId,modelID:Q.modelID,agent:Q.agent,sessionID:Q.sessionID,data:_.kind==="pool"?{kind:"pool",identity:_.identity}:{kind:"vault",credentialId:_.receipt.credentialId,accountIdentity:_.receipt.accountIdentity,wireIdentity:_.receipt.accountIdentity??u2(_.receipt.accessToken)}}),V.size>Z1){let D=V.keys().next().value;if(D!==void 0)V.delete(D)}}let M=_?.kind==="vault"&&p2()?Z.get(Q):void 0;if(Z.delete(Q),_?.kind==="vault"&&M&&!K.error&&!K.limit)Y1(Q.sessionID,_.receipt,{...M,failed:z.has(Q)});if(_?.kind!=="vault"||K.status!==401)return;F?.warn("a vault account answered 401; reporting it to the vault",{accountId:Q.accountId}),await W?.reportFailure(_.receipt,401)}},g=(Q,K,_)=>{let M=_.data;if(M?.kind==="vault"){W?.recordSnapshot(Q,K.snapshot,K.complete,M.receipt);return}if(M?.kind!=="pool")return;if(G.peek().rows.find((O)=>O.id===Q)?.credentialEpoch!==M.credentialEpoch){F?.debug("quota reading dropped: the row holds another credential",{accountId:Q});return}G.recordSnapshot(Q,K.snapshot,M.token,K.complete)},p=(Q,K,_)=>{let M=Y(),D=_.data?.kind==="vault",O=D?W?.routes().find((q)=>q.id===Q)?.quota:G.peek().rows.find((q)=>q.id===Q)?.quota,R=h$(d2(O),K.reason,M,X4,K.retryAfterMs!==void 0?M+K.retryAfterMs:void 0);if(!D){G.markRateLimited(Q,R);return}let f=a.get(Q);if(f===void 0||f<R)a.set(Q,R)};return{adapter:b,attach(Q){Q.on("quota",(K)=>g(K.accountId,K.quota,K.handle)),Q.on("limit",(K)=>{p(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(Q){for(let[K,_]of V)if(_.sessionID===Q)V.delete(K);X.forget(Q),A.forget(Q),H.forget(Q)},activeAccount:(Q)=>A.activeAccount(Q)}}import{resolve as QZ}from"node:path";import{Buffer as F4}from"node:buffer";import{resolve as $Z}from"node:path";function i2($){return F4.byteLength(JSON.stringify($))}function K4($){return $.reduce((Z,z)=>Z+i2(z),0)}function d1($,Z){return 2+$+Math.max(0,Z-1)}function T4($){let{head:Z,pending:z}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+d1(Z.inputBytes,Z.input.length)+1:0)+(z?20+d1(z.inputBytes,z.input.length)+10+d1(z.outputBytes,z.output.length)+(z.responseID===void 0?0:14+z.responseIDBytes)+1:0)}function ZZ($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class JZ{enabled;caps=U1;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 z=ZZ(Z);if(z?.type!=="response.create")return;if(!Array.isArray(z.input)){this.forget($);return}let G=z.previous_response_id,X=this.entries.get($),Y=X?.head;if(G&&G!==Y?.responseID){this.forget($);return}let{type:F,previous_response_id:W,input:H,...N}=z;this.keep($,{fields:G&&X?X.fields:N,fieldsBytes:G&&X?X.fieldsBytes:i2(N),...G&&Y?{head:Y}:{},pending:{input:H,inputBytes:K4(H),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,z){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 X=ZZ(Z);if(!X)return;let Y=G.pending,F=X.response;if(X.type==="response.created"&&typeof F?.id==="string")Y.responseID=F.id,Y.responseIDBytes=i2(F.id),this.keep($,G);else if(X.type==="response.output_item.done"&&X.item){if(typeof X.response_id==="string"&&Y.responseID!==void 0&&X.response_id!==Y.responseID)return;Y.output.push(X.item),Y.outputBytes+=i2(X.item),this.keep($,G)}else if(X.type==="response.completed"&&typeof F?.id==="string"){if(F.id===G.head?.responseID||Y.responseID!==void 0&&F.id!==Y.responseID)return;let W={responseID:F.id,responseIDBytes:Y.responseID===F.id?Y.responseIDBytes:i2(F.id),input:[...G.head?.input??[],...Y.input,...Y.output],inputBytes:(G.head?.inputBytes??0)+Y.inputBytes+Y.outputBytes},H={...G,head:W,pending:void 0};if(!this.keep($,H))return;z?.({sessionID:$,responseID:W.responseID,bodyText:this.body(G.fields,W)})}}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 z=T4(Z);if(this.forget($),z>this.caps.maxBytes)return!1;Z.bytes=z,this.entries.set($,Z),this.bytes+=z;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 zZ=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),GZ=globalThis,i1=GZ[zZ]??new Map;GZ[zZ]=i1;function H1($){let Z=JSON.stringify([$Z($.configPath),$Z($.statePath)]),z=i1.get(Z);if(!z)z=new JZ,i1.set(Z,z);return z}var _4=5000,L4=["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"],P4=["x-opencode-parent-session-id","x-parent-session-id"];function BZ($){let Z=YZ($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:XZ($?{...$,cachekeep:Z}:$)}}var VZ=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),WZ=globalThis,a2=WZ[VZ]??new Map;WZ[VZ]=a2;function M4($,Z){let z=[],G=()=>z.at(-1)?.location,X=()=>{let H=G();if(!H)throw Error("no location holds keep-warm");return H},Y=(H,N)=>{W.remove(H),G()?.log?.debug(`cachekeep dropped target (${N})`,{sessionKey:H})},F=async(H)=>{if(H.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let N=H.accountId??"main",V=X(),P=await V.source.accessFor(N,await V.storage());if(!P)throw Error(`pool row ${N} has no usable token`);return{token:P.token,identity:P.row.identity}},W=jZ({...U1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(H,N)=>X().fetch(H,N),logger:{debug:(H,N)=>G()?.log?.debug(H,N),warn:(H,N)=>G()?.log?.warn(H,N)},getWindow:()=>G()?.settings().window,getSustain:()=>G()?.settings().sustain===!0,resolveLocal:F,vault:{owns:(H)=>G()?.vault.owns(H)===!0,authority:()=>X().vault.authority(),reportUsage:(...H)=>G()?.vault.reportUsage(...H),send:async(H,N,V)=>{let P=X();if(await P.vault.authority()!=="vault")return;return P.vault.send(H,N,V)}},activeAccount:(H)=>{if(H===void 0)throw Error("target has no session");let N=G(),V=N?.settings();if(!N||!V?.enabled){Y(H,"keep-warm is off");return}if(!V.subagents&&W.status().targets.some((C)=>C.sessionKey===H&&C.isSubagent)){Y(H,"subagent warming is off");return}let P=N.accounts.activeAccount(H);if(P===void 0){Y(H,"no account recorded for the session");return}return P},verifyCredential:({target:H,mode:N,identity:V})=>{if(H.meta.credentialMode!==N)throw Error(`a target captured in ${H.meta.credentialMode??"an unknown"} mode is not warmed with a ${N} credential`);if(V!==H.meta.chatgptAccountId)throw Y(H.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:W,settings:Z,holders:z,joinTimeoutMs:$.joinTimeoutMs??_4}}function E4($){try{let Z=JSON.parse($),z=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(z?.role!=="user")return!1;return(typeof z.content==="string"?z.content:Array.isArray(z.content)?z.content.map((X)=>typeof X?.text==="string"?X.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function C4($){let Z={};for(let z of L4){let G=$.get(z);if(G)Z[z]=G}return Z}function UZ($,Z,z){let G=JSON.stringify([QZ($.configPath),QZ($.statePath)]),X=a2.get(G);if(!X)X=M4(z,Z.settings()),a2.set(G,X);let Y=X,F=H1($);F.setEnabled(Y.settings.enabled);let W={location:{...Z,settings:()=>Y.settings}};Y.holders.push(W);let H=!1,N=async(V)=>{try{let P=W.location.settings();if(H||!P.enabled)return;if(V.kind!=="primary"){if(V.kind==="generate"&&E4(await V.request.clone().text())){if(H)return;Y.manager.remove(V.sessionID)}return}let C=V.attempt.data,E=C?.kind==="pool"?"local":C?.kind==="vault"?"vault":void 0;if(!E)return;let h=V.request.headers,a=P4.some((W2)=>h.has(W2))||Z.parentOf!==void 0&&await Z.parentOf(V.sessionID)!==void 0;if(a&&!P.subagents)return;let A=await V.request.clone().text();if(H)return;let k=h.get("chatgpt-account-id")??void 0;Y.manager.track({sessionKey:V.sessionID,bodyText:A,accountId:V.attempt.accountId,isSubagent:a,meta:{replayHeaders:C4(h),...k?{chatgptAccountId:k}:{},routingSessionId:V.sessionID,url:V.request.url,credentialMode:E}})}catch(P){Z.log?.warn("cachekeep capture failed",{error:P instanceof Error?P.message:String(P)})}};return{manager:Y.manager,configure:(V)=>{Object.assign(Y.settings,V),F.setEnabled(Y.settings.enabled)},capture:N,forget:(V)=>Y.manager.remove(V),async release(){if(H)return;H=!0;let V=Y.holders.indexOf(W);if(V>=0)Y.holders.splice(V,1);if(Y.holders.length>0)return;if(a2.get(G)===Y)a2.delete(G);Y.manager.stop();let P;try{await Promise.race([Y.manager.tick().catch(()=>{}),new Promise((C)=>{P=setTimeout(C,Y.joinTimeoutMs),P.unref?.()})])}finally{clearTimeout(P)}}}}import{mkdirSync as O4}from"node:fs";import{dirname as A4,resolve as R4}from"node:path";function x4(){return HZ("opencode2")}var S4=2000;class _Z{path;options;sessions;frameTurns=new I2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Q=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=KZ($,Z.uuid??k2)}get($,Z=k2){let z=this.sessions.get($);if(!z){let G=Z();z={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,z),this.#Z.delete($),this.#z.delete($),this.#$.add($),this.#Y()}return z}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??S4),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{$=a1(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 X=this.sessions.get(G);return X?[[G,X]]:[]}),Z=[...this.#Z],z=null;try{if(O4(A4(this.path),{recursive:!0}),z=await this.#B(),!z)return;let G;try{G=a1(this.path)}catch{G=new Map}await this.options.afterRead?.();let X=!1;for(let Y of Z)if(G.delete(Y))X=!0;for(let[Y,F]of $){if(G.get(Y)===F.threadID)continue;G.set(Y,F.threadID),X=!0}if(X)TZ(this.path,G)}catch{return}finally{await z?.release().catch(()=>{})}for(let[G,X]of $)if(this.sessions.get(G)===X)this.#$.delete(G);for(let G of Z)if(!this.sessions.has(G))this.#Z.delete(G)}#B(){return FZ(this.path,this.options.lockWaitMs??NZ)}}var LZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),PZ=globalThis,N1=PZ[LZ]??new Map;PZ[LZ]=N1;function q4($){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 MZ($=x4()){let Z=R4($),z=N1,G=N1.get(Z),X=N1;if(G!==void 0&&!q4(G))z.compatible??=new Map,X=z.compatible;let Y=X.get(Z);if(!Y)Y=new _Z(Z),X.set(Z,Y);let F=Y;return F.frameTurns??=new I2,Y}var n1=Symbol.for("cortexkit.openai-auth.v2.commands"),b4=R2("v2-command");function F1($){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 o1($){b4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function D4(){let $=globalThis;return $[n1]??={locations:new Map},$[n1].locations??=new Map,$[n1]}async function SZ($,Z){let z=D4(),G=$.location.directory,X={menu:Z,session:$.session,closed:new AbortController},Y=await CZ(G),F=await EZ(RZ,Y.dir,()=>xZ({...Y,drain:AZ,apply:(P)=>{let C=z.locations.get(G);if(!F1(C))throw Error("The OpenAI menu location was closed");return C.menu.apply(P)}})),W=z.locations.get(G);if(z.locations.set(G,X),F1(W))W.closed.abort(),await W.registration?.dispose();let H={name:"openai",description:"OpenAI account menu",async execute(P){let C=[...z.locations.values()].find(F1)?.session;if(!C)return o1("no live location");let E=await C.get({sessionID:P.sessionID}),h=z.locations.get(E.location.directory);if(!F1(h))return o1("location closed");let a=await OZ(P.sessionID,h.closed.signal);if(!a||z.locations.get(E.location.directory)!==h){if(!a&&!h.closed.signal.aborted)s1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},P.sessionID);return o1(h.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let A=await h.menu.open(P.sessionID);s1(A,P.sessionID)}};z.command??=H,z.command.execute=H.execute;let N=z.command;try{X.registration=await $.command.transform((P)=>{P.add(N)})}catch(P){if(X.closed.abort(),z.locations.get(G)===X)z.locations.delete(G);throw await F.release(),P}let V=!1;return async()=>{if(V)return;if(V=!0,X.closed.abort(),z.locations.get(G)===X)z.locations.delete(G);await F.release(),await X.registration?.dispose()}}var k4="openai-auth-pool-browser",w4="openai-auth-pool-headless",y4="openai-auth-vault",I4="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 n2($){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 yZ($){return{method:{id:y4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await qZ($.paths,$.name)!=="vault")throw Error(I4)}}}function IZ($){let Z=(z,G,X)=>({method:{id:z,type:"oauth",label:G},async authorize(){if($.vault)await n2($.vault);let Y=await $.beginLogin({version:$.version,headless:X});return{url:Y.url,instructions:Y.instructions,mode:"auto",callback:Y.completion}}});return[Z(k4,"ChatGPT (openai-auth pool, browser)",!1),Z(w4,"ChatGPT (openai-auth pool, headless)",!0)]}function r1($){let Z=(z)=>typeof z==="string"?z:"";return m2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===kZ||bZ($)}function f4($){if($.accountId)return $.accountId;let Z=$.access?j1($.access):void 0;return Z?B1(Z):void 0}async function fZ($,Z,z,G={}){if(G.vault)await n2(G.vault);if(r1(z))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let X=DZ($,{rowLocks:(E)=>wZ(Z,E)}),Y=await X.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:z.refresh,...z.access!==void 0?{access:z.access}:{},...z.expires!==void 0?{expires:z.expires}:{}},W=f4(z);if(G.vault)await n2(G.vault);let H=W!==void 0?{identity:W}:{};if(G.origin==="import"){let E=Y.rows.find((h)=>W!==void 0&&h.identity===W||h.credential?.type==="oauth"&&h.credential.refresh===z.refresh);if(E)return{id:E.id,operation:"kept"}}let N=Y.rows.filter((E)=>E.type==="oauth"&&!E.invalid),V=W?N.find((E)=>E.identity===W):void 0,P=Y.rows.find((E)=>E.id===K1);if(V)return{id:(await X.replace(V.id,F,H)).id,operation:"replaced"};if(!P){let E=await X.add({id:K1,credential:F,...H,...z.label!==void 0?{label:z.label}:{}});return{id:E.id,operation:E.outcome==="added-disabled"?"added-disabled":"added"}}if(!P.invalid&&!P.credential)return{id:(await X.replace(K1,F,H)).id,operation:"replaced"};let C=await X.add({id:z.id,credential:F,...H,...z.label!==void 0?{label:z.label}:{}});return{id:C.id,operation:C.outcome==="added-disabled"?"added-disabled":C.outcome==="rotated"?"replaced":"added"}}function v4($){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 gZ($){let Z={...$,allowAction:v4,unavailableSections:[]};return{open:(z)=>vZ(Z,z),apply:(z)=>{let G=z!==null&&typeof z==="object"?z:{},X=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 hZ(Z,{command:"openai",sectionId:typeof G.sectionId==="string"?G.sectionId:"",actionId:typeof G.actionId==="string"?G.actionId:"",...X?{values:X}:{},...G.confirmed===!0?{confirmed:!0}:{},...typeof G.itemId==="string"?{itemId:G.itemId}:{},...typeof G.sessionId==="string"?{sessionId:G.sessionId}:{}})}}}function h4($,Z){if(!mZ($.modelID??$.id)){$.enabled=!1;return}let z=lZ($.id);if(z)$.limit={...z};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((G)=>[G.id,G])).values()]}function pZ($){return $.model.transform((Z)=>{let z=Z.list(E2);for(let G of z){let X=uZ(String(G.id)),Y=X?z.find((F)=>String(F.id)===X):void 0;Z.update(E2,String(G.id),(F)=>h4(F,Y?.variants?.map((W)=>({...W,id:String(W.id)}))))}})}class t1{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(!cZ())return;await this.safely(async()=>{let z={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:z}),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 z=this.take($);if(z)await this.safely(()=>T1({...z,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let z=this.requests.get($.attemptId),G=z&&this.take(z);if(!G)return;let{reason:X,message:Y}=Z.error,F=Y?`${X}: ${Y}`:X;await this.safely(()=>T1({...G,error:_1(F,z?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>T1({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 e1{counts=new Map;record($,Z){let z=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof z==="number"&&Number.isFinite(z)?z:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function oZ($){return async(Z)=>{let z=Z.credential;if(z.type!=="oauth"||!z.access)throw Error("the row holds no access token to poll with");let G=await dZ({accessToken:z.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 sZ($){let{source:Z,counts:z,now:G}=$,X=async(N)=>{let V=await Z.rowAccess(N,await $.storage());if(!V?.row)throw new aZ("unknown_account",`${N==="main"?"Main":"Fallback"} account ${N} was not found.`);return nZ(N,V)},Y=async(N)=>{if($.authority&&await $.authority()!=="local")return{account:N,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[V]=await Z.pollRows(await $.storage(),{ids:[N]});if(!V)return{account:N,ok:!1,error:"targeted quota refresh returned no result"};return{account:V.id,ok:V.ok,...V.error!==void 0?{error:V.error}:{}}},F=(N)=>Z.peek().rows.find((V)=>V.id===N),W=(N)=>{let V=F(N);if(!V)return null;let P=d2(V.quota)??{},C=z.applicable(V),E=Math.max(0,...[P.primary?.checkedAt,P.secondary?.checkedAt].filter((h)=>typeof h==="number"));return{quota:{...P,...C!==void 0?{resetCreditsApplicable:C}:{}},checkedAt:E,refreshAfter:E,...V.identity!==void 0?{accountId:V.identity}:{}}};return{resolveResetTarget:X,refreshResetTargetQuota:Y,quotaManager:{isRateLimited:(N)=>{let V=F(N);if(!V)return!1;let P=Z.rateLimitMarks([V]).get(V.id);return P!==void 0&&P>G()},getMain:()=>W("main"),getFallback:(N)=>W(N)}}}import{resolve as rZ}from"node:path";var g4=1024;class $${pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=g4){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 z of this.reservations.values())if(z.sessionId!==$)Z.set(z.sessionId,z.pin);return Z}reserve($,Z){let z={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,z),z}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 z of this.listeners)z($,Z);while(this.pins.size>this.limit){let z=this.pins.keys().next().value;if(z===void 0)break;this.forget(z)}}place($){return V1(this.placementSnapshot($.sessionId),$,(Z,z)=>this.set(Z,z))}}var tZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),eZ=globalThis,L1=eZ[tZ]??new Map;eZ[tZ]=L1;function m4($){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 $0($){let Z=JSON.stringify([rZ($.configPath),rZ($.statePath)]),z=L1,G=L1.get(Z);if(G!==void 0&&!m4(G)){let Y=L1;Y.compatibleV1??=new Map,z=Y.compatibleV1}let X=z.get(Z);if(!X)X=new $$,z.set(Z,X);return X}import{statSync as l4}from"node:fs";import{resolve as u4}from"node:path";function B0($){return $.map((Z)=>{try{let z=l4(Z);return`${z.ino}:${z.size}:${z.mtimeMs}:${z.ctimeMs}`}catch{return"?"}}).join("|")}function Z$($){return B0([$.vault.paths.tokenPath,$.vault.paths.statePath])}function Z0($){return B0([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+Z$($)}class V0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;protocol=U0;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:Z0($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),z=this.subscriptions.get($.pins);if(!z){let G=new Set;z={producers:G,stop:$.pins.subscribe((X,Y)=>{let F=G.values().next().value;if(F)this.publish(F,{sessionId:X,pin:Y,accountId:Y?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,z)}return z.producers.add($),this.timer??=setInterval(()=>{for(let G of this.producers){let X={stamp:Z0(G),roster:G.vault.snapshot()},Y=this.observations.get(G);if(X.stamp!==Y?.stamp||X.roster!==Y?.roster)this.observations.set(G,X),this.publish(G)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),z.producers.delete($),!z.producers.size)z.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;await($.write??W0)(this.file,$,Z,()=>this.producers.has($))}).catch(()=>{R2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var W0=async($,Z,z,G)=>{let Y=await Z.vault.authority()!=="local",F=Z$(Z),W=()=>G()&&Z.vault.enrolled()===Y&&Z$(Z)===F,H=await(Y?s2(Z.paths):f2(Z.paths)),N=Y?X0(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((C)=>C.id)),H,Date.now()):j0((await Z.source.sidebarView()).rows,H,Date.now()),V={canWrite:W,vaultMode:Y};if(await z0(N,$,V),!W()||!z)return;let P=N.vaultAccounts??N.fallbacks;if(z.accountId===void 0){await Q0(z.sessionId,P,$,V);return}if(z.pin){let C=Date.now();await Y0({sessionId:z.sessionId,assignment:{accountId:z.pin.accountId,wireAccountId:z.pin.wireIdentity,inputBytes:z.pin.inputBytes??0,quotaCheckedAt:z.pin.quotaCheckedAt,assignedAt:C,lastSeenAt:C},validPinnedAccountIds:[...Y?[]:["main"],...P.filter((E)=>E.enabled).map((E)=>E.id)]},$,V)}await G0({sessionId:z.sessionId,activeId:z.accountId,route:z.route??N.route,updatedAt:Date.now()},P,$,V)},U0=2,H0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),N0=globalThis,o2=N0[H0]??new Map;N0[H0]=o2;function F0($,Z=J0(),z=2000){let G=u4(Z),X=o2.get(G);if(X?.protocol!==U0)X=new V0(G,z),o2.set(G,X);let Y=X;$={...$,write:$.write??W0};let F=Y.add($),W=!1;for(let[H,N]of $.pins.snapshot())Y.publish($,{sessionId:H,pin:N,accountId:N.accountId,route:"sticky-balanced"});return{publish:()=>Y.publish($),route:(H,N,V)=>{Y.publish($,{sessionId:H,accountId:N,route:V})},async release(){if(W)return;if(W=!0,F(),await Y.settled(),Y.empty&&o2.get(G)===Y)o2.delete(G)}}}var E1="cortexkit-openai-auth",d4=5000;async function K0($,Z,z,G=new l2,X,Y,F){let W=new t1(z),H=new p4,N=new Map,V=new Map,P=(A)=>{V.delete(A);for(let k of N.keys())if(k.startsWith(`${A}:`))N.delete(k)},C=(A)=>{F?.(A.sessionID),Y?.send(A.sessionID,A.frame)},h=await q1({session:{hook:(A,k,W2)=>$.session.hook(A,async(X2)=>{let v=A==="http.request"?X2:void 0,n=A==="experimental.ws.handshake"?X2:void 0,U2=(v?v.request.headers:n?new Headers(n.headers):void 0)?.get("authorization")===`Bearer ${A2(Z.providerID)}`,j2={};if(n)N.delete(`${n.sessionID}:${n.kind}`);try{await H.run(j2,()=>k(X2))}catch(b){if(U2&&!(b instanceof F2))throw E0(b);throw b}if(v&&U2&&j2.attempt){let b=v.request.headers.get("thread-id");if(b)v.request.headers.set("session-id",b)}if(v&&U2&&j2.attempt)await W.captureHttp(v.request,j2.attempt);if(v&&U2&&j2.attempt)await X?.({sessionID:v.sessionID,kind:v.kind,request:v.request,attempt:j2.attempt});if(n&&U2&&j2.attempt)n.headers["session-id"]=G.get(n.sessionID).threadID;if(A==="experimental.ws.send"){let b=X2,g=N.get(`${b.sessionID}:${b.kind}`);if(g)await W.frame(b.frame,g.attempt);if(g&&b.kind==="primary")C(b)}if(v||n){let b=v??n;if(!b)return;let p=(v?v.request.headers:new Headers(b.headers)).get("authorization")?.replace(/^Bearer /,"");if(U2&&p)V.set(b.sessionID,p);else V.delete(b.sessionID);if(n){let Q=`${n.sessionID}:${n.kind}`;if(U2&&p&&j2.attempt)N.set(Q,{bearer:p,attempt:j2.attempt,url:n.url,headers:new Headers(Object.entries(n.headers).filter(([K])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(K.toLowerCase())))});else N.delete(Q)}if(V.size>512){let Q=V.keys().next().value;if(Q)V.delete(Q)}if(N.size>512){let Q=N.keys().next().value;if(Q)N.delete(Q)}}else if(A==="experimental.ws.receive"){let b=X2,g=N.get(`${b.sessionID}:${b.kind}`);if(g){if(G.frameReceived(b.sessionID,b.frame),b.kind==="primary"){let p;if(Y?.receive(b.sessionID,b.frame,(Q)=>{p=Q}),p)try{let Q=O$(p,g.url,g.headers,G);if(Q)await X?.({sessionID:b.sessionID,kind:"primary",request:Q,attempt:g.attempt})}catch(Q){z.warn("cachekeep WebSocket capture failed",{error:Q instanceof Error?Q.message:String(Q)})}}b.frame=C0(b.frame,g.bearer)}}else if(A==="retry"){let b=X2,g=V.get(b.sessionID);if(g)Object.assign(b.error,{message:_1(b.error.message,g)})}},W2)},event:{subscribe:(A)=>async function*(){for await(let k of $.event.subscribe(A)){if(k.type==="session.deleted")P(k.data.sessionID);yield k}}()}},{...Z,rewriteRequest:async(A)=>{let k=H.getStore();if(k)k.attempt=A.attempt;return Z.rewriteRequest?.(A)},rewriteHandshakeURL:(A)=>{let k=H.getStore();if(k)k.attempt=A.attempt;return Z.rewriteHandshakeURL?.(A)},onAttemptEnd:async(A,k)=>{await W.end(A,k),await Z.onAttemptEnd?.(A,k)},rewriteResponse:async(A)=>{await W.response(A.request,A.response.status);let k=await Z.rewriteResponse?.(A)??A.response;return O0(k,A.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(A)=>{let k=A.get("authorization");return k?.startsWith("Bearer ")?k.slice(7):void 0}},logger:{warn:(A,k)=>z.warn(A,{data:k})}}),a=h.dispose;return{...h,dispose:async()=>{V.clear(),N.clear(),await a(),await W.settle(),W.clear()}}}function G$($={}){return{id:E1,setup:(Z)=>i4(Z,$)}}async function i4($,Z={}){let c=[];try{let z=R2("opencode2");let G=R2("quota");let X=Z.version??R0;await h0({version:X,...Z.runtimeLayout});let Y=Z.paths??(()=>S0(A0()));let F=await s2(Y());let W=F?.logging?.level;if(W&&typeof W==="string")_0(W);let H=Z.fetch??fetch;let N=Z.now??Date.now;let V=Z.poolMigration??m0;if(!V&&!v2(Y().configPath)){z.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 T=(Z2)=>{throw new F2({kind:"no-account",providerID:E2,sessionID:Z2.sessionID,requestKind:Z2.kind,message:W1})},l=await K0($,{providerID:E2,chooseAccount:T,accountHeaders:T},z);return()=>l.dispose()}let P=Z.vault?.firstRosterWaitMs??w0;let C=g0({host:"opencode",stateDir:Z.vault?.stateDir??M0(Y().statePath),reservedRouteIds:()=>v.peek().rows.map((T)=>T.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:()=>H},Y());let E=C.vault;let h=async()=>await E.authority()==="local"?f2(Y()):s2(Y());let a=!1;let A=!1;const k=P1(c,{[Symbol.dispose](){if(!a)C.release()}},0);await E.authority();let W2=C.firstRoster;let X2=new e1;let v=new y0({paths:Y,rateLimitMarks:q$(Y()),refreshProvider:async(T)=>{let l=await P0({refreshToken:T.refresh,fetchImpl:H,now:N}),Z2=L0({id_token:"",access_token:l.access,refresh_token:l.refresh});return{...l,...Z2?{identity:Z2}:{}}},pullQuota:oZ({fetchImpl:H,now:N,counts:X2,logger:G}),now:N,vaultIdentities:()=>E.identities(),vaultMode:()=>E.enrolled(),vaultAuthority:()=>E.authority(),vaultFirstRoster:W2,vaultFirstRosterBackgroundWaitMs:P,log:R2("pool")});if(await E.authority()==="local")await v.load();let n=Z.heartbeat===!1?void 0:await f0({version:X,logger:R2("heartbeat")});let K2=Z.fence??(()=>x0({currentVersion:X}));let U2=Z.slot??l0();let j2=async()=>q0(Y(),await U2.get({path:{id:"openai"}}));let b=!1;let g=V?I0({paths:Y,slot:U2,version:X,fence:K2,runDeps:{vaultServes:()=>E.serves()},paused:async()=>await E.authority()!=="local",migrate:async(T)=>{let l=await b0(T);if(b=l.status==="refused",!A)await v.load();return l},adopt:async(T)=>{if(A)return{status:"retry",reason:"unsettled"};if(!await z$(W2,P))return{status:"retry",reason:"vault-roster-pending"};if(A)return{status:"retry",reason:"unsettled"};let l=await D0(T);if(!A)await v.load();return l}}):void 0;g?.start();C.start();let p=$0(Y());let Q=F0({paths:Y(),source:v,pins:p,vault:E},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const K=P1(c,{[Symbol.dispose](){if(!a)Q.release()}},0);Q.publish();let _=Z.codex??new l2(void 0,void 0,MZ());let M=BZ(F);let D=H1(Y());let O=UZ(Y(),{source:v,storage:h,vault:E,accounts:v1(Y()),settings:()=>M,parentOf:async(T)=>(await $.session.get({sessionID:T}))?.parentID??void 0,fetch:H,log:R2("cachekeep")},{now:N,codexResponsesUrl:M1().codexApiEndpoint,...Z.cacheKeep});const R=P1(c,{[Symbol.dispose](){if(!a)O.release()}},0);let f=e$({codex:_,onRoute:Q.route,source:v,slotPlaceholderWithoutMain:j2,storage:h,pins:p,sessionAccounts:v1(Y()),vault:E,awaitVaultRoster:async()=>{await z$(E.awaitRequestRoster(),k0)},responsesLite:()=>M1().responsesLite,codexEndpoint:()=>M1().codexApiEndpoint,now:N,log:z});let q=await K0($,f.adapter,z,_,(T)=>O.capture(T),D,(T)=>O.forget(T));f.attach(q);let w=async(T)=>{if(await n2(E),v2(Y().configPath))return;if(await g?.idle(),v2(Y().configPath))return;if(b&&!r1(T)&&(await K2()).open){await v.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 y=async(T)=>{await w(T);let l=await fZ(v.poolStore(),Y(),T,{vault:E});if(!v2(Y().configPath))await g?.requestAdoption();await v.load(),z.info("ChatGPT login stored in the account pool",l)};let J2=await R1($,{integrationID:E2,methods:IZ({beginLogin:Z.beginLogin??J$,version:X,vault:E}),onLogin:(T)=>y(T),label:"ChatGPT (openai-auth account pool)",vault:yZ(E)});let G2=await pZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let e=$.command&&$.location?await SZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??gZ({...sZ({source:v,storage:h,counts:X2,now:N,authority:()=>E.authority()}),fetchImpl:H,now:N,randomUUID:c4,accountStoragePath:Y().configPath,accountStatePath:Y().statePath,packageVersion:X,layoutNotice:v0,loadAccounts:f2,store:()=>v.poolStore(),migration:async()=>{if(v2(Y().configPath))return{migrated:!0};let T=await K2();return{migrated:!1,blockers:T.open?[]:T.blockers}},beginAccountLogin:Z.beginLogin??J$,refreshAllQuota:async()=>(await v.pollRows(await f2(Y()))).map((T)=>({...T,account:T.id})),getStickyRouting:async(T)=>p.get(T),cacheKeepManager:O.manager,setCacheKeepEnabled:(T)=>O.configure({enabled:T}),setCacheKeepSubagents:(T)=>O.configure({subagents:T}),setCacheKeepSustain:(T)=>O.configure({sustain:T}),setCacheKeepWindow:(T)=>O.configure({window:T}),afterWrite:()=>v.load(),refreshSidebar:()=>Q.publish(),clearStickyRouting:async(T)=>{let l=p.get(T)!==void 0;return p.forget(T),l},vault:E})):void 0;let s=new AbortController;(async()=>{try{for await(let T of $.event.subscribe({signal:s.signal}))if(T.type==="session.deleted")f.forgetSession(T.data.sessionID),O.forget(T.data.sessionID),D.forget(T.data.sessionID)}catch(T){if(!s.signal.aborted)z.warn("stopped listening for session deletion",{error:T instanceof Error?T.message:String(T)})}})();a=!0;return async()=>{A=!0,s.abort();let T=O.release();await e?.(),g?.dispose(),await v.dispose(),await Q.release(),await Promise.allSettled([q.dispose(),J2.dispose(),G2.dispose()]);let l;try{await Promise.race([Promise.all([g?.idle(),v.settled(),_.store?.settled(),T]),new Promise((Z2)=>{l=setTimeout(Z2,d4),l.unref?.()})])}finally{clearTimeout(l),C.release(),await n?.release()}}}catch(m){var $2=m,T2=1}finally{T0(c,$2,T2)}}var a4=G$(),M7={id:E1,setup:a4.setup,server:u0.server};export{M7 as default,G$ as createOpenAIAuthPlugin,E1 as OPENAI_AUTH_PLUGIN_ID};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-openai-auth",
3
- "version": "1.9.5",
3
+ "version": "1.9.6",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -66,9 +66,9 @@
66
66
  },
67
67
  "devDependencies": {
68
68
  "@ai-sdk/openai": "3.0.88",
69
- "@cortexkit/common-auth": "^0.34.0",
69
+ "@cortexkit/common-auth": "^0.36.0",
70
70
  "@cortexkit/openai-auth-core": "workspace:*",
71
- "@opencode/plugin": "2.2.0"
71
+ "@opencode/plugin": "2.2.5"
72
72
  },
73
73
  "dependencies": {
74
74
  "@cortexkit/claustrum-client": "^0.14.0",
@@ -76,7 +76,7 @@
76
76
  "@cortexkit/subc-client": "^0.22.0",
77
77
  "@opentui/core": ">=0.7.0",
78
78
  "@opentui/solid": ">=0.7.0",
79
- "ai": "^7.0.155",
79
+ "ai": "^7.0.159",
80
80
  "jsonc-parser": "^3.3.1",
81
81
  "solid-js": "1.9.12"
82
82
  }
File without changes