@cortexkit/opencode-openai-auth 1.17.0 → 1.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +8 -8
- package/dist/{codex-request-DYqSE0ti.d.ts → codex-request-CTIOw2EZ.d.ts} +322 -322
- package/dist/index-177kc3f1.js +64 -0
- package/dist/{index-k2f9vrcr.js → index-1r7zznds.js} +1 -1
- package/dist/{index-0mhdyzax.js → index-2ecf254a.js} +21 -21
- package/dist/index-5czcaan0.js +101 -0
- package/dist/index-5vh4jgb7.js +12 -0
- package/dist/index-96p0myg1.js +2 -0
- package/dist/{index-1m3vv9rh.js → index-9sh2xnwr.js} +2 -2
- package/dist/{index-d7bsrp0m.js → index-h7xxfm12.js} +1 -1
- package/dist/{index-vmcmpezd.js → index-hrv1msdb.js} +1 -1
- package/dist/index-m6sq5g7q.js +8 -0
- package/dist/{index-99c2fepe.js → index-nkgxq9a6.js} +1 -1
- package/dist/{index-fxqghceg.js → index-raj3tyyz.js} +1 -1
- package/dist/{index-6ts9w66n.js → index-rs8z3per.js} +1 -1
- package/dist/index-smekt6zv.js +2 -0
- package/dist/index.d.ts +24 -24
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-r3vbz9pw.js → token-kdjmv82a.js} +1 -1
- package/dist/token-util-71r7z2vr.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +1 -1
- package/dist/v2/server.d.ts +1 -1
- package/dist/v2/server.js +3 -2
- package/package.json +2 -2
- package/src/tui-compiled/raw/shared/0766d78c6f481f18-watcher.js +9 -2
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +1 -1
- package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +3 -1
- package/src/tui-compiled/raw/shared/44449e891fab9fbc-edit.js +48 -2
- package/src/tui-compiled/raw/shared/54eba94fd64c8c3c-index.js +1 -1
- package/src/tui-compiled/raw/shared/5f4bc45522ab9bc6-update.js +19 -18
- package/src/tui-compiled/raw/shared/6948d70969aa7a55-fs.js +1 -0
- package/src/tui-compiled/raw/shared/836fc615de6afbd9-settings.js +14 -4
- package/src/tui-compiled/raw/shared/94f53cfd572ba4bb-availability.js +1 -1
- package/src/tui-compiled/raw/shared/c14988621dc60a75-port-file.js +55 -49
- package/src/tui-compiled/raw/shared/cf4c37f3975c3a8d-canonical-file-path.js +57 -0
- package/src/tui-compiled/raw/shared/ec971142548df90e-index.js +3 -0
- package/src/tui-compiled/runtime/shared/0766d78c6f481f18-watcher.js +9 -2
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +1 -1
- package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +3 -1
- package/src/tui-compiled/runtime/shared/44449e891fab9fbc-edit.js +48 -2
- package/src/tui-compiled/runtime/shared/54eba94fd64c8c3c-index.js +1 -1
- package/src/tui-compiled/runtime/shared/5f4bc45522ab9bc6-update.js +19 -18
- package/src/tui-compiled/runtime/shared/6948d70969aa7a55-fs.js +1 -0
- package/src/tui-compiled/runtime/shared/836fc615de6afbd9-settings.js +14 -4
- package/src/tui-compiled/runtime/shared/94f53cfd572ba4bb-availability.js +1 -1
- package/src/tui-compiled/runtime/shared/c14988621dc60a75-port-file.js +55 -49
- package/src/tui-compiled/runtime/shared/cf4c37f3975c3a8d-canonical-file-path.js +57 -0
- package/src/tui-compiled/runtime/shared/ec971142548df90e-index.js +3 -0
- package/dist/index-3dv16qvb.js +0 -101
- package/dist/index-dqxk628t.js +0 -12
- package/dist/index-rm4zt5dv.js +0 -64
- package/dist/index-v9p38mg5.js +0 -2
- package/dist/index-xx2z6bs3.js +0 -2
- package/dist/index-ydtpn6ma.js +0 -8
- package/dist/token-util-vks3kgse.js +0 -1
package/dist/v2/server.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
import{c as
|
|
1
|
+
import{c as E4}from"../index-rs8z3per.js";import{A as eZ,B as N0,C as H0,D as v1,E as yZ,F as fZ,G as f1,H as W4,I as S$,J as N4,K as H4,L as F4,M as R1,N as EZ,O as TZ,P as v0,Q as h0,R as M4,S as _4,U as T0,V as O0,Y as $0,Z as Z0,d as J4,e as G4,f as X4,g as r2,h as _0,i as i1,j as B1,k as y1,ka as C4,l as p1,n as y$,na as T4,o as f$,p as w$,q as q1,r as v$,s as h$,v as K0,w as L0,x as P0,y as tZ,z as _$}from"../index-177kc3f1.js";import{$b as Q4,Aa as r0,Ab as HZ,Bb as FZ,Cb as KZ,Cc as K4,Db as L2,Ea as zZ,Eb as LZ,Ec as L4,Fa as JZ,Fc as P4,Gb as PZ,Hb as MZ,Ib as b1,Jb as _Z,Kb as CZ,Nb as t2,Qb as t0,Rb as e0,Sb as c1,Tb as $4,Ub as Z4,Vb as z4,Wb as I1,Xa as Y0,Zb as Y4,_b as lZ,ac as Q0,gb as BZ,ib as UZ,jb as V$,jc as B4,kb as W$,kc as U4,lb as VZ,lc as V4,mc as B0,nb as w1,ra as J1,sa as s$,ua as G$,uc as o2,vb as WZ,vc as uZ,wa as j0,wb as N$,wc as pZ,xb as NZ,xc as L$,yc as cZ,zc as dZ}from"../index-2ecf254a.js";import{Pc as k0,cd as w0,dd as I0,fd as y0,jd as f0}from"../index-nkgxq9a6.js";import{Fe as A$,Ge as r$,Gf as E0,Hd as n$,He as t$,Hf as s2,Id as o$,Ie as e$,If as j$,Je as X0,Jf as Y$,Kf as GZ,Le as s0,Me as C0,Mf as XZ,Nf as Q$,Of as jZ,Qf as YZ,Rf as X1,Sf as B$,Tf as QZ,Uf as U$,_d as J0,fe as G0,kf as Y1,lf as E1,qf as $Z,rf as ZZ,sf as IZ,tf as X$,we as D1,xe as k1,ye as o0,zd as P1,zf as u1}from"../index-5czcaan0.js";import"../index-m6sq5g7q.js";import{ng as sZ,og as j4}from"../index-smekt6zv.js";import"../index-5vh4jgb7.js";import"../index-1r7zznds.js";import{Jg as n0,Lg as l2}from"../index-9sh2xnwr.js";import"../index-96p0myg1.js";import{$g as rZ}from"../index-hrv1msdb.js";import{dh as Q1,eh as a0}from"../index-h7xxfm12.js";import{AsyncLocalStorage as _5}from"node:async_hooks";import{randomUUID as C5}from"node:crypto";class E2 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 m2($){return`common-auth-placeholder.${$}`}function R$($){let Z=m2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function W1($,Z){if($?.type!=="oauth")return!1;let J=Z===void 0?void 0:m2(Z),G=(j)=>J===void 0?j.startsWith("common-auth-placeholder."):j===J;return G($.access)&&G($.refresh)}var D$="No browser sign-in: this connects the plugin to the accounts in its vault.";async function o1($,Z){let J=Z.now??Date.now,{integrationID:G}=Z,j=(L)=>R$({integrationID:G,methodID:L,now:J()}),Q=async(L,U)=>{return await Z.onLogin(L,{integrationID:G,methodID:U}),j(U)},N=(L)=>async(U)=>{let K=L.method.id,V=await L.authorize(U),E={url:V.url,instructions:V.instructions,...V.expiresAt===void 0?{}:{expiresAt:V.expiresAt}};if(V.mode==="auto")return{...E,mode:"auto",callback:V.callback.then((T)=>Q(T,K))};let M=V.callback;return{...E,mode:"code",callback:async(T)=>Q(await M(T),K)}};return $.integration.transform((L)=>{let U=Z.label===void 0?{}:{label:()=>Z.label};for(let E of Z.methods)L.method.update({integrationID:G,method:E.method,authorize:N(E),refresh:async(M)=>{if(!W1(M,G))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return j(M.methodID)},...U});let K=Z.vault;if(K===void 0)return;let V=K.method.id;L.method.update({integrationID:G,method:K.method,authorize:async()=>({url:"",instructions:K.instructions??D$,mode:"auto",callback:Promise.resolve().then(()=>K.activate({integrationID:G,methodID:V})).then(()=>j(V))}),refresh:async(E)=>{if(!W1(E,G)||E.methodID!==V)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return j(V)},...U})})}function x4($){let Z=[],J;for(let G of $.split(/\r?\n/))if(G.startsWith("data:"))Z.push(G.slice(5).replace(/^ /,""));else if(G.startsWith("event:"))J=G.slice(6).trim();if(Z.length===0)return;return J===void 0?{data:Z.join(`
|
|
2
2
|
`)}:{event:J,data:Z.join(`
|
|
3
|
-
`)}}function W1($,Z){let J=new TextDecoder,G="",Y=(F)=>{let M=E4(F);if(!M)return;try{$(M)}catch(U){Z(U)}},j=()=>{for(;;){let F=/\r?\n\r?\n/.exec(G);if(!F)return;let M=G.slice(0,F.index);G=G.slice(F.index+F[0].length),Y(M)}};return new TransformStream({transform(F,M){M.enqueue(F),G+=J.decode(F,{stream:!0}),j()},flush(){if(G+=J.decode(),j(),G.trim()!=="")Y(G);G=""}})}var n2=512,a2=3621000,$1="x-common-auth-attempt",i2=($,Z)=>JSON.stringify([$,Z]),I2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function x4($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function O4($,Z){let J=$.getReader();return new ReadableStream({async pull(G){let Y;try{Y=await J.read()}catch(j){Z({reason:"failed",message:j instanceof Error?j.message:String(j)}),G.error(j);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 J.cancel(G)}})}function E1($,Z){for(let[J,G]of Object.entries(Z)){let Y=J.toLowerCase();for(let j of Object.keys($))if(j.toLowerCase()===Y)delete $[j];if(G!==null)$[J]=G}}function q4($,Z){for(let[J,G]of Object.entries(Z))if(G===null)$.delete(J);else $.set(J,G)}async function o1($,Z,J={}){let{providerID:G}=Z,Y=J.gateOnPlaceholder,j=(z)=>Y===void 0||Y.credential(z)===v2(G),F=J.logger,M=Math.max(1,J.maxRecords??n2),U=J.hostRetryLimit??10,K=[...J.hostCredentials??[v2(G)],...Y?[v2(G)]:[]].filter((z)=>z!==""),V=new Map,P=new WeakMap,T=new Map,O=0,c=new Set,z2=new Map,q=new Map,w=(z)=>{let Q=q.get(z);return Q?.ownedSeen===!0&&Q.foreignSeen},K2=(z,Q)=>{z2.set(z,Q);let N=q.get(z)??{ownedSeen:!1,foreignSeen:!1};if(Q)N.ownedSeen=!0;else N.foreignSeen=!0;q.set(z,N)},X2=(z,Q)=>{let N=Y?.refuseMisplaced,L=N?[...Q].filter(([,h])=>h.includes(v2(G))):[],B=j(Q)&&(!N||L.length>0);if(N){if(L.length>0&&(L.length!==1||!B))throw K2(z.sessionID,!1),new T2({kind:"placement-refused",providerID:G,sessionID:z.sessionID,requestKind:z.kind,message:N(L[0]?.[0]??"")})}return K2(z.sessionID,B),B},p=!1,t=!1,H2=new Map,x2=0,Q2=!1,D=new Map,y=(z,Q)=>{try{F?.warn(z,Q)}catch{}},a=(z)=>z instanceof Error?z.message:String(z),r=(z)=>z.excluded.clear(),O2=(z)=>z.excluded.size===0?{}:{excluded:[...z.excluded]},l2=(z,Q,N)=>{if(!J.enforceRequestExclusion||z===void 0||!N.excluded.has(z))return!1;return y("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:Q.sessionID,kind:Q.kind,phase:Q.phase,accountId:z}),!0},D2=new Map,U2=(z,Q)=>{let N=(D2.get(z)??Promise.resolve()).then(Q),L=N.then(()=>{},()=>{});return D2.set(z,L),L.then(()=>{if(D2.get(z)===L)D2.delete(z)}),N},k2=(z,Q)=>{let N=D2.get(z);return N?N.then(()=>k2(z,Q)):Q()},V2=async(z)=>{try{await Z.dropChoice?.({...z.input,accountId:z.accountId})}catch(Q){y("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:z.input.sessionID,error:a(Q)})}},W2=async(z)=>{try{await Z.dropSameAccountRetry?.({...z.input,accountId:z.accountId})}catch(Q){y("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:z.input.sessionID,error:a(Q)})}},P2=async(z)=>{if(z.next)await V2(z.next);if(z.sameAccount)await W2(z.sameAccount)},e2=(z)=>{let Q=T.get(z);if(T.delete(z),Q)U2(Q.sessionID,()=>P2(Q))},w2=async(z,Q)=>{let N=H2.get(z);if(!N||N.size===0)return;await Promise.all([...N].map(async(L)=>{try{await L(Q)}catch(B){y("opencode2 auth listener threw; the request is unaffected",{event:z,error:a(B)})}}))},g2=async(z)=>{let Q=new Set([...V.values()].filter((L)=>L.scope.sessionID===z.sessionID).map((L)=>L.transport).filter((L)=>L!==void 0)),N=z.handle?.transport??(Q.size===1?[...Q][0]:"unknown");try{F?.info?.("opencode2 auth retry decision",{sessionID:z.sessionID,transport:N,attempt:z.attempt,reason:z.reason==="host-decides"&&w(z.sessionID)?"mixed-session":z.reason,retry:z.decision.retry})}catch{}await w2("retry",z)},B1=async(z,Q)=>{try{await Z.onAttemptEnd?.(z,Q)}catch(N){y("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:z.attemptId,error:a(N)})}},B2=(z,Q)=>{if(z.ended||!z.attempt)return;let N={...z.status===void 0?{}:{status:z.status},outputStarted:z.outputStarted,...z.limit?{limit:z.limit.signal}:{},...Q?{error:Q}:{}};if(Q)z.endError=Q;if(Q?.reason==="cancelled"||!Q&&!z.limit&&(z.status===void 0||z.status<400))r(z.request);z.ended=B1(z.attempt,N)},u2=(z,Q)=>B2(z,{reason:"abandoned",message:Q}),L2=(z)=>[...V.values()].filter((Q)=>Q.key===z),p2=(z)=>L2(z).at(-1),X=(z)=>{if(V.delete(z.id),T.get(z.key)?.attemptId===z.id||!L2(z.key).length)e2(z.key)},W=(z)=>{V.set(z.id,z);while(V.size>M){let Q=V.values().next().value;if(Q===void 0)break;u2(Q,"dropped to keep the record bound"),X(Q)}},_=(z)=>z.accountId===void 0?void 0:{...z.scope,accountId:z.accountId},H=(z,Q)=>new T2({kind:"no-account",providerID:G,sessionID:z.sessionID,requestKind:z.kind,...Q===void 0?{}:{message:Q}}),S=(z)=>{D.get(z)?.clear(),D.delete(z)},x=async(z,Q)=>{let N=()=>H(z,`${G} ${z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(Q2)throw N();let L=D.get(z.sessionID);if(!L)L=new Set,D.set(z.sessionID,L);let B={};L.add(B);let h=()=>{if(!L.has(B))throw N()};try{return await Q(h)}finally{if(L.delete(B),L.size===0&&D.get(z.sessionID)===L)D.delete(z.sessionID)}},E=(z,Q)=>{for(let[N,L]of Q)if(K.some((B)=>L.includes(B)))throw new T2({kind:"host-credential-on-wire",providerID:G,sessionID:z.sessionID,requestKind:z.kind,message:`${G} ${z.kind} request still carries the host's placeholder credential in ${N}; the adapter's account headers must replace it`})},A=(z)=>{for(let Q of L2(z))if(Q.ended||!Q.attempt)X(Q);else if(Q.transport==="ws"||Q.judged)u2(Q,"a newer attempt of its session and kind began"),X(Q)},v=async(z,Q,N,L)=>{let B=i2(z.sessionID,z.kind),{input:h,accountId:I,sameAccountRetry:b,request:f}=await k2(z.sessionID,async()=>{N();let u=T.get(B);T.delete(B);let i=L2(B);if(u&&i.some((j2)=>j2.id!==u.attemptId&&j2.attempt&&!j2.ended))y("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:z.sessionID,kind:z.kind});if(!u){let j2=new Set(i.filter((b2)=>b2.attempt&&!b2.ended).map((b2)=>b2.request));for(let b2 of i)if(!j2.has(b2.request))r(b2.request)}let k=u?.request??{excluded:new Set},m=u?.accountId??p2(B)?.accountId;A(B);let s=u?.next,G2=u?.sameAccount,$2=G2!==void 0&&G2.input.modelID===z.modelID&&G2.input.agent===z.agent,S2=s!==void 0&&s.input.modelID===z.modelID&&s.input.agent===z.agent,f2=u?.wake,Z2={...z,phase:"request",...O2(k),...m===void 0?{}:{previousAccountId:m},...u?.rerouteFrom?{rerouteFrom:u.rerouteFrom}:{},...f2===void 0?{}:{wake:f2,hostAttempt:s?.input.hostAttempt}};if(s&&(!S2||f2!==void 0))await U2(z.sessionID,()=>V2(s)),N();if(G2&&!$2)await U2(z.sessionID,()=>W2(G2)),N();if(G2?.continuation&&(!$2||w(z.sessionID))){if($2)await U2(z.sessionID,()=>W2(G2));throw H(z)}let d2=$2?G2.accountId:S2&&f2===void 0?s.accountId:await Z.chooseAccount(Z2),c2=typeof d2==="string"?d2:void 0;if(l2(c2,Z2,k)){let j2=c2;if($2&&G2)await U2(z.sessionID,()=>W2(G2));else if(j2!==void 0)await U2(z.sessionID,()=>V2(S2&&s?s:{accountId:j2,input:Z2}));c2=void 0,N()}return{input:Z2,accountId:c2,sameAccountRetry:$2,request:k}});N();let M2={},_2;if(I!==void 0){let u=await Z.accountHeaders({...z,accountId:I});if(N(),x4(u))M2=u.headers,_2=u.attempt;else M2=u}let R=`attempt-${++x2}`,l={id:R,key:B,scope:z,request:f,accountId:I,headers:M2,attempt:I===void 0?void 0:{...z,accountId:I,attemptId:R,transport:L,data:_2},...L===void 0?{}:{transport:L},outputStarted:!1,sameAccountRetry:b};if(W(l),l.attempt)w2("select",{...z,accountId:l.attempt.accountId,hook:Q,...h.previousAccountId===void 0?{}:{previousAccountId:h.previousAccountId},...h.rerouteFrom===void 0?{}:{rerouteFrom:h.rerouteFrom},handle:l.attempt});return l},e=async(z,Q,N,L,B)=>{let h=i2(z.sessionID,z.kind),I=L===void 0?void 0:V.get(L);if(I?.key!==h)I=void 0;if(!I){if(I=p2(h),L2(h).filter((f)=>f.transport===void 0&&!f.ended).length>1&&!t)t=!0,y("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:z.sessionID,kind:z.kind})}if(!I||I.transport!==void 0||I.ended)I=await v(z,Q,B,N);else if(I.transport=N,I.attempt)I.attempt.transport=N;if(N==="ws"){for(let b of L2(h))if(b!==I&&b.transport==="ws")u2(b,"a newer attempt of its session and kind went out over WebSocket")}return I},g=async(z,Q)=>{try{return await Q()}catch(N){throw B2(z,{reason:"failed",message:a(N)}),N}},C=(z,Q)=>{let N=L2(i2(z,Q)).filter((L)=>L.transport==="ws").at(-1);return N?.attempt!==void 0&&!N.ended?N:void 0},d=(z,Q,N)=>{let L=_(z);if(!L||!z.attempt||z.limit)return;z.limit={signal:Q,delivered:w2("limit",{...L,via:N,limit:Q,outputStarted:z.outputStarted,handle:z.attempt})}},n=(z,Q,N,L)=>{let B=_(z);if(!B||!z.attempt)return;w2("quota",{...B,transport:Q,...L===void 0?{}:{status:L},quota:N,handle:z.attempt})},Y2=(z,Q,N,L)=>{let B=z.attempt;if(!B)return;let h=Z.inspectEvent?.(L===void 0?{transport:Q,data:N,attempt:B}:{transport:Q,data:N,event:L,attempt:B});if(!h)return;if(h.quota!==void 0)n(z,Q,h.quota);if(h.outputStarted)z.outputStarted=!0;if(h.hostRetry==="veto")z.hostRetry="veto";if(h.limit)d(z,h.limit,Q);if(h.error!==void 0)B2(z,{reason:"failed",message:h.error});else if(h.done)B2(z)},E2=(z,Q)=>{let N=z.attempt;if(!N||Q.accountId===z.accountId)return;if(N.reboundFrom??=N.accountId,N.accountId=Q.accountId,"data"in Q)N.data=Q.data;z.accountId=Q.accountId},N2=(z)=>!z.attempt||z.endError!==void 0||z.status!==void 0&&z.status>=400,q2=(z)=>{let Q=[...V.values()].filter((b)=>b.scope.sessionID===z),N=Q.filter((b)=>b.limit&&!b.rerouted).at(-1);if(N)return N;let L=Q.filter((b)=>b.scope.kind==="primary"),B=L.length>0?L:Q;if(B.length<=1)return B[0];let h=B.filter((b)=>!b.judged&&N2(b)).at(-1);if(h)return h;let I=B.filter((b)=>b.attempt&&!b.ended);if(I.length>1)return"ambiguous";return I[0]??B.at(-1)},o={providerID:G},J2=[];J2.push(await $.session.hook("model.request",(z)=>{if(Y)return;return x(I2(z),async(Q)=>{let N=await v(I2(z),"model.request",Q);if(Q(),N.accountId===void 0)throw H(N.scope);E1(z.headers,{...N.headers,[$1]:N.id})})},o)),J2.push(await $.session.hook("http.request",(z)=>{if(Y){if(!X2(I2(z),z.request.headers))return}return x(I2(z),async(Q)=>{let N=z.request.headers.get($1)??void 0,L=Y?await v(I2(z),"http.request",Q,"http"):await e(I2(z),"http.request","http",N,Q);Q();let B=_(L),h=L.attempt;if(!B||!h)throw H(L.scope);await g(L,async()=>{let I=z.request;if(Z.rewriteRequest){if(N!==void 0){let M2=new Headers(I.headers);M2.delete($1),I=new Request(I,{headers:M2})}I=await Z.rewriteRequest({...B,request:I,attempt:h})??I,Q()}let b=new Headers(I.headers);b.delete($1),q4(b,L.headers),E(L.scope,b.entries());let f=new Request(I,{headers:b});P.set(f,L),z.request=f})})},o)),J2.push(await $.session.hook("http.response",async(z)=>{let Q=P.get(z.request);if(!Q){if(Y)return;if(!p)p=!0,y("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:z.sessionID,kind:z.kind});return}let N=z.response;if(Z.answeredBy&&Q.attempt){let b=Q.attempt,f=await g(Q,async()=>Z.answeredBy?.({request:z.request,response:N,attempt:b}));if(f)E2(Q,f)}let L=_(Q),B=Q.attempt;if(!L||!B)return;Q.status=N.status;let h=Z.quotaFromHeaders?.(N.headers,N.status,B);if(h!==void 0)n(Q,"http",h,N.status);if(!N.ok&&Z.limitFromResponse){let b=await Z.limitFromResponse({status:N.status,headers:N.headers,body:()=>N.clone().text(),attempt:B});if(b)d(Q,b,"http")}if(!N.ok||!N.body)B2(Q);let I=N;if(N.body&&(Z.inspectEvent||Z.onAttemptEnd)){let b=N.body;if(Z.inspectEvent)b=b.pipeThrough(W1((f)=>Y2(Q,"http",f.data,f.event),(f)=>y("opencode2 auth event inspection threw",{error:a(f)})));I=new Response(O4(b,(f)=>{if(f?.reason==="failed")Q.readFailed=!0;B2(Q,f)}),{status:N.status,statusText:N.statusText,headers:N.headers})}if(Z.rewriteResponse)I=await Z.rewriteResponse({...L,request:z.request,response:I,attempt:B})??I;if(Z.responseRetry){if(await Z.responseRetry({...L,request:z.request,response:I,attempt:B})==="veto")Q.hostRetry="veto"}if(I!==N)z.response=I},o)),J2.push(await $.session.hook("experimental.ws.handshake",(z)=>{if(Y){let Q=i2(z.sessionID,z.kind);if(c.delete(Q),!X2(I2(z),new Headers(z.headers)))return}return x(I2(z),async(Q)=>{let N;for(let I of Object.keys(z.headers)){if(I.toLowerCase()!==$1)continue;N??=z.headers[I],delete z.headers[I]}let L=Y?await v(I2(z),"experimental.ws.handshake",Q,"ws"):await e(I2(z),"experimental.ws.handshake","ws",N,Q);Q();let B=_(L),h=L.attempt;if(!B||!h)throw H(L.scope);await g(L,async()=>{if(!Y?.refuseMisplaced)E1(z.headers,L.headers);let I=Z.rewriteHandshakeURL?.({...B,url:z.url,attempt:h});if(I!==void 0)z.url=I;if(Y?.refuseMisplaced)E1(z.headers,L.headers);if(E(L.scope,Object.entries(z.headers)),Y)c.add(L.key)})})},o));let A2=Z.rewriteWebSocketFrame?.bind(Z);if(A2)J2.push(await $.session.hook("experimental.ws.send",async(z)=>{let Q=I2(z);if(Y&&!c.has(i2(Q.sessionID,Q.kind)))return;let N=C(Q.sessionID,Q.kind),L=await A2({...Q,attempt:N?.attempt,frame:z.frame});if(L!==void 0)z.frame=L},o));J2.push(await $.session.hook("experimental.ws.receive",(z)=>{if(Y&&!c.has(i2(z.sessionID,z.kind)))return;let Q=C(z.sessionID,z.kind);if(!Q)return;try{Y2(Q,"ws",z.frame)}catch(N){y("opencode2 auth frame inspection threw",{error:a(N)})}},o)),J2.push(await $.session.hook("retry",async(z)=>{if(Y&&z2.get(z.sessionID)!==!0)return;let Q=z.decision,N=()=>g2({sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:Q,decision:Q});if(w(z.sessionID)&&!Z.retrySameAccount){await N();return}let L=q2(z.sessionID);if(!L)return;if(L==="ambiguous"){await g2({sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:Q,decision:Q});return}let B=L,h=()=>B.hostRetry==="veto";await x(B.scope,async(I)=>{let b=I,f=Z.retrySameAccount?.bind(Z),M2=B.attempt,_2=B.outputStarted;if(B.transport==="ws"&&_2&&!B.ended&&!B.limit&&!(B.status!==void 0&&B.status>=400)&&!(z.error.status!==void 0&&z.error.status>=400)&&z.error.type==="provider.transport")B.readFailed=!0,B2(B,{reason:"failed",message:z.error.message});if(_2&&B.readFailed&&f&&M2&&!w(z.sessionID)){if(!B.limit){let k=Z.limitFromError?.(z.error,M2);if(k)d(B,k,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;b()}let R=()=>B.readFailed===!0&&z.error.type==="provider.transport"&&Q.retry&&U-z.attempt>=1&&!B.limit&&!(B.status!==void 0&&B.status>=400)&&!(z.error.status!==void 0&&z.error.status>=400)&&!M2?.reboundFrom&&!h()&&!w(z.sessionID);if(f&&M2&&(!_2||R())&&(!h()||w(z.sessionID))&&!B.sameAccountRetry){if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;let k=await U2(B.scope.sessionID,async()=>{b();let m=M2.accountId,s=()=>V.has(B.id)&&B.accountId===m&&q2(z.sessionID)===B&&B.outputStarted===_2&&(!_2||R())&&(!h()||w(z.sessionID))&&(!Y||z2.get(z.sessionID)===!0);if(!s()||B.sameAccountRetry)return!1;B.sameAccountRetry=!0;let G2={...B.scope,accountId:m,error:z.error,attempt:z.attempt,...B.limit?{limit:B.limit.signal}:{},..._2?{continuation:"interrupted-read"}:{}},$2;try{$2=await f(G2)}catch(Z2){y("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:z.sessionID,error:a(Z2)})}if(!$2)return b(),!1;let S2={accountId:$2.accountId,input:G2,..._2?{continuation:!0}:{}};try{b()}catch(Z2){throw await W2(S2),Z2}if(!s()||$2.accountId!==m)return await W2(S2),!1;let f2=T.get(B.key);if(T.delete(B.key),f2)await P2(f2);try{b()}catch(Z2){throw await W2(S2),Z2}if(!s())return await W2(S2),!1;return T.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++O,accountId:m,sameAccount:S2}),B.judged=!0,z.decision=_2?Q:{retry:!0,delay:0},!0});if(b(),k){await g2({sessionID:z.sessionID,accountId:B.accountId,kind:B.scope.kind,attempt:z.attempt,reason:_2?"continue-same-account":"same-account",hostDecision:Q,decision:z.decision,handle:B.attempt});return}}if(w(z.sessionID)){await N();return}B.judged=!0;let l=B.attempt;if(l&&!B.outputStarted){if(!B.limit){let k=Z.limitFromError?.(z.error,l);if(k)d(B,k,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered}b();let{decision:u,reason:i}=await U2(B.scope.sessionID,async()=>{if(b(),w(z.sessionID))return{decision:Q,reason:"host-decides"};let k=T.get(B.key);if(T.delete(B.key),k)await P2(k);if(b(),w(z.sessionID))return{decision:Q,reason:"host-decides"};let m=Q,s,G2,$2,S2;if(B.accountId===void 0||!l)m={retry:!1},s="no-account";else if(B.outputStarted)m={retry:!1},s="output-started";else if(h())m={retry:!1},s="adapter-veto";else if(B.limit){let f2={accountId:B.accountId,limit:B.limit.signal},Z2,d2={...B.scope,phase:"retry",...O2(B.request),hostAttempt:z.attempt,previousAccountId:B.accountId,rerouteFrom:f2};try{Z2=await Z.chooseAccount(d2)}catch(a1){y("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:B.scope.sessionID,error:a(a1)})}let c2=typeof Z2==="string"?Z2:typeof Z2==="object"&&("hold"in Z2)?B.accountId:void 0;if(l2(c2,d2,B.request)){if(c2!==void 0)await V2({accountId:c2,input:d2});Z2=void 0}let j2=typeof Z2==="object"&&"hold"in Z2?Z2.hold:void 0,b2=typeof Z2==="object"&&"waitThenReselect"in Z2?Z2.waitThenReselect:void 0,C4=typeof Z2==="object"&&"hostRetry"in Z2?Z2.hostRetry:void 0,C1=typeof Z2==="string"?Z2:j2?B.accountId:void 0;if(C1!==void 0)$2={accountId:C1,input:d2};try{b()}catch(a1){if($2)await V2($2);throw a1}if(w(z.sessionID)){if($2)await V2($2);return{decision:Q,reason:"host-decides"}}if(h()||C4==="veto"){if($2)await V2($2);if($2=void 0,b(),w(z.sessionID))return{decision:Q,reason:"host-decides"};B.hostRetry="veto",m={retry:!1},s="adapter-veto"}else if(!(U-z.attempt>=1)){if($2)await V2($2);$2=void 0,s="host-decides-last-account"}else if(b2&&Number.isFinite(b2.delayMs)&&b2.delayMs>=0&&b2.delayMs<=a2)m={retry:!0,delay:Math.ceil(b2.delayMs)},s="wait-then-reselect";else if(j2&&Number.isFinite(j2.delayMs)&&j2.delayMs>=0&&j2.delayMs<=a2){if(m={retry:!0,delay:Math.ceil(j2.delayMs)},j2.target!==void 0)S2={target:j2.target,...j2.checkpoint===void 0?{}:{checkpoint:j2.checkpoint},...j2.kind===void 0?{}:{kind:j2.kind}};s="hold"}else if(!j2&&C1!==void 0&&C1!==B.accountId)B.rerouted=!0,B.request.excluded.add(B.accountId),G2=f2,m={retry:!0,delay:0},s="reroute";else{if(j2&&$2)await V2($2),$2=void 0;s="host-decides-last-account"}}else s="host-decides";if(z.decision=m,m.retry&&B.accountId!==void 0&&V.has(B.id))T.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++O,accountId:B.accountId,...G2===void 0?{}:{rerouteFrom:G2},...$2===void 0?{}:{next:$2},...S2===void 0?{}:{wake:S2}});else if($2)await V2($2);if(!m.retry)r(B.request);return{decision:m,reason:s}});b(),await g2({sessionID:z.sessionID,...B.accountId===void 0?{}:{accountId:B.accountId},kind:B.scope.kind,attempt:z.attempt,reason:i,hostDecision:Q,decision:u,...l===void 0?{}:{handle:l}})})},o));let y2=(z)=>{if(S(z),z2.delete(z),!q.get(z)?.foreignSeen)q.delete(z);for(let Q of c)if(JSON.parse(Q)[0]===z)c.delete(Q);for(let Q of[...V.values()]){if(Q.scope.sessionID!==z)continue;u2(Q,"its session was forgotten"),r(Q.request),V.delete(Q.id)}for(let[Q,N]of T)if(N.sessionID===z)e2(Q)},m2=new AbortController,U1=$.event;if(U1)(async()=>{try{for await(let z of U1.subscribe({signal:m2.signal}))if(z.type==="session.deleted")y2(z.data.sessionID);else if(z.type==="session.status"&&z.data.status.type==="idle"){let Q=z.data.sessionID,N=++O;U2(Q,async()=>{for(let[L,B]of T)if(B.sessionID===Q&&B.order<N)T.delete(L),r(B.request),await P2(B)})}}catch(z){if(!m2.signal.aborted)y("opencode2 auth stopped listening for session deletion",{error:a(z)})}})();return{on(z,Q){let N=H2.get(z);if(!N)N=new Set,H2.set(z,N);let L=Q;return N.add(L),()=>{N.delete(L)}},accountFor(z,Q){return p2(i2(z,Q))?.accountId},forgetSession:y2,get size(){return V.size},async dispose(){if(Q2)return;Q2=!0;for(let z of D.keys())S(z);m2.abort();for(let z of V.values())u2(z,"the installation was disposed");V.clear();for(let z of T.keys())e2(z);c.clear(),z2.clear(),q.clear(),H2.clear(),await Promise.all(D2.values()),await Promise.all(J2.map(async(z)=>{try{await z.dispose()}catch(Q){y("opencode2 auth hook did not dispose cleanly",{error:a(Q)})}}))}}}import{randomUUID as d$}from"node:crypto";import{createHash as A4}from"node:crypto";var S4=1024,b4=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),R$=($)=>D$($,"user"),R4=($)=>b4($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function D4($){return A4("sha256").update(JSON.stringify($)).digest("hex")}class Z1{runtime;maxSessions;#$=new Map;constructor($,Z=S4){this.runtime=$;this.maxSessions=Z}advance($,Z,J=this.runtime){let G=this.#$.get($),Y=Array.isArray(Z.input)?Z.input:[],j=Y.filter(R$),F=Y.findLastIndex(R$),M=F<0?void 0:D4(Y[F]),U=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,K,V,P;if(U)K=j.length>0,V=M??G?.fingerprint,P=G?.userCount===void 0?void 0:G.userCount+j.length;else{V=M,P=j.length;let O=F>=0&&F>Y.findLastIndex(R4),c=G!==void 0&&!G.completed&&G.fingerprint===V&&G.userCount===P;K=O&&!c}let T=K||!G?{turnID:(J?.uuid??o2)(),turnStartedAt:(J?.now??Date.now)()}:{turnID:G.turnID,turnStartedAt:G.turnStartedAt};return this.#Z($,{...T,completed:!1,fingerprint:V,userCount:P}),T}completed($){let Z=this.#$.get($);if(Z)this.#Z($,{...Z,completed:!0})}get($){return this.#$.get($)}forget($){this.#$.delete($)}#Z($,Z){this.#$.delete($),this.#$.set($,Z);while(this.#$.size>this.maxSessions){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function s1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var k$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function k4(){let $=globalThis;return $[k$]??=crypto.randomUUID(),$[k$]}class N1{runtime;store;sessions;frameTurns;installationID;constructor($,Z,J){this.runtime=$;this.store=J;this.installationID=Z??k4(),this.sessions=J?.sessions??new Map,this.frameTurns=J?.frameTurns??new Z1}get($){let Z=this.runtime?.uuid??o2;if(this.store)return this.store.get($,Z);let J=this.sessions.get($);if(!J){let G=Z();J={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,J)}return J}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(x1(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var r1={version:w$,"user-agent":y$,originator:"codex_exec"};var w4=1024,y4=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,q1=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),v$=($)=>q1($)&&($.type==="message"||("role"in $))&&$.role==="user",h$=($)=>q1($)&&$.type==="configuration_update";class t1{http;#$=new Map;constructor($=new N1){this.http=$}apply($,Z,J){if(Z.kind!=="primary")return!1;let G=typeof $.model==="string"?$.model:"";if(!I$.has(G))return!1;if(y4.test(G))return!1;let Y=q1($.reasoning)?$.reasoning:void 0,j=typeof Y?.effort==="string"?Y.effort:void 0;if(!j)return!1;let F=this.#$.get(Z.sessionID);if(F===void 0)return this.#Z(Z.sessionID,j),!1;if(j===F)return!1;let M=Array.isArray($.input)?$.input:void 0;if(!M||M.length===0)return!1;let U=M.findLastIndex(v$);if(U<0){if(J==="http")return!1;return $.reasoning={...Y,effort:F},!0}if($.reasoning={...Y,effort:F},!h$(M[U-1]))M.splice(U,0,{type:"configuration_update",reasoning:{effort:j}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>w4){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function x1($){try{let Z=JSON.parse($);return q1(Z)?Z:void 0}catch{return}}async function g$($,Z,J,G,Y=J.http,j){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let F=await $.clone().text(),M=x1(F);if(M)delete M.max_output_tokens;let U=new Headers($.headers),K=O1({rewriteLite:f$,init:{body:M?JSON.stringify(M):$.body===null?void 0:F},headers:U,metadata:Y.get(Z.sessionID),installationID:Y.installationID,runtime:Y.runtime,websocket:!1,responsesLite:G,applyEffort:(V)=>{if(J.apply(V,Z,"http"),j&&typeof V.model==="string")j(V.model)}});return new Request($,{headers:U,body:K.init?.body})}function m$($,Z,J,G){let Y=G.sessions.get($.sessionID),j=G.frameTurns.get($.sessionID);if(!Y||!j)return;let F=s1(Y,j),M=new Headers({"content-type":"application/json"});for(let K of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let V=J.get(K);if(V!==null)M.set(K,V)}O1({init:{body:$.bodyText},headers:M,metadata:F,installationID:G.installationID,runtime:G.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let U=new URL(Z);if(U.protocol==="wss:")U.protocol="https:";if(U.protocol==="ws:")U.protocol="http:";return new Request(U,{method:"POST",headers:M,body:$.bodyText})}function I4($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let J=Z.findIndex((G,Y)=>JSON.stringify(G)!==JSON.stringify($[Y]));return J>=0&&h$(Z[J])&&v$(Z[J+1])&&JSON.stringify(Z.slice(J+1))===JSON.stringify($.slice(J))}function l$($,Z,J,G){let Y=x1($);if(Y?.type!=="response.create")return;let j=J.http.advanceFrame(Z.sessionID,Y),F=J.http.get(Z.sessionID);delete Y.max_output_tokens;let M=O1({rewriteLite:()=>{},init:{body:JSON.stringify(Y)},headers:new Headers,metadata:s1(F,j),installationID:J.http.installationID,runtime:J.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(K)=>{J.apply(K,Z,"ws")}}),U=x1(String(M.init?.body));if(!U)return;if(G&&typeof U.model==="string")G(U.model);if(!I4(Y.input,U.input)){if("input"in Y)U.input=Y.input;else delete U.input;return JSON.stringify(U)}return String(M.init?.body)}function f4($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function e1($,Z){let J=new URL($);if(J.origin!=="https://api.openai.com"&&J.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(J.pathname))return $;let G=new URL(`${f4(Z)}/responses`);if(G.search=J.search,J.protocol==="ws:"||J.protocol==="wss:")G.protocol=G.protocol==="https:"?"wss:":"ws:";return G.href}import{resolve as u$}from"node:path";var v4=1024;class A1{accounts=new Map;limit;constructor($=v4){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let J=this.accounts.keys().next().value;if(J===void 0)break;this.accounts.delete(J)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var p$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),c$=globalThis,$$=c$[p$]??new Map;c$[p$]=$$;function Z$($){let Z=JSON.stringify([u$($.configPath),u$($.statePath)]),J=$$.get(Z);if(!J)J=new A1,$$.set(Z,J);return J}var R2="openai",J1=10;var z$=1,h4="request refused: no account with a usable credential",C2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function g4($){let Z=C2($)?$.counters:void 0,J=C2(Z)?Z.resetCredits:void 0,G=C2(J)?J.value:void 0;return typeof G==="number"&&Number.isFinite(G)?G:void 0}function F1($){try{return JSON.parse($)}catch{return}}function H1($){let Z=R1($);return Z?D1(Z):void 0}var m4=new Set(["usage_limit_reached","rate_limit_exceeded"]);function K1($,Z,J,G){return{reason:$.window,windows:YZ($,Z,G,Z),observedAt:Z,...$.resetAt!==void 0?{resetAt:$.resetAt,resetSource:"provider"}:{},...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function CZ($,Z,J){if($.type!=="response.failed"){let j=b1($,Z),F=typeof $.status==="number"?$.status:void 0;return j?K1(j,Z,F,J):void 0}if(!C2($.response))return;let G=$.response.failed;if(C2(G)&&typeof G.rate_limit_reached_type==="string")return K1({window:G.rate_limit_reached_type},Z,void 0,J);let Y=$.response.error;if(C2(Y)){let j=typeof Y.code==="string"?Y.code:typeof Y.type==="string"?Y.type:void 0;if(j&&m4.has(j)){let F=typeof $.status==="number"?$.status:void 0,M=b1({error:{...Y,type:j},status:F},Z);return K1(M??{window:j},Z,F,J)}}return}function EZ($,Z,J){return xZ(F1($),Z,J)}function xZ($,Z,J){if(!C2($))return;let G=typeof $.type==="string"?$.type:void 0;if(G==="codex.rate_limits")return{quota:{snapshot:r$($),complete:!0}};let Y=CZ($,Z,J);if(Y)return{limit:Y};if(G===void 0||G==="error")return;return _Z(G)?void 0:{outputStarted:!0}}function l4($){let Z=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:o$($),complete:s$($)}}function u4($){let Z=$.get("retry-after");if(Z===null)return;let J=Z.trim()?Number(Z):NaN;return Number.isFinite(J)&&J>=0?J*1000:void 0}function OZ($){let Z=new WeakMap,J=new WeakSet,G,Y,j=new WeakMap,F=new Map,M=(X)=>{if(X?.data?.kind!=="vault"||!X.data.receipt.credentialId||!F2())return;let W=X.data.receipt;return(_)=>{let H=`${X.sessionID}\x00${X.kind}`,S=(F.get(H)??0)+1;if(F.set(H,S),F.size>n2){let x=F.keys().next().value;if(x!==void 0)F.delete(x)}j.set(X,new w1(X.sessionID,W,X.kind,_,S,$.cacheWarming,X.data?.kind==="vault"&&X.data.freeQuota))}},{source:U,pins:K}=$,V=$.now??Date.now,P=$.log,T=$.vault,O=$.limits,c=d$(),z2=new WeakMap,q=new Map,w=(X,W)=>s2(W?T?.routes().find((_)=>_.id===X)?.quota:U.peek().rows.find((_)=>_.id===X)?.quota),K2=new t1($.codex),X2=new Map,p=new Map,t=new Map,H2=(X,W,_,H)=>{if(!F2())return;let S=(p.get(X.sessionID)??0)+1,x=FZ({sessionId:X.sessionID,reason:W,now:_,...W==="quota_reading"?{boundMs:H}:{nextMs:_+H},attempt:S});if(x)p.set(X.sessionID,S);return x},x2=(X)=>{p.delete(X);for(let W of t.keys())if(JSON.parse(W)[0]===X)t.delete(W);for(let W of F.keys())if(W.startsWith(`${X}\x00`))F.delete(W);for(let[W,_]of X2)if(_===X)X2.delete(W)},Q2=new Map,D=new Map,y=(X)=>`${X.sessionID}\x00${X.kind}`,a=new Map,r=new Map,O2=(X)=>{let W=r.get(X);if(W)clearTimeout(W.timer);r.delete(X)},l2=(X,W,_)=>{let H=U2({...X,accountId:W});O2(H);let S={request:_,sessionID:X.sessionID,expiresAt:performance.now()+5000,timer:setTimeout(()=>{if(r.get(H)===S)O2(H)},5000)};if(S.timer.unref(),r.set(H,S),r.size>n2){let x=r.keys().next().value;if(x!==void 0)O2(x)}},D2=(X)=>{let W=r.get(X);return O2(X),W&&performance.now()<W.expiresAt?W.request:void 0},U2=(X)=>`${X.sessionID}\x00${X.kind}\x00${X.accountId}`,k2=$.sessionAccounts??new A1,V2=new XZ,W2=(X,W,_)=>{let H=_?[]:TZ(U.peek().rows,X,W,T?.identities()??new Set,$.configPath),S=(T?.routes()??[]).filter((x)=>x.kind==="oauth"&&t$(s2(x.quota),X,W));return[...H.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota,row:x})),...S.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota}))]},P2=(X,W,_)=>{let H=zZ(X,W,_),S=X.map((v)=>({id:v.id,kind:"oauth",...P1(v.quota)?{quota:v.quota}:{}})),x=X.flatMap((v)=>v.row?[v.row]:[]),E=new Set(X.filter((v)=>!v.row).map((v)=>v.id)),A=O?.marks()??new Map;return{rows:S,now:_,rateLimitMarks:A,refreshBackoff:U.refreshBackoffFor(x),killswitch:H,requestPull:(v)=>E.has(v)?T?.requestReading(v):U.requestReading(v)}},e2=(X,W,_,H,S,x)=>{let E=G1({...X,rows:X.rows.filter((v)=>!_.has(v.id)),placement:Y$(W),mainId:S});if(E.kind==="block"){P?.debug("pool admission refused the request",{reason:E.block.reason});return}let A=E.order.filter((v)=>!_.has(v));if(x)for(let v of A){let e=E.tiers[v];if(e)x.set(v,e)}if(H!==void 0&&A.includes(H))return H;return A[0]},w2=(X,W)=>{let _=new Map(X.map((H)=>[H.id,H.quota]));return{requestBytes:z$,reservePercent:(H)=>G$(W,H===X$?void 0:H),resetCredits:(H)=>g4(_.get(H))}},g2=(X,W,_,H,S,x,E,A,v)=>{let e=w2(W,_),g=Q$(X),C=(N2,q2)=>k1(E,{sessionId:H,requestBytes:z$,validPinnedAccountIds:X.rows.map((o)=>o.id).filter((o)=>!g.excluded.has(o)),excludeAccountIds:N2,quotaCheckedAtByAccount:Object.fromEntries(X.rows.map((o)=>[o.id,g.projections.get(o.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(W.map((o)=>[o.id,o.identity])),select:(o)=>{let J2=A?{accountId:A,source:"mode-fallback",quotaCheckedAt:g.projections.get(A)?.checkedAt}:jZ(X,e,new Set(N2),o);if(J2&&"tier"in J2)v?.set(J2.accountId,J2.tier);return J2},persist:q2},(o,J2)=>E.set(o,J2)),d=[...S],n=C(d,x);if(!n)return;let Y2=n.accountId,E2=B$(X,e,Y2);if(E2.kind==="serve")v?.set(Y2,E2.tier);else v?.delete(Y2);if(E2.kind==="none")return;if(E2.kind==="move"){let N2=C([...d,Y2],x);if(N2)return N2.accountId;return E2.reason==="killswitch"?void 0:Y2}if(E2.kind==="detour")return C([...d,Y2],!1)?.accountId;return Y2},u2={providerID:R2,async retrySameAccount(X){if(X.continuation!=="interrupted-read")return;let W=D.get(y(X));if(D.delete(y(X)),!W||W.accountId!==X.accountId||W.modelID!==X.modelID||W.agent!==X.agent||X.limit)return;let _=T!==void 0&&await T.authority()!=="local",H=r2(await $.storage(),$.configPath);if(!_&&!(await U.current()).active)return;let S=V(),x=W2(H,S,_),E=x.find((g)=>g.id===X.accountId);if(!E)return;let A=P2(x,H,S),v=H?.routing?.mode??"main-first";if(v==="sticky-balanced"){let g=B$(A,w2(x,H),X.accountId);if(g.kind!=="serve"&&g.kind!=="last-path")return}else{let g=G1({...A,placement:Y$(v),..._?{mainId:j$(T?.routes()??[])}:{}});if(g.kind==="block"||!g.order.includes(X.accountId))return}let e=W.data;if(E.row){if(e?.kind!=="pool")return;let g=U.usableToken(E.row),C=E.row.identity??(g&&H1(g));if(!g||!e.identity||C!==e.identity)return}else{if(e?.kind!=="vault"||!T)return;let g=await T.authorize(X.accountId);if(!g||g.credentialId!==e.credentialId||g.accountIdentity!==e.accountIdentity||(g.accountIdentity??H1(g.accessToken))!==e.wireIdentity||E.identity!==void 0&&E.identity!==e.wireIdentity)return}return{accountId:X.accountId}},dropSameAccountRetry(){},dropChoice(X){let W=U2(X);O2(W),a.get(W)?.drop(),a.delete(W),Q2.delete(W)},chooseAccount:async(X)=>{let W,_=await T?.authority(),H=r2(await $.storage(),$.configPath),S=_!==void 0&&_!=="local",x=()=>{throw new T2({kind:"no-account",providerID:R2,sessionID:X.sessionID,requestKind:X.kind,message:y1})};if(S){let R=performance.now()+I1;await $.awaitVaultRoster?.(),W=await O?.forRequest(R)}else{if(W=await O?.forRequest(),!(await U.current()).active){if(await $.slotPlaceholderWithoutMain?.())x();P?.warn("the account pool does not serve requests yet; refusing the request",{kind:X.kind});return}await U.prepareTokens(U.peek().rows,H)}let E=V(),A=W2(H,E,S),v=GZ(P2(A.filter((R)=>R.id!==X.rerouteFrom?.accountId),H,E));if(v){let R=H2(X,"quota_reading",E,JZ);if(await v,E=V(),A=W2(H,E,S),R)R(G1({...P2(A,H,E),requestPull:()=>{},placement:"roster",mainId:null}).kind==="block"?"abandoned":"resumed")}let e=new Map(A.map((R)=>[R.id,R])),g=P2(A,H,E),C=F2()?new Map:void 0,d=H?.routing?.maxSameAccountWait,n=JSON.stringify([X.sessionID,X.kind]),Y2=t.get(n);if(X.phase==="request"&&Y2&&(Y2.checkpoint?JSON.stringify(X.wake?.checkpoint)===Y2.checkpoint:E>=Y2.nextMs))Y2.end("resumed"),t.delete(n);let E2=[...X2.values()].includes(X.sessionID),N2=O?.activity.get(X.sessionID),q2=N2&&O?.accountKey(N2.accountKey.accountId),o=X.previousAccountId??X.rerouteFrom?.accountId,J2=o&&O?.accountKey(o),A2=X.rerouteFrom?.limit,y2=A.flatMap((R)=>{let l=O?.accountKey(R.id);if(!l)return[];let u=s2(R.quota),i=QZ(A2&&R.id===o?{account:l,kind:"rate-limit",reason:A2.reason,scope:{kind:"pool"},windows:A2.windows??[],observedAt:A2.observedAt??E}:void 0,u,E),k=g.rateLimitMarks.get(R.id),m=g.refreshBackoff.get(R.id),s=[...k&&k>E?[{kind:"hard",until:k,cause:"rate-limit"}]:[],...m&&m>E?[{kind:"cooldown",until:m}]:[]],G2=g.killswitch.get(R.id)!==!1&&!!(u?.primary||u?.secondary)&&!a$(i$(P1(R.quota)?R.quota:void 0),E)&&!(m&&m>E)&&(!R.row||!!U.usableToken(R.row));return[{account:l,admitted:G2,placementEligible:G2,ready:G2&&!s.length&&!i.length,blockers:s,confirmedBlockers:i}]}),m2={phase:X.phase==="retry"?"after-limit":"pre-send",host:"opencode2",hostPhase:X.phase,now:E,clockNow:E,sessionId:X.sessionID,requestScope:{kind:"pool"},history:n$({requestId:X.sessionID,originalUrl:"https://api.openai.com/v1/responses",clockNow:E}),delivery:{owned:!0,attributable:!0,replayable:!0},candidates:y2,...X.phase==="retry"&&J2?{attempted:J2}:{},...X.phase==="retry"&&J2&&A2?{signal:{account:J2,kind:"rate-limit",reason:A2.reason,scope:{kind:"pool"},windows:A2.windows??[],observedAt:A2.observedAt??E},status:A2.status}:{},remainingRetries:J1-(X.hostAttempt??J1)},U1=()=>{let R=O?.owner();return UZ({accounts:y2.flatMap((l)=>{let u=e.get(l.account.accountId);if(!u)return[];return[{account:l.account,reading:s2(u.quota),usable:!u.row||!!U.usableToken(u.row),confirmedBlockers:l.confirmedBlockers,floors:e$(H)?G$(H,u.id===X$?void 0:u.id):void 0,marks:R?.snapshot()?.marks.filter((i)=>i.key.window==="account"&&i.key.scope.kind==="pool"&&z1(i.key.account,l.account)).flatMap((i)=>i.entries.map((k)=>({until:k.until,evidenceAt:k.evidenceAt})))}]}),now:E,effectiveModel:X.modelID,maxSameAccountWait:d,activity:N2,currentAccountKey:q2,provenance:R?.provenance})},z=y2.find((R)=>J2&&z1(R.account,J2));if(X.phase==="retry"&&A2&&z){let R=U$({candidate:z,activity:N2,maxSameAccountWait:d,now:E,maxDelayMs:a2}),l=V$({...m2,hold:R},{mode:"sticky"});if(l?.action==="hold"&&!E2){X2.set(n,X.sessionID);let k=H2(X,"account_limit",E,l.delayMs);if(k)t.set(n,{checkpoint:JSON.stringify(l.checkpoint),nextMs:E+l.delayMs,end:k});return{hold:{delayMs:l.delayMs,target:l.target,checkpoint:l.checkpoint,kind:"hold"}}}let u=A.filter((k)=>k.id!==o);if(z.confirmedBlockers?.some((k)=>k.confirmed)&&u.length>0&&u.every((k)=>{let m=y2.find((s)=>s.account.accountId===k.id);return m&&(!m.admitted||(g.rateLimitMarks.get(k.id)??0)>E)})){if(E2)return{hostRetry:"veto"};let k=W$(m2,U1());if(J$(d)===0)return{hostRetry:"veto"};let m="delayMs"in k?k.delayMs:("retryAfterMs"in k)?k.retryAfterMs:void 0;if((m2.remainingRetries??0)<1||m===void 0||m>a2)return{hostRetry:"leave"};if(k.action==="hold"&&z1(k.account,z.account)){X2.set(n,X.sessionID);let G2=H2(X,"account_limit",E,m);if(G2)t.set(n,{checkpoint:JSON.stringify(k.checkpoint),nextMs:E+m,end:G2});return{hold:{delayMs:m,target:k.target,checkpoint:k.checkpoint,kind:"terminal"}}}X2.set(n,X.sessionID);let s=H2(X,"account_free",E,m);if(s)t.set(n,{nextMs:E+m,end:s});return{waitThenReselect:{delayMs:m}}}}let Q;if(X.phase==="request"&&X.wake?.checkpoint&&z&&(X.hostAttempt??J1)<J1&&J$(d)!==0&&z1(z.account,X.wake.checkpoint.accountKey)){let R=X.wake.checkpoint,l=new Map(R.blockers.map((m)=>[m.window,{...m,confirmed:!0,confirmedByReading:!1,observedAt:R.decidedAt,provenance:"provider"}]));for(let m of z.confirmedBlockers??[])l.set(m.window,m);let u={...z,confirmedBlockers:[...l.values()]},i=U$({candidate:u,activity:N2,maxSameAccountWait:d,now:E,maxDelayMs:a2});if(V$({...m2,attempted:z.account,candidates:y2.map((m)=>m===z?u:m),hold:i,wake:{...X.wake,checkpoint:R}},{mode:"sticky"})?.action==="retain")Q=z.account.accountId}let N=new Set(X.rerouteFrom?[X.rerouteFrom.accountId]:[]),L=H?.routing?.mode??"main-first",B=X.kind==="primary",h=new Set,I,b,f,M2=!1,_2=(R)=>{let l=Q$(g).projections.get(R)?.checkedAt,u=e.get(R)?.identity;return K.reserve(X.sessionID,{accountId:R,inputBytes:z$,...l!==void 0?{quotaCheckedAt:l}:{},...u!==void 0?{wireIdentity:u}:{}})};try{for(;;){let R=new Set([...N,...h]);f=void 0,C?.clear(),I=void 0;let l=L!=="sticky-balanced";if(Q&&!R.has(Q))f=Q,Q=void 0;else if(L==="sticky-balanced"){let i=new Map(K.placementSnapshot(X.sessionID)),k=i.get(X.sessionID);if(l=k===void 0,f=g2(g,A,H,X.sessionID,R,B&&h.size===0,i,void 0,C),f!==void 0&&i.get(X.sessionID)!==k)I=i.get(X.sessionID)}if(f??=e2(g,L,R,B?void 0:k2.activeAccount(X.sessionID),S?L==="sticky-balanced"?null:j$(T?.routes()??[]):void 0,C),f===void 0||h.has(f)){if(N.size>0){let i=new Map(g.rateLimitMarks);for(let k of N)i.delete(k);g={...g,rateLimitMarks:i},N.clear();continue}if(g.rateLimitMarks.size>0){g={...g,rateLimitMarks:new Map};continue}f=void 0;break}if(B&&L==="sticky-balanced")b=_2(f);if(!M2){M2=!0;let i=X.wake?void 0:await KZ({vaultMode:S,fresh:l,sessionId:X.sessionID,request:{modelId:X.modelID,kind:X.kind,retry:X.phase==="retry"||X.rerouteFrom!==void 0},routes:T?.routes()??[],warmAccountId:L==="sticky-balanced"?K.get(X.sessionID):k2.activeAccount(X.sessionID),routing:g,wait:{activity:N2,accountKey:q2,maxSameAccountWait:d},eligibleIds:A.filter((k)=>!R.has(k.id)).map((k)=>k.id)});if(i&&typeof i!=="string")throw new T2({kind:"no-account",providerID:R2,sessionID:X.sessionID,requestKind:X.kind,message:HZ});if(i&&i!==f){if(b)K.rollback(b);if(b=void 0,L==="sticky-balanced"){let k=new Map(K.placementSnapshot(X.sessionID));f=g2(g,A,H,X.sessionID,R,B,k,i,C)??f,I=k.get(X.sessionID)??I}else f=i;if(B&&L==="sticky-balanced")b=_2(f)}}let u=e.get(f)?.row;if(u){if(U.usableToken(u)!==void 0)break;P?.debug("pool row holds no usable token; choosing again",{accountId:f})}else{if(!T)break;let i=await T.authorize(f);if(i){Q2.set(U2({...X,accountId:f}),{receipt:i,freeQuota:C?.get(f)==="free"});break}P?.debug("the vault refused to serve an account; choosing again",{accountId:f})}if(b)K.rollback(b);b=void 0,h.add(f)}if(f===void 0&&!S&&A.length===0&&await $.slotPlaceholderWithoutMain?.())x();if(f===void 0&&S&&T&&(A.length===0||h.size>0)){let R=h.size>0?"vault-refused":ZZ(T);throw P?.warn("vault mode: no vault account can serve; refusing the request",{cause:R}),new T2({kind:"no-account",providerID:R2,sessionID:X.sessionID,requestKind:X.kind,message:$Z(R,T.name)})}if(f!==void 0){if(W)l2(X,f,W);let R=f,l=b,u=I,i=()=>{if(l)K.finish(l,u);if(B)k2.record(X.sessionID,R),$.onRoute?.(X.sessionID,R,L)};if(X.phase==="retry")a.set(U2({...X,accountId:f}),{commit:i,drop:()=>{if(l)K.rollback(l)}}),b=void 0;else i();let k=P?.info;V2.served(g,f,P&&k?{info:(m,s)=>k.call(P,m,s)}:void 0)}if(f===void 0&&X.phase==="request"&&y2.length>0&&y2.every((R)=>!R.admitted)&&y2.some((R)=>g.killswitch.get(R.account.accountId)===!1||R.confirmedBlockers?.length)){let R=W$(m2,U1()),l=VZ({decision:R,now:E,host:"opencode2",requestThrow:!0,maxSameAccountWait:d});if(l.kind==="http"){let u=JSON.parse(l.body);throw new T2({kind:"no-account",providerID:R2,sessionID:X.sessionID,requestKind:X.kind,message:u.error.message})}}return P?.debug("pool account chosen",{kind:X.kind,accountId:f,mode:L,...X.rerouteFrom?{rerouteFrom:X.rerouteFrom.accountId}:{}}),f}finally{if(b)K.rollback(b)}},accountHeaders:async(X)=>{let{accountId:W}=X;D.delete(y(X));let _=U2(X),H=a.get(_);a.delete(_);let S=()=>{H?.commit()};try{let x=()=>new T2({kind:"no-account",providerID:R2,sessionID:X.sessionID,requestKind:X.kind,message:h4}),E=async(C)=>{if(!O)return;let d=D2(_)??await O.forRequest();if(C.kind==="pool"){let o=U.peek().rows.find((J2)=>J2.id===W);if(!o||o.credentialEpoch!==C.credentialEpoch||U.usableToken(o)!==C.token)throw x()}let n=O.bindings().find((o)=>o.account.accountId===W),Y2=await d?.beforeDispatch(n,()=>O.ownershipBindings(),W),E2=O.accountKey(W);if(Y2&&Y2.status!=="ready"||n&&(!E2||!z1(n.account,E2)))throw x();let N2=O.owner(),q2=n?{sessionId:X.sessionID,accountKey:n.account,dispatchedAt:V(),ttlMs:WZ(JSON.stringify({model:X.modelID}))}:void 0;if(q2){if(q.delete(q2.sessionId),q.set(q2.sessionId,q2),q.size>n2){let o=q.keys().next().value;if(o!==void 0)q.delete(o)}}z2.set(C,{owner:N2,probe:N2?.observe(n),dispatch:q2,failed:!1,completed:!1})},A=T&&await T.authority()!=="local"?void 0:U.peek().rows.find((C)=>C.id===W);if(!A&&T){let C=U2(X),d=Q2.get(C),n=d?.receipt??await T.authorize(W);if(Q2.delete(C),!n)throw P?.warn("the vault refused to serve an account; refusing the request",{accountId:W}),x();let Y2={kind:"vault",routeId:W,receipt:n,...d?.freeQuota?{freeQuota:!0}:{}};return await E(Y2),S(),{headers:{...r1,"session-id":X.sessionID,authorization:`Bearer ${n.accessToken}`,"chatgpt-account-id":n.accountIdentity??H1(n.accessToken)??null},attempt:Y2}}let v=A?U.usableToken(A):void 0;if(!A||!v)throw P?.warn("pool row holds no usable token; refusing the request",{accountId:W}),x();let e=A.identity??H1(v),g={kind:"pool",token:v,credentialEpoch:A.credentialEpoch,...e!==void 0?{identity:e}:{}};return await E(g),S(),{headers:{...r1,"session-id":X.sessionID,authorization:`Bearer ${v}`,"chatgpt-account-id":e??null},attempt:g}}finally{H?.drop()}},async rewriteRequest({request:X,sessionID:W,kind:_,attempt:H}){let S=$.codexEndpoint?e1(X.url,$.codexEndpoint()):X.url,x=S===X.url?X:new Request(S,X);return await g$(x,{sessionID:W,kind:_},K2,$.responsesLite?.()??!1,void 0,M(H))??x},rewriteHandshakeURL:({url:X})=>$.codexEndpoint?e1(X,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:X,sessionID:W,kind:_,attempt:H})=>l$(X,{sessionID:W,kind:_},K2,M(H)),quotaFromHeaders:(X,W,_)=>{if(_.data?.kind==="vault")T?.reportUsage(_.data.routeId,{headers:X},_.data.receipt);if(_.data?.kind==="vault"&&F2()&&W>=200&&W<300)Z.set(_,{status:W,headers:X});return l4(X)},async limitFromResponse({status:X,headers:W,body:_,attempt:H}){if(X<400)return;let S=F1(await _().catch(()=>"")),x=V(),E=b1({...C2(S)?S:{},status:X},x);if(H.data?.kind==="vault"&&F2())S1(H.sessionID,H.data.receipt,{status:X,headers:W,body:S,limit:E,quota:T?.routes().find((e)=>e.id===H.accountId)?.quota,now:V()}),Y??=new WeakSet,Y.add(H);if(!E)return;let A=K1(E,x,X,w(H.accountId,H.data?.kind==="vault"));if(A.retryAfterMs!==void 0)return A;let v=u4(W);return v===void 0?A:{...A,retryAfterMs:v,resetAt:x+v,resetSource:"retry-after"}},inspectEvent:({data:X,transport:W,attempt:_})=>{let H=F1(X),S=!1,x=_.data&&z2.get(_.data);if(x&&C2(H)&&(H.type==="response.failed"||H.type==="error"))x.failed=!0;if(x&&C2(H)&&H.type==="response.completed")x.completed=!0;if(_.data?.kind==="vault"&&X.includes("codex.rate_limits")){let A=F1(X);if(C2(A)&&A.type==="codex.rate_limits")T?.reportUsage(_.data.routeId,{frame:A},_.data.receipt)}if(_.data?.kind==="vault"&&F2()){let A=j.get(_);if(A)A.event(H),S=W==="ws"&&C2(H)&&(H.type==="response.incomplete"||H.type==="response.failed"||H.type==="error");if(MZ(X)||W==="ws"&&X.includes('"response.completed"')){if(LZ(H))J.add(_);if(W==="ws"&&C2(H)&&H.type==="response.completed")S1(_.sessionID,_.data.receipt,{status:200,headers:new Headers,failed:J.has(_)})}}let E=xZ(H,V(),w(_.accountId,_.data?.kind==="vault"));if(_.data?.kind==="vault"&&F2()&&E?.limit)G??=new WeakMap,G.set(_,H);return S||W==="ws"&&C2(H)&&H.type==="response.completed"?{...E,done:!0}:E},limitFromError(X,W){let _=F1(X.message),H=V(),S=w(W.accountId,W.data?.kind==="vault"),x=CZ({...C2(_)?_:{},...X.status!==void 0?{status:X.status}:{}},H,S)??(X.message.includes("usage_limit_reached")?K1({window:"usage_limit_reached"},H,X.status,S):void 0);if(W.data?.kind==="vault"&&F2()&&x)G??=new WeakMap,G.set(W,_);return x},async onAttemptEnd(X,W){let _=X.data?.kind==="vault"&&F2()?j.get(X):void 0;if(_)j.delete(X),_.end(W.outputStarted,!W.error,W.status,W.error?.reason==="cancelled");let H=X.data,S=H&&z2.get(H);if(S){let E=!W.error&&!W.limit&&!S.failed&&(X.transport==="ws"?S.completed:W.status!==void 0&&W.status>=200&&W.status<300);if(E&&S.dispatch&&O){let A=q.get(S.dispatch.sessionId);NZ(O.activity,S.dispatch,A===S.dispatch?O.accountKey(X.accountId):void 0,X.transport==="ws"?{kind:"ws",event:"response.completed",aborted:!1}:{kind:"http",completed:!0,failed:!1,aborted:!1})}S.owner?.afterProbe(S.probe,E,Boolean(W.limit))}if(H&&W.outputStarted&&W.error?.reason==="failed"){if(D.set(y(X),{accountId:X.accountId,modelID:X.modelID,agent:X.agent,sessionID:X.sessionID,data:H.kind==="pool"?{kind:"pool",identity:H.identity}:{kind:"vault",credentialId:H.receipt.credentialId,accountIdentity:H.receipt.accountIdentity,wireIdentity:H.receipt.accountIdentity??H1(H.receipt.accessToken)}}),D.size>n2){let E=D.keys().next().value;if(E!==void 0)D.delete(E)}}let x=H?.kind==="vault"&&F2()?Z.get(X):void 0;if(Z.delete(X),H?.kind==="vault"&&F2()&&W.limit&&G?.has(X)&&!Y?.has(X)){Y??=new WeakSet,Y.add(X);let E=W.limit;if(E.windows?.some((A)=>A.confirmed))PZ(X.sessionID,H.receipt,{window:E.reason,resetAt:E.resetAt},{body:G?.get(X),headers:x?.headers,quota:T?.routes().find((A)=>A.id===X.accountId)?.quota,now:E.observedAt})}if(G?.delete(X),H?.kind==="vault"&&x&&!W.error&&!W.limit)S1(X.sessionID,H.receipt,{...x,failed:J.has(X)});if(H?.kind!=="vault"||W.status!==401)return;P?.warn("a vault account answered 401; reporting it to the vault",{accountId:X.accountId}),await T?.reportFailure(H.receipt,401)}},L2=(X,W,_)=>{let H=_.data;if(H?.kind==="vault"){T?.recordSnapshot(X,W.snapshot,W.complete,H.receipt);return}if(H?.kind!=="pool")return;if(U.peek().rows.find((x)=>x.id===X)?.credentialEpoch!==H.credentialEpoch){P?.debug("quota reading dropped: the row holds another credential",{accountId:X});return}U.recordSnapshot(X,W.snapshot,H.token,W.complete)},p2=(X,W,_)=>{let H=V(),S=_.data?.kind==="vault";if(O){let x=_.data&&z2.get(_.data),E=x?.owner??O.owner();if(!E)return;if(!x?.probe||E.registry!==x.probe.registry){E.dropSignal();return}let A=W,{command:v,provenance:e}=BZ({binding:x.probe.binding,baseRevision:x.probe.baseRevision,producerId:c,operationId:d$(),parsed:{window:W.reason,resetAt:A.resetAt??(W.retryAfterMs!==void 0?H+W.retryAfterMs:void 0)},reading:w(X,S),now:H,observedAt:A.observedAt??H,evidenceAt:H,resetSource:A.resetSource});E.enqueue(v,e);return}};return{adapter:u2,beginTurn:x2,dispose:()=>{X2.clear(),p.clear(),t.clear(),F.clear()},attach(X){X.on("quota",(W)=>L2(W.accountId,W.quota,W.handle)),X.on("limit",(W)=>{p2(W.accountId,W.limit,W.handle),P?.debug("pool row refused the request",{accountId:W.accountId,via:W.via,reason:W.limit.reason,outputStarted:W.outputStarted})})},forgetSession(X){x2(X);for(let[W,_]of r)if(_.sessionID===X)O2(W);q.delete(X),O?.forget(X);for(let[W,_]of D)if(_.sessionID===X)D.delete(W);K.forget(X),k2.forget(X),K2.forget(X)},activeAccount:(X)=>k2.activeAccount(X)}}import{resolve as h1}from"node:path";function qZ($,Z){if(!Z.ok||!Z.body)return $.end(!1,!0,Z.status),Z;let J=!1,Y=Z.body.pipeThrough(W1((j)=>{J||=EZ(j.data,Date.now())?.outputStarted===!0;try{$.event(JSON.parse(j.data))}catch{}},()=>{})).getReader();return new Response(new ReadableStream({async pull(j){try{let F=await Y.read();if(F.done)j.close(),$.end(J,!0,Z.status);else j.enqueue(F.value)}catch(F){j.error(F),$.end(J,!1,Z.status)}},cancel(j){return $.end(J,!1,Z.status),Y.cancel(j)}}),{status:Z.status,statusText:Z.statusText,headers:Z.headers})}import{Buffer as p4}from"node:buffer";import{resolve as AZ}from"node:path";function L1($){return p4.byteLength(JSON.stringify($))}function c4($){return $.reduce((Z,J)=>Z+L1(J),0)}function N$($,Z){return 2+$+Math.max(0,Z-1)}function d4($){let{head:Z,pending:J}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+N$(Z.inputBytes,Z.input.length)+1:0)+(J?20+N$(J.inputBytes,J.input.length)+10+N$(J.outputBytes,J.output.length)+(J.responseID===void 0?0:14+J.responseIDBytes)+1:0)}function SZ($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class bZ{enabled;caps=f1;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$){for(let Z of this.entries.keys())if(!t2(Z,$))this.forget(Z)}}send($,Z){if(!t2($,this.enabled)){this.forget($);return}let J=SZ(Z);if(J?.type!=="response.create")return;if(!Array.isArray(J.input)){this.forget($);return}let G=J.previous_response_id,Y=this.entries.get($),j=Y?.head;if(G&&G!==j?.responseID){this.forget($);return}let{type:F,previous_response_id:M,input:U,...K}=J;this.keep($,{fields:G&&Y?Y.fields:K,fieldsBytes:G&&Y?Y.fieldsBytes:L1(K),...G&&j?{head:j}:{},pending:{input:U,inputBytes:c4(U),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,J){if(!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed")||!t2($,this.enabled))return;let G=this.entries.get($);if(!G?.pending)return;let Y=SZ(Z);if(!Y)return;let j=G.pending,F=Y.response;if(Y.type==="response.created"&&typeof F?.id==="string")j.responseID=F.id,j.responseIDBytes=L1(F.id),this.keep($,G);else if(Y.type==="response.output_item.done"&&Y.item){if(typeof Y.response_id==="string"&&j.responseID!==void 0&&Y.response_id!==j.responseID)return;j.output.push(Y.item),j.outputBytes+=L1(Y.item),this.keep($,G)}else if(Y.type==="response.completed"&&typeof F?.id==="string"){if(F.id===G.head?.responseID||j.responseID!==void 0&&F.id!==j.responseID)return;let M={responseID:F.id,responseIDBytes:j.responseID===F.id?j.responseIDBytes:L1(F.id),input:[...G.head?.input??[],...j.input,...j.output],inputBytes:(G.head?.inputBytes??0)+j.inputBytes+j.outputBytes},U={...G,head:M,pending:void 0};if(!this.keep($,U))return;J?.({sessionID:$,responseID:M.responseID,bodyText:this.body(G.fields,M)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let J=d4(Z);if(this.forget($),J>this.caps.maxBytes)return!1;Z.bytes=J,this.entries.set($,Z),this.bytes+=J;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let G=this.entries.keys().next().value;if(G===void 0)break;this.forget(G)}return this.entries.has($)}}var RZ=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),DZ=globalThis,H$=DZ[RZ]??new Map;DZ[RZ]=H$;function v1($){let Z=JSON.stringify([AZ($.configPath),AZ($.statePath)]),J=H$.get(Z);if(!J)J=new bZ,H$.set(Z,J);return J}var i4=5000,a4=["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"],n4=["x-opencode-parent-session-id","x-parent-session-id"];function F$($,Z){let J=r2($,Z),G=kZ(J);return{enabled:G?.enabled===!0,subagents:G?.subagents===!0,sustain:G?.sustain===!0,window:wZ({...J,cachekeep:G})}}var IZ=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),fZ=globalThis,X1=fZ[IZ]??new Map;fZ[IZ]=X1;function vZ($,Z){let J=JSON.stringify([h1($.configPath),h1($.statePath)]);return X1.get(J)?.manager.warming(Z)??{on:!1}}function o4($,Z){let J=[],G=()=>J.at(-1)?.location,Y=()=>{let U=G();if(!U)throw Error("no location holds keep-warm");return U},j=(U,K)=>{M.remove(U),G()?.log?.debug(`cachekeep dropped target (${K})`,{sessionKey:U})},F=async(U)=>{if(U.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let K=U.accountId??"main",V=Y(),P=await V.source.accessFor(K,await V.storage());if(!P)throw Error(`pool row ${K} has no usable token`);return{token:P.token,identity:P.row.identity}},M=yZ({observeBillingSend(U,K,V,P){if(!V.credentialId||!F2())return;let T=U.meta.routingSessionId;if(!T)return;let O;try{O=JSON.parse(K).model}catch{return}if(typeof O!=="string")return;let c=Y().vault.routes().find((w)=>w.id===U.accountId),z2=G1({rows:c?[{id:c.id,kind:"oauth",...P1(c.quota)?{quota:c.quota}:{}}]:[],now:$.now(),placement:"roster",mainId:null,rateLimitMarks:new Map,refreshBackoff:new Map,killswitch:new Map,requestPull:()=>{}}),q=new w1(T,V,"keep_warm",O,P,(w)=>M.warming(w),c!==void 0&&z2.kind==="send"&&z2.tiers[c.id]==="free");return{response:(w)=>qZ(q,w),failed:()=>q.end(!1,!1)}},...f1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(U,K)=>Y().fetch(U,K),logger:{debug:(U,K)=>G()?.log?.debug(U,K),warn:(U,K)=>G()?.log?.warn(U,K)},getWindow:()=>G()?.settings().window,getSustain:()=>G()?.settings().sustain===!0,resolveLocal:F,activity:{store:{get size(){return G()?.limits?.activity.size??0},get:(U)=>G()?.limits?.activity.get(U),forgetSession:(U)=>G()?.limits?.activity.forgetSession(U),recordAccepted:(U)=>G()?.limits?.activity.recordAccepted(U)??!1},accountKey:({target:U})=>{let K=G(),V=U.meta.routingSessionId??U.sessionKey,P=U.accountId??"main";return K?.accounts.activeAccount(V)===P?K.limits?.accountKey(P):void 0}},vault:{owns:(U)=>G()?.vault.owns(U)===!0,authority:()=>Y().vault.authority(),reportUsage:(...U)=>G()?.vault.reportUsage(...U),send:async(U,K,V)=>{let P=Y(),T=await P.vault.authority();if(T!=="vault"&&T!=="host")return;return P.vault.send(U,K,V)}},activeAccount:(U)=>{if(U===void 0)throw Error("target has no session");let K=G(),V=K?.settings();if(!K||!V||!t2(U,V.enabled)){j(U,"keep-warm is off");return}if(!V.subagents&&M.status().targets.some((T)=>T.sessionKey===U&&T.isSubagent)){j(U,"subagent warming is off");return}let P=K.accounts.activeAccount(U);if(P===void 0){j(U,"no account recorded for the session");return}return P},verifyCredential:({target:U,mode:K,identity:V})=>{if(U.meta.credentialMode!==K)throw Error(`a target captured in ${U.meta.credentialMode??"an unknown"} mode is not warmed with a ${K} credential`);if(V!==U.meta.chatgptAccountId)throw j(U.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:M,settings:Z,holders:J,joinTimeoutMs:$.joinTimeoutMs??i4}}function s4($){try{let Z=JSON.parse($),J=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(J?.role!=="user")return!1;return(typeof J.content==="string"?J.content:Array.isArray(J.content)?J.content.map((Y)=>typeof Y?.text==="string"?Y.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function r4($){let Z={};for(let J of a4){let G=$.get(J);if(G)Z[J]=G}return Z}function hZ($,Z,J){let G=JSON.stringify([h1($.configPath),h1($.statePath)]),Y=X1.get(G);if(!Y)Y=o4(J,Z.settings()),X1.set(G,Y);let j=Y,F=v1($);F.setEnabled(j.settings.enabled);let M={location:{...Z,settings:()=>j.settings}};j.holders.push(M);let U=!1,K=async(V)=>{try{let P=M.location.settings();if(U||!t2(V.sessionID,P.enabled))return;if(V.kind!=="primary"){if(V.kind==="generate"&&s4(await V.request.clone().text())){if(U)return;j.manager.remove(V.sessionID)}return}let T=V.attempt.data,O=T?.kind==="pool"?"local":T?.kind==="vault"?"vault":void 0;if(!O)return;let c=V.request.headers,z2=n4.some((K2)=>c.has(K2))||Z.parentOf!==void 0&&await Z.parentOf(V.sessionID)!==void 0;if(z2&&!P.subagents)return;let q=await V.request.clone().text();if(U)return;let w=c.get("chatgpt-account-id")??void 0;j.manager.track({sessionKey:V.sessionID,bodyText:q,accountId:V.attempt.accountId,isSubagent:z2,meta:{replayHeaders:r4(c),...w?{chatgptAccountId:w}:{},routingSessionId:V.sessionID,url:V.request.url,credentialMode:O}})}catch(P){Z.log?.warn("cachekeep capture failed",{error:P instanceof Error?P.message:String(P)})}};return{manager:j.manager,configure:(V)=>{Object.assign(j.settings,V),F.setEnabled(j.settings.enabled)},capture:K,forget:(V)=>j.manager.remove(V),async release(){if(U)return;U=!0;let V=j.holders.indexOf(M);if(V>=0)j.holders.splice(V,1);if(j.holders.length>0)return;if(X1.get(G)===j)X1.delete(G);j.manager.stop();let P;try{await Promise.race([j.manager.tick().catch(()=>{}),new Promise((T)=>{P=setTimeout(T,j.joinTimeoutMs),P.unref?.()})])}finally{clearTimeout(P)}}}}import{mkdirSync as t4}from"node:fs";import{dirname as e4,resolve as $5}from"node:path";function Z5(){return gZ("opencode2")}var z5=2000;class cZ{path;options;sessions;frameTurns=new Z1;#$=new Set;#Z=new Set;#J=new Set;#G=Promise.resolve();#X=!1;#z;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=uZ($,Z.uuid??o2)}get($,Z=o2){let J=this.sessions.get($);if(!J){let G=Z();J={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,J),this.#Z.delete($),this.#J.delete($),this.#$.add($),this.#j()}return J}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#J.add($);this.#j()}#j(){if(this.#z)return;this.#z=setTimeout(()=>{this.#z=void 0,this.save()},this.options.saveDelayMs??z5),this.#z.unref?.()}save(){if(clearTimeout(this.#z),this.#z=void 0,!this.#X)this.#X=!0,this.#G=this.#G.then(()=>{return this.#X=!1,this.#Q()});return this.#G}settled(){return this.#z?this.save():this.#G}#Y(){if(this.#J.size===0)return;let $;try{$=K$(this.path)}catch{$=new Map}for(let Z of this.#J)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#J.clear()}async#Q(){if(this.#Y(),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],J=null;try{if(t4(e4(this.path),{recursive:!0}),J=await this.#B(),!J)return;let G;try{G=K$(this.path)}catch{G=new Map}await this.options.afterRead?.();let Y=!1;for(let j of Z)if(G.delete(j))Y=!0;for(let[j,F]of $){if(G.get(j)===F.threadID)continue;G.set(j,F.threadID),Y=!0}if(Y)pZ(this.path,G)}catch{return}finally{await J?.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 lZ(this.path,this.options.lockWaitMs??mZ)}}var dZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),iZ=globalThis,g1=iZ[dZ]??new Map;iZ[dZ]=g1;function J5($){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 aZ($=Z5()){let Z=$5($),J=g1,G=g1.get(Z),Y=g1;if(G!==void 0&&!J5(G))J.compatible??=new Map,Y=J.compatible;let j=Y.get(Z);if(!j)j=new cZ(Z),Y.set(Z,j);let F=j;return F.frameTurns??=new Z1,j}var P$=Symbol.for("cortexkit.openai-auth.v2.commands"),G5=h2("v2-command");function m1($){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 L$($){G5.warn(`/openai needs the terminal UI (session state: ${$}).`)}function X5(){let $=globalThis;return $[P$]??={locations:new Map},$[P$].locations??=new Map,$[P$]}async function $0($,Z){let J=X5(),G=$.location.directory,Y={menu:Z,session:$.session,closed:new AbortController},j=await oZ(G),F=await nZ(tZ,j.dir,()=>eZ({...j,drain:rZ,apply:(P)=>{let T=J.locations.get(G);if(!m1(T))throw Error("The OpenAI menu location was closed");return T.menu.apply(P)}})),M=J.locations.get(G);if(J.locations.set(G,Y),m1(M))M.closed.abort(),await M.registration?.dispose();let U={name:"openai",description:"OpenAI account menu",async execute(P){let T=[...J.locations.values()].find(m1)?.session;if(!T)return L$("no live location");let O=await T.get({sessionID:P.sessionID}),c=J.locations.get(O.location.directory);if(!m1(c))return L$("location closed");let z2=await sZ(P.sessionID,c.closed.signal);if(!z2||J.locations.get(O.location.directory)!==c){if(!z2&&!c.closed.signal.aborted)M$({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},P.sessionID);return L$(c.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let q=await c.menu.open(P.sessionID);M$(q,P.sessionID)}};J.command??=U,J.command.execute=U.execute;let K=J.command;try{Y.registration=await $.command.transform((P)=>{P.add(K)})}catch(P){if(Y.closed.abort(),J.locations.get(G)===Y)J.locations.delete(G);throw await F.release(),P}let V=!1;return async()=>{if(V)return;if(V=!0,Y.closed.abort(),J.locations.get(G)===Y)J.locations.delete(G);await F.release(),await Y.registration?.dispose()}}var j5="openai-auth-pool-browser",Y5="openai-auth-pool-headless",Q5="openai-auth-vault",B5="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 M1($){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 Q0($){return{method:{id:Q5,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){let Z=await z0($.paths,$.name);if(Z==="host"){let J=Z0(G0);await Promise.resolve(J.close()).catch(()=>{return})}else if(Z!=="vault")throw Error(B5)}}}function B0($){let Z=(J,G,Y)=>({method:{id:J,type:"oauth",label:G},async authorize(){if($.vault)await M1($.vault);let j=await $.beginLogin({version:$.version,headless:Y});return{url:j.url,instructions:j.instructions,mode:"auto",callback:j.completion}}});return[Z(j5,"ChatGPT (openai-auth pool, browser)",!1),Z(Y5,"ChatGPT (openai-auth pool, headless)",!0)]}function _$($){let Z=(J)=>typeof J==="string"?J:"";return V1({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===j0||J0($)}function U5($){if($.accountId)return $.accountId;let Z=$.access?R1($.access):void 0;return Z?D1(Z):void 0}async function U0($,Z,J,G={}){if(G.vault)await M1(G.vault);if(_$(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Y=X0($,{rowLocks:(O)=>Y0(Z,O)}),j=await Y.read();if(j.status!=="ready")throw Error(`the account pool cannot be read (${j.status}); the login was not stored`);let F={type:"oauth",refresh:J.refresh,...J.access!==void 0?{access:J.access}:{},...J.expires!==void 0?{expires:J.expires}:{}},M=U5(J);if(G.vault)await M1(G.vault);let U=M!==void 0?{identity:M}:{};if(G.origin==="import"){let O=j.rows.find((c)=>M!==void 0&&c.identity===M||c.credential?.type==="oauth"&&c.credential.refresh===J.refresh);if(O)return{id:O.id,operation:"kept"}}let K=j.rows.filter((O)=>O.type==="oauth"&&!O.invalid),V=M?K.find((O)=>O.identity===M):void 0,P=j.rows.find((O)=>O.id===l1);if(V)return{id:(await Y.replace(V.id,F,U)).id,operation:"replaced"};if(!P){let O=await Y.add({id:l1,credential:F,...U,...J.label!==void 0?{label:J.label}:{}});return{id:O.id,operation:O.outcome==="added-disabled"?"added-disabled":"added"}}if(!P.invalid&&!P.credential)return{id:(await Y.replace(l1,F,U)).id,operation:"replaced"};let T=await Y.add({id:J.id,credential:F,...U,...J.label!==void 0?{label:J.label}:{}});return{id:T.id,operation:T.outcome==="added-disabled"?"added-disabled":T.outcome==="rotated"?"replaced":"added"}}function V5($){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","maxSameAccountWait"].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 N0($){let Z={...$,allowAction:V5,unavailableSections:[]};return{open:(J)=>V0(Z,J),apply:(J)=>{let G=J!==null&&typeof J==="object"?J:{},Y=G.values&&typeof G.values==="object"&&!Array.isArray(G.values)?Object.fromEntries(Object.entries(G.values).filter(([,j])=>j===null||["string","number","boolean"].includes(typeof j))):void 0;return W0(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 W5($,Z){if(!H0($.modelID??$.id)){$.enabled=!1;return}let J=F0($.id);if(J)$.limit={...J};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((G)=>[G.id,G])).values()]}function P0($){return $.model.transform((Z)=>{let J=Z.list(R2);for(let G of J){let Y=K0(String(G.id)),j=Y?J.find((F)=>String(F.id)===Y):void 0;Z.update(R2,String(G.id),(F)=>W5(F,j?.variants?.map((M)=>({...M,id:String(M.id)}))))}})}class T${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(!L0())return;await this.safely(async()=>{let J={sessionID:Z.sessionID,accountId:Z.accountId,transport:"http",phase:"http",url:$.url,method:$.method,headers:new Headers($.headers),bodyText:await $.clone().text()};if(this.pending.set($,{attemptId:Z.attemptId,input:J}),this.requests.set(Z.attemptId,$),this.pending.size>512){let G=this.pending.keys().next().value;if(G)this.take(G)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let J=this.take($);if(J)await this.safely(()=>u1({...J,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let J=this.requests.get($.attemptId),G=J&&this.take(J);if(!G)return;let{reason:Y,message:j}=Z.error,F=j?`${Y}: ${j}`:Y;await this.safely(()=>u1({...G,error:p1(F,J?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>u1({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 C${counts=new Map;record($,Z){let J=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof J==="number"&&Number.isFinite(J)?J:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function E0($){return async(Z)=>{let J=Z.credential;if(J.type!=="oauth"||!J.access)throw Error("the row holds no access token to poll with");let G=await M0({accessToken:J.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,G),_0(G,$.now(),!0)}}function x0($){let{source:Z,counts:J,now:G}=$,Y=async(K)=>{let V=await Z.rowAccess(K,await $.storage());if(!V?.row)throw new T0("unknown_account",`${K==="main"?"Main":"Fallback"} account ${K} was not found.`);return C0(K,V)},j=async(K)=>{if($.authority&&await $.authority()!=="local")return{account:K,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[V]=await Z.pollRows(await $.storage(),{ids:[K]});if(!V)return{account:K,ok:!1,error:"targeted quota refresh returned no result"};return{account:V.id,ok:V.ok,...V.error!==void 0?{error:V.error}:{}}},F=(K)=>Z.peek().rows.find((V)=>V.id===K),M=(K)=>{let V=F(K);if(!V)return null;let P=s2(V.quota)??{},T=J.applicable(V),O=Math.max(0,...[P.primary?.checkedAt,P.secondary?.checkedAt].filter((c)=>typeof c==="number"));return{quota:{...P,...T!==void 0?{resetCreditsApplicable:T}:{}},checkedAt:O,refreshAfter:O,...V.identity!==void 0?{accountId:V.identity}:{}}};return{resolveResetTarget:Y,refreshResetTargetQuota:j,quotaManager:{isRateLimited:(K)=>{let V=F(K);if(!V)return!1;let P=$.rateLimitMarks().get(V.id);return P!==void 0&&P>G()},getMain:()=>M("main"),getFallback:(K)=>M(K)}}}import{resolve as O0}from"node:path";var N5=1024;class E${pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=N5){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.reservations.delete($),this.pins.delete($);for(let Z of this.listeners)Z($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}snapshot(){return new Map(this.pins)}placementSnapshot($){let Z=new Map(this.pins);for(let J of this.reservations.values())if(J.sessionId!==$)Z.set(J.sessionId,J.pin);return Z}reserve($,Z){let J={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,J),J}rollback($){if(this.reservations.get($.sessionId)===$)this.reservations.delete($.sessionId)}finish($,Z){if(this.reservations.get($.sessionId)!==$)return;if(this.rollback($),Z&&this.pins.get($.sessionId)===$.previous)this.set($.sessionId,Z)}get size(){return this.pins.size}set($,Z){this.reservations.delete($),this.pins.delete($),this.pins.set($,Z);for(let J of this.listeners)J($,Z);while(this.pins.size>this.limit){let J=this.pins.keys().next().value;if(J===void 0)break;this.forget(J)}}place($){return k1(this.placementSnapshot($.sessionId),$,(Z,J)=>this.set(Z,J))}}var q0=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),A0=globalThis,c1=A0[q0]??new Map;A0[q0]=c1;function H5($){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 S0($){let Z=JSON.stringify([O0($.configPath),O0($.statePath)]),J=c1,G=c1.get(Z);if(G!==void 0&&!H5(G)){let j=c1;j.compatibleV1??=new Map,J=j.compatibleV1}let Y=J.get(Z);if(!Y)Y=new E$,J.set(Z,Y);return Y}import{statSync as F5}from"node:fs";import{resolve as K5}from"node:path";function v0($){return $.map((Z)=>{try{let J=F5(Z);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}function x$($){return v0([$.vault.paths.tokenPath,$.vault.paths.statePath])}function b0($){return v0([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+x$($)}class h0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;protocol=m0;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:b0($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),J=this.subscriptions.get($.pins);if(!J){let G=new Set;J={producers:G,stop:$.pins.subscribe((Y,j)=>{let F=G.values().next().value;if(F)this.publish(F,{sessionId:Y,pin:j,accountId:j?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,J)}return J.producers.add($),this.timer??=setInterval(()=>{for(let G of this.producers){let Y={stamp:b0(G),roster:G.vault.snapshot()},j=this.observations.get(G);if(Y.stamp!==j?.stamp||Y.roster!==j?.roster)this.observations.set(G,Y),this.publish(G)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),J.producers.delete($),!J.producers.size)J.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;await($.write??g0)(this.file,$,Z,()=>this.producers.has($))}).catch(()=>{h2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var g0=async($,Z,J,G)=>{let j=await Z.vault.authority()!=="local",F=x$(Z),M=()=>G()&&Z.vault.enrolled()===j&&x$(Z)===F,U=await(j?T1(Z.paths):j1(Z.paths)),K=j?I0(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((T)=>T.id)),U,Date.now()):f0((await Z.source.sidebarView()).rows,U,Date.now()),V={canWrite:M,vaultMode:j};if(await D0(K,$,V),!M()||!J)return;let P=K.vaultAccounts??K.fallbacks;if(J.accountId===void 0){await w0(J.sessionId,P,$,V);return}if(J.pin){let T=Date.now();await y0({sessionId:J.sessionId,assignment:{accountId:J.pin.accountId,wireAccountId:J.pin.wireIdentity,inputBytes:J.pin.inputBytes??0,quotaCheckedAt:J.pin.quotaCheckedAt,assignedAt:T,lastSeenAt:T},validPinnedAccountIds:[...j?[]:["main"],...P.filter((O)=>O.enabled).map((O)=>O.id)]},$,V)}await k0({sessionId:J.sessionId,activeId:J.accountId,route:J.route??K.route,updatedAt:Date.now()},P,$,V)},m0=2,l0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),u0=globalThis,_1=u0[l0]??new Map;u0[l0]=_1;function p0($,Z=R0(),J=2000){let G=K5(Z),Y=_1.get(G);if(Y?.protocol!==m0)Y=new h0(G,J),_1.set(G,Y);let j=Y;$={...$,write:$.write??g0};let F=j.add($),M=!1;for(let[U,K]of $.pins.snapshot())j.publish($,{sessionId:U,pin:K,accountId:K.accountId,route:"sticky-balanced"});return{publish:()=>j.publish($),route:(U,K,V)=>{j.publish($,{sessionId:U,accountId:K,route:V})},async release(){if(M)return;if(M=!0,F(),await j.settled(),j.empty&&_1.get(G)===j)_1.delete(G)}}}var i1="cortexkit-openai-auth",M5=5000;async function c0($,Z,J,G=new N1,Y,j,F){let M=new T$(J),U=new P5,K=new Map,V=new Map,P=(q)=>{V.delete(q);for(let w of K.keys())if(w.startsWith(`${q}:`))K.delete(w)},T=(q)=>{F?.(q.sessionID),j?.send(q.sessionID,q.frame)},c=await o1({session:{hook:(q,w,K2)=>$.session.hook(q,async(X2)=>{let p=q==="http.request"?X2:void 0,t=q==="experimental.ws.handshake"?X2:void 0,x2=(p?p.request.headers:t?new Headers(t.headers):void 0)?.get("authorization")===`Bearer ${v2(Z.providerID)}`,Q2={};if(t)K.delete(`${t.sessionID}:${t.kind}`);try{await U.run(Q2,()=>w(X2))}catch(D){if(x2&&!(D instanceof T2))throw t0(D);throw D}if(p&&x2&&Q2.attempt){let D=p.request.headers.get("thread-id");if(D)p.request.headers.set("session-id",D)}if(p&&x2&&Q2.attempt)await M.captureHttp(p.request,Q2.attempt);if(p&&x2&&Q2.attempt)await Y?.({sessionID:p.sessionID,kind:p.kind,request:p.request,attempt:Q2.attempt});if(t&&x2&&Q2.attempt)t.headers["session-id"]=G.get(t.sessionID).threadID;if(q==="experimental.ws.send"){let D=X2,y=K.get(`${D.sessionID}:${D.kind}`);if(y)y.pending=!0;if(y)await M.frame(D.frame,y.attempt);if(y&&D.kind==="primary")T(D)}if(p||t){let D=p??t;if(!D)return;let a=(p?p.request.headers:new Headers(D.headers)).get("authorization")?.replace(/^Bearer /,"");if(x2&&a)V.set(D.sessionID,a);else V.delete(D.sessionID);if(t){let r=`${t.sessionID}:${t.kind}`;if(x2&&a&&Q2.attempt)K.set(r,{bearer:a,attempt:Q2.attempt,pending:!1,url:t.url,headers:new Headers(Object.entries(t.headers).filter(([O2])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(O2.toLowerCase())))});else K.delete(r)}if(V.size>512){let r=V.keys().next().value;if(r)V.delete(r)}if(K.size>512){let r=K.keys().next().value;if(r)K.delete(r)}}else if(q==="experimental.ws.receive"){let D=X2,y=K.get(`${D.sessionID}:${D.kind}`);if(y){if(G.frameReceived(D.sessionID,D.frame),D.kind==="primary"){let a;if(j?.receive(D.sessionID,D.frame,(r)=>{a=r}),a)try{let r=m$(a,y.url,y.headers,G);if(r)await Y?.({sessionID:D.sessionID,kind:"primary",request:r,attempt:y.attempt})}catch(r){J.warn("cachekeep WebSocket capture failed",{error:r instanceof Error?r.message:String(r)})}}if(D.frame=e0(D.frame,y.bearer),D.kind==="primary"&&y.pending&&F2()&&(D.frame.includes('"response.completed"')||D.frame.includes('"response.failed"')||D.frame.includes('"response.incomplete"')||D.frame.includes('"error"')))try{let a=JSON.parse(D.frame);if(a.type==="response.completed")y.pending=!1,s0(D.sessionID,Date.now());else if(["response.failed","response.incomplete","error"].includes(a.type))y.pending=!1}catch{}}}else if(q==="retry"){let D=X2,y=V.get(D.sessionID);if(y)Object.assign(D.error,{message:p1(D.error.message,y)})}},K2)},event:{subscribe:(q)=>async function*(){for await(let w of $.event.subscribe(q)){if(w.type==="session.deleted")P(w.data.sessionID);yield w}}()}},{...Z,rewriteRequest:async(q)=>{let w=U.getStore();if(w)w.attempt=q.attempt;return Z.rewriteRequest?.(q)},rewriteHandshakeURL:(q)=>{let w=U.getStore();if(w)w.attempt=q.attempt;return Z.rewriteHandshakeURL?.(q)},onAttemptEnd:async(q,w)=>{await M.end(q,w),await Z.onAttemptEnd?.(q,w)},rewriteResponse:async(q)=>{await M.response(q.request,q.response.status);let w=await Z.rewriteResponse?.(q)??q.response,K2=await $4(w,q.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream");return r0(K2,q.kind==="primary"?q.sessionID:void 0)}},{gateOnPlaceholder:{credential:(q)=>{let w=q.get("authorization");return w?.startsWith("Bearer ")?w.slice(7):void 0}},hostRetryLimit:J1,logger:{info:(q,w)=>J.info?.(q,{data:w}),warn:(q,w)=>J.warn(q,{data:w})}}),z2=c.dispose;return{...c,dispose:async()=>{V.clear(),K.clear(),await z2(),await M.settle(),M.clear()}}}function A$($={}){return{id:i1,setup:(Z)=>_5(Z,$)}}async function _5($,Z={}){let A=[];try{let J=h2("opencode2");let G=h2("quota");let Y=Z.version??G4;await K4({version:Y,...Z.runtimeLayout});let j=Z.paths??(()=>j4(z4()));let F=j().configPath;let M=await P4({version:Y,paths:j(),log:J});let U=M.snapshot;let K=U?J4(F,U):void 0;let V=()=>{K?.(),U?.dispose()};let P=!1;const T=Y1(A,{[Symbol.dispose](){if(!P)V()}},0);let O=await T1(j());let c=r2(O,F).logging?.level;if(!U&&c&&typeof c==="string")i0(c);let z2=Z.fetch??fetch;let q=Z.now??Date.now;let w=Z.poolMigration??M4;if(!w&&!Q1(j().configPath)){J.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let C=(n)=>{throw new T2({kind:"no-account",providerID:R2,sessionID:n.sessionID,requestKind:n.kind,message:y1})},d=await c0($,{providerID:R2,chooseAccount:C,accountHeaders:C},J);return P=!0,async()=>{try{await d.dispose()}finally{V()}}}let K2=Z.vault?.firstRosterWaitMs??U4;let X2=L4({host:"opencode",stateDir:Z.vault?.stateDir??o0(j().statePath),reservedRouteIds:()=>y.peek().rows.map((C)=>C.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}:{},...Z.vault?.now?{now:Z.vault.now}:{},...Z.vault?.setTimeoutImpl?{setTimeoutImpl:Z.vault.setTimeoutImpl}:{},...Z.vault?.clearTimeoutImpl?{clearTimeoutImpl:Z.vault.clearTimeoutImpl}:{},fetchImpl:()=>z2},j());let p=X2.vault;let t=async()=>await p.authority()==="local"?j1(j()):T1(j());let H2=!1;const x2=Y1(A,{[Symbol.dispose](){if(!P)X2.release()}},0);await p.authority();let Q2=X2.firstRoster;let D=new C$;let y=new V4({paths:j,refreshProvider:async(C)=>{let d=await n0({refreshToken:C.refresh,fetchImpl:z2,now:q}),n=a0({id_token:"",access_token:d.access,refresh_token:d.refresh});return{...d,...n?{identity:n}:{}}},pullQuota:E0({fetchImpl:z2,now:q,counts:D,logger:G}),now:q,vaultIdentities:()=>p.identities(),vaultMode:()=>p.enrolled(),vaultAuthority:()=>p.authority(),vaultFirstRoster:Q2,vaultFirstRosterBackgroundWaitMs:K2,log:h2("pool")});if(await p.authority()==="local")await y.load();let a=new W4({pool:y,vault:p,log:(C)=>J.warn(C)});const r=Y1(A,{[Symbol.dispose](){if(!P)a.dispose()}},0);let O2=Z.heartbeat===!1?void 0:await H4({version:Y,logger:h2("heartbeat")});let l2=Z.fence??(()=>X4({currentVersion:Y}));let D2=Z.slot??_4();let U2=async()=>Y4(j(),await D2.get({path:{id:"openai"}}));let k2=!1;let V2=w?N4({paths:j,slot:D2,version:Y,fence:l2,runDeps:{vaultServes:()=>p.serves()},paused:async()=>await p.authority()!=="local",migrate:async(C)=>{let d=await Q4(C);if(k2=d.status==="refused",!H2)await y.load();return d},adopt:async(C)=>{if(H2)return{status:"retry",reason:"unsettled"};if(!await q$(Q2,K2))return{status:"retry",reason:"vault-roster-pending"};if(H2)return{status:"retry",reason:"unsettled"};let d=await B4(C);if(!H2)await y.load();return d}}):void 0;V2?.start();X2.start();let W2=S0(j());let P2=p0({paths:j(),source:y,pins:W2,vault:p},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const e2=Y1(A,{[Symbol.dispose](){if(!P)P2.release()}},0);P2.publish();let w2=Z.codex??new N1(void 0,void 0,aZ());let g2=F$(O,F);let B1=v1(j());let B2=hZ(j(),{source:y,limits:a,storage:t,vault:p,accounts:Z$(j()),settings:()=>g2,parentOf:async(C)=>(await $.session.get({sessionID:C}))?.parentID??void 0,fetch:z2,log:h2("cachekeep")},{now:q,codexResponsesUrl:d1(F).codexApiEndpoint,...Z.cacheKeep});U?.onChange(()=>{B2.configure(F$(O,F))});const u2=Y1(A,{[Symbol.dispose](){if(!P)B2.release()}},0);let L2=OZ({cacheWarming:(C)=>vZ(j(),C),limits:a,codex:w2,onRoute:P2.route,source:y,slotPlaceholderWithoutMain:U2,storage:t,configPath:F,pins:W2,sessionAccounts:Z$(j()),vault:p,awaitVaultRoster:async()=>{await q$(p.awaitRequestRoster(),I1)},responsesLite:()=>d1(F).responsesLite,codexEndpoint:()=>d1(F).codexApiEndpoint,now:q,log:J});let p2=await c0($,L2.adapter,J,w2,(C)=>B2.capture(C),B1,(C)=>B2.forget(C));L2.attach(p2);let X=await $.session.hook("prompt",(C)=>{L2.beginTurn(C.sessionID)});let W=async(C)=>{if(await M1(p),Q1(j().configPath))return;if(await V2?.idle(),Q1(j().configPath))return;if(k2&&!_$(C)&&(await l2()).open){await y.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 _=async(C)=>{await W(C);let d=await U0(y.poolStore(),j(),C,{vault:p});if(!Q1(j().configPath))await V2?.requestAdoption();await y.load(),J.info("ChatGPT login stored in the account pool",d)};let H=await n1($,{integrationID:R2,methods:B0({beginLogin:Z.beginLogin??O$,version:Y,vault:p}),onLogin:(C)=>_(C),label:"ChatGPT (openai-auth account pool)",vault:Q0(p)});let S=await P0($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let x=$.command&&$.location?await $0({session:$.session,command:$.command,location:$.location},Z.controlPlane??N0({...x0({rateLimitMarks:()=>a.marks(),source:y,storage:t,counts:D,now:q,authority:()=>p.authority()}),fetchImpl:z2,now:q,randomUUID:L5,accountStoragePath:j().configPath,accountStatePath:j().statePath,configPath:F,...U?{settingsSnapshot:U,settings:Z4({file:M.authority.install.target,host:"opencode",snapshot:U,log:J})}:{},packageVersion:Y,layoutNotice:F4,loadAccounts:j1,store:()=>y.poolStore(),migration:async()=>{if(Q1(j().configPath))return{migrated:!0};let C=await l2();return{migrated:!1,blockers:C.open?[]:C.blockers}},beginAccountLogin:Z.beginLogin??O$,refreshAllQuota:async()=>(await y.pollRows(await j1(j()))).map((C)=>({...C,account:C.id})),getStickyRouting:async(C)=>W2.get(C),cacheKeepManager:B2.manager,setCacheKeepEnabled:(C)=>B2.configure({enabled:C}),setCacheKeepSubagents:(C)=>B2.configure({subagents:C}),setCacheKeepSustain:(C)=>B2.configure({sustain:C}),setCacheKeepWindow:(C)=>B2.configure({window:C}),afterWrite:()=>y.load(),refreshSidebar:()=>P2.publish(),clearStickyRouting:async(C)=>{let d=W2.get(C)!==void 0;return W2.forget(C),d},vault:p})):void 0;let E=new AbortController;(async()=>{try{for await(let C of $.event.subscribe({signal:E.signal}))if(C.type==="session.deleted")L2.forgetSession(C.data.sessionID),B2.forget(C.data.sessionID),B1.forget(C.data.sessionID)}catch(C){if(!E.signal.aborted)J.warn("stopped listening for session deletion",{error:C instanceof Error?C.message:String(C)})}})();P=!0;return async()=>{H2=!0,E.abort(),L2.dispose();let C=B2.release();await x?.(),V2?.dispose(),await a.dispose(),await P2.release(),await Promise.allSettled([p2.dispose(),X.dispose(),H.dispose(),S.dispose()]);let d;try{await Promise.race([Promise.all([V2?.idle(),y.settled(),w2.store?.settled(),C]),new Promise((n)=>{d=setTimeout(n,M5),d.unref?.()})])}finally{clearTimeout(d),V(),await X2.release(),await O2?.release()}}}catch(v){var e=v,g=1}finally{d0(A,e,g)}}var T5=A$(),j9={id:i1,setup:T5.setup,server:T4.server};export{j9 as default,A$ as createOpenAIAuthPlugin,i1 as OPENAI_AUTH_PLUGIN_ID};
|
|
3
|
+
`)}}function N1($,Z){let J=new TextDecoder,G="",j=(N)=>{let L=x4(N);if(!L)return;try{$(L)}catch(U){Z(U)}},Q=()=>{for(;;){let N=/\r?\n\r?\n/.exec(G);if(!N)return;let L=G.slice(0,N.index);G=G.slice(N.index+N[0].length),j(L)}};return new TransformStream({transform(N,L){L.enqueue(N),G+=J.decode(N,{stream:!0}),Q()},flush(){if(G+=J.decode(),Q(),G.trim()!=="")j(G);G=""}})}var n2=512,a2=3621000,Z1="x-common-auth-attempt",i2=($,Z)=>JSON.stringify([$,Z]),y2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function q4($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function A4($,Z){let J=$.getReader();return new ReadableStream({async pull(G){let j;try{j=await J.read()}catch(Q){Z({reason:"failed",message:Q instanceof Error?Q.message:String(Q)}),G.error(Q);return}if(j.done)Z(),G.close();else G.enqueue(j.value)},async cancel(G){Z({reason:"cancelled",...G===void 0?{}:{message:String(G)}}),await J.cancel(G)}})}function O1($,Z){for(let[J,G]of Object.entries(Z)){let j=J.toLowerCase();for(let Q of Object.keys($))if(Q.toLowerCase()===j)delete $[Q];if(G!==null)$[J]=G}}function S4($,Z){for(let[J,G]of Object.entries(Z))if(G===null)$.delete(J);else $.set(J,G)}async function s1($,Z,J={}){let{providerID:G}=Z,j=J.gateOnPlaceholder,Q=(z)=>j===void 0||j.credential(z)===m2(G),N=J.logger,L=Math.max(1,J.maxRecords??n2),U=J.hostRetryLimit??10,K=[...J.hostCredentials??[m2(G)],...j?[m2(G)]:[]].filter((z)=>z!==""),V=new Map,E=new WeakMap,M=new Map,T=0,a=new Set,Z2=new Map,q=new Map,A=(z)=>{let Y=q.get(z);return Y?.ownedSeen===!0&&Y.foreignSeen},F2=(z,Y)=>{Z2.set(z,Y);let H=q.get(z)??{ownedSeen:!1,foreignSeen:!1};if(Y)H.ownedSeen=!0;else H.foreignSeen=!0;q.set(z,H)},U2=(z,Y)=>{let H=j?.refuseMisplaced,P=H?[...Y].filter(([,v])=>v.includes(m2(G))):[],B=Q(Y)&&(!H||P.length>0);if(H){if(P.length>0&&(P.length!==1||!B))throw F2(z.sessionID,!1),new E2({kind:"placement-refused",providerID:G,sessionID:z.sessionID,requestKind:z.kind,message:H(P[0]?.[0]??"")})}return F2(z.sessionID,B),B},$2=!1,m=!1,O2=new Map,N2=0,W2=!1,D=new Map,d=(z,Y)=>{try{N?.warn(z,Y)}catch{}},l=(z)=>z instanceof Error?z.message:String(z),t=(z)=>z.excluded.clear(),K2=(z)=>z.excluded.size===0?{}:{excluded:[...z.excluded]},U1=(z,Y,H)=>{if(!J.enforceRequestExclusion||z===void 0||!H.excluded.has(z))return!1;return d("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:Y.sessionID,kind:Y.kind,phase:Y.phase,accountId:z}),!0},f2=new Map,V2=(z,Y)=>{let H=(f2.get(z)??Promise.resolve()).then(Y),P=H.then(()=>{},()=>{});return f2.set(z,P),P.then(()=>{if(f2.get(z)===P)f2.delete(z)}),H},k2=(z,Y)=>{let H=f2.get(z);return H?H.then(()=>k2(z,Y)):Y()},x2=async(z)=>{try{await Z.dropChoice?.({...z.input,accountId:z.accountId})}catch(Y){d("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:z.input.sessionID,error:l(Y)})}},P2=async(z)=>{try{await Z.dropSameAccountRetry?.({...z.input,accountId:z.accountId})}catch(Y){d("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:z.input.sessionID,error:l(Y)})}},M2=async(z)=>{if(z.next)await x2(z.next);if(z.sameAccount)await P2(z.sameAccount)},w2=(z)=>{let Y=M.get(z);if(M.delete(z),Y)V2(Y.sessionID,()=>M2(Y))},q2=async(z,Y)=>{let H=O2.get(z);if(!H||H.size===0)return;await Promise.all([...H].map(async(P)=>{try{await P(Y)}catch(B){d("opencode2 auth listener threw; the request is unaffected",{event:z,error:l(B)})}}))},p2=async(z)=>{let Y=new Set([...V.values()].filter((P)=>P.scope.sessionID===z.sessionID).map((P)=>P.transport).filter((P)=>P!==void 0)),H=z.handle?.transport??(Y.size===1?[...Y][0]:"unknown");try{N?.info?.("opencode2 auth retry decision",{sessionID:z.sessionID,transport:H,attempt:z.attempt,reason:z.reason==="host-decides"&&A(z.sessionID)?"mixed-session":z.reason,retry:z.decision.retry})}catch{}await q2("retry",z)},e2=async(z,Y)=>{try{await Z.onAttemptEnd?.(z,Y)}catch(H){d("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:z.attemptId,error:l(H)})}},v2=(z,Y)=>{if(z.ended||!z.attempt)return;let H={...z.status===void 0?{}:{status:z.status},outputStarted:z.outputStarted,...z.limit?{limit:z.limit.signal}:{},...Y?{error:Y}:{}};if(Y)z.endError=Y;if(Y?.reason==="cancelled"||!Y&&!z.limit&&(z.status===void 0||z.status<400))t(z.request);z.ended=e2(z.attempt,H)},h2=(z,Y)=>v2(z,{reason:"abandoned",message:Y}),B2=(z)=>[...V.values()].filter((Y)=>Y.key===z),$1=(z)=>B2(z).at(-1),X=(z)=>{if(V.delete(z.id),M.get(z.key)?.attemptId===z.id||!B2(z.key).length)w2(z.key)},W=(z)=>{V.set(z.id,z);while(V.size>L){let Y=V.values().next().value;if(Y===void 0)break;h2(Y,"dropped to keep the record bound"),X(Y)}},_=(z)=>z.accountId===void 0?void 0:{...z.scope,accountId:z.accountId},F=(z,Y)=>new E2({kind:"no-account",providerID:G,sessionID:z.sessionID,requestKind:z.kind,...Y===void 0?{}:{message:Y}}),S=(z)=>{D.get(z)?.clear(),D.delete(z)},x=async(z,Y)=>{let H=()=>F(z,`${G} ${z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(W2)throw H();let P=D.get(z.sessionID);if(!P)P=new Set,D.set(z.sessionID,P);let B={};P.add(B);let v=()=>{if(!P.has(B))throw H()};try{return await Y(v)}finally{if(P.delete(B),P.size===0&&D.get(z.sessionID)===P)D.delete(z.sessionID)}},O=(z,Y)=>{for(let[H,P]of Y)if(K.some((B)=>P.includes(B)))throw new E2({kind:"host-credential-on-wire",providerID:G,sessionID:z.sessionID,requestKind:z.kind,message:`${G} ${z.kind} request still carries the host's placeholder credential in ${H}; the adapter's account headers must replace it`})},k=(z)=>{for(let Y of B2(z))if(Y.ended||!Y.attempt)X(Y);else if(Y.transport==="ws"||Y.judged)h2(Y,"a newer attempt of its session and kind began"),X(Y)},f=async(z,Y,H,P)=>{let B=i2(z.sessionID,z.kind),{input:v,accountId:I,sameAccountRetry:b,request:y}=await k2(z.sessionID,async()=>{H();let p=M.get(B);M.delete(B);let n=B2(B);if(p&&n.some((Y2)=>Y2.id!==p.attemptId&&Y2.attempt&&!Y2.ended))d("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:z.sessionID,kind:z.kind});if(!p){let Y2=new Set(n.filter((R2)=>R2.attempt&&!R2.ended).map((R2)=>R2.request));for(let R2 of n)if(!Y2.has(R2.request))t(R2.request)}let w=p?.request??{excluded:new Set},g=p?.accountId??$1(B)?.accountId;k(B);let r=p?.next,X2=p?.sameAccount,e=X2!==void 0&&X2.input.modelID===z.modelID&&X2.input.agent===z.agent,b2=r!==void 0&&r.input.modelID===z.modelID&&r.input.agent===z.agent,g2=p?.wake,z2={...z,phase:"request",...K2(w),...g===void 0?{}:{previousAccountId:g},...p?.rerouteFrom?{rerouteFrom:p.rerouteFrom}:{},...g2===void 0?{}:{wake:g2,hostAttempt:r?.input.hostAttempt}};if(r&&(!b2||g2!==void 0))await V2(z.sessionID,()=>x2(r)),H();if(X2&&!e)await V2(z.sessionID,()=>P2(X2)),H();if(X2?.continuation&&(!e||A(z.sessionID))){if(e)await V2(z.sessionID,()=>P2(X2));throw F(z)}let d2=e?X2.accountId:b2&&g2===void 0?r.accountId:await Z.chooseAccount(z2),c2=typeof d2==="string"?d2:void 0;if(U1(c2,z2,w)){let Y2=c2;if(e&&X2)await V2(z.sessionID,()=>P2(X2));else if(Y2!==void 0)await V2(z.sessionID,()=>x2(b2&&r?r:{accountId:Y2,input:z2}));c2=void 0,H()}return{input:z2,accountId:c2,sameAccountRetry:e,request:w}});H();let _2={},C2;if(I!==void 0){let p=await Z.accountHeaders({...z,accountId:I});if(H(),q4(p))_2=p.headers,C2=p.attempt;else _2=p}let R=`attempt-${++N2}`,u={id:R,key:B,scope:z,request:y,accountId:I,headers:_2,attempt:I===void 0?void 0:{...z,accountId:I,attemptId:R,transport:P,data:C2},...P===void 0?{}:{transport:P},outputStarted:!1,sameAccountRetry:b};if(W(u),u.attempt)q2("select",{...z,accountId:u.attempt.accountId,hook:Y,...v.previousAccountId===void 0?{}:{previousAccountId:v.previousAccountId},...v.rerouteFrom===void 0?{}:{rerouteFrom:v.rerouteFrom},handle:u.attempt});return u},o=async(z,Y,H,P,B)=>{let v=i2(z.sessionID,z.kind),I=P===void 0?void 0:V.get(P);if(I?.key!==v)I=void 0;if(!I){if(I=$1(v),B2(v).filter((y)=>y.transport===void 0&&!y.ended).length>1&&!m)m=!0,d("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:z.sessionID,kind:z.kind})}if(!I||I.transport!==void 0||I.ended)I=await f(z,Y,B,H);else if(I.transport=H,I.attempt)I.attempt.transport=H;if(H==="ws"){for(let b of B2(v))if(b!==I&&b.transport==="ws")h2(b,"a newer attempt of its session and kind went out over WebSocket")}return I},h=async(z,Y)=>{try{return await Y()}catch(H){throw v2(z,{reason:"failed",message:l(H)}),H}},J2=(z,Y)=>{let H=B2(i2(z,Y)).filter((P)=>P.transport==="ws").at(-1);return H?.attempt!==void 0&&!H.ended?H:void 0},j2=(z,Y,H)=>{let P=_(z);if(!P||!z.attempt||z.limit)return;z.limit={signal:Y,delivered:q2("limit",{...P,via:H,limit:Y,outputStarted:z.outputStarted,handle:z.attempt})}},C=(z,Y,H,P)=>{let B=_(z);if(!B||!z.attempt)return;q2("quota",{...B,transport:Y,...P===void 0?{}:{status:P},quota:H,handle:z.attempt})},i=(z,Y,H,P)=>{let B=z.attempt;if(!B)return;let v=Z.inspectEvent?.(P===void 0?{transport:Y,data:H,attempt:B}:{transport:Y,data:H,event:P,attempt:B});if(!v)return;if(v.quota!==void 0)C(z,Y,v.quota);if(v.outputStarted)z.outputStarted=!0;if(v.hostRetry==="veto")z.hostRetry="veto";if(v.limit)j2(z,v.limit,Y);if(v.error!==void 0)v2(z,{reason:"failed",message:v.error});else if(v.done)v2(z)},Q2=(z,Y)=>{let H=z.attempt;if(!H||Y.accountId===z.accountId)return;if(H.reboundFrom??=H.accountId,H.accountId=Y.accountId,"data"in Y)H.data=Y.data;z.accountId=Y.accountId},H2=(z)=>!z.attempt||z.endError!==void 0||z.status!==void 0&&z.status>=400,A2=(z)=>{let Y=[...V.values()].filter((b)=>b.scope.sessionID===z),H=Y.filter((b)=>b.limit&&!b.rerouted).at(-1);if(H)return H;let P=Y.filter((b)=>b.scope.kind==="primary"),B=P.length>0?P:Y;if(B.length<=1)return B[0];let v=B.filter((b)=>!b.judged&&H2(b)).at(-1);if(v)return v;let I=B.filter((b)=>b.attempt&&!b.ended);if(I.length>1)return"ambiguous";return I[0]??B.at(-1)},s={providerID:G},G2=[];G2.push(await $.session.hook("model.request",(z)=>{if(j)return;return x(y2(z),async(Y)=>{let H=await f(y2(z),"model.request",Y);if(Y(),H.accountId===void 0)throw F(H.scope);O1(z.headers,{...H.headers,[Z1]:H.id})})},s)),G2.push(await $.session.hook("http.request",(z)=>{if(j){if(!U2(y2(z),z.request.headers))return}return x(y2(z),async(Y)=>{let H=z.request.headers.get(Z1)??void 0,P=j?await f(y2(z),"http.request",Y,"http"):await o(y2(z),"http.request","http",H,Y);Y();let B=_(P),v=P.attempt;if(!B||!v)throw F(P.scope);await h(P,async()=>{let I=z.request;if(Z.rewriteRequest){if(H!==void 0){let _2=new Headers(I.headers);_2.delete(Z1),I=new Request(I,{headers:_2})}I=await Z.rewriteRequest({...B,request:I,attempt:v})??I,Y()}let b=new Headers(I.headers);b.delete(Z1),S4(b,P.headers),O(P.scope,b.entries());let y=new Request(I,{headers:b});E.set(y,P),z.request=y})})},s)),G2.push(await $.session.hook("http.response",async(z)=>{let Y=E.get(z.request);if(!Y){if(j)return;if(!$2)$2=!0,d("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:z.sessionID,kind:z.kind});return}let H=z.response;if(Z.answeredBy&&Y.attempt){let b=Y.attempt,y=await h(Y,async()=>Z.answeredBy?.({request:z.request,response:H,attempt:b}));if(y)Q2(Y,y)}let P=_(Y),B=Y.attempt;if(!P||!B)return;Y.status=H.status;let v=Z.quotaFromHeaders?.(H.headers,H.status,B);if(v!==void 0)C(Y,"http",v,H.status);if(!H.ok&&Z.limitFromResponse){let b=await Z.limitFromResponse({status:H.status,headers:H.headers,body:()=>H.clone().text(),attempt:B});if(b)j2(Y,b,"http")}if(!H.ok||!H.body)v2(Y);let I=H;if(H.body&&(Z.inspectEvent||Z.onAttemptEnd)){let b=H.body;if(Z.inspectEvent)b=b.pipeThrough(N1((y)=>i(Y,"http",y.data,y.event),(y)=>d("opencode2 auth event inspection threw",{error:l(y)})));I=new Response(A4(b,(y)=>{if(y?.reason==="failed")Y.readFailed=!0;v2(Y,y)}),{status:H.status,statusText:H.statusText,headers:H.headers})}if(Z.rewriteResponse)I=await Z.rewriteResponse({...P,request:z.request,response:I,attempt:B})??I;if(Z.responseRetry){if(await Z.responseRetry({...P,request:z.request,response:I,attempt:B})==="veto")Y.hostRetry="veto"}if(I!==H)z.response=I},s)),G2.push(await $.session.hook("experimental.ws.handshake",(z)=>{if(j){let Y=i2(z.sessionID,z.kind);if(a.delete(Y),!U2(y2(z),new Headers(z.headers)))return}return x(y2(z),async(Y)=>{let H;for(let I of Object.keys(z.headers)){if(I.toLowerCase()!==Z1)continue;H??=z.headers[I],delete z.headers[I]}let P=j?await f(y2(z),"experimental.ws.handshake",Y,"ws"):await o(y2(z),"experimental.ws.handshake","ws",H,Y);Y();let B=_(P),v=P.attempt;if(!B||!v)throw F(P.scope);await h(P,async()=>{if(!j?.refuseMisplaced)O1(z.headers,P.headers);let I=Z.rewriteHandshakeURL?.({...B,url:z.url,attempt:v});if(I!==void 0)z.url=I;if(j?.refuseMisplaced)O1(z.headers,P.headers);if(O(P.scope,Object.entries(z.headers)),j)a.add(P.key)})})},s));let S2=Z.rewriteWebSocketFrame?.bind(Z);if(S2)G2.push(await $.session.hook("experimental.ws.send",async(z)=>{let Y=y2(z);if(j&&!a.has(i2(Y.sessionID,Y.kind)))return;let H=J2(Y.sessionID,Y.kind),P=await S2({...Y,attempt:H?.attempt,frame:z.frame});if(P!==void 0)z.frame=P},s));G2.push(await $.session.hook("experimental.ws.receive",(z)=>{if(j&&!a.has(i2(z.sessionID,z.kind)))return;let Y=J2(z.sessionID,z.kind);if(!Y)return;try{i(Y,"ws",z.frame)}catch(H){d("opencode2 auth frame inspection threw",{error:l(H)})}},s)),G2.push(await $.session.hook("retry",async(z)=>{if(j&&Z2.get(z.sessionID)!==!0)return;let Y=z.decision,H=()=>p2({sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:Y,decision:Y});if(A(z.sessionID)&&!Z.retrySameAccount){await H();return}let P=A2(z.sessionID);if(!P)return;if(P==="ambiguous"){await p2({sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:Y,decision:Y});return}let B=P,v=()=>B.hostRetry==="veto";await x(B.scope,async(I)=>{let b=I,y=Z.retrySameAccount?.bind(Z),_2=B.attempt,C2=B.outputStarted;if(B.transport==="ws"&&C2&&!B.ended&&!B.limit&&!(B.status!==void 0&&B.status>=400)&&!(z.error.status!==void 0&&z.error.status>=400)&&z.error.type==="provider.transport")B.readFailed=!0,v2(B,{reason:"failed",message:z.error.message});if(C2&&B.readFailed&&y&&_2&&!A(z.sessionID)){if(!B.limit){let w=Z.limitFromError?.(z.error,_2);if(w)j2(B,w,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;b()}let R=()=>B.readFailed===!0&&z.error.type==="provider.transport"&&Y.retry&&U-z.attempt>=1&&!B.limit&&!(B.status!==void 0&&B.status>=400)&&!(z.error.status!==void 0&&z.error.status>=400)&&!_2?.reboundFrom&&!v()&&!A(z.sessionID);if(y&&_2&&(!C2||R())&&(!v()||A(z.sessionID))&&!B.sameAccountRetry){if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;let w=await V2(B.scope.sessionID,async()=>{b();let g=_2.accountId,r=()=>V.has(B.id)&&B.accountId===g&&A2(z.sessionID)===B&&B.outputStarted===C2&&(!C2||R())&&(!v()||A(z.sessionID))&&(!j||Z2.get(z.sessionID)===!0);if(!r()||B.sameAccountRetry)return!1;B.sameAccountRetry=!0;let X2={...B.scope,accountId:g,error:z.error,attempt:z.attempt,...B.limit?{limit:B.limit.signal}:{},...C2?{continuation:"interrupted-read"}:{}},e;try{e=await y(X2)}catch(z2){d("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:z.sessionID,error:l(z2)})}if(!e)return b(),!1;let b2={accountId:e.accountId,input:X2,...C2?{continuation:!0}:{}};try{b()}catch(z2){throw await P2(b2),z2}if(!r()||e.accountId!==g)return await P2(b2),!1;let g2=M.get(B.key);if(M.delete(B.key),g2)await M2(g2);try{b()}catch(z2){throw await P2(b2),z2}if(!r())return await P2(b2),!1;return M.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++T,accountId:g,sameAccount:b2}),B.judged=!0,z.decision=C2?Y:{retry:!0,delay:0},!0});if(b(),w){await p2({sessionID:z.sessionID,accountId:B.accountId,kind:B.scope.kind,attempt:z.attempt,reason:C2?"continue-same-account":"same-account",hostDecision:Y,decision:z.decision,handle:B.attempt});return}}if(A(z.sessionID)){await H();return}B.judged=!0;let u=B.attempt;if(u&&!B.outputStarted){if(!B.limit){let w=Z.limitFromError?.(z.error,u);if(w)j2(B,w,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered}b();let{decision:p,reason:n}=await V2(B.scope.sessionID,async()=>{if(b(),A(z.sessionID))return{decision:Y,reason:"host-decides"};let w=M.get(B.key);if(M.delete(B.key),w)await M2(w);if(b(),A(z.sessionID))return{decision:Y,reason:"host-decides"};let g=Y,r,X2,e,b2;if(B.accountId===void 0||!u)g={retry:!1},r="no-account";else if(B.outputStarted)g={retry:!1},r="output-started";else if(v())g={retry:!1},r="adapter-veto";else if(B.limit){let g2={accountId:B.accountId,limit:B.limit.signal},z2,d2={...B.scope,phase:"retry",...K2(B.request),hostAttempt:z.attempt,previousAccountId:B.accountId,rerouteFrom:g2};try{z2=await Z.chooseAccount(d2)}catch(n1){d("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:B.scope.sessionID,error:l(n1)})}let c2=typeof z2==="string"?z2:typeof z2==="object"&&("hold"in z2)?B.accountId:void 0;if(U1(c2,d2,B.request)){if(c2!==void 0)await x2({accountId:c2,input:d2});z2=void 0}let Y2=typeof z2==="object"&&"hold"in z2?z2.hold:void 0,R2=typeof z2==="object"&&"waitThenReselect"in z2?z2.waitThenReselect:void 0,O4=typeof z2==="object"&&"hostRetry"in z2?z2.hostRetry:void 0,T1=typeof z2==="string"?z2:Y2?B.accountId:void 0;if(T1!==void 0)e={accountId:T1,input:d2};try{b()}catch(n1){if(e)await x2(e);throw n1}if(A(z.sessionID)){if(e)await x2(e);return{decision:Y,reason:"host-decides"}}if(v()||O4==="veto"){if(e)await x2(e);if(e=void 0,b(),A(z.sessionID))return{decision:Y,reason:"host-decides"};B.hostRetry="veto",g={retry:!1},r="adapter-veto"}else if(!(U-z.attempt>=1)){if(e)await x2(e);e=void 0,r="host-decides-last-account"}else if(R2&&Number.isFinite(R2.delayMs)&&R2.delayMs>=0&&R2.delayMs<=a2)g={retry:!0,delay:Math.ceil(R2.delayMs)},r="wait-then-reselect";else if(Y2&&Number.isFinite(Y2.delayMs)&&Y2.delayMs>=0&&Y2.delayMs<=a2){if(g={retry:!0,delay:Math.ceil(Y2.delayMs)},Y2.target!==void 0)b2={target:Y2.target,...Y2.checkpoint===void 0?{}:{checkpoint:Y2.checkpoint},...Y2.kind===void 0?{}:{kind:Y2.kind}};r="hold"}else if(!Y2&&T1!==void 0&&T1!==B.accountId)B.rerouted=!0,B.request.excluded.add(B.accountId),X2=g2,g={retry:!0,delay:0},r="reroute";else{if(Y2&&e)await x2(e),e=void 0;r="host-decides-last-account"}}else r="host-decides";if(z.decision=g,g.retry&&B.accountId!==void 0&&V.has(B.id))M.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++T,accountId:B.accountId,...X2===void 0?{}:{rerouteFrom:X2},...e===void 0?{}:{next:e},...b2===void 0?{}:{wake:b2}});else if(e)await x2(e);if(!g.retry)t(B.request);return{decision:g,reason:r}});b(),await p2({sessionID:z.sessionID,...B.accountId===void 0?{}:{accountId:B.accountId},kind:B.scope.kind,attempt:z.attempt,reason:n,hostDecision:Y,decision:p,...u===void 0?{}:{handle:u}})})},s));let I2=(z)=>{if(S(z),Z2.delete(z),!q.get(z)?.foreignSeen)q.delete(z);for(let Y of a)if(JSON.parse(Y)[0]===z)a.delete(Y);for(let Y of[...V.values()]){if(Y.scope.sessionID!==z)continue;h2(Y,"its session was forgotten"),t(Y.request),V.delete(Y.id)}for(let[Y,H]of M)if(H.sessionID===z)w2(Y)},u2=new AbortController,V1=$.event;if(V1)(async()=>{try{for await(let z of V1.subscribe({signal:u2.signal}))if(z.type==="session.deleted")I2(z.data.sessionID);else if(z.type==="session.status"&&z.data.status.type==="idle"){let Y=z.data.sessionID,H=++T;V2(Y,async()=>{for(let[P,B]of M)if(B.sessionID===Y&&B.order<H)M.delete(P),t(B.request),await M2(B)})}}catch(z){if(!u2.signal.aborted)d("opencode2 auth stopped listening for session deletion",{error:l(z)})}})();return{on(z,Y){let H=O2.get(z);if(!H)H=new Set,O2.set(z,H);let P=Y;return H.add(P),()=>{H.delete(P)}},accountFor(z,Y){return $1(i2(z,Y))?.accountId},forgetSession:I2,get size(){return V.size},async dispose(){if(W2)return;W2=!0;for(let z of D.keys())S(z);u2.abort();for(let z of V.values())h2(z,"the installation was disposed");V.clear();for(let z of M.keys())w2(z);a.clear(),Z2.clear(),q.clear(),O2.clear(),await Promise.all(f2.values()),await Promise.all(G2.map(async(z)=>{try{await z.dispose()}catch(Y){d("opencode2 auth hook did not dispose cleanly",{error:l(Y)})}}))}}}import{randomUUID as a$}from"node:crypto";import{createHash as b4}from"node:crypto";var R4=1024,D4=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),k$=($)=>w$($,"user"),k4=($)=>D4($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function w4($){return b4("sha256").update(JSON.stringify($)).digest("hex")}class z1{runtime;maxSessions;#$=new Map;constructor($,Z=R4){this.runtime=$;this.maxSessions=Z}advance($,Z,J=this.runtime){let G=this.#$.get($),j=Array.isArray(Z.input)?Z.input:[],Q=j.filter(k$),N=j.findLastIndex(k$),L=N<0?void 0:w4(j[N]),U=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,K,V,E;if(U)K=Q.length>0,V=L??G?.fingerprint,E=G?.userCount===void 0?void 0:G.userCount+Q.length;else{V=L,E=Q.length;let T=N>=0&&N>j.findLastIndex(k4),a=G!==void 0&&!G.completed&&G.fingerprint===V&&G.userCount===E;K=T&&!a}let M=K||!G?{turnID:(J?.uuid??o2)(),turnStartedAt:(J?.now??Date.now)()}:{turnID:G.turnID,turnStartedAt:G.turnStartedAt};return this.#Z($,{...M,completed:!1,fingerprint:V,userCount:E}),M}completed($){let Z=this.#$.get($);if(Z)this.#Z($,{...Z,completed:!0})}get($){return this.#$.get($)}forget($){this.#$.delete($)}#Z($,Z){this.#$.delete($),this.#$.set($,Z);while(this.#$.size>this.maxSessions){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function r1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var I$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function I4(){let $=globalThis;return $[I$]??=crypto.randomUUID(),$[I$]}class H1{runtime;store;sessions;frameTurns;installationID;constructor($,Z,J){this.runtime=$;this.store=J;this.installationID=Z??I4(),this.sessions=J?.sessions??new Map,this.frameTurns=J?.frameTurns??new z1}get($){let Z=this.runtime?.uuid??o2;if(this.store)return this.store.get($,Z);let J=this.sessions.get($);if(!J){let G=Z();J={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,J)}return J}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(x1(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var t1={version:y$,"user-agent":f$,originator:"codex_exec"};var y4=1024,f4=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,A1=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),g$=($)=>A1($)&&($.type==="message"||("role"in $))&&$.role==="user",m$=($)=>A1($)&&$.type==="configuration_update";class e1{http;#$=new Map;constructor($=new H1){this.http=$}apply($,Z,J){if(Z.kind!=="primary")return!1;let G=typeof $.model==="string"?$.model:"";if(!v$.has(G))return!1;if(f4.test(G))return!1;let j=A1($.reasoning)?$.reasoning:void 0,Q=typeof j?.effort==="string"?j.effort:void 0;if(!Q)return!1;let N=this.#$.get(Z.sessionID);if(N===void 0)return this.#Z(Z.sessionID,Q),!1;if(Q===N)return!1;let L=Array.isArray($.input)?$.input:void 0;if(!L||L.length===0)return!1;let U=L.findLastIndex(g$);if(U<0){if(J==="http")return!1;return $.reasoning={...j,effort:N},!0}if($.reasoning={...j,effort:N},!m$(L[U-1]))L.splice(U,0,{type:"configuration_update",reasoning:{effort:Q}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>y4){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function x1($){try{let Z=JSON.parse($);return A1(Z)?Z:void 0}catch{return}}async function l$($,Z,J,G,j=J.http,Q){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let N=await $.clone().text(),L=x1(N);if(L)delete L.max_output_tokens;let U=new Headers($.headers),K=q1({rewriteLite:h$,init:{body:L?JSON.stringify(L):$.body===null?void 0:N},headers:U,metadata:j.get(Z.sessionID),installationID:j.installationID,runtime:j.runtime,websocket:!1,responsesLite:G,applyEffort:(V)=>{if(J.apply(V,Z,"http"),Q&&typeof V.model==="string")Q(V.model)}});return new Request($,{headers:U,body:K.init?.body})}function u$($,Z,J,G){let j=G.sessions.get($.sessionID),Q=G.frameTurns.get($.sessionID);if(!j||!Q)return;let N=r1(j,Q),L=new Headers({"content-type":"application/json"});for(let K of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let V=J.get(K);if(V!==null)L.set(K,V)}q1({init:{body:$.bodyText},headers:L,metadata:N,installationID:G.installationID,runtime:G.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let U=new URL(Z);if(U.protocol==="wss:")U.protocol="https:";if(U.protocol==="ws:")U.protocol="http:";return new Request(U,{method:"POST",headers:L,body:$.bodyText})}function v4($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let J=Z.findIndex((G,j)=>JSON.stringify(G)!==JSON.stringify($[j]));return J>=0&&m$(Z[J])&&g$(Z[J+1])&&JSON.stringify(Z.slice(J+1))===JSON.stringify($.slice(J))}function p$($,Z,J,G){let j=x1($);if(j?.type!=="response.create")return;let Q=J.http.advanceFrame(Z.sessionID,j),N=J.http.get(Z.sessionID);delete j.max_output_tokens;let L=q1({rewriteLite:()=>{},init:{body:JSON.stringify(j)},headers:new Headers,metadata:r1(N,Q),installationID:J.http.installationID,runtime:J.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(K)=>{J.apply(K,Z,"ws")}}),U=x1(String(L.init?.body));if(!U)return;if(G&&typeof U.model==="string")G(U.model);if(!v4(j.input,U.input)){if("input"in j)U.input=j.input;else delete U.input;return JSON.stringify(U)}return String(L.init?.body)}function h4($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function $$($,Z){let J=new URL($);if(J.origin!=="https://api.openai.com"&&J.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(J.pathname))return $;let G=new URL(`${h4(Z)}/responses`);if(G.search=J.search,J.protocol==="ws:"||J.protocol==="wss:")G.protocol=G.protocol==="https:"?"wss:":"ws:";return G.href}import{resolve as c$}from"node:path";var g4=1024;class S1{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 J=this.accounts.keys().next().value;if(J===void 0)break;this.accounts.delete(J)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var d$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),i$=globalThis,Z$=i$[d$]??new Map;i$[d$]=Z$;function z$($){let Z=JSON.stringify([c$($.configPath),c$($.statePath)]),J=Z$.get(Z);if(!J)J=new S1,Z$.set(Z,J);return J}var D2="openai",G1=10;var J$=1,m4="request refused: no account with a usable credential",T2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function l4($){let Z=T2($)?$.counters:void 0,J=T2(Z)?Z.resetCredits:void 0,G=T2(J)?J.value:void 0;return typeof G==="number"&&Number.isFinite(G)?G:void 0}function K1($){try{return JSON.parse($)}catch{return}}function F1($){let Z=D1($);return Z?k1(Z):void 0}var u4=new Set(["usage_limit_reached","rate_limit_exceeded"]);function L1($,Z,J,G){return{reason:$.window,windows:BZ($,Z,G,Z),observedAt:Z,...$.resetAt!==void 0?{resetAt:$.resetAt,resetSource:"provider"}:{},...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function OZ($,Z,J){if($.type!=="response.failed"){let Q=R1($,Z),N=typeof $.status==="number"?$.status:void 0;return Q?L1(Q,Z,N,J):void 0}if(!T2($.response))return;let G=$.response.failed;if(T2(G)&&typeof G.rate_limit_reached_type==="string")return L1({window:G.rate_limit_reached_type},Z,void 0,J);let j=$.response.error;if(T2(j)){let Q=typeof j.code==="string"?j.code:typeof j.type==="string"?j.type:void 0;if(Q&&u4.has(Q)){let N=typeof $.status==="number"?$.status:void 0,L=R1({error:{...j,type:Q},status:N},Z);return L1(L??{window:Q},Z,N,J)}}return}function xZ($,Z,J){return qZ(K1($),Z,J)}function qZ($,Z,J){if(!T2($))return;let G=typeof $.type==="string"?$.type:void 0;if(G==="codex.rate_limits")return{quota:{snapshot:e$($),complete:!0}};let j=OZ($,Z,J);if(j)return{limit:j};if(G===void 0||G==="error")return;return EZ(G)?void 0:{outputStarted:!0}}function p4($){let Z=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:r$($),complete:t$($)}}function c4($){let Z=$.get("retry-after");if(Z===null)return;let J=Z.trim()?Number(Z):NaN;return Number.isFinite(J)&&J>=0?J*1000:void 0}function AZ($){let Z=new WeakMap,J=new WeakSet,G,j,Q=new WeakMap,N=new Map,L=(X)=>{if(X?.data?.kind!=="vault"||!X.data.receipt.credentialId||!L2())return;let W=X.data.receipt;return(_)=>{let F=`${X.sessionID}\x00${X.kind}`,S=(N.get(F)??0)+1;if(N.set(F,S),N.size>n2){let x=N.keys().next().value;if(x!==void 0)N.delete(x)}Q.set(X,new I1(X.sessionID,W,X.kind,_,S,$.cacheWarming,X.data?.kind==="vault"&&X.data.freeQuota))}},{source:U,pins:K}=$,V=$.now??Date.now,E=$.log,M=$.vault,T=$.limits,a=a$(),Z2=new WeakMap,q=new Map,A=(X,W)=>s2(W?M?.routes().find((_)=>_.id===X)?.quota:U.peek().rows.find((_)=>_.id===X)?.quota),F2=new e1($.codex),U2=new Map,$2=new Map,m=new Map,O2=(X,W,_,F)=>{if(!L2())return;let S=($2.get(X.sessionID)??0)+1,x=LZ({sessionId:X.sessionID,reason:W,now:_,...W==="quota_reading"?{boundMs:F}:{nextMs:_+F},attempt:S});if(x)$2.set(X.sessionID,S);return x},N2=(X)=>{$2.delete(X);for(let W of m.keys())if(JSON.parse(W)[0]===X)m.delete(W);for(let W of N.keys())if(W.startsWith(`${X}\x00`))N.delete(W);for(let[W,_]of U2)if(_===X)U2.delete(W)},W2=new Map,D=new Map,d=(X)=>`${X.sessionID}\x00${X.kind}`,l=new Map,t=new Map,K2=(X)=>{let W=t.get(X);if(W)clearTimeout(W.timer);t.delete(X)},U1=(X,W,_)=>{let F=V2({...X,accountId:W});K2(F);let S={request:_,sessionID:X.sessionID,expiresAt:performance.now()+5000,timer:setTimeout(()=>{if(t.get(F)===S)K2(F)},5000)};if(S.timer.unref(),t.set(F,S),t.size>n2){let x=t.keys().next().value;if(x!==void 0)K2(x)}},f2=(X)=>{let W=t.get(X);return K2(X),W&&performance.now()<W.expiresAt?W.request:void 0},V2=(X)=>`${X.sessionID}\x00${X.kind}\x00${X.accountId}`,k2=$.sessionAccounts??new S1,x2=new YZ,P2=(X,W,_)=>{let F=_?[]:TZ(U.peek().rows,X,W,M?.identities()??new Set,$.configPath),S=(M?.routes()??[]).filter((x)=>x.kind==="oauth"&&$Z(s2(x.quota),X,W));return[...F.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota,row:x})),...S.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota}))]},M2=(X,W,_)=>{let F=GZ(X,W,_),S=X.map((f)=>({id:f.id,kind:"oauth",...P1(f.quota)?{quota:f.quota}:{}})),x=X.flatMap((f)=>f.row?[f.row]:[]),O=new Set(X.filter((f)=>!f.row).map((f)=>f.id)),k=T?.marks()??new Map;return{rows:S,now:_,rateLimitMarks:k,refreshBackoff:U.refreshBackoffFor(x),killswitch:F,requestPull:(f)=>O.has(f)?M?.requestReading(f):U.requestReading(f)}},w2=(X,W,_,F,S,x)=>{let O=X1({...X,rows:X.rows.filter((f)=>!_.has(f.id)),placement:Q$(W),mainId:S});if(O.kind==="block"){E?.debug("pool admission refused the request",{reason:O.block.reason});return}let k=O.order.filter((f)=>!_.has(f));if(x)for(let f of k){let o=O.tiers[f];if(o)x.set(f,o)}if(F!==void 0&&k.includes(F))return F;return k[0]},q2=(X,W)=>{let _=new Map(X.map((F)=>[F.id,F.quota]));return{requestBytes:J$,reservePercent:(F)=>X$(W,F===j$?void 0:F),resetCredits:(F)=>l4(_.get(F))}},p2=(X,W,_,F,S,x,O,k,f)=>{let o=q2(W,_),h=B$(X),J2=(H2,A2)=>w1(O,{sessionId:F,requestBytes:J$,validPinnedAccountIds:X.rows.map((s)=>s.id).filter((s)=>!h.excluded.has(s)),excludeAccountIds:H2,quotaCheckedAtByAccount:Object.fromEntries(X.rows.map((s)=>[s.id,h.projections.get(s.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(W.map((s)=>[s.id,s.identity])),select:(s)=>{let G2=k?{accountId:k,source:"mode-fallback",quotaCheckedAt:h.projections.get(k)?.checkedAt}:QZ(X,o,new Set(H2),s);if(G2&&"tier"in G2)f?.set(G2.accountId,G2.tier);return G2},persist:A2},(s,G2)=>O.set(s,G2)),j2=[...S],C=J2(j2,x);if(!C)return;let i=C.accountId,Q2=U$(X,o,i);if(Q2.kind==="serve")f?.set(i,Q2.tier);else f?.delete(i);if(Q2.kind==="none")return;if(Q2.kind==="move"){let H2=J2([...j2,i],x);if(H2)return H2.accountId;return Q2.reason==="killswitch"?void 0:i}if(Q2.kind==="detour")return J2([...j2,i],!1)?.accountId;return i},h2={providerID:D2,async retrySameAccount(X){if(X.continuation!=="interrupted-read")return;let W=D.get(d(X));if(D.delete(d(X)),!W||W.accountId!==X.accountId||W.modelID!==X.modelID||W.agent!==X.agent||X.limit)return;let _=M!==void 0&&await M.authority()!=="local",F=r2(await $.storage(),$.configPath);if(!_&&!(await U.current()).active)return;let S=V(),x=P2(F,S,_),O=x.find((h)=>h.id===X.accountId);if(!O)return;let k=M2(x,F,S),f=F?.routing?.mode??"main-first";if(f==="sticky-balanced"){let h=U$(k,q2(x,F),X.accountId);if(h.kind!=="serve"&&h.kind!=="last-path")return}else{let h=X1({...k,placement:Q$(f),..._?{mainId:Y$(M?.routes()??[])}:{}});if(h.kind==="block"||!h.order.includes(X.accountId))return}let o=W.data;if(O.row){if(o?.kind!=="pool")return;let h=U.usableToken(O.row),J2=O.row.identity??(h&&F1(h));if(!h||!o.identity||J2!==o.identity)return}else{if(o?.kind!=="vault"||!M)return;let h=await M.authorize(X.accountId);if(!h||h.credentialId!==o.credentialId||h.accountIdentity!==o.accountIdentity||(h.accountIdentity??F1(h.accessToken))!==o.wireIdentity||O.identity!==void 0&&O.identity!==o.wireIdentity)return}return{accountId:X.accountId}},dropSameAccountRetry(){},dropChoice(X){let W=V2(X);K2(W),l.get(W)?.drop(),l.delete(W),W2.delete(W)},chooseAccount:async(X)=>{let W,_=await M?.authority(),F=r2(await $.storage(),$.configPath),S=_!==void 0&&_!=="local",x=()=>{throw new E2({kind:"no-account",providerID:D2,sessionID:X.sessionID,requestKind:X.kind,message:y1})};if(S){let R=performance.now()+f1;await $.awaitVaultRoster?.(),W=await T?.forRequest(R)}else{if(W=await T?.forRequest(),!(await U.current()).active){if(await $.slotPlaceholderWithoutMain?.())x();E?.warn("the account pool does not serve requests yet; refusing the request",{kind:X.kind});return}await U.prepareTokens(U.peek().rows,F)}let O=V(),k=P2(F,O,S),f=jZ(M2(k.filter((R)=>R.id!==X.rerouteFrom?.accountId),F,O));if(f){let R=O2(X,"quota_reading",O,XZ);if(await f,O=V(),k=P2(F,O,S),R)R(X1({...M2(k,F,O),requestPull:()=>{},placement:"roster",mainId:null}).kind==="block"?"abandoned":"resumed")}let o=new Map(k.map((R)=>[R.id,R])),h=M2(k,F,O),J2=L2()?new Map:void 0,j2=F?.routing?.maxSameAccountWait,C=JSON.stringify([X.sessionID,X.kind]),i=m.get(C);if(X.phase==="request"&&i&&(i.checkpoint?JSON.stringify(X.wake?.checkpoint)===i.checkpoint:O>=i.nextMs))i.end("resumed"),m.delete(C);let Q2=[...U2.values()].includes(X.sessionID),H2=T?.activity.get(X.sessionID),A2=H2&&T?.accountKey(H2.accountKey.accountId),s=X.previousAccountId??X.rerouteFrom?.accountId,G2=s&&T?.accountKey(s),S2=X.rerouteFrom?.limit,I2=k.flatMap((R)=>{let u=T?.accountKey(R.id);if(!u)return[];let p=s2(R.quota),n=UZ(S2&&R.id===s?{account:u,kind:"rate-limit",reason:S2.reason,scope:{kind:"pool"},windows:S2.windows??[],observedAt:S2.observedAt??O}:void 0,p,O),w=h.rateLimitMarks.get(R.id),g=h.refreshBackoff.get(R.id),r=[...w&&w>O?[{kind:"hard",until:w,cause:"rate-limit"}]:[],...g&&g>O?[{kind:"cooldown",until:g}]:[]],X2=h.killswitch.get(R.id)!==!1&&!!(p?.primary||p?.secondary)&&!o$(n$(P1(R.quota)?R.quota:void 0),O)&&!(g&&g>O)&&(!R.row||!!U.usableToken(R.row));return[{account:u,admitted:X2,placementEligible:X2,ready:X2&&!r.length&&!n.length,blockers:r,confirmedBlockers:n}]}),u2={phase:X.phase==="retry"?"after-limit":"pre-send",host:"opencode2",hostPhase:X.phase,now:O,clockNow:O,sessionId:X.sessionID,requestScope:{kind:"pool"},history:s$({requestId:X.sessionID,originalUrl:"https://api.openai.com/v1/responses",clockNow:O}),delivery:{owned:!0,attributable:!0,replayable:!0},candidates:I2,...X.phase==="retry"&&G2?{attempted:G2}:{},...X.phase==="retry"&&G2&&S2?{signal:{account:G2,kind:"rate-limit",reason:S2.reason,scope:{kind:"pool"},windows:S2.windows??[],observedAt:S2.observedAt??O},status:S2.status}:{},remainingRetries:G1-(X.hostAttempt??G1)},V1=()=>{let R=T?.owner();return WZ({accounts:I2.flatMap((u)=>{let p=o.get(u.account.accountId);if(!p)return[];return[{account:u.account,reading:s2(p.quota),usable:!p.row||!!U.usableToken(p.row),confirmedBlockers:u.confirmedBlockers,floors:ZZ(F)?X$(F,p.id===j$?void 0:p.id):void 0,marks:R?.snapshot()?.marks.filter((n)=>n.key.window==="account"&&n.key.scope.kind==="pool"&&J1(n.key.account,u.account)).flatMap((n)=>n.entries.map((w)=>({until:w.until,evidenceAt:w.evidenceAt})))}]}),now:O,effectiveModel:X.modelID,maxSameAccountWait:j2,activity:H2,currentAccountKey:A2,provenance:R?.provenance})},z=I2.find((R)=>G2&&J1(R.account,G2));if(X.phase==="retry"&&S2&&z){let R=V$({candidate:z,activity:H2,maxSameAccountWait:j2,now:O,maxDelayMs:a2}),u=W$({...u2,hold:R},{mode:"sticky"});if(u?.action==="hold"&&!Q2){U2.set(C,X.sessionID);let w=O2(X,"account_limit",O,u.delayMs);if(w)m.set(C,{checkpoint:JSON.stringify(u.checkpoint),nextMs:O+u.delayMs,end:w});return{hold:{delayMs:u.delayMs,target:u.target,checkpoint:u.checkpoint,kind:"hold"}}}let p=k.filter((w)=>w.id!==s);if(z.confirmedBlockers?.some((w)=>w.confirmed)&&p.length>0&&p.every((w)=>{let g=I2.find((r)=>r.account.accountId===w.id);return g&&(!g.admitted||(h.rateLimitMarks.get(w.id)??0)>O)})){if(Q2)return{hostRetry:"veto"};let w=N$(u2,V1());if(G$(j2)===0)return{hostRetry:"veto"};let g="delayMs"in w?w.delayMs:("retryAfterMs"in w)?w.retryAfterMs:void 0;if((u2.remainingRetries??0)<1||g===void 0||g>a2)return{hostRetry:"leave"};if(w.action==="hold"&&J1(w.account,z.account)){U2.set(C,X.sessionID);let X2=O2(X,"account_limit",O,g);if(X2)m.set(C,{checkpoint:JSON.stringify(w.checkpoint),nextMs:O+g,end:X2});return{hold:{delayMs:g,target:w.target,checkpoint:w.checkpoint,kind:"terminal"}}}U2.set(C,X.sessionID);let r=O2(X,"account_free",O,g);if(r)m.set(C,{nextMs:O+g,end:r});return{waitThenReselect:{delayMs:g}}}}let Y;if(X.phase==="request"&&X.wake?.checkpoint&&z&&(X.hostAttempt??G1)<G1&&G$(j2)!==0&&J1(z.account,X.wake.checkpoint.accountKey)){let R=X.wake.checkpoint,u=new Map(R.blockers.map((g)=>[g.window,{...g,confirmed:!0,confirmedByReading:!1,observedAt:R.decidedAt,provenance:"provider"}]));for(let g of z.confirmedBlockers??[])u.set(g.window,g);let p={...z,confirmedBlockers:[...u.values()]},n=V$({candidate:p,activity:H2,maxSameAccountWait:j2,now:O,maxDelayMs:a2});if(W$({...u2,attempted:z.account,candidates:I2.map((g)=>g===z?p:g),hold:n,wake:{...X.wake,checkpoint:R}},{mode:"sticky"})?.action==="retain")Y=z.account.accountId}let H=new Set(X.rerouteFrom?[X.rerouteFrom.accountId]:[]),P=F?.routing?.mode??"main-first",B=X.kind==="primary",v=new Set,I,b,y,_2=!1,C2=(R)=>{let u=B$(h).projections.get(R)?.checkedAt,p=o.get(R)?.identity;return K.reserve(X.sessionID,{accountId:R,inputBytes:J$,...u!==void 0?{quotaCheckedAt:u}:{},...p!==void 0?{wireIdentity:p}:{}})};try{for(;;){let R=new Set([...H,...v]);y=void 0,J2?.clear(),I=void 0;let u=P!=="sticky-balanced";if(Y&&!R.has(Y))y=Y,Y=void 0;else if(P==="sticky-balanced"){let n=new Map(K.placementSnapshot(X.sessionID)),w=n.get(X.sessionID);if(u=w===void 0,y=p2(h,k,F,X.sessionID,R,B&&v.size===0,n,void 0,J2),y!==void 0&&n.get(X.sessionID)!==w)I=n.get(X.sessionID)}if(y??=w2(h,P,R,B?void 0:k2.activeAccount(X.sessionID),S?P==="sticky-balanced"?null:Y$(M?.routes()??[]):void 0,J2),y===void 0||v.has(y)){if(H.size>0){let n=new Map(h.rateLimitMarks);for(let w of H)n.delete(w);h={...h,rateLimitMarks:n},H.clear();continue}if(h.rateLimitMarks.size>0){h={...h,rateLimitMarks:new Map};continue}y=void 0;break}if(B&&P==="sticky-balanced")b=C2(y);if(!_2){_2=!0;let n=X.wake?void 0:await PZ({vaultMode:S,fresh:u,sessionId:X.sessionID,request:{modelId:X.modelID,kind:X.kind,retry:X.phase==="retry"||X.rerouteFrom!==void 0},routes:M?.routes()??[],warmAccountId:P==="sticky-balanced"?K.get(X.sessionID):k2.activeAccount(X.sessionID),routing:h,wait:{activity:H2,accountKey:A2,maxSameAccountWait:j2},eligibleIds:k.filter((w)=>!R.has(w.id)).map((w)=>w.id)});if(n&&typeof n!=="string")throw new E2({kind:"no-account",providerID:D2,sessionID:X.sessionID,requestKind:X.kind,message:KZ});if(n&&n!==y){if(b)K.rollback(b);if(b=void 0,P==="sticky-balanced"){let w=new Map(K.placementSnapshot(X.sessionID));y=p2(h,k,F,X.sessionID,R,B,w,n,J2)??y,I=w.get(X.sessionID)??I}else y=n;if(B&&P==="sticky-balanced")b=C2(y)}}let p=o.get(y)?.row;if(p){if(U.usableToken(p)!==void 0)break;E?.debug("pool row holds no usable token; choosing again",{accountId:y})}else{if(!M)break;let n=await M.authorize(y);if(n){W2.set(V2({...X,accountId:y}),{receipt:n,freeQuota:J2?.get(y)==="free"});break}E?.debug("the vault refused to serve an account; choosing again",{accountId:y})}if(b)K.rollback(b);b=void 0,v.add(y)}if(y===void 0&&!S&&k.length===0&&await $.slotPlaceholderWithoutMain?.())x();if(y===void 0&&S&&M&&(k.length===0||v.size>0)){let R=v.size>0?"vault-refused":JZ(M);throw E?.warn("vault mode: no vault account can serve; refusing the request",{cause:R}),new E2({kind:"no-account",providerID:D2,sessionID:X.sessionID,requestKind:X.kind,message:zZ(R,M.name)})}if(y!==void 0){if(W)U1(X,y,W);let R=y,u=b,p=I,n=()=>{if(u)K.finish(u,p);if(B)k2.record(X.sessionID,R),$.onRoute?.(X.sessionID,R,P)};if(X.phase==="retry")l.set(V2({...X,accountId:y}),{commit:n,drop:()=>{if(u)K.rollback(u)}}),b=void 0;else n();let w=E?.info;x2.served(h,y,E&&w?{info:(g,r)=>w.call(E,g,r)}:void 0)}if(y===void 0&&X.phase==="request"&&I2.length>0&&I2.every((R)=>!R.admitted)&&I2.some((R)=>h.killswitch.get(R.account.accountId)===!1||R.confirmedBlockers?.length)){let R=N$(u2,V1()),u=NZ({decision:R,now:O,host:"opencode2",requestThrow:!0,maxSameAccountWait:j2});if(u.kind==="http"){let p=JSON.parse(u.body);throw new E2({kind:"no-account",providerID:D2,sessionID:X.sessionID,requestKind:X.kind,message:p.error.message})}}return E?.debug("pool account chosen",{kind:X.kind,accountId:y,mode:P,...X.rerouteFrom?{rerouteFrom:X.rerouteFrom.accountId}:{}}),y}finally{if(b)K.rollback(b)}},accountHeaders:async(X)=>{let{accountId:W}=X;D.delete(d(X));let _=V2(X),F=l.get(_);l.delete(_);let S=()=>{F?.commit()};try{let x=()=>new E2({kind:"no-account",providerID:D2,sessionID:X.sessionID,requestKind:X.kind,message:m4}),O=async(J2)=>{if(!T)return;let j2=f2(_)??await T.forRequest();if(J2.kind==="pool"){let s=U.peek().rows.find((G2)=>G2.id===W);if(!s||s.credentialEpoch!==J2.credentialEpoch||U.usableToken(s)!==J2.token)throw x()}let C=T.bindings().find((s)=>s.account.accountId===W),i=await j2?.beforeDispatch(C,()=>T.ownershipBindings(),W),Q2=T.accountKey(W);if(i&&i.status!=="ready"||C&&(!Q2||!J1(C.account,Q2)))throw x();let H2=T.owner(),A2=C?{sessionId:X.sessionID,accountKey:C.account,dispatchedAt:V(),ttlMs:HZ(JSON.stringify({model:X.modelID}))}:void 0;if(A2){if(q.delete(A2.sessionId),q.set(A2.sessionId,A2),q.size>n2){let s=q.keys().next().value;if(s!==void 0)q.delete(s)}}Z2.set(J2,{owner:H2,probe:H2?.observe(C),dispatch:A2,failed:!1,completed:!1})},k=M&&await M.authority()!=="local"?void 0:U.peek().rows.find((J2)=>J2.id===W);if(!k&&M){let J2=V2(X),j2=W2.get(J2),C=j2?.receipt??await M.authorize(W);if(W2.delete(J2),!C)throw E?.warn("the vault refused to serve an account; refusing the request",{accountId:W}),x();let i={kind:"vault",routeId:W,receipt:C,...j2?.freeQuota?{freeQuota:!0}:{}};return await O(i),S(),{headers:{...t1,"session-id":X.sessionID,authorization:`Bearer ${C.accessToken}`,"chatgpt-account-id":C.accountIdentity??F1(C.accessToken)??null},attempt:i}}let f=k?U.usableToken(k):void 0;if(!k||!f)throw E?.warn("pool row holds no usable token; refusing the request",{accountId:W}),x();let o=k.identity??F1(f),h={kind:"pool",token:f,credentialEpoch:k.credentialEpoch,...o!==void 0?{identity:o}:{}};return await O(h),S(),{headers:{...t1,"session-id":X.sessionID,authorization:`Bearer ${f}`,"chatgpt-account-id":o??null},attempt:h}}finally{F?.drop()}},async rewriteRequest({request:X,sessionID:W,kind:_,attempt:F}){let S=$.codexEndpoint?$$(X.url,$.codexEndpoint()):X.url,x=S===X.url?X:new Request(S,X);return await l$(x,{sessionID:W,kind:_},F2,$.responsesLite?.()??!1,void 0,L(F))??x},rewriteHandshakeURL:({url:X})=>$.codexEndpoint?$$(X,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:X,sessionID:W,kind:_,attempt:F})=>p$(X,{sessionID:W,kind:_},F2,L(F)),quotaFromHeaders:(X,W,_)=>{if(_.data?.kind==="vault")M?.reportUsage(_.data.routeId,{headers:X},_.data.receipt);if(_.data?.kind==="vault"&&L2()&&W>=200&&W<300)Z.set(_,{status:W,headers:X});return p4(X)},async limitFromResponse({status:X,headers:W,body:_,attempt:F}){if(X<400)return;let S=K1(await _().catch(()=>"")),x=V(),O=R1({...T2(S)?S:{},status:X},x);if(F.data?.kind==="vault"&&L2())b1(F.sessionID,F.data.receipt,{status:X,headers:W,body:S,limit:O,quota:M?.routes().find((o)=>o.id===F.accountId)?.quota,now:V()}),j??=new WeakSet,j.add(F);if(!O)return;let k=L1(O,x,X,A(F.accountId,F.data?.kind==="vault"));if(k.retryAfterMs!==void 0)return k;let f=c4(W);return f===void 0?k:{...k,retryAfterMs:f,resetAt:x+f,resetSource:"retry-after"}},inspectEvent:({data:X,transport:W,attempt:_})=>{let F=K1(X),S=!1,x=_.data&&Z2.get(_.data);if(x&&T2(F)&&(F.type==="response.failed"||F.type==="error"))x.failed=!0;if(x&&T2(F)&&F.type==="response.completed")x.completed=!0;if(_.data?.kind==="vault"&&X.includes("codex.rate_limits")){let k=K1(X);if(T2(k)&&k.type==="codex.rate_limits")M?.reportUsage(_.data.routeId,{frame:k},_.data.receipt)}if(_.data?.kind==="vault"&&L2()){let k=Q.get(_);if(k)k.event(F),S=W==="ws"&&T2(F)&&(F.type==="response.incomplete"||F.type==="response.failed"||F.type==="error");if(CZ(X)||W==="ws"&&X.includes('"response.completed"')){if(_Z(F))J.add(_);if(W==="ws"&&T2(F)&&F.type==="response.completed")b1(_.sessionID,_.data.receipt,{status:200,headers:new Headers,failed:J.has(_)})}}let O=qZ(F,V(),A(_.accountId,_.data?.kind==="vault"));if(_.data?.kind==="vault"&&L2()&&O?.limit)G??=new WeakMap,G.set(_,F);return S||W==="ws"&&T2(F)&&F.type==="response.completed"?{...O,done:!0}:O},limitFromError(X,W){let _=K1(X.message),F=V(),S=A(W.accountId,W.data?.kind==="vault"),x=OZ({...T2(_)?_:{},...X.status!==void 0?{status:X.status}:{}},F,S)??(X.message.includes("usage_limit_reached")?L1({window:"usage_limit_reached"},F,X.status,S):void 0);if(W.data?.kind==="vault"&&L2()&&x)G??=new WeakMap,G.set(W,_);return x},async onAttemptEnd(X,W){let _=X.data?.kind==="vault"&&L2()?Q.get(X):void 0;if(_)Q.delete(X),_.end(W.outputStarted,!W.error,W.status,W.error?.reason==="cancelled");let F=X.data,S=F&&Z2.get(F);if(S){let O=!W.error&&!W.limit&&!S.failed&&(X.transport==="ws"?S.completed:W.status!==void 0&&W.status>=200&&W.status<300);if(O&&S.dispatch&&T){let k=q.get(S.dispatch.sessionId);FZ(T.activity,S.dispatch,k===S.dispatch?T.accountKey(X.accountId):void 0,X.transport==="ws"?{kind:"ws",event:"response.completed",aborted:!1}:{kind:"http",completed:!0,failed:!1,aborted:!1})}S.owner?.afterProbe(S.probe,O,Boolean(W.limit))}if(F&&W.outputStarted&&W.error?.reason==="failed"){if(D.set(d(X),{accountId:X.accountId,modelID:X.modelID,agent:X.agent,sessionID:X.sessionID,data:F.kind==="pool"?{kind:"pool",identity:F.identity}:{kind:"vault",credentialId:F.receipt.credentialId,accountIdentity:F.receipt.accountIdentity,wireIdentity:F.receipt.accountIdentity??F1(F.receipt.accessToken)}}),D.size>n2){let O=D.keys().next().value;if(O!==void 0)D.delete(O)}}let x=F?.kind==="vault"&&L2()?Z.get(X):void 0;if(Z.delete(X),F?.kind==="vault"&&L2()&&W.limit&&G?.has(X)&&!j?.has(X)){j??=new WeakSet,j.add(X);let O=W.limit;if(O.windows?.some((k)=>k.confirmed))MZ(X.sessionID,F.receipt,{window:O.reason,resetAt:O.resetAt},{body:G?.get(X),headers:x?.headers,quota:M?.routes().find((k)=>k.id===X.accountId)?.quota,now:O.observedAt})}if(G?.delete(X),F?.kind==="vault"&&x&&!W.error&&!W.limit)b1(X.sessionID,F.receipt,{...x,failed:J.has(X)});if(F?.kind!=="vault"||W.status!==401)return;E?.warn("a vault account answered 401; reporting it to the vault",{accountId:X.accountId}),await M?.reportFailure(F.receipt,401)}},B2=(X,W,_)=>{let F=_.data;if(F?.kind==="vault"){M?.recordSnapshot(X,W.snapshot,W.complete,F.receipt);return}if(F?.kind!=="pool")return;if(U.peek().rows.find((x)=>x.id===X)?.credentialEpoch!==F.credentialEpoch){E?.debug("quota reading dropped: the row holds another credential",{accountId:X});return}U.recordSnapshot(X,W.snapshot,F.token,W.complete)},$1=(X,W,_)=>{let F=V(),S=_.data?.kind==="vault";if(T){let x=_.data&&Z2.get(_.data),O=x?.owner??T.owner();if(!O)return;if(!x?.probe||O.registry!==x.probe.registry){O.dropSignal();return}let k=W,{command:f,provenance:o}=VZ({binding:x.probe.binding,baseRevision:x.probe.baseRevision,producerId:a,operationId:a$(),parsed:{window:W.reason,resetAt:k.resetAt??(W.retryAfterMs!==void 0?F+W.retryAfterMs:void 0)},reading:A(X,S),now:F,observedAt:k.observedAt??F,evidenceAt:F,resetSource:k.resetSource});O.enqueue(f,o);return}};return{adapter:h2,beginTurn:N2,dispose:()=>{U2.clear(),$2.clear(),m.clear(),N.clear()},attach(X){X.on("quota",(W)=>B2(W.accountId,W.quota,W.handle)),X.on("limit",(W)=>{$1(W.accountId,W.limit,W.handle),E?.debug("pool row refused the request",{accountId:W.accountId,via:W.via,reason:W.limit.reason,outputStarted:W.outputStarted})})},forgetSession(X){N2(X);for(let[W,_]of t)if(_.sessionID===X)K2(W);q.delete(X),T?.forget(X);for(let[W,_]of D)if(_.sessionID===X)D.delete(W);K.forget(X),k2.forget(X),F2.forget(X)},activeAccount:(X)=>k2.activeAccount(X)}}import{resolve as g1}from"node:path";function SZ($,Z){if(!Z.ok||!Z.body)return $.end(!1,!0,Z.status),Z;let J=!1,j=Z.body.pipeThrough(N1((Q)=>{J||=xZ(Q.data,Date.now())?.outputStarted===!0;try{$.event(JSON.parse(Q.data))}catch{}},()=>{})).getReader();return new Response(new ReadableStream({async pull(Q){try{let N=await j.read();if(N.done)Q.close(),$.end(J,!0,Z.status);else Q.enqueue(N.value)}catch(N){Q.error(N),$.end(J,!1,Z.status)}},cancel(Q){return $.end(J,!1,Z.status),j.cancel(Q)}}),{status:Z.status,statusText:Z.statusText,headers:Z.headers})}import{Buffer as d4}from"node:buffer";import{resolve as bZ}from"node:path";function M1($){return d4.byteLength(JSON.stringify($))}function i4($){return $.reduce((Z,J)=>Z+M1(J),0)}function H$($,Z){return 2+$+Math.max(0,Z-1)}function a4($){let{head:Z,pending:J}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+H$(Z.inputBytes,Z.input.length)+1:0)+(J?20+H$(J.inputBytes,J.input.length)+10+H$(J.outputBytes,J.output.length)+(J.responseID===void 0?0:14+J.responseIDBytes)+1:0)}function RZ($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class DZ{enabled;caps=v1;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$){for(let Z of this.entries.keys())if(!t2(Z,$))this.forget(Z)}}send($,Z){if(!t2($,this.enabled)){this.forget($);return}let J=RZ(Z);if(J?.type!=="response.create")return;if(!Array.isArray(J.input)){this.forget($);return}let G=J.previous_response_id,j=this.entries.get($),Q=j?.head;if(G&&G!==Q?.responseID){this.forget($);return}let{type:N,previous_response_id:L,input:U,...K}=J;this.keep($,{fields:G&&j?j.fields:K,fieldsBytes:G&&j?j.fieldsBytes:M1(K),...G&&Q?{head:Q}:{},pending:{input:U,inputBytes:i4(U),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,J){if(!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed")||!t2($,this.enabled))return;let G=this.entries.get($);if(!G?.pending)return;let j=RZ(Z);if(!j)return;let Q=G.pending,N=j.response;if(j.type==="response.created"&&typeof N?.id==="string")Q.responseID=N.id,Q.responseIDBytes=M1(N.id),this.keep($,G);else if(j.type==="response.output_item.done"&&j.item){if(typeof j.response_id==="string"&&Q.responseID!==void 0&&j.response_id!==Q.responseID)return;Q.output.push(j.item),Q.outputBytes+=M1(j.item),this.keep($,G)}else if(j.type==="response.completed"&&typeof N?.id==="string"){if(N.id===G.head?.responseID||Q.responseID!==void 0&&N.id!==Q.responseID)return;let L={responseID:N.id,responseIDBytes:Q.responseID===N.id?Q.responseIDBytes:M1(N.id),input:[...G.head?.input??[],...Q.input,...Q.output],inputBytes:(G.head?.inputBytes??0)+Q.inputBytes+Q.outputBytes},U={...G,head:L,pending:void 0};if(!this.keep($,U))return;J?.({sessionID:$,responseID:L.responseID,bodyText:this.body(G.fields,L)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let J=a4(Z);if(this.forget($),J>this.caps.maxBytes)return!1;Z.bytes=J,this.entries.set($,Z),this.bytes+=J;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let G=this.entries.keys().next().value;if(G===void 0)break;this.forget(G)}return this.entries.has($)}}var kZ=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),wZ=globalThis,F$=wZ[kZ]??new Map;wZ[kZ]=F$;function h1($){let Z=JSON.stringify([bZ($.configPath),bZ($.statePath)]),J=F$.get(Z);if(!J)J=new DZ,F$.set(Z,J);return J}var n4=5000,o4=["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"],s4=["x-opencode-parent-session-id","x-parent-session-id"];function K$($,Z){let J=r2($,Z),G=IZ(J);return{enabled:G?.enabled===!0,subagents:G?.subagents===!0,sustain:G?.sustain===!0,window:yZ({...J,cachekeep:G})}}var vZ=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),hZ=globalThis,j1=hZ[vZ]??new Map;hZ[vZ]=j1;function gZ($,Z){let J=JSON.stringify([g1($.configPath),g1($.statePath)]);return j1.get(J)?.manager.warming(Z)??{on:!1}}function r4($,Z){let J=[],G=()=>J.at(-1)?.location,j=()=>{let U=G();if(!U)throw Error("no location holds keep-warm");return U},Q=(U,K)=>{L.remove(U),G()?.log?.debug(`cachekeep dropped target (${K})`,{sessionKey:U})},N=async(U)=>{if(U.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let K=U.accountId??"main",V=j(),E=await V.source.accessFor(K,await V.storage());if(!E)throw Error(`pool row ${K} has no usable token`);return{token:E.token,identity:E.row.identity}},L=fZ({observeBillingSend(U,K,V,E){if(!V.credentialId||!L2())return;let M=U.meta.routingSessionId;if(!M)return;let T;try{T=JSON.parse(K).model}catch{return}if(typeof T!=="string")return;let a=j().vault.routes().find((A)=>A.id===U.accountId),Z2=X1({rows:a?[{id:a.id,kind:"oauth",...P1(a.quota)?{quota:a.quota}:{}}]:[],now:$.now(),placement:"roster",mainId:null,rateLimitMarks:new Map,refreshBackoff:new Map,killswitch:new Map,requestPull:()=>{}}),q=new I1(M,V,"keep_warm",T,E,(A)=>L.warming(A),a!==void 0&&Z2.kind==="send"&&Z2.tiers[a.id]==="free");return{response:(A)=>SZ(q,A),failed:()=>q.end(!1,!1)}},...v1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(U,K)=>j().fetch(U,K),logger:{debug:(U,K)=>G()?.log?.debug(U,K),warn:(U,K)=>G()?.log?.warn(U,K)},getWindow:()=>G()?.settings().window,getSustain:()=>G()?.settings().sustain===!0,resolveLocal:N,activity:{store:{get size(){return G()?.limits?.activity.size??0},get:(U)=>G()?.limits?.activity.get(U),forgetSession:(U)=>G()?.limits?.activity.forgetSession(U),recordAccepted:(U)=>G()?.limits?.activity.recordAccepted(U)??!1},accountKey:({target:U})=>{let K=G(),V=U.meta.routingSessionId??U.sessionKey,E=U.accountId??"main";return K?.accounts.activeAccount(V)===E?K.limits?.accountKey(E):void 0}},vault:{owns:(U)=>G()?.vault.owns(U)===!0,authority:()=>j().vault.authority(),reportUsage:(...U)=>G()?.vault.reportUsage(...U),send:async(U,K,V)=>{let E=j(),M=await E.vault.authority();if(M!=="vault"&&M!=="host")return;return E.vault.send(U,K,V)}},activeAccount:(U)=>{if(U===void 0)throw Error("target has no session");let K=G(),V=K?.settings();if(!K||!V||!t2(U,V.enabled)){Q(U,"keep-warm is off");return}if(!V.subagents&&L.status().targets.some((M)=>M.sessionKey===U&&M.isSubagent)){Q(U,"subagent warming is off");return}let E=K.accounts.activeAccount(U);if(E===void 0){Q(U,"no account recorded for the session");return}return E},verifyCredential:({target:U,mode:K,identity:V})=>{if(U.meta.credentialMode!==K)throw Error(`a target captured in ${U.meta.credentialMode??"an unknown"} mode is not warmed with a ${K} credential`);if(V!==U.meta.chatgptAccountId)throw Q(U.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:L,settings:Z,holders:J,joinTimeoutMs:$.joinTimeoutMs??n4}}function t4($){try{let Z=JSON.parse($),J=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(J?.role!=="user")return!1;return(typeof J.content==="string"?J.content:Array.isArray(J.content)?J.content.map((j)=>typeof j?.text==="string"?j.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function e4($){let Z={};for(let J of o4){let G=$.get(J);if(G)Z[J]=G}return Z}function mZ($,Z,J){let G=JSON.stringify([g1($.configPath),g1($.statePath)]),j=j1.get(G);if(!j)j=r4(J,Z.settings()),j1.set(G,j);let Q=j,N=h1($);N.setEnabled(Q.settings.enabled);let L={location:{...Z,settings:()=>Q.settings}};Q.holders.push(L);let U=!1,K=async(V)=>{try{let E=L.location.settings();if(U||!t2(V.sessionID,E.enabled))return;if(V.kind!=="primary"){if(V.kind==="generate"&&t4(await V.request.clone().text())){if(U)return;Q.manager.remove(V.sessionID)}return}let M=V.attempt.data,T=M?.kind==="pool"?"local":M?.kind==="vault"?"vault":void 0;if(!T)return;let a=V.request.headers,Z2=s4.some((F2)=>a.has(F2))||Z.parentOf!==void 0&&await Z.parentOf(V.sessionID)!==void 0;if(Z2&&!E.subagents)return;let q=await V.request.clone().text();if(U)return;let A=a.get("chatgpt-account-id")??void 0;Q.manager.track({sessionKey:V.sessionID,bodyText:q,accountId:V.attempt.accountId,isSubagent:Z2,meta:{replayHeaders:e4(a),...A?{chatgptAccountId:A}:{},routingSessionId:V.sessionID,url:V.request.url,credentialMode:T}})}catch(E){Z.log?.warn("cachekeep capture failed",{error:E instanceof Error?E.message:String(E)})}};return{manager:Q.manager,configure:(V)=>{Object.assign(Q.settings,V),N.setEnabled(Q.settings.enabled)},capture:K,forget:(V)=>Q.manager.remove(V),async release(){if(U)return;U=!0;let V=Q.holders.indexOf(L);if(V>=0)Q.holders.splice(V,1);if(Q.holders.length>0)return;if(j1.get(G)===Q)j1.delete(G);Q.manager.stop();let E;try{await Promise.race([Q.manager.tick().catch(()=>{}),new Promise((M)=>{E=setTimeout(M,Q.joinTimeoutMs),E.unref?.()})])}finally{clearTimeout(E)}}}}import{mkdirSync as $5}from"node:fs";import{dirname as Z5,resolve as z5}from"node:path";function J5(){return lZ("opencode2")}var G5=2000;class iZ{path;options;sessions;frameTurns=new z1;#$=new Set;#Z=new Set;#J=new Set;#G=Promise.resolve();#X=!1;#z;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=cZ($,Z.uuid??o2)}get($,Z=o2){let J=this.sessions.get($);if(!J){let G=Z();J={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,J),this.#Z.delete($),this.#J.delete($),this.#$.add($),this.#j()}return J}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#J.add($);this.#j()}#j(){if(this.#z)return;this.#z=setTimeout(()=>{this.#z=void 0,this.save()},this.options.saveDelayMs??G5),this.#z.unref?.()}save(){if(clearTimeout(this.#z),this.#z=void 0,!this.#X)this.#X=!0,this.#G=this.#G.then(()=>{return this.#X=!1,this.#Q()});return this.#G}settled(){return this.#z?this.save():this.#G}#Y(){if(this.#J.size===0)return;let $;try{$=L$(this.path)}catch{$=new Map}for(let Z of this.#J)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#J.clear()}async#Q(){if(this.#Y(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((G)=>{let j=this.sessions.get(G);return j?[[G,j]]:[]}),Z=[...this.#Z],J=null;try{if($5(Z5(this.path),{recursive:!0}),J=await this.#B(),!J)return;let G;try{G=L$(this.path)}catch{G=new Map}await this.options.afterRead?.();let j=!1;for(let Q of Z)if(G.delete(Q))j=!0;for(let[Q,N]of $){if(G.get(Q)===N.threadID)continue;G.set(Q,N.threadID),j=!0}if(j)dZ(this.path,G)}catch{return}finally{await J?.release().catch(()=>{})}for(let[G,j]of $)if(this.sessions.get(G)===j)this.#$.delete(G);for(let G of Z)if(!this.sessions.has(G))this.#Z.delete(G)}#B(){return pZ(this.path,this.options.lockWaitMs??uZ)}}var aZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),nZ=globalThis,m1=nZ[aZ]??new Map;nZ[aZ]=m1;function X5($){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 oZ($=J5()){let Z=z5($),J=m1,G=m1.get(Z),j=m1;if(G!==void 0&&!X5(G))J.compatible??=new Map,j=J.compatible;let Q=j.get(Z);if(!Q)Q=new iZ(Z),j.set(Z,Q);let N=Q;return N.frameTurns??=new z1,Q}import{appendFileSync as j5}from"node:fs";function c($,Z){let J=process.env.OPENAI_AUTH_E2E_RELOAD_TRACE;if(!J)return;try{j5(J,`${JSON.stringify({event:"setup-step",step:$,directory:Z,at:Date.now()})}
|
|
4
|
+
`)}catch{}}var P$=Symbol.for("cortexkit.openai-auth.v2.commands"),C$=l2("v2-command"),Y5=5000;function l1($){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 M$($){C$.warn(`/openai needs the terminal UI (session state: ${$}).`)}function Q5(){let $=globalThis;return $[P$]??={locations:new Map},$[P$].locations??=new Map,$[P$]}async function z0($,Z){let J=Q5(),G=$.location.directory,j={menu:Z,session:$.session,closed:new AbortController};c("before resolveRpcDir",G);let Q=await rZ(G);c("after resolveRpcDir",G);let N,L=(async()=>{try{c("before adoptRpcServer",G);let T=await sZ($0,Q.dir,()=>Z0({...Q,drain:eZ,apply:(a)=>{let Z2=J.locations.get(G);if(!l1(Z2))throw Error("The OpenAI menu location was closed");return Z2.menu.apply(a)}}));if(c("after adoptRpcServer",G),j.closed.signal.aborted)await T.release();else N=T}catch{C$.warn("OpenAI menu RPC hand-over failed",{directory:G})}})(),U;c("before RPC hand-over wait",G);try{await Promise.race([L,new Promise((T)=>{U=setTimeout(()=>{C$.warn("OpenAI menu RPC hand-over is still pending after 5 seconds",{directory:G}),T()},Y5),U.unref?.()})])}finally{clearTimeout(U)}c("after RPC hand-over wait",G);let K=J.locations.get(G);if(J.locations.set(G,j),l1(K))K.closed.abort(),c("before previous.registration.dispose",G),await K.registration?.dispose(),c("after previous.registration.dispose",G);let V={name:"openai",description:"OpenAI account menu",async execute(T){let a=[...J.locations.values()].find(l1)?.session;if(!a)return M$("no live location");let Z2=await a.get({sessionID:T.sessionID}),q=J.locations.get(Z2.location.directory);if(!l1(q))return M$("location closed");let A=await tZ(T.sessionID,q.closed.signal);if(!A||J.locations.get(Z2.location.directory)!==q){if(!A&&!q.closed.signal.aborted)_$({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},T.sessionID);return M$(q.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let F2=await q.menu.open(T.sessionID);_$(F2,T.sessionID)}};J.command??=V,J.command.execute=V.execute;let E=J.command;try{c("before command.transform",G),j.registration=await $.command.transform((T)=>{T.add(E)}),c("after command.transform",G)}catch(T){if(j.closed.abort(),J.locations.get(G)===j)J.locations.delete(G);throw await N?.release(),T}let M=!1;return async()=>{if(M)return;if(M=!0,j.closed.abort(),J.locations.get(G)===j)J.locations.delete(G);await N?.release(),await j.registration?.dispose()}}var B5="openai-auth-pool-browser",U5="openai-auth-pool-headless",V5="openai-auth-vault",W5="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 _1($){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 U0($){return{method:{id:V5,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){let Z=await G0($.paths,$.name);if(Z==="host"){let J=J0(j0);await Promise.resolve(J.close()).catch(()=>{return})}else if(Z!=="vault")throw Error(W5)}}}function V0($){let Z=(J,G,j)=>({method:{id:J,type:"oauth",label:G},async authorize(){if($.vault)await _1($.vault);let Q=await $.beginLogin({version:$.version,headless:j});return{url:Q.url,instructions:Q.instructions,mode:"auto",callback:Q.completion}}});return[Z(B5,"ChatGPT (openai-auth pool, browser)",!1),Z(U5,"ChatGPT (openai-auth pool, headless)",!0)]}function E$($){let Z=(J)=>typeof J==="string"?J:"";return W1({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===Q0||X0($)}function N5($){if($.accountId)return $.accountId;let Z=$.access?D1($.access):void 0;return Z?k1(Z):void 0}async function W0($,Z,J,G={}){if(G.vault)await _1(G.vault);if(E$(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let j=Y0($,{rowLocks:(T)=>B0(Z,T)}),Q=await j.read();if(Q.status!=="ready")throw Error(`the account pool cannot be read (${Q.status}); the login was not stored`);let N={type:"oauth",refresh:J.refresh,...J.access!==void 0?{access:J.access}:{},...J.expires!==void 0?{expires:J.expires}:{}},L=N5(J);if(G.vault)await _1(G.vault);let U=L!==void 0?{identity:L}:{};if(G.origin==="import"){let T=Q.rows.find((a)=>L!==void 0&&a.identity===L||a.credential?.type==="oauth"&&a.credential.refresh===J.refresh);if(T)return{id:T.id,operation:"kept"}}let K=Q.rows.filter((T)=>T.type==="oauth"&&!T.invalid),V=L?K.find((T)=>T.identity===L):void 0,E=Q.rows.find((T)=>T.id===u1);if(V)return{id:(await j.replace(V.id,N,U)).id,operation:"replaced"};if(!E){let T=await j.add({id:u1,credential:N,...U,...J.label!==void 0?{label:J.label}:{}});return{id:T.id,operation:T.outcome==="added-disabled"?"added-disabled":"added"}}if(!E.invalid&&!E.credential)return{id:(await j.replace(u1,N,U)).id,operation:"replaced"};let M=await j.add({id:J.id,credential:N,...U,...J.label!==void 0?{label:J.label}:{}});return{id:M.id,operation:M.outcome==="added-disabled"?"added-disabled":M.outcome==="rotated"?"replaced":"added"}}function H5($){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","maxSameAccountWait"].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 F0($){let Z={...$,allowAction:H5,unavailableSections:[]};return{open:(J)=>N0(Z,J),apply:(J)=>{let G=J!==null&&typeof J==="object"?J:{},j=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 H0(Z,{command:"openai",sectionId:typeof G.sectionId==="string"?G.sectionId:"",actionId:typeof G.actionId==="string"?G.actionId:"",...j?{values:j}:{},...G.confirmed===!0?{confirmed:!0}:{},...typeof G.itemId==="string"?{itemId:G.itemId}:{},...typeof G.sessionId==="string"?{sessionId:G.sessionId}:{}})}}}function F5($,Z){if(!K0($.modelID??$.id)){$.enabled=!1;return}let J=L0($.id);if(J)$.limit={...J};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((G)=>[G.id,G])).values()]}function M0($){return $.model.transform((Z)=>{let J=Z.list(D2);for(let G of J){let j=P0(String(G.id)),Q=j?J.find((N)=>String(N.id)===j):void 0;Z.update(D2,String(G.id),(N)=>F5(N,Q?.variants?.map((L)=>({...L,id:String(L.id)}))))}})}class T${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(!_0())return;await this.safely(async()=>{let J={sessionID:Z.sessionID,accountId:Z.accountId,transport:"http",phase:"http",url:$.url,method:$.method,headers:new Headers($.headers),bodyText:await $.clone().text()};if(this.pending.set($,{attemptId:Z.attemptId,input:J}),this.requests.set(Z.attemptId,$),this.pending.size>512){let G=this.pending.keys().next().value;if(G)this.take(G)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let J=this.take($);if(J)await this.safely(()=>p1({...J,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let J=this.requests.get($.attemptId),G=J&&this.take(J);if(!G)return;let{reason:j,message:Q}=Z.error,N=Q?`${j}: ${Q}`:j;await this.safely(()=>p1({...G,error:c1(N,J?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>p1({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 O${counts=new Map;record($,Z){let J=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof J==="number"&&Number.isFinite(J)?J:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function x0($){return async(Z)=>{let J=Z.credential;if(J.type!=="oauth"||!J.access)throw Error("the row holds no access token to poll with");let G=await C0({accessToken:J.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,G),E0(G,$.now(),!0)}}function q0($){let{source:Z,counts:J,now:G}=$,j=async(K)=>{let V=await Z.rowAccess(K,await $.storage());if(!V?.row)throw new T0("unknown_account",`${K==="main"?"Main":"Fallback"} account ${K} was not found.`);return O0(K,V)},Q=async(K)=>{if($.authority&&await $.authority()!=="local")return{account:K,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[V]=await Z.pollRows(await $.storage(),{ids:[K]});if(!V)return{account:K,ok:!1,error:"targeted quota refresh returned no result"};return{account:V.id,ok:V.ok,...V.error!==void 0?{error:V.error}:{}}},N=(K)=>Z.peek().rows.find((V)=>V.id===K),L=(K)=>{let V=N(K);if(!V)return null;let E=s2(V.quota)??{},M=J.applicable(V),T=Math.max(0,...[E.primary?.checkedAt,E.secondary?.checkedAt].filter((a)=>typeof a==="number"));return{quota:{...E,...M!==void 0?{resetCreditsApplicable:M}:{}},checkedAt:T,refreshAfter:T,...V.identity!==void 0?{accountId:V.identity}:{}}};return{resolveResetTarget:j,refreshResetTargetQuota:Q,quotaManager:{isRateLimited:(K)=>{let V=N(K);if(!V)return!1;let E=$.rateLimitMarks().get(V.id);return E!==void 0&&E>G()},getMain:()=>L("main"),getFallback:(K)=>L(K)}}}import{resolve as A0}from"node:path";var K5=1024;class x${pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=K5){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.reservations.delete($),this.pins.delete($);for(let Z of this.listeners)Z($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}snapshot(){return new Map(this.pins)}placementSnapshot($){let Z=new Map(this.pins);for(let J of this.reservations.values())if(J.sessionId!==$)Z.set(J.sessionId,J.pin);return Z}reserve($,Z){let J={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,J),J}rollback($){if(this.reservations.get($.sessionId)===$)this.reservations.delete($.sessionId)}finish($,Z){if(this.reservations.get($.sessionId)!==$)return;if(this.rollback($),Z&&this.pins.get($.sessionId)===$.previous)this.set($.sessionId,Z)}get size(){return this.pins.size}set($,Z){this.reservations.delete($),this.pins.delete($),this.pins.set($,Z);for(let J of this.listeners)J($,Z);while(this.pins.size>this.limit){let J=this.pins.keys().next().value;if(J===void 0)break;this.forget(J)}}place($){return w1(this.placementSnapshot($.sessionId),$,(Z,J)=>this.set(Z,J))}}var S0=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),b0=globalThis,d1=b0[S0]??new Map;b0[S0]=d1;function L5($){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 R0($){let Z=JSON.stringify([A0($.configPath),A0($.statePath)]),J=d1,G=d1.get(Z);if(G!==void 0&&!L5(G)){let Q=d1;Q.compatibleV1??=new Map,J=Q.compatibleV1}let j=J.get(Z);if(!j)j=new x$,J.set(Z,j);return j}import{statSync as P5}from"node:fs";import{resolve as M5}from"node:path";function g0($){return $.map((Z)=>{try{let J=P5(Z);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}function q$($){return g0([$.vault.paths.tokenPath,$.vault.paths.statePath])}function D0($){return g0([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+q$($)}class m0{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:D0($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),J=this.subscriptions.get($.pins);if(!J){let G=new Set;J={producers:G,stop:$.pins.subscribe((j,Q)=>{let N=G.values().next().value;if(N)this.publish(N,{sessionId:j,pin:Q,accountId:Q?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,J)}return J.producers.add($),this.timer??=setInterval(()=>{for(let G of this.producers){let j={stamp:D0(G),roster:G.vault.snapshot()},Q=this.observations.get(G);if(j.stamp!==Q?.stamp||j.roster!==Q?.roster)this.observations.set(G,j),this.publish(G)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),J.producers.delete($),!J.producers.size)J.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;await($.write??l0)(this.file,$,Z,()=>this.producers.has($))}).catch(()=>{l2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var l0=async($,Z,J,G)=>{let Q=await Z.vault.authority()!=="local",N=q$(Z),L=()=>G()&&Z.vault.enrolled()===Q&&q$(Z)===N,U=await(Q?E1(Z.paths):Y1(Z.paths)),K=Q?v0(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((M)=>M.id)),U,Date.now()):h0((await Z.source.sidebarView()).rows,U,Date.now()),V={canWrite:L,vaultMode:Q};if(await w0(K,$,V),!L()||!J)return;let E=K.vaultAccounts??K.fallbacks;if(J.accountId===void 0){await y0(J.sessionId,E,$,V);return}if(J.pin){let M=Date.now();await f0({sessionId:J.sessionId,assignment:{accountId:J.pin.accountId,wireAccountId:J.pin.wireIdentity,inputBytes:J.pin.inputBytes??0,quotaCheckedAt:J.pin.quotaCheckedAt,assignedAt:M,lastSeenAt:M},validPinnedAccountIds:[...Q?[]:["main"],...E.filter((T)=>T.enabled).map((T)=>T.id)]},$,V)}await I0({sessionId:J.sessionId,activeId:J.accountId,route:J.route??K.route,updatedAt:Date.now()},E,$,V)},u0=2,p0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),c0=globalThis,C1=c0[p0]??new Map;c0[p0]=C1;function d0($,Z=k0(),J=2000){let G=M5(Z),j=C1.get(G);if(j?.protocol!==u0)j=new m0(G,J),C1.set(G,j);let Q=j;$={...$,write:$.write??l0};let N=Q.add($),L=!1;for(let[U,K]of $.pins.snapshot())Q.publish($,{sessionId:U,pin:K,accountId:K.accountId,route:"sticky-balanced"});return{publish:()=>Q.publish($),route:(U,K,V)=>{Q.publish($,{sessionId:U,accountId:K,route:V})},async release(){if(L)return;if(L=!0,N(),await Q.settled(),Q.empty&&C1.get(G)===Q)C1.delete(G)}}}var a1="cortexkit-openai-auth",E5=5000;async function i0($,Z,J,G=new H1,j,Q,N){let L=new T$(J),U=new _5,K=new Map,V=new Map,E=(q)=>{V.delete(q);for(let A of K.keys())if(A.startsWith(`${q}:`))K.delete(A)},M=(q)=>{N?.(q.sessionID),Q?.send(q.sessionID,q.frame)},T={session:{hook:(q,A,F2)=>$.session.hook(q,async(U2)=>{let $2=q==="http.request"?U2:void 0,m=q==="experimental.ws.handshake"?U2:void 0,N2=($2?$2.request.headers:m?new Headers(m.headers):void 0)?.get("authorization")===`Bearer ${m2(Z.providerID)}`,W2={};if(m)K.delete(`${m.sessionID}:${m.kind}`);try{await U.run(W2,()=>A(U2))}catch(D){if(N2&&!(D instanceof E2))throw $4(D);throw D}if($2&&N2&&W2.attempt){let D=$2.request.headers.get("thread-id");if(D)$2.request.headers.set("session-id",D)}if($2&&N2&&W2.attempt)await L.captureHttp($2.request,W2.attempt);if($2&&N2&&W2.attempt)await j?.({sessionID:$2.sessionID,kind:$2.kind,request:$2.request,attempt:W2.attempt});if(m&&N2&&W2.attempt)m.headers["session-id"]=G.get(m.sessionID).threadID;if(q==="experimental.ws.send"){let D=U2,d=K.get(`${D.sessionID}:${D.kind}`);if(d)d.pending=!0;if(d)await L.frame(D.frame,d.attempt);if(d&&D.kind==="primary")M(D)}if($2||m){let D=$2??m;if(!D)return;let l=($2?$2.request.headers:new Headers(D.headers)).get("authorization")?.replace(/^Bearer /,"");if(N2&&l)V.set(D.sessionID,l);else V.delete(D.sessionID);if(m){let t=`${m.sessionID}:${m.kind}`;if(N2&&l&&W2.attempt)K.set(t,{bearer:l,attempt:W2.attempt,pending:!1,url:m.url,headers:new Headers(Object.entries(m.headers).filter(([K2])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(K2.toLowerCase())))});else K.delete(t)}if(V.size>512){let t=V.keys().next().value;if(t)V.delete(t)}if(K.size>512){let t=K.keys().next().value;if(t)K.delete(t)}}else if(q==="experimental.ws.receive"){let D=U2,d=K.get(`${D.sessionID}:${D.kind}`);if(d){if(G.frameReceived(D.sessionID,D.frame),D.kind==="primary"){let l;if(Q?.receive(D.sessionID,D.frame,(t)=>{l=t}),l)try{let t=u$(l,d.url,d.headers,G);if(t)await j?.({sessionID:D.sessionID,kind:"primary",request:t,attempt:d.attempt})}catch(t){J.warn("cachekeep WebSocket capture failed",{error:t instanceof Error?t.message:String(t)})}}if(D.frame=Z4(D.frame,d.bearer),D.kind==="primary"&&d.pending&&L2()&&(D.frame.includes('"response.completed"')||D.frame.includes('"response.failed"')||D.frame.includes('"response.incomplete"')||D.frame.includes('"error"')))try{let l=JSON.parse(D.frame);if(l.type==="response.completed")d.pending=!1,t0(D.sessionID,Date.now());else if(["response.failed","response.incomplete","error"].includes(l.type))d.pending=!1}catch{}}}else if(q==="retry"){let D=U2,d=V.get(D.sessionID);if(d)Object.assign(D.error,{message:c1(D.error.message,d)})}},F2)},event:{subscribe:(q)=>async function*(){for await(let A of $.event.subscribe(q)){if(A.type==="session.deleted")E(A.data.sessionID);yield A}}()}};c("before installOpenCode2Auth",$.location?.directory);let a=await s1(T,{...Z,rewriteRequest:async(q)=>{let A=U.getStore();if(A)A.attempt=q.attempt;return Z.rewriteRequest?.(q)},rewriteHandshakeURL:(q)=>{let A=U.getStore();if(A)A.attempt=q.attempt;return Z.rewriteHandshakeURL?.(q)},onAttemptEnd:async(q,A)=>{await L.end(q,A),await Z.onAttemptEnd?.(q,A)},rewriteResponse:async(q)=>{await L.response(q.request,q.response.status);let A=await Z.rewriteResponse?.(q)??q.response,F2=await z4(A,q.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream");return e0(F2,q.kind==="primary"?q.sessionID:void 0)}},{gateOnPlaceholder:{credential:(q)=>{let A=q.get("authorization");return A?.startsWith("Bearer ")?A.slice(7):void 0}},hostRetryLimit:G1,logger:{info:(q,A)=>J.info?.(q,{data:A}),warn:(q,A)=>J.warn(q,{data:A})}}),Z2=a.dispose;return c("after installOpenCode2Auth",$.location?.directory),{...a,dispose:async()=>{V.clear(),K.clear(),await Z2(),await L.settle(),L.clear()}}}function b$($={}){return{id:a1,setup:(Z)=>T5(Z,$)}}async function T5($,Z={}){let o=[];try{let J=$.location?.directory;c("setup enter",J);let G=l2("opencode2");let j=l2("quota");let Q=Z.version??j4;c("before prepareRuntimeLayout",J);await P4({version:Q,...Z.runtimeLayout});c("after prepareRuntimeLayout",J);let N=Z.paths??(()=>Q4(G4()));let L=N().configPath;c("before prepareSettingsStartup",J);let U=await M4({version:Q,paths:N(),log:G});c("after prepareSettingsStartup",J);let K=U.snapshot;let V=K?X4(L,K):void 0;let E=()=>{V?.(),K?.dispose()};let M=!1;const T=Q1(o,{[Symbol.dispose](){if(!M)E()}},0);c("before loadAccountSettings",J);let a=await E1(N());c("after loadAccountSettings",J);let Z2=r2(a,L).logging?.level;if(!K&&Z2&&typeof Z2==="string")n0(Z2);let q=Z.fetch??fetch;let A=Z.now??Date.now;let F2=Z.poolMigration??C4;if(!F2&&!B1(N().configPath)){G.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 C=(Q2)=>{throw new E2({kind:"no-account",providerID:D2,sessionID:Q2.sessionID,requestKind:Q2.kind,message:y1})};c("before installPoolHooks (stand-aside)",J);let i=await i0($,{providerID:D2,chooseAccount:C,accountHeaders:C},G);return c("after installPoolHooks (stand-aside)",J),M=!0,c("setup exit (stand-aside)",J),async()=>{try{await i.dispose()}finally{E()}}}let U2=Z.vault?.firstRosterWaitMs??W4;let $2=_4({host:"opencode",stateDir:Z.vault?.stateDir??r0(N().statePath),reservedRouteIds:()=>l.peek().rows.map((C)=>C.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}:{},...Z.vault?.now?{now:Z.vault.now}:{},...Z.vault?.setTimeoutImpl?{setTimeoutImpl:Z.vault.setTimeoutImpl}:{},...Z.vault?.clearTimeoutImpl?{clearTimeoutImpl:Z.vault.clearTimeoutImpl}:{},fetchImpl:()=>q},N());let m=$2.vault;let O2=async()=>await m.authority()==="local"?Y1(N()):E1(N());let N2=!1;const W2=Q1(o,{[Symbol.dispose](){if(!M)$2.release()}},0);c("before vault.authority",J);await m.authority();c("after vault.authority",J);let D=$2.firstRoster;let d=new O$;let l=new N4({paths:N,refreshProvider:async(C)=>{let i=await s0({refreshToken:C.refresh,fetchImpl:q,now:A}),Q2=o0({id_token:"",access_token:i.access,refresh_token:i.refresh});return{...i,...Q2?{identity:Q2}:{}}},pullQuota:x0({fetchImpl:q,now:A,counts:d,logger:j}),now:A,vaultIdentities:()=>m.identities(),vaultMode:()=>m.enrolled(),vaultAuthority:()=>m.authority(),vaultFirstRoster:D,vaultFirstRosterBackgroundWaitMs:U2,log:l2("pool")});c("before vault.authority (source)",J);let t=await m.authority();c("after vault.authority (source)",J);if(t==="local")c("before source.load",J),await l.load(),c("after source.load",J);let K2=new H4({pool:l,vault:m,log:(C)=>G.warn(C)});const U1=Q1(o,{[Symbol.dispose](){if(!M)K2.dispose()}},0);c("before startProcessHeartbeat",J);let f2=Z.heartbeat===!1?void 0:await K4({version:Q,logger:l2("heartbeat")});c("after startProcessHeartbeat",J);let V2=Z.fence??(()=>Y4({currentVersion:Q}));let k2=Z.slot??E4();let x2=async()=>B4(N(),await k2.get({path:{id:"openai"}}));let P2=!1;let M2=F2?F4({paths:N,slot:k2,version:Q,fence:V2,runDeps:{vaultServes:()=>m.serves()},paused:async()=>await m.authority()!=="local",migrate:async(C)=>{let i=await U4(C);if(P2=i.status==="refused",!N2)await l.load();return i},adopt:async(C)=>{if(N2)return{status:"retry",reason:"unsettled"};if(!await S$(D,U2))return{status:"retry",reason:"vault-roster-pending"};if(N2)return{status:"retry",reason:"unsettled"};let i=await V4(C);if(!N2)await l.load();return i}}):void 0;M2?.start();$2.start();let w2=R0(N());let q2=d0({paths:N(),source:l,pins:w2,vault:m},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const p2=Q1(o,{[Symbol.dispose](){if(!M)q2.release()}},0);q2.publish();let e2=Z.codex??new H1(void 0,void 0,oZ());let v2=K$(a,L);let h2=h1(N());let B2=mZ(N(),{source:l,limits:K2,storage:O2,vault:m,accounts:z$(N()),settings:()=>v2,parentOf:async(C)=>(await $.session.get({sessionID:C}))?.parentID??void 0,fetch:q,log:l2("cachekeep")},{now:A,codexResponsesUrl:i1(L).codexApiEndpoint,...Z.cacheKeep});K?.onChange(()=>{B2.configure(K$(a,L))});const $1=Q1(o,{[Symbol.dispose](){if(!M)B2.release()}},0);let X=AZ({cacheWarming:(C)=>gZ(N(),C),limits:K2,codex:e2,onRoute:q2.route,source:l,slotPlaceholderWithoutMain:x2,storage:O2,configPath:L,pins:w2,sessionAccounts:z$(N()),vault:m,awaitVaultRoster:async()=>{await S$(m.awaitRequestRoster(),f1)},responsesLite:()=>i1(L).responsesLite,codexEndpoint:()=>i1(L).codexApiEndpoint,now:A,log:G});c("before installPoolHooks",J);let W=await i0($,X.adapter,G,e2,(C)=>B2.capture(C),h2,(C)=>B2.forget(C));c("after installPoolHooks",J);X.attach(W);c("before session.hook (prompt)",J);let _=await $.session.hook("prompt",(C)=>{X.beginTurn(C.sessionID)});c("after session.hook (prompt)",J);let F=async(C)=>{if(await _1(m),B1(N().configPath))return;if(await M2?.idle(),B1(N().configPath))return;if(P2&&!E$(C)&&(await V2()).open){await l.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let S=async(C)=>{await F(C);let i=await W0(l.poolStore(),N(),C,{vault:m});if(!B1(N().configPath))await M2?.requestAdoption();await l.load(),G.info("ChatGPT login stored in the account pool",i)};c("before registerOpenCode2AuthMethods",J);let x=await o1($,{integrationID:D2,methods:V0({beginLogin:Z.beginLogin??A$,version:Q,vault:m}),onLogin:(C)=>S(C),label:"ChatGPT (openai-auth account pool)",vault:U0(m)});c("after registerOpenCode2AuthMethods",J);c("before registerCodexModelRules",J);let O=await M0($);c("after registerCodexModelRules",J);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");c("before installControlPlane",J);let k=$.command&&$.location?await z0({session:$.session,command:$.command,location:$.location},Z.controlPlane??F0({...q0({rateLimitMarks:()=>K2.marks(),source:l,storage:O2,counts:d,now:A,authority:()=>m.authority()}),fetchImpl:q,now:A,randomUUID:C5,accountStoragePath:N().configPath,accountStatePath:N().statePath,configPath:L,...K?{settingsSnapshot:K,settings:J4({file:U.authority.install.target,host:"opencode",snapshot:K,log:G})}:{},packageVersion:Q,layoutNotice:L4,loadAccounts:Y1,store:()=>l.poolStore(),migration:async()=>{if(B1(N().configPath))return{migrated:!0};let C=await V2();return{migrated:!1,blockers:C.open?[]:C.blockers}},beginAccountLogin:Z.beginLogin??A$,refreshAllQuota:async()=>(await l.pollRows(await Y1(N()))).map((C)=>({...C,account:C.id})),getStickyRouting:async(C)=>w2.get(C),cacheKeepManager:B2.manager,setCacheKeepEnabled:(C)=>B2.configure({enabled:C}),setCacheKeepSubagents:(C)=>B2.configure({subagents:C}),setCacheKeepSustain:(C)=>B2.configure({sustain:C}),setCacheKeepWindow:(C)=>B2.configure({window:C}),afterWrite:()=>l.load(),refreshSidebar:()=>q2.publish(),clearStickyRouting:async(C)=>{let i=w2.get(C)!==void 0;return w2.forget(C),i},vault:m})):void 0;c("after installControlPlane",J);let f=new AbortController;(async()=>{try{for await(let C of $.event.subscribe({signal:f.signal}))if(C.type==="session.deleted")X.forgetSession(C.data.sessionID),B2.forget(C.data.sessionID),h2.forget(C.data.sessionID)}catch(C){if(!f.signal.aborted)G.warn("stopped listening for session deletion",{error:C instanceof Error?C.message:String(C)})}})();M=!0;c("setup exit",J);return async()=>{N2=!0,f.abort(),X.dispose();let C=B2.release();await k?.(),M2?.dispose(),await K2.dispose(),await q2.release(),await Promise.allSettled([W.dispose(),_.dispose(),x.dispose(),O.dispose()]);let i;try{await Promise.race([Promise.all([M2?.idle(),l.settled(),e2.store?.settled(),C]),new Promise((Q2)=>{i=setTimeout(Q2,E5),i.unref?.()})])}finally{clearTimeout(i),E(),await $2.release(),await f2?.release()}}}catch(h){var J2=h,j2=1}finally{a0(o,J2,j2)}}var O5=b$(),N9={id:a1,setup:O5.setup,server:T4.server};export{N9 as default,b$ as createOpenAIAuthPlugin,a1 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.
|
|
3
|
+
"version": "1.18.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -66,7 +66,7 @@
|
|
|
66
66
|
},
|
|
67
67
|
"devDependencies": {
|
|
68
68
|
"@ai-sdk/openai": "3.0.88",
|
|
69
|
-
"@cortexkit/common-auth": "^0.
|
|
69
|
+
"@cortexkit/common-auth": "^0.52.1",
|
|
70
70
|
"@cortexkit/openai-auth-core": "workspace:*",
|
|
71
71
|
"@cortexkit/opencode-sidebar": "0.1.0",
|
|
72
72
|
"@opencode/plugin": "2.2.6"
|
|
@@ -1,8 +1,15 @@
|
|
|
1
|
-
import { readFileSync, realpathSync, statSync, watch, } from "node:fs";
|
|
1
|
+
import { lstatSync, readFileSync, readlinkSync, realpathSync, statSync, watch, } from "node:fs";
|
|
2
2
|
import { readFile, stat } from "node:fs/promises";
|
|
3
3
|
import { basename, dirname, join, resolve } from "node:path";
|
|
4
4
|
import { clearTimeout, setTimeout } from "node:timers";
|
|
5
|
+
import { canonicalFilePathSync } from "./cf4c37f3975c3a8d-canonical-file-path.js";
|
|
5
6
|
import { PrivateFileError, readPrivateText, windowsPrivateFiles, } from "./375d9cca2def037d-private-files.js";
|
|
7
|
+
const pathFsDefaults = { lstatSync, readlinkSync, realpathSync };
|
|
8
|
+
const pathFs = { ...pathFsDefaults };
|
|
9
|
+
/** Internal test hook; omitted path operations use the native implementation. */
|
|
10
|
+
export function setTuiPreferencesPathFsForTest(overrides) {
|
|
11
|
+
Object.assign(pathFs, pathFsDefaults, overrides);
|
|
12
|
+
}
|
|
6
13
|
function canonicalPath(file) {
|
|
7
14
|
const path = resolve(file);
|
|
8
15
|
// Leave reparse points in the path for private-files' ancestor walk to reject;
|
|
@@ -10,7 +17,7 @@ function canonicalPath(file) {
|
|
|
10
17
|
if (windowsPrivateFiles)
|
|
11
18
|
return path;
|
|
12
19
|
try {
|
|
13
|
-
return
|
|
20
|
+
return canonicalFilePathSync(path, pathFs);
|
|
14
21
|
}
|
|
15
22
|
catch {
|
|
16
23
|
// Resolve existing ancestors even when the preferences file is not yet present.
|
|
@@ -404,7 +404,7 @@ export class ClaustrumScopedCustody {
|
|
|
404
404
|
throw error;
|
|
405
405
|
if (classifyVaultFailure(error) === 'unreachable')
|
|
406
406
|
throw new ClaustrumUnreachableError(error instanceof ClaustrumUnreachableError ? error.reason : undefined);
|
|
407
|
-
throw new ClaustrumConsumerError('unavailable', 'Claustrum scoped operation
|
|
407
|
+
throw new ClaustrumConsumerError('unavailable', 'Claustrum scoped operation failed');
|
|
408
408
|
}
|
|
409
409
|
finally {
|
|
410
410
|
removeAbortListener?.();
|
|
@@ -24,7 +24,9 @@ export function setPrivateFilesBackendForTest(api) {
|
|
|
24
24
|
/** The fixed `reason` of a refusal because the Windows native addon did not load. */
|
|
25
25
|
export const PRIVATE_FILES_UNAVAILABLE_REASON = 'native-addon-unavailable';
|
|
26
26
|
function privateFilesUnavailable(cause) {
|
|
27
|
-
return Object.assign(new Error('Windows private-files native addon
|
|
27
|
+
return Object.assign(new Error('Windows private-files native addon could not be loaded', {
|
|
28
|
+
cause,
|
|
29
|
+
}), {
|
|
28
30
|
code: 'ERR_PRIVATE_FILES_UNAVAILABLE',
|
|
29
31
|
reason: PRIVATE_FILES_UNAVAILABLE_REASON,
|
|
30
32
|
});
|