@cortexkit/opencode-openai-auth 1.12.0 → 1.14.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 +9 -9
- package/dist/{codex-request-DFeGDzpN.d.ts → codex-request-Cl6zEfsR.d.ts} +21 -3
- package/dist/{index-5p6vw484.js → index-1abcvt9p.js} +1 -1
- package/dist/{index-2xsz3z63.js → index-3c9pk6zn.js} +2 -2
- package/dist/{index-dcvxs9xj.js → index-4tpttpjw.js} +1 -1
- package/dist/index-4zpxwh8y.js +91 -0
- package/dist/{index-7p1s64b4.js → index-a9tzfpxy.js} +1 -1
- package/dist/index-bc2d4vma.js +64 -0
- package/dist/{index-wtmxk263.js → index-f7t7cc9b.js} +2 -2
- package/dist/{index-7qztyb1b.js → index-nfbmjq6g.js} +2 -2
- package/dist/{index-3pm1cvhy.js → index-q111b2h5.js} +1 -1
- package/dist/{index-3nwj0h10.js → index-wap9mf5f.js} +2 -2
- package/dist/{index-p4qaa85r.js → index-xxmaf5ks.js} +2 -2
- package/dist/index-yew3mp47.js +76 -0
- package/dist/index-zcpher1w.js +8 -0
- package/dist/index.d.ts +1 -1
- 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-dr80qm6g.js → token-6x4q5r2r.js} +1 -1
- package/dist/token-util-54mhq85x.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.d.ts +1 -1
- package/dist/v2/server.js +3 -3
- package/package.json +8 -7
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +89 -31
- package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +19 -13
- package/src/tui-compiled/raw/shared/549daf371622c304-index.tsx +49 -607
- package/src/tui-compiled/raw/shared/723b00f96290a097-lock-record.js +55 -0
- package/src/tui-compiled/raw/shared/94f53cfd572ba4bb-availability.js +9 -1
- package/src/tui-compiled/raw/shared/a75d0d866c227b3f-index.tsx +681 -0
- package/src/tui-compiled/raw/shared/abd062d633e29fd2-pool-routing.js +21 -15
- package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +110 -2
- package/src/tui-compiled/raw/shared/c97089ed4243981c-host.js +11 -7
- package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +148 -92
- package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +1 -1
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +89 -31
- package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +19 -13
- package/src/tui-compiled/runtime/shared/549daf371622c304-index.js +36 -674
- package/src/tui-compiled/runtime/shared/723b00f96290a097-lock-record.js +55 -0
- package/src/tui-compiled/runtime/shared/94f53cfd572ba4bb-availability.js +9 -1
- package/src/tui-compiled/runtime/shared/a75d0d866c227b3f-index.js +678 -0
- package/src/tui-compiled/runtime/shared/abd062d633e29fd2-pool-routing.js +21 -15
- package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +110 -2
- package/src/tui-compiled/runtime/shared/c97089ed4243981c-host.js +11 -7
- package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +148 -92
- package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +1 -1
- package/dist/index-2egbrywb.js +0 -8
- package/dist/index-dqk0c7wr.js +0 -64
- package/dist/index-n5jtwtrs.js +0 -76
- package/dist/index-phgm1zwn.js +0 -91
- package/dist/token-util-97td5ex3.js +0 -1
package/dist/v2/server.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{c as
|
|
2
|
-
`)}:{event:
|
|
3
|
-
`)}}function p1($,Z){let G=new TextDecoder,J="",Q=(K)=>{let N=W4(K);if(!N)return;try{$(N)}catch(V){Z(V)}},Y=()=>{for(;;){let K=/\r?\n\r?\n/.exec(J);if(!K)return;let N=J.slice(0,K.index);J=J.slice(K.index+K[0].length),Q(N)}};return new TransformStream({transform(K,N){N.enqueue(K),J+=G.decode(K,{stream:!0}),Y()},flush(){if(J+=G.decode(),Y(),J.trim()!=="")Q(J);J=""}})}var s2=512,p2=3621000,o2="x-common-auth-attempt",u2=($,Z)=>JSON.stringify([$,Z]),R2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function V4($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function U4($,Z){let G=$.getReader();return new ReadableStream({async pull(J){let Q;try{Q=await G.read()}catch(Y){Z({reason:"failed",message:Y instanceof Error?Y.message:String(Y)}),J.error(Y);return}if(Q.done)Z(),J.close();else J.enqueue(Q.value)},async cancel(J){Z({reason:"cancelled",...J===void 0?{}:{message:String(J)}}),await G.cancel(J)}})}function M1($,Z){for(let[G,J]of Object.entries(Z)){let Q=G.toLowerCase();for(let Y of Object.keys($))if(Y.toLowerCase()===Q)delete $[Y];if(J!==null)$[G]=J}}function N4($,Z){for(let[G,J]of Object.entries(Z))if(J===null)$.delete(G);else $.set(G,J)}async function c1($,Z,G={}){let{providerID:J}=Z,Q=G.gateOnPlaceholder,Y=(z)=>Q===void 0||Q.credential(z)===y2(J),K=G.logger,N=Math.max(1,G.maxRecords??s2),V=G.hostRetryLimit??10,P=[...G.hostCredentials??[y2(J)],...Q?[y2(J)]:[]].filter((z)=>z!==""),U=new Map,_=new WeakMap,A=new Map,q=0,v=new Set,$2=new Map,S=new Map,k=(z)=>{let X=S.get(z);return X?.ownedSeen===!0&&X.foreignSeen},Q2=(z,X)=>{$2.set(z,X);let W=S.get(z)??{ownedSeen:!1,foreignSeen:!1};if(X)W.ownedSeen=!0;else W.foreignSeen=!0;S.set(z,W)},X2=(z,X)=>{let W=Q?.refuseMisplaced,F=W?[...X].filter(([,C])=>C.includes(y2(J))):[],B=Y(X)&&(!W||F.length>0);if(W){if(F.length>0&&(F.length!==1||!B))throw Q2(z.sessionID,!1),new P2({kind:"placement-refused",providerID:J,sessionID:z.sessionID,requestKind:z.kind,message:W(F[0]?.[0]??"")})}return Q2(z.sessionID,B),B},I=!1,p=!1,f2=new Map,M2=0,t=!1,R=new Map,h=(z,X)=>{try{K?.warn(z,X)}catch{}},d=(z)=>z instanceof Error?z.message:String(z),l=(z)=>z.excluded.clear(),E2=(z)=>z.excluded.size===0?{}:{excluded:[...z.excluded]},S2=(z,X,W)=>{if(!G.enforceRequestExclusion||z===void 0||!W.excluded.has(z))return!1;return h("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:X.sessionID,kind:X.kind,phase:X.phase,accountId:z}),!0},D2=new Map,U2=(z,X)=>{let W=(D2.get(z)??Promise.resolve()).then(X),F=W.then(()=>{},()=>{});return D2.set(z,F),F.then(()=>{if(D2.get(z)===F)D2.delete(z)}),W},z1=(z,X)=>{let W=D2.get(z);return W?W.then(()=>z1(z,X)):X()},B2=async(z)=>{try{await Z.dropChoice?.({...z.input,accountId:z.accountId})}catch(X){h("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:z.input.sessionID,error:d(X)})}},z2=async(z)=>{try{await Z.dropSameAccountRetry?.({...z.input,accountId:z.accountId})}catch(X){h("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:z.input.sessionID,error:d(X)})}},g2=async(z)=>{if(z.next)await B2(z.next);if(z.sameAccount)await z2(z.sameAccount)},j=(z)=>{let X=A.get(z);if(A.delete(z),X)U2(X.sessionID,()=>g2(X))},H=async(z,X)=>{let W=f2.get(z);if(!W||W.size===0)return;await Promise.all([...W].map(async(F)=>{try{await F(X)}catch(B){h("opencode2 auth listener threw; the request is unaffected",{event:z,error:d(B)})}}))},L=async(z)=>{let X=new Set([...U.values()].filter((F)=>F.scope.sessionID===z.sessionID).map((F)=>F.transport).filter((F)=>F!==void 0)),W=z.handle?.transport??(X.size===1?[...X][0]:"unknown");try{K?.info?.("opencode2 auth retry decision",{sessionID:z.sessionID,transport:W,attempt:z.attempt,reason:z.reason==="host-decides"&&k(z.sessionID)?"mixed-session":z.reason,retry:z.decision.retry})}catch{}await H("retry",z)},M=async(z,X)=>{try{await Z.onAttemptEnd?.(z,X)}catch(W){h("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:z.attemptId,error:d(W)})}},b=(z,X)=>{if(z.ended||!z.attempt)return;let W={...z.status===void 0?{}:{status:z.status},outputStarted:z.outputStarted,...z.limit?{limit:z.limit.signal}:{},...X?{error:X}:{}};if(X)z.endError=X;if(X?.reason==="cancelled"||!X&&!z.limit&&(z.status===void 0||z.status<400))l(z.request);z.ended=M(z.attempt,W)},x=(z,X)=>b(z,{reason:"abandoned",message:X}),O=(z)=>[...U.values()].filter((X)=>X.key===z),y=(z)=>O(z).at(-1),f=(z)=>{if(U.delete(z.id),A.get(z.key)?.attemptId===z.id||!O(z.key).length)j(z.key)},u=(z)=>{U.set(z.id,z);while(U.size>N){let X=U.values().next().value;if(X===void 0)break;x(X,"dropped to keep the record bound"),f(X)}},w=(z)=>z.accountId===void 0?void 0:{...z.scope,accountId:z.accountId},c=(z,X)=>new P2({kind:"no-account",providerID:J,sessionID:z.sessionID,requestKind:z.kind,...X===void 0?{}:{message:X}}),G2=(z)=>{R.get(z)?.clear(),R.delete(z)},T=async(z,X)=>{let W=()=>c(z,`${J} ${z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(t)throw W();let F=R.get(z.sessionID);if(!F)F=new Set,R.set(z.sessionID,F);let B={};F.add(B);let C=()=>{if(!F.has(B))throw W()};try{return await X(C)}finally{if(F.delete(B),F.size===0&&R.get(z.sessionID)===F)R.delete(z.sessionID)}},g=(z,X)=>{for(let[W,F]of X)if(P.some((B)=>F.includes(B)))throw new P2({kind:"host-credential-on-wire",providerID:J,sessionID:z.sessionID,requestKind:z.kind,message:`${J} ${z.kind} request still carries the host's placeholder credential in ${W}; the adapter's account headers must replace it`})},Z2=(z)=>{for(let X of O(z))if(X.ended||!X.attempt)f(X);else if(X.transport==="ws"||X.judged)x(X,"a newer attempt of its session and kind began"),f(X)},N2=async(z,X,W,F)=>{let B=u2(z.sessionID,z.kind),{input:C,accountId:E,sameAccountRetry:D,request:o}=await z1(z.sessionID,async()=>{W();let j2=A.get(B);A.delete(B);let j1=O(B);if(j2&&j1.some((e)=>e.id!==j2.attemptId&&e.attempt&&!e.ended))h("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:z.sessionID,kind:z.kind});if(!j2){let e=new Set(j1.filter((_2)=>_2.attempt&&!_2.ended).map((_2)=>_2.request));for(let _2 of j1)if(!e.has(_2.request))l(_2.request)}let K2=j2?.request??{excluded:new Set},J2=j2?.accountId??y(B)?.accountId;Z2(B);let r=j2?.next,Y2=j2?.sameAccount,i=Y2!==void 0&&Y2.input.modelID===z.modelID&&Y2.input.agent===z.agent,C2=r!==void 0&&r.input.modelID===z.modelID&&r.input.agent===z.agent,w2=j2?.wake,a={...z,phase:"request",...E2(K2),...J2===void 0?{}:{previousAccountId:J2},...j2?.rerouteFrom?{rerouteFrom:j2.rerouteFrom}:{},...w2===void 0?{}:{wake:w2,hostAttempt:r?.input.hostAttempt}};if(r&&(!C2||w2!==void 0))await U2(z.sessionID,()=>B2(r)),W();if(Y2&&!i)await U2(z.sessionID,()=>z2(Y2)),W();if(Y2?.continuation&&(!i||k(z.sessionID))){if(i)await U2(z.sessionID,()=>z2(Y2));throw c(z)}let l2=i?Y2.accountId:C2&&w2===void 0?r.accountId:await Z.chooseAccount(a),h2=typeof l2==="string"?l2:void 0;if(S2(h2,a,K2)){let e=h2;if(i&&Y2)await U2(z.sessionID,()=>z2(Y2));else if(e!==void 0)await U2(z.sessionID,()=>B2(C2&&r?r:{accountId:e,input:a}));h2=void 0,W()}return{input:a,accountId:h2,sameAccountRetry:i,request:K2}});W();let x2={},A2;if(E!==void 0){let j2=await Z.accountHeaders({...z,accountId:E});if(W(),V4(j2))x2=j2.headers,A2=j2.attempt;else x2=j2}let X1=`attempt-${++M2}`,b2={id:X1,key:B,scope:z,request:o,accountId:E,headers:x2,attempt:E===void 0?void 0:{...z,accountId:E,attemptId:X1,transport:F,data:A2},...F===void 0?{}:{transport:F},outputStarted:!1,sameAccountRetry:D};if(u(b2),b2.attempt)H("select",{...z,accountId:b2.attempt.accountId,hook:X,...C.previousAccountId===void 0?{}:{previousAccountId:C.previousAccountId},...C.rerouteFrom===void 0?{}:{rerouteFrom:C.rerouteFrom},handle:b2.attempt});return b2},n=async(z,X,W,F,B)=>{let C=u2(z.sessionID,z.kind),E=F===void 0?void 0:U.get(F);if(E?.key!==C)E=void 0;if(!E){if(E=y(C),O(C).filter((o)=>o.transport===void 0&&!o.ended).length>1&&!p)p=!0,h("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:z.sessionID,kind:z.kind})}if(!E||E.transport!==void 0||E.ended)E=await N2(z,X,B,W);else if(E.transport=W,E.attempt)E.attempt.transport=W;if(W==="ws"){for(let D of O(C))if(D!==E&&D.transport==="ws")x(D,"a newer attempt of its session and kind went out over WebSocket")}return E},s=async(z,X)=>{try{return await X()}catch(W){throw b(z,{reason:"failed",message:d(W)}),W}},T2=(z,X)=>{let W=O(u2(z,X)).filter((F)=>F.transport==="ws").at(-1);return W?.attempt!==void 0&&!W.ended?W:void 0},k2=(z,X,W)=>{let F=w(z);if(!F||!z.attempt||z.limit)return;z.limit={signal:X,delivered:H("limit",{...F,via:W,limit:X,outputStarted:z.outputStarted,handle:z.attempt})}},G1=(z,X,W,F)=>{let B=w(z);if(!B||!z.attempt)return;H("quota",{...B,transport:X,...F===void 0?{}:{status:F},quota:W,handle:z.attempt})},H2=(z,X,W,F)=>{let B=z.attempt;if(!B)return;let C=Z.inspectEvent?.(F===void 0?{transport:X,data:W,attempt:B}:{transport:X,data:W,event:F,attempt:B});if(!C)return;if(C.quota!==void 0)G1(z,X,C.quota);if(C.outputStarted)z.outputStarted=!0;if(C.hostRetry==="veto")z.hostRetry="veto";if(C.limit)k2(z,C.limit,X);if(C.error!==void 0)b(z,{reason:"failed",message:C.error});else if(C.done)b(z)},m2=(z,X)=>{let W=z.attempt;if(!W||X.accountId===z.accountId)return;if(W.reboundFrom??=W.accountId,W.accountId=X.accountId,"data"in X)W.data=X.data;z.accountId=X.accountId},a2=(z)=>!z.attempt||z.endError!==void 0||z.status!==void 0&&z.status>=400,O2=(z)=>{let X=[...U.values()].filter((D)=>D.scope.sessionID===z),W=X.filter((D)=>D.limit&&!D.rerouted).at(-1);if(W)return W;let F=X.filter((D)=>D.scope.kind==="primary"),B=F.length>0?F:X;if(B.length<=1)return B[0];let C=B.filter((D)=>!D.judged&&a2(D)).at(-1);if(C)return C;let E=B.filter((D)=>D.attempt&&!D.ended);if(E.length>1)return"ambiguous";return E[0]??B.at(-1)},F2={providerID:J},W2=[];W2.push(await $.session.hook("model.request",(z)=>{if(Q)return;return T(R2(z),async(X)=>{let W=await N2(R2(z),"model.request",X);if(X(),W.accountId===void 0)throw c(W.scope);M1(z.headers,{...W.headers,[o2]:W.id})})},F2)),W2.push(await $.session.hook("http.request",(z)=>{if(Q){if(!X2(R2(z),z.request.headers))return}return T(R2(z),async(X)=>{let W=z.request.headers.get(o2)??void 0,F=Q?await N2(R2(z),"http.request",X,"http"):await n(R2(z),"http.request","http",W,X);X();let B=w(F),C=F.attempt;if(!B||!C)throw c(F.scope);await s(F,async()=>{let E=z.request;if(Z.rewriteRequest){if(W!==void 0){let x2=new Headers(E.headers);x2.delete(o2),E=new Request(E,{headers:x2})}E=await Z.rewriteRequest({...B,request:E,attempt:C})??E,X()}let D=new Headers(E.headers);D.delete(o2),N4(D,F.headers),g(F.scope,D.entries());let o=new Request(E,{headers:D});_.set(o,F),z.request=o})})},F2)),W2.push(await $.session.hook("http.response",async(z)=>{let X=_.get(z.request);if(!X){if(Q)return;if(!I)I=!0,h("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:z.sessionID,kind:z.kind});return}let W=z.response;if(Z.answeredBy&&X.attempt){let D=X.attempt,o=await s(X,async()=>Z.answeredBy?.({request:z.request,response:W,attempt:D}));if(o)m2(X,o)}let F=w(X),B=X.attempt;if(!F||!B)return;X.status=W.status;let C=Z.quotaFromHeaders?.(W.headers,W.status,B);if(C!==void 0)G1(X,"http",C,W.status);if(!W.ok&&Z.limitFromResponse){let D=await Z.limitFromResponse({status:W.status,headers:W.headers,body:()=>W.clone().text(),attempt:B});if(D)k2(X,D,"http")}if(!W.ok||!W.body)b(X);let E=W;if(W.body&&(Z.inspectEvent||Z.onAttemptEnd)){let D=W.body;if(Z.inspectEvent)D=D.pipeThrough(p1((o)=>H2(X,"http",o.data,o.event),(o)=>h("opencode2 auth event inspection threw",{error:d(o)})));E=new Response(U4(D,(o)=>{if(o?.reason==="failed")X.readFailed=!0;b(X,o)}),{status:W.status,statusText:W.statusText,headers:W.headers})}if(Z.rewriteResponse)E=await Z.rewriteResponse({...F,request:z.request,response:E,attempt:B})??E;if(Z.responseRetry){if(await Z.responseRetry({...F,request:z.request,response:E,attempt:B})==="veto")X.hostRetry="veto"}if(E!==W)z.response=E},F2)),W2.push(await $.session.hook("experimental.ws.handshake",(z)=>{if(Q){let X=u2(z.sessionID,z.kind);if(v.delete(X),!X2(R2(z),new Headers(z.headers)))return}return T(R2(z),async(X)=>{let W;for(let E of Object.keys(z.headers)){if(E.toLowerCase()!==o2)continue;W??=z.headers[E],delete z.headers[E]}let F=Q?await N2(R2(z),"experimental.ws.handshake",X,"ws"):await n(R2(z),"experimental.ws.handshake","ws",W,X);X();let B=w(F),C=F.attempt;if(!B||!C)throw c(F.scope);await s(F,async()=>{if(!Q?.refuseMisplaced)M1(z.headers,F.headers);let E=Z.rewriteHandshakeURL?.({...B,url:z.url,attempt:C});if(E!==void 0)z.url=E;if(Q?.refuseMisplaced)M1(z.headers,F.headers);if(g(F.scope,Object.entries(z.headers)),Q)v.add(F.key)})})},F2));let v2=Z.rewriteWebSocketFrame?.bind(Z);if(v2)W2.push(await $.session.hook("experimental.ws.send",async(z)=>{let X=R2(z);if(Q&&!v.has(u2(X.sessionID,X.kind)))return;let W=T2(X.sessionID,X.kind),F=await v2({...X,attempt:W?.attempt,frame:z.frame});if(F!==void 0)z.frame=F},F2));W2.push(await $.session.hook("experimental.ws.receive",(z)=>{if(Q&&!v.has(u2(z.sessionID,z.kind)))return;let X=T2(z.sessionID,z.kind);if(!X)return;try{H2(X,"ws",z.frame)}catch(W){h("opencode2 auth frame inspection threw",{error:d(W)})}},F2)),W2.push(await $.session.hook("retry",async(z)=>{if(Q&&$2.get(z.sessionID)!==!0)return;let X=z.decision,W=()=>L({sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:X,decision:X});if(k(z.sessionID)&&!Z.retrySameAccount){await W();return}let F=O2(z.sessionID);if(!F)return;if(F==="ambiguous"){await L({sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:X,decision:X});return}let B=F,C=()=>B.hostRetry==="veto";await T(B.scope,async(E)=>{let D=E,o=Z.retrySameAccount?.bind(Z),x2=B.attempt,A2=B.outputStarted;if(B.transport==="ws"&&A2&&!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,b(B,{reason:"failed",message:z.error.message});if(A2&&B.readFailed&&o&&x2&&!k(z.sessionID)){if(!B.limit){let K2=Z.limitFromError?.(z.error,x2);if(K2)k2(B,K2,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;D()}let X1=()=>B.readFailed===!0&&z.error.type==="provider.transport"&&X.retry&&V-z.attempt>=1&&!B.limit&&!(B.status!==void 0&&B.status>=400)&&!(z.error.status!==void 0&&z.error.status>=400)&&!x2?.reboundFrom&&!C()&&!k(z.sessionID);if(o&&x2&&(!A2||X1())&&(!C()||k(z.sessionID))&&!B.sameAccountRetry){if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;let K2=await U2(B.scope.sessionID,async()=>{D();let J2=x2.accountId,r=()=>U.has(B.id)&&B.accountId===J2&&O2(z.sessionID)===B&&B.outputStarted===A2&&(!A2||X1())&&(!C()||k(z.sessionID))&&(!Q||$2.get(z.sessionID)===!0);if(!r()||B.sameAccountRetry)return!1;B.sameAccountRetry=!0;let Y2={...B.scope,accountId:J2,error:z.error,attempt:z.attempt,...B.limit?{limit:B.limit.signal}:{},...A2?{continuation:"interrupted-read"}:{}},i;try{i=await o(Y2)}catch(a){h("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:z.sessionID,error:d(a)})}if(!i)return D(),!1;let C2={accountId:i.accountId,input:Y2,...A2?{continuation:!0}:{}};try{D()}catch(a){throw await z2(C2),a}if(!r()||i.accountId!==J2)return await z2(C2),!1;let w2=A.get(B.key);if(A.delete(B.key),w2)await g2(w2);try{D()}catch(a){throw await z2(C2),a}if(!r())return await z2(C2),!1;return A.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++q,accountId:J2,sameAccount:C2}),B.judged=!0,z.decision=A2?X:{retry:!0,delay:0},!0});if(D(),K2){await L({sessionID:z.sessionID,accountId:B.accountId,kind:B.scope.kind,attempt:z.attempt,reason:A2?"continue-same-account":"same-account",hostDecision:X,decision:z.decision,handle:B.attempt});return}}if(k(z.sessionID)){await W();return}B.judged=!0;let b2=B.attempt;if(b2&&!B.outputStarted){if(!B.limit){let K2=Z.limitFromError?.(z.error,b2);if(K2)k2(B,K2,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered}D();let{decision:j2,reason:j1}=await U2(B.scope.sessionID,async()=>{if(D(),k(z.sessionID))return{decision:X,reason:"host-decides"};let K2=A.get(B.key);if(A.delete(B.key),K2)await g2(K2);if(D(),k(z.sessionID))return{decision:X,reason:"host-decides"};let J2=X,r,Y2,i,C2;if(B.accountId===void 0||!b2)J2={retry:!1},r="no-account";else if(B.outputStarted)J2={retry:!1},r="output-started";else if(C())J2={retry:!1},r="adapter-veto";else if(B.limit){let w2={accountId:B.accountId,limit:B.limit.signal},a,l2={...B.scope,phase:"retry",...E2(B.request),hostAttempt:z.attempt,previousAccountId:B.accountId,rerouteFrom:w2};try{a=await Z.chooseAccount(l2)}catch(l1){h("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:B.scope.sessionID,error:d(l1)})}let h2=typeof a==="string"?a:typeof a==="object"&&("hold"in a)?B.accountId:void 0;if(S2(h2,l2,B.request)){if(h2!==void 0)await B2({accountId:h2,input:l2});a=void 0}let e=typeof a==="object"&&"hold"in a?a.hold:void 0,_2=typeof a==="object"&&"waitThenReselect"in a?a.waitThenReselect:void 0,B4=typeof a==="object"&&"hostRetry"in a?a.hostRetry:void 0,L1=typeof a==="string"?a:e?B.accountId:void 0;if(L1!==void 0)i={accountId:L1,input:l2};try{D()}catch(l1){if(i)await B2(i);throw l1}if(k(z.sessionID)){if(i)await B2(i);return{decision:X,reason:"host-decides"}}if(C()||B4==="veto"){if(i)await B2(i);if(i=void 0,D(),k(z.sessionID))return{decision:X,reason:"host-decides"};B.hostRetry="veto",J2={retry:!1},r="adapter-veto"}else if(!(V-z.attempt>=1)){if(i)await B2(i);i=void 0,r="host-decides-last-account"}else if(_2&&Number.isFinite(_2.delayMs)&&_2.delayMs>=0&&_2.delayMs<=p2)J2={retry:!0,delay:Math.ceil(_2.delayMs)},r="wait-then-reselect";else if(e&&Number.isFinite(e.delayMs)&&e.delayMs>=0&&e.delayMs<=p2){if(J2={retry:!0,delay:Math.ceil(e.delayMs)},e.target!==void 0)C2={target:e.target,...e.checkpoint===void 0?{}:{checkpoint:e.checkpoint},...e.kind===void 0?{}:{kind:e.kind}};r="hold"}else if(!e&&L1!==void 0&&L1!==B.accountId)B.rerouted=!0,B.request.excluded.add(B.accountId),Y2=w2,J2={retry:!0,delay:0},r="reroute";else{if(e&&i)await B2(i),i=void 0;r="host-decides-last-account"}}else r="host-decides";if(z.decision=J2,J2.retry&&B.accountId!==void 0&&U.has(B.id))A.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++q,accountId:B.accountId,...Y2===void 0?{}:{rerouteFrom:Y2},...i===void 0?{}:{next:i},...C2===void 0?{}:{wake:C2}});else if(i)await B2(i);if(!J2.retry)l(B.request);return{decision:J2,reason:r}});D(),await L({sessionID:z.sessionID,...B.accountId===void 0?{}:{accountId:B.accountId},kind:B.scope.kind,attempt:z.attempt,reason:j1,hostDecision:X,decision:j2,...b2===void 0?{}:{handle:b2}})})},F2));let V2=(z)=>{if(G2(z),$2.delete(z),!S.get(z)?.foreignSeen)S.delete(z);for(let X of v)if(JSON.parse(X)[0]===z)v.delete(X);for(let X of[...U.values()]){if(X.scope.sessionID!==z)continue;x(X,"its session was forgotten"),l(X.request),U.delete(X.id)}for(let[X,W]of A)if(W.sessionID===z)j(X)},m=new AbortController,J1=$.event;if(J1)(async()=>{try{for await(let z of J1.subscribe({signal:m.signal}))if(z.type==="session.deleted")V2(z.data.sessionID);else if(z.type==="session.status"&&z.data.status.type==="idle"){let X=z.data.sessionID,W=++q;U2(X,async()=>{for(let[F,B]of A)if(B.sessionID===X&&B.order<W)A.delete(F),l(B.request),await g2(B)})}}catch(z){if(!m.signal.aborted)h("opencode2 auth stopped listening for session deletion",{error:d(z)})}})();return{on(z,X){let W=f2.get(z);if(!W)W=new Set,f2.set(z,W);let F=X;return W.add(F),()=>{W.delete(F)}},accountFor(z,X){return y(u2(z,X))?.accountId},forgetSession:V2,get size(){return U.size},async dispose(){if(t)return;t=!0;for(let z of R.keys())G2(z);m.abort();for(let z of U.values())x(z,"the installation was disposed");U.clear();for(let z of A.keys())j(z);v.clear(),$2.clear(),S.clear(),f2.clear(),await Promise.all(D2.values()),await Promise.all(W2.map(async(z)=>{try{await z.dispose()}catch(X){h("opencode2 auth hook did not dispose cleanly",{error:d(X)})}}))}}}import{randomUUID as l$}from"node:crypto";import{createHash as H4}from"node:crypto";var F4=1024,K4=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),A$=($)=>q$($,"user"),P4=($)=>K4($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function L4($){return H4("sha256").update(JSON.stringify($)).digest("hex")}class r2{runtime;maxSessions;#$=new Map;constructor($,Z=F4){this.runtime=$;this.maxSessions=Z}advance($,Z,G=this.runtime){let J=this.#$.get($),Q=Array.isArray(Z.input)?Z.input:[],Y=Q.filter(A$),K=Q.findLastIndex(A$),N=K<0?void 0:L4(Q[K]),V=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,P,U,_;if(V)P=Y.length>0,U=N??J?.fingerprint,_=J?.userCount===void 0?void 0:J.userCount+Y.length;else{U=N,_=Y.length;let q=K>=0&&K>Q.findLastIndex(P4),v=J!==void 0&&!J.completed&&J.fingerprint===U&&J.userCount===_;P=q&&!v}let A=P||!J?{turnID:(G?.uuid??c2)(),turnStartedAt:(G?.now??Date.now)()}:{turnID:J.turnID,turnStartedAt:J.turnStartedAt};return this.#Z($,{...A,completed:!1,fingerprint:U,userCount:_}),A}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 G=this.#$.keys().next().value;if(G===void 0)break;this.#$.delete(G)}}}function d1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var S$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function M4(){let $=globalThis;return $[S$]??=crypto.randomUUID(),$[S$]}class Q1{runtime;store;sessions;frameTurns;installationID;constructor($,Z,G){this.runtime=$;this.store=G;this.installationID=Z??M4(),this.sessions=G?.sessions??new Map,this.frameTurns=G?.frameTurns??new r2}get($){let Z=this.runtime?.uuid??c2;if(this.store)return this.store.get($,Z);let G=this.sessions.get($);if(!G){let J=Z();G={threadID:J,turnID:Z(),windowID:`${J}:0`},this.sessions.set($,G)}return G}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(T1(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var i1={version:b$,"user-agent":R$,originator:"codex_exec"};var T4=1024,C4=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,_1=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),w$=($)=>_1($)&&($.type==="message"||("role"in $))&&$.role==="user",y$=($)=>_1($)&&$.type==="configuration_update";class n1{http;#$=new Map;constructor($=new Q1){this.http=$}apply($,Z,G){if(Z.kind!=="primary")return!1;let J=typeof $.model==="string"?$.model:"";if(!D$.has(J))return!1;if(C4.test(J))return!1;let Q=_1($.reasoning)?$.reasoning:void 0,Y=typeof Q?.effort==="string"?Q.effort:void 0;if(!Y)return!1;let K=this.#$.get(Z.sessionID);if(K===void 0)return this.#Z(Z.sessionID,Y),!1;if(Y===K)return!1;let N=Array.isArray($.input)?$.input:void 0;if(!N||N.length===0)return!1;let V=N.findLastIndex(w$);if(V<0){if(G==="http")return!1;return $.reasoning={...Q,effort:K},!0}if($.reasoning={...Q,effort:K},!y$(N[V-1]))N.splice(V,0,{type:"configuration_update",reasoning:{effort:Y}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>T4){let G=this.#$.keys().next().value;if(G===void 0)break;this.#$.delete(G)}}}function T1($){try{let Z=JSON.parse($);return _1(Z)?Z:void 0}catch{return}}async function I$($,Z,G,J,Q=G.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Y=await $.clone().text(),K=T1(Y);if(K)delete K.max_output_tokens;let N=new Headers($.headers),V=C1({rewriteLite:k$,init:{body:K?JSON.stringify(K):$.body===null?void 0:Y},headers:N,metadata:Q.get(Z.sessionID),installationID:Q.installationID,runtime:Q.runtime,websocket:!1,responsesLite:J,applyEffort:(P)=>{G.apply(P,Z,"http")}});return new Request($,{headers:N,body:V.init?.body})}function f$($,Z,G,J){let Q=J.sessions.get($.sessionID),Y=J.frameTurns.get($.sessionID);if(!Q||!Y)return;let K=d1(Q,Y),N=new Headers({"content-type":"application/json"});for(let P of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let U=G.get(P);if(U!==null)N.set(P,U)}C1({init:{body:$.bodyText},headers:N,metadata:K,installationID:J.installationID,runtime:J.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let V=new URL(Z);if(V.protocol==="wss:")V.protocol="https:";if(V.protocol==="ws:")V.protocol="http:";return new Request(V,{method:"POST",headers:N,body:$.bodyText})}function _4($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let G=Z.findIndex((J,Q)=>JSON.stringify(J)!==JSON.stringify($[Q]));return G>=0&&y$(Z[G])&&w$(Z[G+1])&&JSON.stringify(Z.slice(G+1))===JSON.stringify($.slice(G))}function v$($,Z,G){let J=T1($);if(J?.type!=="response.create")return;let Q=G.http.advanceFrame(Z.sessionID,J),Y=G.http.get(Z.sessionID);delete J.max_output_tokens;let K=C1({rewriteLite:()=>{},init:{body:JSON.stringify(J)},headers:new Headers,metadata:d1(Y,Q),installationID:G.http.installationID,runtime:G.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(V)=>{G.apply(V,Z,"ws")}}),N=T1(String(K.init?.body));if(!N)return;if(!_4(J.input,N.input)){if("input"in J)N.input=J.input;else delete N.input;return JSON.stringify(N)}return String(K.init?.body)}function E4($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function a1($,Z){let G=new URL($);if(G.origin!=="https://api.openai.com"&&G.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(G.pathname))return $;let J=new URL(`${E4(Z)}/responses`);if(J.search=G.search,G.protocol==="ws:"||G.protocol==="wss:")J.protocol=J.protocol==="https:"?"wss:":"ws:";return J.href}import{resolve as h$}from"node:path";var O4=1024;class E1{accounts=new Map;limit;constructor($=O4){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let G=this.accounts.keys().next().value;if(G===void 0)break;this.accounts.delete(G)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var g$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),m$=globalThis,o1=m$[g$]??new Map;m$[g$]=o1;function s1($){let Z=JSON.stringify([h$($.configPath),h$($.statePath)]),G=o1.get(Z);if(!G)G=new E1,o1.set(Z,G);return G}var q2="openai",e2=10;var r1=1,x4="request refused: no account with a usable credential",L2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function A4($){let Z=L2($)?$.counters:void 0,G=L2(Z)?Z.resetCredits:void 0,J=L2(G)?G.value:void 0;return typeof J==="number"&&Number.isFinite(J)?J:void 0}function B1($){try{return JSON.parse($)}catch{return}}function W1($){let Z=A1($);return Z?q1(Z):void 0}var q4=new Set(["usage_limit_reached","rate_limit_exceeded"]);function V1($,Z,G,J){return{reason:$.window,windows:zZ($,Z,J,Z),observedAt:Z,...$.resetAt!==void 0?{resetAt:$.resetAt,resetSource:"provider"}:{},...G!==void 0?{status:G}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function HZ($,Z,G){if($.type!=="response.failed"){let Y=x1($,Z),K=typeof $.status==="number"?$.status:void 0;return Y?V1(Y,Z,K,G):void 0}if(!L2($.response))return;let J=$.response.failed;if(L2(J)&&typeof J.rate_limit_reached_type==="string")return V1({window:J.rate_limit_reached_type},Z,void 0,G);let Q=$.response.error;if(L2(Q)){let Y=typeof Q.code==="string"?Q.code:typeof Q.type==="string"?Q.type:void 0;if(Y&&q4.has(Y)){let K=typeof $.status==="number"?$.status:void 0,N=x1({error:{...Q,type:Y},status:K},Z);return V1(N??{window:Y},Z,K,G)}}return}function S4($,Z,G){if(!L2($))return;let J=typeof $.type==="string"?$.type:void 0;if(J==="codex.rate_limits")return{quota:{snapshot:n$($),complete:!0}};let Q=HZ($,Z,G);if(Q)return{limit:Q};if(J===void 0||J==="error")return;return UZ(J)?void 0:{outputStarted:!0}}function b4($){let Z=!1;for(let G of $.keys())if(G.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:d$($),complete:i$($)}}function R4($){let Z=$.get("retry-after");if(Z===null)return;let G=Z.trim()?Number(Z):NaN;return Number.isFinite(G)&&G>=0?G*1000:void 0}function FZ($){let Z=new WeakMap,G=new WeakSet,{source:J,pins:Q}=$,Y=$.now??Date.now,K=$.log,N=$.vault,V=$.limits,P=l$(),U=new WeakMap,_=new Map,A=(j,H)=>d2(H?N?.routes().find((L)=>L.id===j)?.quota:J.peek().rows.find((L)=>L.id===j)?.quota),q=new n1($.codex),v=new Map,$2=(j)=>{for(let[H,L]of v)if(L===j)v.delete(H)},S=new Map,k=new Map,Q2=(j)=>`${j.sessionID}\x00${j.kind}`,X2=new Map,I=new Map,p=(j)=>{let H=I.get(j);if(H)clearTimeout(H.timer);I.delete(j)},f2=(j,H,L)=>{let M=t({...j,accountId:H});p(M);let b={request:L,sessionID:j.sessionID,expiresAt:performance.now()+5000,timer:setTimeout(()=>{if(I.get(M)===b)p(M)},5000)};if(b.timer.unref(),I.set(M,b),I.size>s2){let x=I.keys().next().value;if(x!==void 0)p(x)}},M2=(j)=>{let H=I.get(j);return p(j),H&&performance.now()<H.expiresAt?H.request:void 0},t=(j)=>`${j.sessionID}\x00${j.kind}\x00${j.accountId}`,R=$.sessionAccounts??new E1,h=new $Z,d=(j,H,L)=>{let M=L?[]:NZ(J.peek().rows,j,H,N?.identities()??new Set),b=(N?.routes()??[]).filter((x)=>x.kind==="oauth"&&a$(d2(x.quota),j,H));return[...M.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota,row:x})),...b.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota}))]},l=(j,H,L)=>{let M=t$(j,H,L),b=j.map((f)=>({id:f.id,kind:"oauth",...t1(f.quota)?{quota:f.quota}:{}})),x=j.flatMap((f)=>f.row?[f.row]:[]),O=new Set(j.filter((f)=>!f.row).map((f)=>f.id)),y=V?.marks()??new Map;return{rows:b,now:L,rateLimitMarks:y,refreshBackoff:J.refreshBackoffFor(x),killswitch:M,requestPull:(f)=>O.has(f)?N?.requestReading(f):J.requestReading(f)}},E2=(j,H,L,M,b)=>{let x=J$({...j,rows:j.rows.filter((y)=>!L.has(y.id)),placement:G$(H),mainId:b});if(x.kind==="block"){K?.debug("pool admission refused the request",{reason:x.block.reason});return}let O=x.order.filter((y)=>!L.has(y));if(M!==void 0&&O.includes(M))return M;return O[0]},S2=(j,H)=>{let L=new Map(j.map((M)=>[M.id,M.quota]));return{requestBytes:r1,reservePercent:(M)=>$$(H,M===Z$?void 0:M),resetCredits:(M)=>A4(L.get(M))}},D2=(j,H,L,M,b,x,O,y)=>{let f=S2(H,L),u=X$(j),w=(Z2,N2)=>S1(O,{sessionId:M,requestBytes:r1,validPinnedAccountIds:j.rows.map((n)=>n.id).filter((n)=>!u.excluded.has(n)),excludeAccountIds:Z2,quotaCheckedAtByAccount:Object.fromEntries(j.rows.map((n)=>[n.id,u.projections.get(n.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(H.map((n)=>[n.id,n.identity])),select:(n)=>y?{accountId:y,source:"mode-fallback",quotaCheckedAt:u.projections.get(y)?.checkedAt}:ZZ(j,f,new Set(Z2),n),persist:N2},(n,s)=>O.set(n,s)),c=[...b],G2=w(c,x);if(!G2)return;let T=G2.accountId,g=j$(j,f,T);if(g.kind==="none")return;if(g.kind==="move"){let Z2=w([...c,T],x);if(Z2)return Z2.accountId;return g.reason==="killswitch"?void 0:T}if(g.kind==="detour")return w([...c,T],!1)?.accountId;return T},B2={providerID:q2,async retrySameAccount(j){if(j.continuation!=="interrupted-read")return;let H=k.get(Q2(j));if(k.delete(Q2(j)),!H||H.accountId!==j.accountId||H.modelID!==j.modelID||H.agent!==j.agent||j.limit)return;let L=N!==void 0&&await N.authority()!=="local",M=await $.storage();if(!L&&!(await J.current()).active)return;let b=Y(),x=d(M,b,L),O=x.find((w)=>w.id===j.accountId);if(!O)return;let y=l(x,M,b),f=M?.routing?.mode??"main-first";if(f==="sticky-balanced"){let w=j$(y,S2(x,M),j.accountId);if(w.kind!=="serve"&&w.kind!=="last-path")return}else{let w=J$({...y,placement:G$(f),...L?{mainId:z$(N?.routes()??[])}:{}});if(w.kind==="block"||!w.order.includes(j.accountId))return}let u=H.data;if(O.row){if(u?.kind!=="pool")return;let w=J.usableToken(O.row),c=O.row.identity??(w&&W1(w));if(!w||!u.identity||c!==u.identity)return}else{if(u?.kind!=="vault"||!N)return;let w=await N.authorize(j.accountId);if(!w||w.credentialId!==u.credentialId||w.accountIdentity!==u.accountIdentity||(w.accountIdentity??W1(w.accessToken))!==u.wireIdentity||O.identity!==void 0&&O.identity!==u.wireIdentity)return}return{accountId:j.accountId}},dropSameAccountRetry(){},dropChoice(j){let H=t(j);p(H),X2.get(H)?.drop(),X2.delete(H),S.delete(H)},chooseAccount:async(j)=>{let H,L=await N?.authority(),M=await $.storage(),b=L!==void 0&&L!=="local",x=()=>{throw new P2({kind:"no-account",providerID:q2,sessionID:j.sessionID,requestKind:j.kind,message:b1})};if(b){let X=performance.now()+R1;await $.awaitVaultRoster?.(),H=await V?.forRequest(X)}else{if(H=await V?.forRequest(),!(await J.current()).active){if(await $.slotPlaceholderWithoutMain?.())x();K?.warn("the account pool does not serve requests yet; refusing the request",{kind:j.kind});return}await J.prepareTokens(J.peek().rows,M)}let O=Y(),y=d(M,O,b),f=e$(l(y.filter((X)=>X.id!==j.rerouteFrom?.accountId),M,O));if(f)await f,O=Y(),y=d(M,O,b);let u=new Map(y.map((X)=>[X.id,X])),w=l(y,M,O),c=M?.routing?.maxSameAccountWait,G2=JSON.stringify([j.sessionID,j.kind]),T=[...v.values()].includes(j.sessionID),g=V?.activity.get(j.sessionID),Z2=g&&V?.accountKey(g.accountKey.accountId),N2=j.previousAccountId??j.rerouteFrom?.accountId,n=N2&&V?.accountKey(N2),s=j.rerouteFrom?.limit,T2=y.flatMap((X)=>{let W=V?.accountKey(X.id);if(!W)return[];let F=d2(X.quota),B=GZ(s&&X.id===N2?{account:W,kind:"rate-limit",reason:s.reason,scope:{kind:"pool"},windows:s.windows??[],observedAt:s.observedAt??O}:void 0,F,O),C=w.rateLimitMarks.get(X.id),E=w.refreshBackoff.get(X.id),D=[...C&&C>O?[{kind:"hard",until:C,cause:"rate-limit"}]:[],...E&&E>O?[{kind:"cooldown",until:E}]:[]],o=w.killswitch.get(X.id)!==!1&&!!(F?.primary||F?.secondary)&&!p$(u$(t1(X.quota)?X.quota:void 0),O)&&!(E&&E>O)&&(!X.row||!!J.usableToken(X.row));return[{account:W,admitted:o,placementEligible:o,ready:o&&!D.length&&!B.length,blockers:D,confirmedBlockers:B}]}),k2={phase:j.phase==="retry"?"after-limit":"pre-send",host:"opencode2",hostPhase:j.phase,now:O,clockNow:O,sessionId:j.sessionID,requestScope:{kind:"pool"},history:c$({requestId:j.sessionID,originalUrl:"https://api.openai.com/v1/responses",clockNow:O}),delivery:{owned:!0,attributable:!0,replayable:!0},candidates:T2,...j.phase==="retry"&&n?{attempted:n}:{},...j.phase==="retry"&&n&&s?{signal:{account:n,kind:"rate-limit",reason:s.reason,scope:{kind:"pool"},windows:s.windows??[],observedAt:s.observedAt??O},status:s.status}:{},remainingRetries:e2-(j.hostAttempt??e2)},G1=()=>{let X=V?.owner();return XZ({accounts:T2.flatMap((W)=>{let F=u.get(W.account.accountId);if(!F)return[];return[{account:W.account,reading:d2(F.quota),usable:!F.row||!!J.usableToken(F.row),confirmedBlockers:W.confirmedBlockers,floors:o$(M)?$$(M,F.id===Z$?void 0:F.id):void 0,marks:X?.snapshot()?.marks.filter((B)=>B.key.window==="account"&&B.key.scope.kind==="pool"&&t2(B.key.account,W.account)).flatMap((B)=>B.entries.map((C)=>({until:C.until,evidenceAt:C.evidenceAt})))}]}),now:O,effectiveModel:j.modelID,maxSameAccountWait:c,activity:g,currentAccountKey:Z2,provenance:X?.provenance})},H2=T2.find((X)=>n&&t2(X.account,n));if(j.phase==="retry"&&s&&H2){let X=Y$({candidate:H2,activity:g,maxSameAccountWait:c,now:O,maxDelayMs:p2}),W=Q$({...k2,hold:X},{mode:"sticky"});if(W?.action==="hold"&&!T)return v.set(G2,j.sessionID),{hold:{delayMs:W.delayMs,target:W.target,checkpoint:W.checkpoint,kind:"hold"}};let F=y.filter((C)=>C.id!==N2);if(H2.confirmedBlockers?.some((C)=>C.confirmed)&&F.length>0&&F.every((C)=>{let E=T2.find((D)=>D.account.accountId===C.id);return E&&(!E.admitted||(w.rateLimitMarks.get(C.id)??0)>O)})){if(T)return{hostRetry:"veto"};let C=B$(k2,G1());if(e1(c)===0)return{hostRetry:"veto"};let E="delayMs"in C?C.delayMs:("retryAfterMs"in C)?C.retryAfterMs:void 0;if((k2.remainingRetries??0)<1||E===void 0||E>p2)return{hostRetry:"leave"};if(C.action==="hold"&&t2(C.account,H2.account))return v.set(G2,j.sessionID),{hold:{delayMs:E,target:C.target,checkpoint:C.checkpoint,kind:"terminal"}};return v.set(G2,j.sessionID),{waitThenReselect:{delayMs:E}}}}let m2;if(j.phase==="request"&&j.wake?.checkpoint&&H2&&(j.hostAttempt??e2)<e2&&e1(c)!==0&&t2(H2.account,j.wake.checkpoint.accountKey)){let X=j.wake.checkpoint,W=new Map(X.blockers.map((E)=>[E.window,{...E,confirmed:!0,confirmedByReading:!1,observedAt:X.decidedAt,provenance:"provider"}]));for(let E of H2.confirmedBlockers??[])W.set(E.window,E);let F={...H2,confirmedBlockers:[...W.values()]},B=Y$({candidate:F,activity:g,maxSameAccountWait:c,now:O,maxDelayMs:p2});if(Q$({...k2,attempted:H2.account,candidates:T2.map((E)=>E===H2?F:E),hold:B,wake:{...j.wake,checkpoint:X}},{mode:"sticky"})?.action==="retain")m2=H2.account.accountId}let a2=new Set(j.rerouteFrom?[j.rerouteFrom.accountId]:[]),O2=M?.routing?.mode??"main-first",F2=j.kind==="primary",W2=new Set,v2,V2,m,J1=!1,z=(X)=>{let W=X$(w).projections.get(X)?.checkedAt,F=u.get(X)?.identity;return Q.reserve(j.sessionID,{accountId:X,inputBytes:r1,...W!==void 0?{quotaCheckedAt:W}:{},...F!==void 0?{wireIdentity:F}:{}})};try{for(;;){let X=new Set([...a2,...W2]);m=void 0,v2=void 0;let W=O2!=="sticky-balanced";if(m2&&!X.has(m2))m=m2,m2=void 0;else if(O2==="sticky-balanced"){let B=new Map(Q.placementSnapshot(j.sessionID)),C=B.get(j.sessionID);if(W=C===void 0,m=D2(w,y,M,j.sessionID,X,F2&&W2.size===0,B),m!==void 0&&B.get(j.sessionID)!==C)v2=B.get(j.sessionID)}if(m??=E2(w,O2,X,F2?void 0:R.activeAccount(j.sessionID),b?O2==="sticky-balanced"?null:z$(N?.routes()??[]):void 0),m===void 0||W2.has(m)){if(a2.size>0){let B=new Map(w.rateLimitMarks);for(let C of a2)B.delete(C);w={...w,rateLimitMarks:B},a2.clear();continue}if(w.rateLimitMarks.size>0){w={...w,rateLimitMarks:new Map};continue}m=void 0;break}if(F2&&O2==="sticky-balanced")V2=z(m);if(!J1){J1=!0;let B=j.wake?void 0:await BZ({vaultMode:b,fresh:W,sessionId:j.sessionID,request:{modelId:j.modelID,kind:j.kind,retry:j.phase==="retry"||j.rerouteFrom!==void 0},routes:N?.routes()??[],routing:w,wait:{activity:g,accountKey:Z2,maxSameAccountWait:c},eligibleIds:y.filter((C)=>!X.has(C.id)).map((C)=>C.id)});if(B&&B!==m){if(V2)Q.rollback(V2);if(V2=void 0,O2==="sticky-balanced"){let C=new Map(Q.placementSnapshot(j.sessionID));m=D2(w,y,M,j.sessionID,X,F2,C,B)??m,v2=C.get(j.sessionID)??v2}else m=B;if(F2&&O2==="sticky-balanced")V2=z(m)}}let F=u.get(m)?.row;if(F){if(J.usableToken(F)!==void 0)break;K?.debug("pool row holds no usable token; choosing again",{accountId:m})}else{if(!N)break;let B=await N.authorize(m);if(B){S.set(t({...j,accountId:m}),B);break}K?.debug("the vault refused to serve an account; choosing again",{accountId:m})}if(V2)Q.rollback(V2);V2=void 0,W2.add(m)}if(m===void 0&&!b&&y.length===0&&await $.slotPlaceholderWithoutMain?.())x();if(m===void 0&&b&&N&&(y.length===0||W2.size>0)){let X=W2.size>0?"vault-refused":r$(N);throw K?.warn("vault mode: no vault account can serve; refusing the request",{cause:X}),new P2({kind:"no-account",providerID:q2,sessionID:j.sessionID,requestKind:j.kind,message:s$(X,N.name)})}if(m!==void 0){if(H)f2(j,m,H);let X=m,W=V2,F=v2,B=()=>{if(W)Q.finish(W,F);if(F2)R.record(j.sessionID,X),$.onRoute?.(j.sessionID,X,O2)};if(j.phase==="retry")X2.set(t({...j,accountId:m}),{commit:B,drop:()=>{if(W)Q.rollback(W)}}),V2=void 0;else B();let C=K?.info;h.served(w,m,K&&C?{info:(E,D)=>C.call(K,E,D)}:void 0)}if(m===void 0&&j.phase==="request"&&T2.length>0&&T2.every((X)=>!X.admitted)&&T2.some((X)=>w.killswitch.get(X.account.accountId)===!1||X.confirmedBlockers?.length)){let X=B$(k2,G1()),W=jZ({decision:X,now:O,host:"opencode2",requestThrow:!0,maxSameAccountWait:c});if(W.kind==="http"){let F=JSON.parse(W.body);throw new P2({kind:"no-account",providerID:q2,sessionID:j.sessionID,requestKind:j.kind,message:F.error.message})}}return K?.debug("pool account chosen",{kind:j.kind,accountId:m,mode:O2,...j.rerouteFrom?{rerouteFrom:j.rerouteFrom.accountId}:{}}),m}finally{if(V2)Q.rollback(V2)}},accountHeaders:async(j)=>{let{accountId:H}=j;k.delete(Q2(j));let L=t(j),M=X2.get(L);X2.delete(L);let b=()=>{M?.commit()};try{let x=()=>new P2({kind:"no-account",providerID:q2,sessionID:j.sessionID,requestKind:j.kind,message:x4}),O=async(c)=>{if(!V)return;let G2=M2(L)??await V.forRequest();if(c.kind==="pool"){let s=J.peek().rows.find((T2)=>T2.id===H);if(!s||s.credentialEpoch!==c.credentialEpoch||J.usableToken(s)!==c.token)throw x()}let T=V.bindings().find((s)=>s.account.accountId===H),g=await G2?.beforeDispatch(T,()=>V.ownershipBindings(),H),Z2=V.accountKey(H);if(g&&g.status!=="ready"||T&&(!Z2||!t2(T.account,Z2)))throw x();let N2=V.owner(),n=T?{sessionId:j.sessionID,accountKey:T.account,dispatchedAt:Y(),ttlMs:YZ(JSON.stringify({model:j.modelID}))}:void 0;if(n){if(_.delete(n.sessionId),_.set(n.sessionId,n),_.size>s2){let s=_.keys().next().value;if(s!==void 0)_.delete(s)}}U.set(c,{owner:N2,probe:N2?.observe(T),dispatch:n,failed:!1,completed:!1})},y=N&&await N.authority()!=="local"?void 0:J.peek().rows.find((c)=>c.id===H);if(!y&&N){let c=t(j),G2=S.get(c)??await N.authorize(H);if(S.delete(c),!G2)throw K?.warn("the vault refused to serve an account; refusing the request",{accountId:H}),x();let T={kind:"vault",routeId:H,receipt:G2};return await O(T),b(),{headers:{...i1,"session-id":j.sessionID,authorization:`Bearer ${G2.accessToken}`,"chatgpt-account-id":G2.accountIdentity??W1(G2.accessToken)??null},attempt:T}}let f=y?J.usableToken(y):void 0;if(!y||!f)throw K?.warn("pool row holds no usable token; refusing the request",{accountId:H}),x();let u=y.identity??W1(f),w={kind:"pool",token:f,credentialEpoch:y.credentialEpoch,...u!==void 0?{identity:u}:{}};return await O(w),b(),{headers:{...i1,"session-id":j.sessionID,authorization:`Bearer ${f}`,"chatgpt-account-id":u??null},attempt:w}}finally{M?.drop()}},async rewriteRequest({request:j,sessionID:H,kind:L}){let M=$.codexEndpoint?a1(j.url,$.codexEndpoint()):j.url,b=M===j.url?j:new Request(M,j);return await I$(b,{sessionID:H,kind:L},q,$.responsesLite?.()??!1)??b},rewriteHandshakeURL:({url:j})=>$.codexEndpoint?a1(j,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:j,sessionID:H,kind:L})=>v$(j,{sessionID:H,kind:L},q),quotaFromHeaders:(j,H,L)=>{if(L.data?.kind==="vault")N?.reportUsage(L.data.routeId,{headers:j},L.data.receipt);if(L.data?.kind==="vault"&&i2()&&H>=200&&H<300)Z.set(L,{status:H,headers:j});return b4(j)},async limitFromResponse({status:j,headers:H,body:L,attempt:M}){if(j<400)return;let b=B1(await L().catch(()=>"")),x=Y(),O=x1({...L2(b)?b:{},status:j},x);if(M.data?.kind==="vault"&&i2())O1(M.sessionID,M.data.receipt,{status:j,headers:H,body:b,limit:O,quota:N?.routes().find((u)=>u.id===M.accountId)?.quota,now:Y()});if(!O)return;let y=V1(O,x,j,A(M.accountId,M.data?.kind==="vault"));if(y.retryAfterMs!==void 0)return y;let f=R4(H);return f===void 0?y:{...y,retryAfterMs:f,resetAt:x+f,resetSource:"retry-after"}},inspectEvent:({data:j,transport:H,attempt:L})=>{let M=B1(j),b=L.data&&U.get(L.data);if(b&&L2(M)&&(M.type==="response.failed"||M.type==="error"))b.failed=!0;if(b&&L2(M)&&M.type==="response.completed")b.completed=!0;if(L.data?.kind==="vault"&&j.includes("codex.rate_limits")){let O=B1(j);if(L2(O)&&O.type==="codex.rate_limits")N?.reportUsage(L.data.routeId,{frame:O},L.data.receipt)}if(L.data?.kind==="vault"&&i2()&&(VZ(j)||H==="ws"&&j.includes('"response.completed"'))){let O=B1(j);if(WZ(O))G.add(L);if(H==="ws"&&L2(O)&&O.type==="response.completed")O1(L.sessionID,L.data.receipt,{status:200,headers:new Headers,failed:G.has(L)})}let x=S4(M,Y(),A(L.accountId,L.data?.kind==="vault"));return H==="ws"&&L2(M)&&M.type==="response.completed"?{...x,done:!0}:x},limitFromError(j,H){let L=B1(j.message),M=Y(),b=A(H.accountId,H.data?.kind==="vault");return HZ({...L2(L)?L:{},...j.status!==void 0?{status:j.status}:{}},M,b)??(j.message.includes("usage_limit_reached")?V1({window:"usage_limit_reached"},M,j.status,b):void 0)},async onAttemptEnd(j,H){let L=j.data,M=L&&U.get(L);if(M){let x=!H.error&&!H.limit&&!M.failed&&(j.transport==="ws"?M.completed:H.status!==void 0&&H.status>=200&&H.status<300);if(x&&M.dispatch&&V){let O=_.get(M.dispatch.sessionId);QZ(V.activity,M.dispatch,O===M.dispatch?V.accountKey(j.accountId):void 0,j.transport==="ws"?{kind:"ws",event:"response.completed",aborted:!1}:{kind:"http",completed:!0,failed:!1,aborted:!1})}M.owner?.afterProbe(M.probe,x,Boolean(H.limit))}if(L&&H.outputStarted&&H.error?.reason==="failed"){if(k.set(Q2(j),{accountId:j.accountId,modelID:j.modelID,agent:j.agent,sessionID:j.sessionID,data:L.kind==="pool"?{kind:"pool",identity:L.identity}:{kind:"vault",credentialId:L.receipt.credentialId,accountIdentity:L.receipt.accountIdentity,wireIdentity:L.receipt.accountIdentity??W1(L.receipt.accessToken)}}),k.size>s2){let x=k.keys().next().value;if(x!==void 0)k.delete(x)}}let b=L?.kind==="vault"&&i2()?Z.get(j):void 0;if(Z.delete(j),L?.kind==="vault"&&b&&!H.error&&!H.limit)O1(j.sessionID,L.receipt,{...b,failed:G.has(j)});if(L?.kind!=="vault"||H.status!==401)return;K?.warn("a vault account answered 401; reporting it to the vault",{accountId:j.accountId}),await N?.reportFailure(L.receipt,401)}},z2=(j,H,L)=>{let M=L.data;if(M?.kind==="vault"){N?.recordSnapshot(j,H.snapshot,H.complete,M.receipt);return}if(M?.kind!=="pool")return;if(J.peek().rows.find((x)=>x.id===j)?.credentialEpoch!==M.credentialEpoch){K?.debug("quota reading dropped: the row holds another credential",{accountId:j});return}J.recordSnapshot(j,H.snapshot,M.token,H.complete)},g2=(j,H,L)=>{let M=Y(),b=L.data?.kind==="vault";if(V){let x=L.data&&U.get(L.data),O=x?.owner??V.owner();if(!O)return;if(!x?.probe||O.registry!==x.probe.registry){O.dropSignal();return}let y=H,{command:f,provenance:u}=JZ({binding:x.probe.binding,baseRevision:x.probe.baseRevision,producerId:P,operationId:l$(),parsed:{window:H.reason,resetAt:y.resetAt??(H.retryAfterMs!==void 0?M+H.retryAfterMs:void 0)},reading:A(j,b),now:M,observedAt:y.observedAt??M,evidenceAt:M,resetSource:y.resetSource});O.enqueue(f,u);return}};return{adapter:B2,beginTurn:$2,dispose:()=>v.clear(),attach(j){j.on("quota",(H)=>z2(H.accountId,H.quota,H.handle)),j.on("limit",(H)=>{g2(H.accountId,H.limit,H.handle),K?.debug("pool row refused the request",{accountId:H.accountId,via:H.via,reason:H.limit.reason,outputStarted:H.outputStarted})})},forgetSession(j){$2(j);for(let[H,L]of I)if(L.sessionID===j)p(H);_.delete(j),V?.forget(j);for(let[H,L]of k)if(L.sessionID===j)k.delete(H);Q.forget(j),R.forget(j),q.forget(j)},activeAccount:(j)=>R.activeAccount(j)}}import{resolve as CZ}from"node:path";import{Buffer as D4}from"node:buffer";import{resolve as KZ}from"node:path";function U1($){return D4.byteLength(JSON.stringify($))}function k4($){return $.reduce((Z,G)=>Z+U1(G),0)}function W$($,Z){return 2+$+Math.max(0,Z-1)}function w4($){let{head:Z,pending:G}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+W$(Z.inputBytes,Z.input.length)+1:0)+(G?20+W$(G.inputBytes,G.input.length)+10+W$(G.outputBytes,G.output.length)+(G.responseID===void 0?0:14+G.responseIDBytes)+1:0)}function PZ($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class LZ{enabled;caps=D1;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$){for(let Z of this.entries.keys())if(!n2(Z,$))this.forget(Z)}}send($,Z){if(!n2($,this.enabled)){this.forget($);return}let G=PZ(Z);if(G?.type!=="response.create")return;if(!Array.isArray(G.input)){this.forget($);return}let J=G.previous_response_id,Q=this.entries.get($),Y=Q?.head;if(J&&J!==Y?.responseID){this.forget($);return}let{type:K,previous_response_id:N,input:V,...P}=G;this.keep($,{fields:J&&Q?Q.fields:P,fieldsBytes:J&&Q?Q.fieldsBytes:U1(P),...J&&Y?{head:Y}:{},pending:{input:V,inputBytes:k4(V),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,G){if(!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed")||!n2($,this.enabled))return;let J=this.entries.get($);if(!J?.pending)return;let Q=PZ(Z);if(!Q)return;let Y=J.pending,K=Q.response;if(Q.type==="response.created"&&typeof K?.id==="string")Y.responseID=K.id,Y.responseIDBytes=U1(K.id),this.keep($,J);else if(Q.type==="response.output_item.done"&&Q.item){if(typeof Q.response_id==="string"&&Y.responseID!==void 0&&Q.response_id!==Y.responseID)return;Y.output.push(Q.item),Y.outputBytes+=U1(Q.item),this.keep($,J)}else if(Q.type==="response.completed"&&typeof K?.id==="string"){if(K.id===J.head?.responseID||Y.responseID!==void 0&&K.id!==Y.responseID)return;let N={responseID:K.id,responseIDBytes:Y.responseID===K.id?Y.responseIDBytes:U1(K.id),input:[...J.head?.input??[],...Y.input,...Y.output],inputBytes:(J.head?.inputBytes??0)+Y.inputBytes+Y.outputBytes},V={...J,head:N,pending:void 0};if(!this.keep($,V))return;G?.({sessionID:$,responseID:N.responseID,bodyText:this.body(J.fields,N)})}}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 G=w4(Z);if(this.forget($),G>this.caps.maxBytes)return!1;Z.bytes=G,this.entries.set($,Z),this.bytes+=G;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let J=this.entries.keys().next().value;if(J===void 0)break;this.forget(J)}return this.entries.has($)}}var MZ=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),TZ=globalThis,V$=TZ[MZ]??new Map;TZ[MZ]=V$;function k1($){let Z=JSON.stringify([KZ($.configPath),KZ($.statePath)]),G=V$.get(Z);if(!G)G=new LZ,V$.set(Z,G);return G}var y4=5000,I4=["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"],f4=["x-opencode-parent-session-id","x-parent-session-id"];function xZ($){let Z=_Z($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:EZ($?{...$,cachekeep:Z}:$)}}var AZ=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),qZ=globalThis,N1=qZ[AZ]??new Map;qZ[AZ]=N1;function v4($,Z){let G=[],J=()=>G.at(-1)?.location,Q=()=>{let V=J();if(!V)throw Error("no location holds keep-warm");return V},Y=(V,P)=>{N.remove(V),J()?.log?.debug(`cachekeep dropped target (${P})`,{sessionKey:V})},K=async(V)=>{if(V.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let P=V.accountId??"main",U=Q(),_=await U.source.accessFor(P,await U.storage());if(!_)throw Error(`pool row ${P} has no usable token`);return{token:_.token,identity:_.row.identity}},N=OZ({...D1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(V,P)=>Q().fetch(V,P),logger:{debug:(V,P)=>J()?.log?.debug(V,P),warn:(V,P)=>J()?.log?.warn(V,P)},getWindow:()=>J()?.settings().window,getSustain:()=>J()?.settings().sustain===!0,resolveLocal:K,activity:{store:{get size(){return J()?.limits?.activity.size??0},get:(V)=>J()?.limits?.activity.get(V),forgetSession:(V)=>J()?.limits?.activity.forgetSession(V),recordAccepted:(V)=>J()?.limits?.activity.recordAccepted(V)??!1},accountKey:({target:V})=>{let P=J(),U=V.meta.routingSessionId??V.sessionKey,_=V.accountId??"main";return P?.accounts.activeAccount(U)===_?P.limits?.accountKey(_):void 0}},vault:{owns:(V)=>J()?.vault.owns(V)===!0,authority:()=>Q().vault.authority(),reportUsage:(...V)=>J()?.vault.reportUsage(...V),send:async(V,P,U)=>{let _=Q(),A=await _.vault.authority();if(A!=="vault"&&A!=="host")return;return _.vault.send(V,P,U)}},activeAccount:(V)=>{if(V===void 0)throw Error("target has no session");let P=J(),U=P?.settings();if(!P||!U||!n2(V,U.enabled)){Y(V,"keep-warm is off");return}if(!U.subagents&&N.status().targets.some((A)=>A.sessionKey===V&&A.isSubagent)){Y(V,"subagent warming is off");return}let _=P.accounts.activeAccount(V);if(_===void 0){Y(V,"no account recorded for the session");return}return _},verifyCredential:({target:V,mode:P,identity:U})=>{if(V.meta.credentialMode!==P)throw Error(`a target captured in ${V.meta.credentialMode??"an unknown"} mode is not warmed with a ${P} credential`);if(U!==V.meta.chatgptAccountId)throw Y(V.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:N,settings:Z,holders:G,joinTimeoutMs:$.joinTimeoutMs??y4}}function h4($){try{let Z=JSON.parse($),G=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(G?.role!=="user")return!1;return(typeof G.content==="string"?G.content:Array.isArray(G.content)?G.content.map((Q)=>typeof Q?.text==="string"?Q.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function g4($){let Z={};for(let G of I4){let J=$.get(G);if(J)Z[G]=J}return Z}function SZ($,Z,G){let J=JSON.stringify([CZ($.configPath),CZ($.statePath)]),Q=N1.get(J);if(!Q)Q=v4(G,Z.settings()),N1.set(J,Q);let Y=Q,K=k1($);K.setEnabled(Y.settings.enabled);let N={location:{...Z,settings:()=>Y.settings}};Y.holders.push(N);let V=!1,P=async(U)=>{try{let _=N.location.settings();if(V||!n2(U.sessionID,_.enabled))return;if(U.kind!=="primary"){if(U.kind==="generate"&&h4(await U.request.clone().text())){if(V)return;Y.manager.remove(U.sessionID)}return}let A=U.attempt.data,q=A?.kind==="pool"?"local":A?.kind==="vault"?"vault":void 0;if(!q)return;let v=U.request.headers,$2=f4.some((Q2)=>v.has(Q2))||Z.parentOf!==void 0&&await Z.parentOf(U.sessionID)!==void 0;if($2&&!_.subagents)return;let S=await U.request.clone().text();if(V)return;let k=v.get("chatgpt-account-id")??void 0;Y.manager.track({sessionKey:U.sessionID,bodyText:S,accountId:U.attempt.accountId,isSubagent:$2,meta:{replayHeaders:g4(v),...k?{chatgptAccountId:k}:{},routingSessionId:U.sessionID,url:U.request.url,credentialMode:q}})}catch(_){Z.log?.warn("cachekeep capture failed",{error:_ instanceof Error?_.message:String(_)})}};return{manager:Y.manager,configure:(U)=>{Object.assign(Y.settings,U),K.setEnabled(Y.settings.enabled)},capture:P,forget:(U)=>Y.manager.remove(U),async release(){if(V)return;V=!0;let U=Y.holders.indexOf(N);if(U>=0)Y.holders.splice(U,1);if(Y.holders.length>0)return;if(N1.get(J)===Y)N1.delete(J);Y.manager.stop();let _;try{await Promise.race([Y.manager.tick().catch(()=>{}),new Promise((A)=>{_=setTimeout(A,Y.joinTimeoutMs),_.unref?.()})])}finally{clearTimeout(_)}}}}import{mkdirSync as m4}from"node:fs";import{dirname as l4,resolve as u4}from"node:path";function p4(){return bZ("opencode2")}var c4=2000;class yZ{path;options;sessions;frameTurns=new r2;#$=new Set;#Z=new Set;#G=new Set;#J=Promise.resolve();#X=!1;#z;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=kZ($,Z.uuid??c2)}get($,Z=c2){let G=this.sessions.get($);if(!G){let J=Z();G={threadID:J,turnID:Z(),windowID:`${J}:0`},this.sessions.set($,G),this.#Z.delete($),this.#G.delete($),this.#$.add($),this.#j()}return G}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#G.add($);this.#j()}#j(){if(this.#z)return;this.#z=setTimeout(()=>{this.#z=void 0,this.save()},this.options.saveDelayMs??c4),this.#z.unref?.()}save(){if(clearTimeout(this.#z),this.#z=void 0,!this.#X)this.#X=!0,this.#J=this.#J.then(()=>{return this.#X=!1,this.#Q()});return this.#J}settled(){return this.#z?this.save():this.#J}#Y(){if(this.#G.size===0)return;let $;try{$=U$(this.path)}catch{$=new Map}for(let Z of this.#G)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#G.clear()}async#Q(){if(this.#Y(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((J)=>{let Q=this.sessions.get(J);return Q?[[J,Q]]:[]}),Z=[...this.#Z],G=null;try{if(m4(l4(this.path),{recursive:!0}),G=await this.#B(),!G)return;let J;try{J=U$(this.path)}catch{J=new Map}await this.options.afterRead?.();let Q=!1;for(let Y of Z)if(J.delete(Y))Q=!0;for(let[Y,K]of $){if(J.get(Y)===K.threadID)continue;J.set(Y,K.threadID),Q=!0}if(Q)wZ(this.path,J)}catch{return}finally{await G?.release().catch(()=>{})}for(let[J,Q]of $)if(this.sessions.get(J)===Q)this.#$.delete(J);for(let J of Z)if(!this.sessions.has(J))this.#Z.delete(J)}#B(){return DZ(this.path,this.options.lockWaitMs??RZ)}}var IZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),fZ=globalThis,w1=fZ[IZ]??new Map;fZ[IZ]=w1;function d4($){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 vZ($=p4()){let Z=u4($),G=w1,J=w1.get(Z),Q=w1;if(J!==void 0&&!d4(J))G.compatible??=new Map,Q=G.compatible;let Y=Q.get(Z);if(!Y)Y=new yZ(Z),Q.set(Z,Y);let K=Y;return K.frameTurns??=new r2,Y}var N$=Symbol.for("cortexkit.openai-auth.v2.commands"),i4=I2("v2-command");function y1($){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 H$($){i4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function n4(){let $=globalThis;return $[N$]??={locations:new Map},$[N$].locations??=new Map,$[N$]}async function cZ($,Z){let G=n4(),J=$.location.directory,Q={menu:Z,session:$.session,closed:new AbortController},Y=await gZ(J),K=await hZ(uZ,Y.dir,()=>pZ({...Y,drain:lZ,apply:(_)=>{let A=G.locations.get(J);if(!y1(A))throw Error("The OpenAI menu location was closed");return A.menu.apply(_)}})),N=G.locations.get(J);if(G.locations.set(J,Q),y1(N))N.closed.abort(),await N.registration?.dispose();let V={name:"openai",description:"OpenAI account menu",async execute(_){let A=[...G.locations.values()].find(y1)?.session;if(!A)return H$("no live location");let q=await A.get({sessionID:_.sessionID}),v=G.locations.get(q.location.directory);if(!y1(v))return H$("location closed");let $2=await mZ(_.sessionID,v.closed.signal);if(!$2||G.locations.get(q.location.directory)!==v){if(!$2&&!v.closed.signal.aborted)F$({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},_.sessionID);return H$(v.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let S=await v.menu.open(_.sessionID);F$(S,_.sessionID)}};G.command??=V,G.command.execute=V.execute;let P=G.command;try{Q.registration=await $.command.transform((_)=>{_.add(P)})}catch(_){if(Q.closed.abort(),G.locations.get(J)===Q)G.locations.delete(J);throw await K.release(),_}let U=!1;return async()=>{if(U)return;if(U=!0,Q.closed.abort(),G.locations.get(J)===Q)G.locations.delete(J);await K.release(),await Q.registration?.dispose()}}var a4="openai-auth-pool-browser",o4="openai-auth-pool-headless",s4="openai-auth-vault",r4="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 H1($){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 tZ($){return{method:{id:s4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){let Z=await iZ($.paths,$.name);if(Z==="host"){let G=dZ(aZ);await Promise.resolve(G.close()).catch(()=>{return})}else if(Z!=="vault")throw Error(r4)}}}function eZ($){let Z=(G,J,Q)=>({method:{id:G,type:"oauth",label:J},async authorize(){if($.vault)await H1($.vault);let Y=await $.beginLogin({version:$.version,headless:Q});return{url:Y.url,instructions:Y.instructions,mode:"auto",callback:Y.completion}}});return[Z(a4,"ChatGPT (openai-auth pool, browser)",!1),Z(o4,"ChatGPT (openai-auth pool, headless)",!0)]}function K$($){let Z=(G)=>typeof G==="string"?G:"";return Y1({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===sZ||nZ($)}function t4($){if($.accountId)return $.accountId;let Z=$.access?A1($.access):void 0;return Z?q1(Z):void 0}async function $0($,Z,G,J={}){if(J.vault)await H1(J.vault);if(K$(G))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Q=oZ($,{rowLocks:(q)=>rZ(Z,q)}),Y=await Q.read();if(Y.status!=="ready")throw Error(`the account pool cannot be read (${Y.status}); the login was not stored`);let K={type:"oauth",refresh:G.refresh,...G.access!==void 0?{access:G.access}:{},...G.expires!==void 0?{expires:G.expires}:{}},N=t4(G);if(J.vault)await H1(J.vault);let V=N!==void 0?{identity:N}:{};if(J.origin==="import"){let q=Y.rows.find((v)=>N!==void 0&&v.identity===N||v.credential?.type==="oauth"&&v.credential.refresh===G.refresh);if(q)return{id:q.id,operation:"kept"}}let P=Y.rows.filter((q)=>q.type==="oauth"&&!q.invalid),U=N?P.find((q)=>q.identity===N):void 0,_=Y.rows.find((q)=>q.id===I1);if(U)return{id:(await Q.replace(U.id,K,V)).id,operation:"replaced"};if(!_){let q=await Q.add({id:I1,credential:K,...V,...G.label!==void 0?{label:G.label}:{}});return{id:q.id,operation:q.outcome==="added-disabled"?"added-disabled":"added"}}if(!_.invalid&&!_.credential)return{id:(await Q.replace(I1,K,V)).id,operation:"replaced"};let A=await Q.add({id:G.id,credential:K,...V,...G.label!==void 0?{label:G.label}:{}});return{id:A.id,operation:A.outcome==="added-disabled"?"added-disabled":A.outcome==="rotated"?"replaced":"added"}}function e4($){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 G0($){let Z={...$,allowAction:e4,unavailableSections:[]};return{open:(G)=>Z0(Z,G),apply:(G)=>{let J=G!==null&&typeof G==="object"?G:{},Q=J.values&&typeof J.values==="object"&&!Array.isArray(J.values)?Object.fromEntries(Object.entries(J.values).filter(([,Y])=>Y===null||["string","number","boolean"].includes(typeof Y))):void 0;return z0(Z,{command:"openai",sectionId:typeof J.sectionId==="string"?J.sectionId:"",actionId:typeof J.actionId==="string"?J.actionId:"",...Q?{values:Q}:{},...J.confirmed===!0?{confirmed:!0}:{},...typeof J.itemId==="string"?{itemId:J.itemId}:{},...typeof J.sessionId==="string"?{sessionId:J.sessionId}:{}})}}}function $5($,Z){if(!J0($.modelID??$.id)){$.enabled=!1;return}let G=X0($.id);if(G)$.limit={...G};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((J)=>[J.id,J])).values()]}function Y0($){return $.model.transform((Z)=>{let G=Z.list(q2);for(let J of G){let Q=j0(String(J.id)),Y=Q?G.find((K)=>String(K.id)===Q):void 0;Z.update(q2,String(J.id),(K)=>$5(K,Y?.variants?.map((N)=>({...N,id:String(N.id)}))))}})}class P${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(!Q0())return;await this.safely(async()=>{let G={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:G}),this.requests.set(Z.attemptId,$),this.pending.size>512){let J=this.pending.keys().next().value;if(J)this.take(J)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let G=this.take($);if(G)await this.safely(()=>f1({...G,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let G=this.requests.get($.attemptId),J=G&&this.take(G);if(!J)return;let{reason:Q,message:Y}=Z.error,K=Y?`${Q}: ${Y}`:Q;await this.safely(()=>f1({...J,error:v1(K,G?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>f1({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 L${counts=new Map;record($,Z){let G=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof G==="number"&&Number.isFinite(G)?G:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function N0($){return async(Z)=>{let G=Z.credential;if(G.type!=="oauth"||!G.access)throw Error("the row holds no access token to poll with");let J=await B0({accessToken:G.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,J),W0(J,$.now(),!0)}}function H0($){let{source:Z,counts:G,now:J}=$,Q=async(P)=>{let U=await Z.rowAccess(P,await $.storage());if(!U?.row)throw new V0("unknown_account",`${P==="main"?"Main":"Fallback"} account ${P} was not found.`);return U0(P,U)},Y=async(P)=>{if($.authority&&await $.authority()!=="local")return{account:P,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[U]=await Z.pollRows(await $.storage(),{ids:[P]});if(!U)return{account:P,ok:!1,error:"targeted quota refresh returned no result"};return{account:U.id,ok:U.ok,...U.error!==void 0?{error:U.error}:{}}},K=(P)=>Z.peek().rows.find((U)=>U.id===P),N=(P)=>{let U=K(P);if(!U)return null;let _=d2(U.quota)??{},A=G.applicable(U),q=Math.max(0,...[_.primary?.checkedAt,_.secondary?.checkedAt].filter((v)=>typeof v==="number"));return{quota:{..._,...A!==void 0?{resetCreditsApplicable:A}:{}},checkedAt:q,refreshAfter:q,...U.identity!==void 0?{accountId:U.identity}:{}}};return{resolveResetTarget:Q,refreshResetTargetQuota:Y,quotaManager:{isRateLimited:(P)=>{let U=K(P);if(!U)return!1;let _=$.rateLimitMarks().get(U.id);return _!==void 0&&_>J()},getMain:()=>N("main"),getFallback:(P)=>N(P)}}}import{resolve as F0}from"node:path";var Z5=1024;class M${pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=Z5){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 G of this.reservations.values())if(G.sessionId!==$)Z.set(G.sessionId,G.pin);return Z}reserve($,Z){let G={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,G),G}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 G of this.listeners)G($,Z);while(this.pins.size>this.limit){let G=this.pins.keys().next().value;if(G===void 0)break;this.forget(G)}}place($){return S1(this.placementSnapshot($.sessionId),$,(Z,G)=>this.set(Z,G))}}var K0=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),P0=globalThis,h1=P0[K0]??new Map;P0[K0]=h1;function z5($){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 L0($){let Z=JSON.stringify([F0($.configPath),F0($.statePath)]),G=h1,J=h1.get(Z);if(J!==void 0&&!z5(J)){let Y=h1;Y.compatibleV1??=new Map,G=Y.compatibleV1}let Q=G.get(Z);if(!Q)Q=new M$,G.set(Z,Q);return Q}import{statSync as G5}from"node:fs";import{resolve as J5}from"node:path";function q0($){return $.map((Z)=>{try{let G=G5(Z);return`${G.ino}:${G.size}:${G.mtimeMs}:${G.ctimeMs}`}catch{return"?"}}).join("|")}function T$($){return q0([$.vault.paths.tokenPath,$.vault.paths.statePath])}function M0($){return q0([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+T$($)}class S0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;protocol=R0;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:M0($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),G=this.subscriptions.get($.pins);if(!G){let J=new Set;G={producers:J,stop:$.pins.subscribe((Q,Y)=>{let K=J.values().next().value;if(K)this.publish(K,{sessionId:Q,pin:Y,accountId:Y?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,G)}return G.producers.add($),this.timer??=setInterval(()=>{for(let J of this.producers){let Q={stamp:M0(J),roster:J.vault.snapshot()},Y=this.observations.get(J);if(Q.stamp!==Y?.stamp||Q.roster!==Y?.roster)this.observations.set(J,Q),this.publish(J)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),G.producers.delete($),!G.producers.size)G.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;await($.write??b0)(this.file,$,Z,()=>this.producers.has($))}).catch(()=>{I2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var b0=async($,Z,G,J)=>{let Y=await Z.vault.authority()!=="local",K=T$(Z),N=()=>J()&&Z.vault.enrolled()===Y&&T$(Z)===K,V=await(Y?K1(Z.paths):$1(Z.paths)),P=Y?x0(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((A)=>A.id)),V,Date.now()):A0((await Z.source.sidebarView()).rows,V,Date.now()),U={canWrite:N,vaultMode:Y};if(await C0(P,$,U),!N()||!G)return;let _=P.vaultAccounts??P.fallbacks;if(G.accountId===void 0){await E0(G.sessionId,_,$,U);return}if(G.pin){let A=Date.now();await O0({sessionId:G.sessionId,assignment:{accountId:G.pin.accountId,wireAccountId:G.pin.wireIdentity,inputBytes:G.pin.inputBytes??0,quotaCheckedAt:G.pin.quotaCheckedAt,assignedAt:A,lastSeenAt:A},validPinnedAccountIds:[...Y?[]:["main"],..._.filter((q)=>q.enabled).map((q)=>q.id)]},$,U)}await _0({sessionId:G.sessionId,activeId:G.accountId,route:G.route??P.route,updatedAt:Date.now()},_,$,U)},R0=2,D0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),k0=globalThis,F1=k0[D0]??new Map;k0[D0]=F1;function w0($,Z=T0(),G=2000){let J=J5(Z),Q=F1.get(J);if(Q?.protocol!==R0)Q=new S0(J,G),F1.set(J,Q);let Y=Q;$={...$,write:$.write??b0};let K=Y.add($),N=!1;for(let[V,P]of $.pins.snapshot())Y.publish($,{sessionId:V,pin:P,accountId:P.accountId,route:"sticky-balanced"});return{publish:()=>Y.publish($),route:(V,P,U)=>{Y.publish($,{sessionId:V,accountId:P,route:U})},async release(){if(N)return;if(N=!0,K(),await Y.settled(),Y.empty&&F1.get(J)===Y)F1.delete(J)}}}var m1="cortexkit-openai-auth",Y5=5000;async function y0($,Z,G,J=new Q1,Q,Y,K){let N=new P$(G),V=new X5,P=new Map,U=new Map,_=(S)=>{U.delete(S);for(let k of P.keys())if(k.startsWith(`${S}:`))P.delete(k)},A=(S)=>{K?.(S.sessionID),Y?.send(S.sessionID,S.frame)},v=await c1({session:{hook:(S,k,Q2)=>$.session.hook(S,async(X2)=>{let I=S==="http.request"?X2:void 0,p=S==="experimental.ws.handshake"?X2:void 0,M2=(I?I.request.headers:p?new Headers(p.headers):void 0)?.get("authorization")===`Bearer ${y2(Z.providerID)}`,t={};if(p)P.delete(`${p.sessionID}:${p.kind}`);try{await V.run(t,()=>k(X2))}catch(R){if(M2&&!(R instanceof P2))throw u0(R);throw R}if(I&&M2&&t.attempt){let R=I.request.headers.get("thread-id");if(R)I.request.headers.set("session-id",R)}if(I&&M2&&t.attempt)await N.captureHttp(I.request,t.attempt);if(I&&M2&&t.attempt)await Q?.({sessionID:I.sessionID,kind:I.kind,request:I.request,attempt:t.attempt});if(p&&M2&&t.attempt)p.headers["session-id"]=J.get(p.sessionID).threadID;if(S==="experimental.ws.send"){let R=X2,h=P.get(`${R.sessionID}:${R.kind}`);if(h)h.pending=!0;if(h)await N.frame(R.frame,h.attempt);if(h&&R.kind==="primary")A(R)}if(I||p){let R=I??p;if(!R)return;let d=(I?I.request.headers:new Headers(R.headers)).get("authorization")?.replace(/^Bearer /,"");if(M2&&d)U.set(R.sessionID,d);else U.delete(R.sessionID);if(p){let l=`${p.sessionID}:${p.kind}`;if(M2&&d&&t.attempt)P.set(l,{bearer:d,attempt:t.attempt,pending:!1,url:p.url,headers:new Headers(Object.entries(p.headers).filter(([E2])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(E2.toLowerCase())))});else P.delete(l)}if(U.size>512){let l=U.keys().next().value;if(l)U.delete(l)}if(P.size>512){let l=P.keys().next().value;if(l)P.delete(l)}}else if(S==="experimental.ws.receive"){let R=X2,h=P.get(`${R.sessionID}:${R.kind}`);if(h){if(J.frameReceived(R.sessionID,R.frame),R.kind==="primary"){let d;if(Y?.receive(R.sessionID,R.frame,(l)=>{d=l}),d)try{let l=f$(d,h.url,h.headers,J);if(l)await Q?.({sessionID:R.sessionID,kind:"primary",request:l,attempt:h.attempt})}catch(l){G.warn("cachekeep WebSocket capture failed",{error:l instanceof Error?l.message:String(l)})}}if(R.frame=p0(R.frame,h.bearer),R.kind==="primary"&&h.pending&&i2()&&(R.frame.includes('"response.completed"')||R.frame.includes('"response.failed"')||R.frame.includes('"response.incomplete"')||R.frame.includes('"error"')))try{let d=JSON.parse(R.frame);if(d.type==="response.completed")h.pending=!1,m0(R.sessionID,Date.now());else if(["response.failed","response.incomplete","error"].includes(d.type))h.pending=!1}catch{}}}else if(S==="retry"){let R=X2,h=U.get(R.sessionID);if(h)Object.assign(R.error,{message:v1(R.error.message,h)})}},Q2)},event:{subscribe:(S)=>async function*(){for await(let k of $.event.subscribe(S)){if(k.type==="session.deleted")_(k.data.sessionID);yield k}}()}},{...Z,rewriteRequest:async(S)=>{let k=V.getStore();if(k)k.attempt=S.attempt;return Z.rewriteRequest?.(S)},rewriteHandshakeURL:(S)=>{let k=V.getStore();if(k)k.attempt=S.attempt;return Z.rewriteHandshakeURL?.(S)},onAttemptEnd:async(S,k)=>{await N.end(S,k),await Z.onAttemptEnd?.(S,k)},rewriteResponse:async(S)=>{await N.response(S.request,S.response.status);let k=await Z.rewriteResponse?.(S)??S.response,Q2=await c0(k,S.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream");return l0(Q2,S.kind==="primary"?S.sessionID:void 0)}},{gateOnPlaceholder:{credential:(S)=>{let k=S.get("authorization");return k?.startsWith("Bearer ")?k.slice(7):void 0}},hostRetryLimit:e2,logger:{info:(S,k)=>G.info?.(S,{data:k}),warn:(S,k)=>G.warn(S,{data:k})}}),$2=v.dispose;return{...v,dispose:async()=>{U.clear(),P.clear(),await $2(),await N.settle(),N.clear()}}}function E$($={}){return{id:m1,setup:(Z)=>Q5(Z,$)}}async function Q5($,Z={}){let u=[];try{let G=I2("opencode2");let J=I2("quota");let Q=Z.version??i0;await J4({version:Q,...Z.runtimeLayout});let Y=Z.paths??(()=>a0(d0()));let K=await K1(Y());let N=K?.logging?.level;if(N&&typeof N==="string")f0(N);let V=Z.fetch??fetch;let P=Z.now??Date.now;let U=Z.poolMigration??j4;if(!U&&!Z1(Y().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 T=(Z2)=>{throw new P2({kind:"no-account",providerID:q2,sessionID:Z2.sessionID,requestKind:Z2.kind,message:b1})},g=await y0($,{providerID:q2,chooseAccount:T,accountHeaders:T},G);return()=>g.dispose()}let _=Z.vault?.firstRosterWaitMs??t0;let A=X4({host:"opencode",stateDir:Z.vault?.stateDir??g0(Y().statePath),reservedRouteIds:()=>I.peek().rows.map((T)=>T.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>V},Y());let q=A.vault;let v=async()=>await q.authority()==="local"?$1(Y()):K1(Y());let $2=!1;let S=!1;const k=P1(u,{[Symbol.dispose](){if(!$2)A.release()}},0);await q.authority();let Q2=A.firstRoster;let X2=new L$;let I=new e0({paths:Y,refreshProvider:async(T)=>{let g=await h0({refreshToken:T.refresh,fetchImpl:V,now:P}),Z2=v0({id_token:"",access_token:g.access,refresh_token:g.refresh});return{...g,...Z2?{identity:Z2}:{}}},pullQuota:N0({fetchImpl:V,now:P,counts:X2,logger:J}),now:P,vaultIdentities:()=>q.identities(),vaultMode:()=>q.enrolled(),vaultAuthority:()=>q.authority(),vaultFirstRoster:Q2,vaultFirstRosterBackgroundWaitMs:_,log:I2("pool")});if(await q.authority()==="local")await I.load();let p=new $4({pool:I,vault:q,log:(T)=>G.warn(T)});const f2=P1(u,{[Symbol.dispose](){if(!$2)p.dispose()}},0);let M2=Z.heartbeat===!1?void 0:await z4({version:Q,logger:I2("heartbeat")});let t=Z.fence??(()=>n0({currentVersion:Q}));let R=Z.slot??Y4();let h=async()=>o0(Y(),await R.get({path:{id:"openai"}}));let d=!1;let l=U?Z4({paths:Y,slot:R,version:Q,fence:t,runDeps:{vaultServes:()=>q.serves()},paused:async()=>await q.authority()!=="local",migrate:async(T)=>{let g=await s0(T);if(d=g.status==="refused",!S)await I.load();return g},adopt:async(T)=>{if(S)return{status:"retry",reason:"unsettled"};if(!await _$(Q2,_))return{status:"retry",reason:"vault-roster-pending"};if(S)return{status:"retry",reason:"unsettled"};let g=await r0(T);if(!S)await I.load();return g}}):void 0;l?.start();A.start();let E2=L0(Y());let S2=w0({paths:Y(),source:I,pins:E2,vault:q},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const D2=P1(u,{[Symbol.dispose](){if(!$2)S2.release()}},0);S2.publish();let U2=Z.codex??new Q1(void 0,void 0,vZ());let z1=xZ(K);let B2=k1(Y());let z2=SZ(Y(),{source:I,limits:p,storage:v,vault:q,accounts:s1(Y()),settings:()=>z1,parentOf:async(T)=>(await $.session.get({sessionID:T}))?.parentID??void 0,fetch:V,log:I2("cachekeep")},{now:P,codexResponsesUrl:g1().codexApiEndpoint,...Z.cacheKeep});const g2=P1(u,{[Symbol.dispose](){if(!$2)z2.release()}},0);let j=FZ({limits:p,codex:U2,onRoute:S2.route,source:I,slotPlaceholderWithoutMain:h,storage:v,pins:E2,sessionAccounts:s1(Y()),vault:q,awaitVaultRoster:async()=>{await _$(q.awaitRequestRoster(),R1)},responsesLite:()=>g1().responsesLite,codexEndpoint:()=>g1().codexApiEndpoint,now:P,log:G});let H=await y0($,j.adapter,G,U2,(T)=>z2.capture(T),B2,(T)=>z2.forget(T));j.attach(H);let L=await $.session.hook("prompt",(T)=>{j.beginTurn(T.sessionID)});let M=async(T)=>{if(await H1(q),Z1(Y().configPath))return;if(await l?.idle(),Z1(Y().configPath))return;if(d&&!K$(T)&&(await t()).open){await I.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let b=async(T)=>{await M(T);let g=await $0(I.poolStore(),Y(),T,{vault:q});if(!Z1(Y().configPath))await l?.requestAdoption();await I.load(),G.info("ChatGPT login stored in the account pool",g)};let x=await u1($,{integrationID:q2,methods:eZ({beginLogin:Z.beginLogin??C$,version:Q,vault:q}),onLogin:(T)=>b(T),label:"ChatGPT (openai-auth account pool)",vault:tZ(q)});let O=await Y0($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let y=$.command&&$.location?await cZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??G0({...H0({rateLimitMarks:()=>p.marks(),source:I,storage:v,counts:X2,now:P,authority:()=>q.authority()}),fetchImpl:V,now:P,randomUUID:j5,accountStoragePath:Y().configPath,accountStatePath:Y().statePath,packageVersion:Q,layoutNotice:G4,loadAccounts:$1,store:()=>I.poolStore(),migration:async()=>{if(Z1(Y().configPath))return{migrated:!0};let T=await t();return{migrated:!1,blockers:T.open?[]:T.blockers}},beginAccountLogin:Z.beginLogin??C$,refreshAllQuota:async()=>(await I.pollRows(await $1(Y()))).map((T)=>({...T,account:T.id})),getStickyRouting:async(T)=>E2.get(T),cacheKeepManager:z2.manager,setCacheKeepEnabled:(T)=>z2.configure({enabled:T}),setCacheKeepSubagents:(T)=>z2.configure({subagents:T}),setCacheKeepSustain:(T)=>z2.configure({sustain:T}),setCacheKeepWindow:(T)=>z2.configure({window:T}),afterWrite:()=>I.load(),refreshSidebar:()=>S2.publish(),clearStickyRouting:async(T)=>{let g=E2.get(T)!==void 0;return E2.forget(T),g},vault:q})):void 0;let f=new AbortController;(async()=>{try{for await(let T of $.event.subscribe({signal:f.signal}))if(T.type==="session.deleted")j.forgetSession(T.data.sessionID),z2.forget(T.data.sessionID),B2.forget(T.data.sessionID)}catch(T){if(!f.signal.aborted)G.warn("stopped listening for session deletion",{error:T instanceof Error?T.message:String(T)})}})();$2=!0;return async()=>{S=!0,f.abort(),j.dispose();let T=z2.release();await y?.(),l?.dispose(),await p.dispose(),await S2.release(),await Promise.allSettled([H.dispose(),L.dispose(),x.dispose(),O.dispose()]);let g;try{await Promise.race([Promise.all([l?.idle(),I.settled(),U2.store?.settled(),T]),new Promise((Z2)=>{g=setTimeout(Z2,Y5),g.unref?.()})])}finally{clearTimeout(g),await A.release(),await M2?.release()}}}catch(w){var c=w,G2=1}finally{I0(u,c,G2)}}var B5=E$(),h7={id:m1,setup:B5.setup,server:Q4.server};export{h7 as default,E$ as createOpenAIAuthPlugin,m1 as OPENAI_AUTH_PLUGIN_ID};
|
|
1
|
+
import{c as U4}from"../index-a9tzfpxy.js";import{$ as V4,A as X4,B as j4,C as S1,D as HZ,E as FZ,F as R0,G as D0,H as W4,I as aZ,J as nZ,M as B0,N as W0,O as V0,W as K0,X as P0,d as s0,e as N0,f as c1,fa as w$,g as X1,ga as y$,h as w1,i as l1,ja as N4,k as D$,l as k$,m as b$,n as O1,o as dZ,p as P$,q as iZ,r as j0,s as Y0,t as I1,u as AZ,v as SZ,w as y1,x as J4,y as O$,z as G4}from"../index-bc2d4vma.js";import{Aa as t$,Ab as VZ,Ba as e$,Bb as A1,Cb as UZ,Db as NZ,Gb as r2,Jb as d0,Kb as i0,Lb as u1,Mb as a0,Nb as n0,Ob as o0,Pb as k1,Qb as t0,Rb as yZ,Ta as $0,Tb as e0,Ub as Z0,bc as $4,cb as GZ,cc as Z4,dc as z4,eb as XZ,ec as z0,fb as B$,gb as W$,hb as jZ,jb as D1,mc as o2,na as Z1,nc as IZ,oa as i$,oc as fZ,pc as H$,qa as z$,qc as vZ,rb as YZ,rc as hZ,sa as eZ,sb as V$,tb as QZ,uc as Y4,vc as Q4,wa as c0,wb as BZ,wc as B4,xb as WZ,yb as S2}from"../index-yew3mp47.js";import{Gc as x0,Vc as q0,Wc as A0,Yc as S0,ad as b0}from"../index-f7t7cc9b.js";import{Ae as p0,Be as H0,Le as G1,Me as M1,Pd as sZ,Re as s$,Se as r$,Te as qZ,Ue as J$,Wd as rZ,_e as m1,ff as F0,gf as s2,hf as G$,if as X$,jf as $Z,le as b1,lf as j$,me as R1,mf as ZZ,ne as u0,of as zZ,pf as F1,qd as H1,qf as Y$,rf as JZ,sf as Q$,ue as E$,ve as a$,we as n$,xe as o$,yd as c$,ye as tZ,zd as d$}from"../index-4zpxwh8y.js";import"../index-zcpher1w.js";import{If as pZ,Jf as r0}from"../index-xxmaf5ks.js";import"../index-3c9pk6zn.js";import{Uf as l0,Wf as v2}from"../index-wap9mf5f.js";import"../index-nfbmjq6g.js";import{sg as cZ}from"../index-q111b2h5.js";import{wg as _1,xg as m0}from"../index-1abcvt9p.js";import{AsyncLocalStorage as B5}from"node:async_hooks";import{randomUUID as W5}from"node:crypto";class _2 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 f2($){return`common-auth-placeholder.${$}`}function q$($){let Z=f2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function Q1($,Z){if($?.type!=="oauth")return!1;let J=Z===void 0?void 0:f2(Z),G=(j)=>J===void 0?j.startsWith("common-auth-placeholder."):j===J;return G($.access)&&G($.refresh)}var A$="No browser sign-in: this connects the plugin to the accounts in its vault.";async function a1($,Z){let J=Z.now??Date.now,{integrationID:G}=Z,j=(L)=>q$({integrationID:G,methodID:L,now:J()}),Y=async(L,U)=>{return await Z.onLogin(L,{integrationID:G,methodID:U}),j(U)},K=(L)=>async(U)=>{let H=L.method.id,B=await L.authorize(U),M={url:B.url,instructions:B.instructions,...B.expiresAt===void 0?{}:{expiresAt:B.expiresAt}};if(B.mode==="auto")return{...M,mode:"auto",callback:B.callback.then((q)=>Y(q,H))};let S=B.callback;return{...M,mode:"code",callback:async(q)=>Y(await S(q),H)}};return $.integration.transform((L)=>{let U=Z.label===void 0?{}:{label:()=>Z.label};for(let M of Z.methods)L.method.update({integrationID:G,method:M.method,authorize:K(M),refresh:async(S)=>{if(!Q1(S,G))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return j(S.methodID)},...U});let H=Z.vault;if(H===void 0)return;let B=H.method.id;L.method.update({integrationID:G,method:H.method,authorize:async()=>({url:"",instructions:H.instructions??A$,mode:"auto",callback:Promise.resolve().then(()=>H.activate({integrationID:G,methodID:B})).then(()=>j(B))}),refresh:async(M)=>{if(!Q1(M,G)||M.methodID!==B)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return j(B)},...U})})}function F4($){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
|
+
`)}:{event:J,data:Z.join(`
|
|
3
|
+
`)}}function B1($,Z){let J=new TextDecoder,G="",j=(K)=>{let L=F4(K);if(!L)return;try{$(L)}catch(U){Z(U)}},Y=()=>{for(;;){let K=/\r?\n\r?\n/.exec(G);if(!K)return;let L=G.slice(0,K.index);G=G.slice(K.index+K[0].length),j(L)}};return new TransformStream({transform(K,L){L.enqueue(K),G+=J.decode(K,{stream:!0}),Y()},flush(){if(G+=J.decode(),Y(),G.trim()!=="")j(G);G=""}})}var n2=512,a2=3621000,e2="x-common-auth-attempt",i2=($,Z)=>JSON.stringify([$,Z]),k2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function K4($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function P4($,Z){let J=$.getReader();return new ReadableStream({async pull(G){let j;try{j=await J.read()}catch(Y){Z({reason:"failed",message:Y instanceof Error?Y.message:String(Y)}),G.error(Y);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 C1($,Z){for(let[J,G]of Object.entries(Z)){let j=J.toLowerCase();for(let Y of Object.keys($))if(Y.toLowerCase()===j)delete $[Y];if(G!==null)$[J]=G}}function L4($,Z){for(let[J,G]of Object.entries(Z))if(G===null)$.delete(J);else $.set(J,G)}async function n1($,Z,J={}){let{providerID:G}=Z,j=J.gateOnPlaceholder,Y=(z)=>j===void 0||j.credential(z)===f2(G),K=J.logger,L=Math.max(1,J.maxRecords??n2),U=J.hostRetryLimit??10,H=[...J.hostCredentials??[f2(G)],...j?[f2(G)]:[]].filter((z)=>z!==""),B=new Map,M=new WeakMap,S=new Map,q=0,v=new Set,o=new Map,b=new Map,D=(z)=>{let Q=b.get(z);return Q?.ownedSeen===!0&&Q.foreignSeen},P2=(z,Q)=>{o.set(z,Q);let W=b.get(z)??{ownedSeen:!1,foreignSeen:!1};if(Q)W.ownedSeen=!0;else W.foreignSeen=!0;b.set(z,W)},Q2=(z,Q)=>{let W=j?.refuseMisplaced,T=W?[...Q].filter(([,_])=>_.includes(f2(G))):[],V=Y(Q)&&(!W||T.length>0);if(W){if(T.length>0&&(T.length!==1||!V))throw P2(z.sessionID,!1),new _2({kind:"placement-refused",providerID:G,sessionID:z.sessionID,requestKind:z.kind,message:W(T[0]?.[0]??"")})}return P2(z.sessionID,V),V},h=!1,a=!1,E2=new Map,z2=0,t=!1,y=new Map,m=(z,Q)=>{try{K?.warn(z,Q)}catch{}},p=(z)=>z instanceof Error?z.message:String(z),u=(z)=>z.excluded.clear(),O2=(z)=>z.excluded.size===0?{}:{excluded:[...z.excluded]},x2=(z,Q,W)=>{if(!J.enforceRequestExclusion||z===void 0||!W.excluded.has(z))return!1;return m("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:Q.sessionID,kind:Q.kind,phase:Q.phase,accountId:z}),!0},R2=new Map,N2=(z,Q)=>{let W=(R2.get(z)??Promise.resolve()).then(Q),T=W.then(()=>{},()=>{});return R2.set(z,T),T.then(()=>{if(R2.get(z)===T)R2.delete(z)}),W},u2=(z,Q)=>{let W=R2.get(z);return W?W.then(()=>u2(z,Q)):Q()},U2=async(z)=>{try{await Z.dropChoice?.({...z.input,accountId:z.accountId})}catch(Q){m("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:z.input.sessionID,error:p(Q)})}},J2=async(z)=>{try{await Z.dropSameAccountRetry?.({...z.input,accountId:z.accountId})}catch(Q){m("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:z.input.sessionID,error:p(Q)})}},t2=async(z)=>{if(z.next)await U2(z.next);if(z.sameAccount)await J2(z.sameAccount)},D2=(z)=>{let Q=S.get(z);if(S.delete(z),Q)N2(Q.sessionID,()=>t2(Q))},h2=async(z,Q)=>{let W=E2.get(z);if(!W||W.size===0)return;await Promise.all([...W].map(async(T)=>{try{await T(Q)}catch(V){m("opencode2 auth listener threw; the request is unaffected",{event:z,error:p(V)})}}))},m2=async(z)=>{let Q=new Set([...B.values()].filter((T)=>T.scope.sessionID===z.sessionID).map((T)=>T.transport).filter((T)=>T!==void 0)),W=z.handle?.transport??(Q.size===1?[...Q][0]:"unknown");try{K?.info?.("opencode2 auth retry decision",{sessionID:z.sessionID,transport:W,attempt:z.attempt,reason:z.reason==="host-decides"&&D(z.sessionID)?"mixed-session":z.reason,retry:z.decision.retry})}catch{}await h2("retry",z)},X=async(z,Q)=>{try{await Z.onAttemptEnd?.(z,Q)}catch(W){m("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:z.attemptId,error:p(W)})}},N=(z,Q)=>{if(z.ended||!z.attempt)return;let W={...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))u(z.request);z.ended=X(z.attempt,W)},C=(z,Q)=>N(z,{reason:"abandoned",message:Q}),F=(z)=>[...B.values()].filter((Q)=>Q.key===z),R=(z)=>F(z).at(-1),x=(z)=>{if(B.delete(z.id),S.get(z.key)?.attemptId===z.id||!F(z.key).length)D2(z.key)},A=(z)=>{B.set(z.id,z);while(B.size>L){let Q=B.values().next().value;if(Q===void 0)break;C(Q,"dropped to keep the record bound"),x(Q)}},k=(z)=>z.accountId===void 0?void 0:{...z.scope,accountId:z.accountId},f=(z,Q)=>new _2({kind:"no-account",providerID:G,sessionID:z.sessionID,requestKind:z.kind,...Q===void 0?{}:{message:Q}}),d=(z)=>{y.get(z)?.clear(),y.delete(z)},P=async(z,Q)=>{let W=()=>f(z,`${G} ${z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(t)throw W();let T=y.get(z.sessionID);if(!T)T=new Set,y.set(z.sessionID,T);let V={};T.add(V);let _=()=>{if(!T.has(V))throw W()};try{return await Q(_)}finally{if(T.delete(V),T.size===0&&y.get(z.sessionID)===T)y.delete(z.sessionID)}},g=(z,Q)=>{for(let[W,T]of Q)if(H.some((V)=>T.includes(V)))throw new _2({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 ${W}; the adapter's account headers must replace it`})},s=(z)=>{for(let Q of F(z))if(Q.ended||!Q.attempt)x(Q);else if(Q.transport==="ws"||Q.judged)C(Q,"a newer attempt of its session and kind began"),x(Q)},e=async(z,Q,W,T)=>{let V=i2(z.sessionID,z.kind),{input:_,accountId:E,sameAccountRetry:O,request:w}=await u2(z.sessionID,async()=>{W();let W2=S.get(V);S.delete(V);let Y1=F(V);if(W2&&Y1.some((Z2)=>Z2.id!==W2.attemptId&&Z2.attempt&&!Z2.ended))m("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:z.sessionID,kind:z.kind});if(!W2){let Z2=new Set(Y1.filter((C2)=>C2.attempt&&!C2.ended).map((C2)=>C2.request));for(let C2 of Y1)if(!Z2.has(C2.request))u(C2.request)}let M2=W2?.request??{excluded:new Set},Y2=W2?.accountId??R(V)?.accountId;s(V);let r=W2?.next,V2=W2?.sameAccount,i=V2!==void 0&&V2.input.modelID===z.modelID&&V2.input.agent===z.agent,T2=r!==void 0&&r.input.modelID===z.modelID&&r.input.agent===z.agent,I2=W2?.wake,n={...z,phase:"request",...O2(M2),...Y2===void 0?{}:{previousAccountId:Y2},...W2?.rerouteFrom?{rerouteFrom:W2.rerouteFrom}:{},...I2===void 0?{}:{wake:I2,hostAttempt:r?.input.hostAttempt}};if(r&&(!T2||I2!==void 0))await N2(z.sessionID,()=>U2(r)),W();if(V2&&!i)await N2(z.sessionID,()=>J2(V2)),W();if(V2?.continuation&&(!i||D(z.sessionID))){if(i)await N2(z.sessionID,()=>J2(V2));throw f(z)}let d2=i?V2.accountId:T2&&I2===void 0?r.accountId:await Z.chooseAccount(n),l2=typeof d2==="string"?d2:void 0;if(x2(l2,n,M2)){let Z2=l2;if(i&&V2)await N2(z.sessionID,()=>J2(V2));else if(Z2!==void 0)await N2(z.sessionID,()=>U2(T2&&r?r:{accountId:Z2,input:n}));l2=void 0,W()}return{input:n,accountId:l2,sameAccountRetry:i,request:M2}});W();let I={},l;if(E!==void 0){let W2=await Z.accountHeaders({...z,accountId:E});if(W(),K4(W2))I=W2.headers,l=W2.attempt;else I=W2}let A2=`attempt-${++z2}`,F2={id:A2,key:V,scope:z,request:w,accountId:E,headers:I,attempt:E===void 0?void 0:{...z,accountId:E,attemptId:A2,transport:T,data:l},...T===void 0?{}:{transport:T},outputStarted:!1,sameAccountRetry:O};if(A(F2),F2.attempt)h2("select",{...z,accountId:F2.attempt.accountId,hook:Q,..._.previousAccountId===void 0?{}:{previousAccountId:_.previousAccountId},..._.rerouteFrom===void 0?{}:{rerouteFrom:_.rerouteFrom},handle:F2.attempt});return F2},X2=async(z,Q,W,T,V)=>{let _=i2(z.sessionID,z.kind),E=T===void 0?void 0:B.get(T);if(E?.key!==_)E=void 0;if(!E){if(E=R(_),F(_).filter((w)=>w.transport===void 0&&!w.ended).length>1&&!a)a=!0,m("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:z.sessionID,kind:z.kind})}if(!E||E.transport!==void 0||E.ended)E=await e(z,Q,V,W);else if(E.transport=W,E.attempt)E.attempt.transport=W;if(W==="ws"){for(let O of F(_))if(O!==E&&O.transport==="ws")C(O,"a newer attempt of its session and kind went out over WebSocket")}return E},G2=async(z,Q)=>{try{return await Q()}catch(W){throw N(z,{reason:"failed",message:p(W)}),W}},H2=(z,Q)=>{let W=F(i2(z,Q)).filter((T)=>T.transport==="ws").at(-1);return W?.attempt!==void 0&&!W.ended?W:void 0},B2=(z,Q,W)=>{let T=k(z);if(!T||!z.attempt||z.limit)return;z.limit={signal:Q,delivered:h2("limit",{...T,via:W,limit:Q,outputStarted:z.outputStarted,handle:z.attempt})}},c=(z,Q,W,T)=>{let V=k(z);if(!V||!z.attempt)return;h2("quota",{...V,transport:Q,...T===void 0?{}:{status:T},quota:W,handle:z.attempt})},$2=(z,Q,W,T)=>{let V=z.attempt;if(!V)return;let _=Z.inspectEvent?.(T===void 0?{transport:Q,data:W,attempt:V}:{transport:Q,data:W,event:T,attempt:V});if(!_)return;if(_.quota!==void 0)c(z,Q,_.quota);if(_.outputStarted)z.outputStarted=!0;if(_.hostRetry==="veto")z.hostRetry="veto";if(_.limit)B2(z,_.limit,Q);if(_.error!==void 0)N(z,{reason:"failed",message:_.error});else if(_.done)N(z)},w2=(z,Q)=>{let W=z.attempt;if(!W||Q.accountId===z.accountId)return;if(W.reboundFrom??=W.accountId,W.accountId=Q.accountId,"data"in Q)W.data=Q.data;z.accountId=Q.accountId},p2=(z)=>!z.attempt||z.endError!==void 0||z.status!==void 0&&z.status>=400,j1=(z)=>{let Q=[...B.values()].filter((O)=>O.scope.sessionID===z),W=Q.filter((O)=>O.limit&&!O.rerouted).at(-1);if(W)return W;let T=Q.filter((O)=>O.scope.kind==="primary"),V=T.length>0?T:Q;if(V.length<=1)return V[0];let _=V.filter((O)=>!O.judged&&p2(O)).at(-1);if(_)return _;let E=V.filter((O)=>O.attempt&&!O.ended);if(E.length>1)return"ambiguous";return E[0]??V.at(-1)},j2={providerID:G},L2=[];L2.push(await $.session.hook("model.request",(z)=>{if(j)return;return P(k2(z),async(Q)=>{let W=await e(k2(z),"model.request",Q);if(Q(),W.accountId===void 0)throw f(W.scope);C1(z.headers,{...W.headers,[e2]:W.id})})},j2)),L2.push(await $.session.hook("http.request",(z)=>{if(j){if(!Q2(k2(z),z.request.headers))return}return P(k2(z),async(Q)=>{let W=z.request.headers.get(e2)??void 0,T=j?await e(k2(z),"http.request",Q,"http"):await X2(k2(z),"http.request","http",W,Q);Q();let V=k(T),_=T.attempt;if(!V||!_)throw f(T.scope);await G2(T,async()=>{let E=z.request;if(Z.rewriteRequest){if(W!==void 0){let I=new Headers(E.headers);I.delete(e2),E=new Request(E,{headers:I})}E=await Z.rewriteRequest({...V,request:E,attempt:_})??E,Q()}let O=new Headers(E.headers);O.delete(e2),L4(O,T.headers),g(T.scope,O.entries());let w=new Request(E,{headers:O});M.set(w,T),z.request=w})})},j2)),L2.push(await $.session.hook("http.response",async(z)=>{let Q=M.get(z.request);if(!Q){if(j)return;if(!h)h=!0,m("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:z.sessionID,kind:z.kind});return}let W=z.response;if(Z.answeredBy&&Q.attempt){let O=Q.attempt,w=await G2(Q,async()=>Z.answeredBy?.({request:z.request,response:W,attempt:O}));if(w)w2(Q,w)}let T=k(Q),V=Q.attempt;if(!T||!V)return;Q.status=W.status;let _=Z.quotaFromHeaders?.(W.headers,W.status,V);if(_!==void 0)c(Q,"http",_,W.status);if(!W.ok&&Z.limitFromResponse){let O=await Z.limitFromResponse({status:W.status,headers:W.headers,body:()=>W.clone().text(),attempt:V});if(O)B2(Q,O,"http")}if(!W.ok||!W.body)N(Q);let E=W;if(W.body&&(Z.inspectEvent||Z.onAttemptEnd)){let O=W.body;if(Z.inspectEvent)O=O.pipeThrough(B1((w)=>$2(Q,"http",w.data,w.event),(w)=>m("opencode2 auth event inspection threw",{error:p(w)})));E=new Response(P4(O,(w)=>{if(w?.reason==="failed")Q.readFailed=!0;N(Q,w)}),{status:W.status,statusText:W.statusText,headers:W.headers})}if(Z.rewriteResponse)E=await Z.rewriteResponse({...T,request:z.request,response:E,attempt:V})??E;if(Z.responseRetry){if(await Z.responseRetry({...T,request:z.request,response:E,attempt:V})==="veto")Q.hostRetry="veto"}if(E!==W)z.response=E},j2)),L2.push(await $.session.hook("experimental.ws.handshake",(z)=>{if(j){let Q=i2(z.sessionID,z.kind);if(v.delete(Q),!Q2(k2(z),new Headers(z.headers)))return}return P(k2(z),async(Q)=>{let W;for(let E of Object.keys(z.headers)){if(E.toLowerCase()!==e2)continue;W??=z.headers[E],delete z.headers[E]}let T=j?await e(k2(z),"experimental.ws.handshake",Q,"ws"):await X2(k2(z),"experimental.ws.handshake","ws",W,Q);Q();let V=k(T),_=T.attempt;if(!V||!_)throw f(T.scope);await G2(T,async()=>{if(!j?.refuseMisplaced)C1(z.headers,T.headers);let E=Z.rewriteHandshakeURL?.({...V,url:z.url,attempt:_});if(E!==void 0)z.url=E;if(j?.refuseMisplaced)C1(z.headers,T.headers);if(g(T.scope,Object.entries(z.headers)),j)v.add(T.key)})})},j2));let c2=Z.rewriteWebSocketFrame?.bind(Z);if(c2)L2.push(await $.session.hook("experimental.ws.send",async(z)=>{let Q=k2(z);if(j&&!v.has(i2(Q.sessionID,Q.kind)))return;let W=H2(Q.sessionID,Q.kind),T=await c2({...Q,attempt:W?.attempt,frame:z.frame});if(T!==void 0)z.frame=T},j2));L2.push(await $.session.hook("experimental.ws.receive",(z)=>{if(j&&!v.has(i2(z.sessionID,z.kind)))return;let Q=H2(z.sessionID,z.kind);if(!Q)return;try{$2(Q,"ws",z.frame)}catch(W){m("opencode2 auth frame inspection threw",{error:p(W)})}},j2)),L2.push(await $.session.hook("retry",async(z)=>{if(j&&o.get(z.sessionID)!==!0)return;let Q=z.decision,W=()=>m2({sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:Q,decision:Q});if(D(z.sessionID)&&!Z.retrySameAccount){await W();return}let T=j1(z.sessionID);if(!T)return;if(T==="ambiguous"){await m2({sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:Q,decision:Q});return}let V=T,_=()=>V.hostRetry==="veto";await P(V.scope,async(E)=>{let O=E,w=Z.retrySameAccount?.bind(Z),I=V.attempt,l=V.outputStarted;if(V.transport==="ws"&&l&&!V.ended&&!V.limit&&!(V.status!==void 0&&V.status>=400)&&!(z.error.status!==void 0&&z.error.status>=400)&&z.error.type==="provider.transport")V.readFailed=!0,N(V,{reason:"failed",message:z.error.message});if(l&&V.readFailed&&w&&I&&!D(z.sessionID)){if(!V.limit){let M2=Z.limitFromError?.(z.error,I);if(M2)B2(V,M2,"error")}if(V.ended)await V.ended;if(V.limit)await V.limit.delivered;O()}let A2=()=>V.readFailed===!0&&z.error.type==="provider.transport"&&Q.retry&&U-z.attempt>=1&&!V.limit&&!(V.status!==void 0&&V.status>=400)&&!(z.error.status!==void 0&&z.error.status>=400)&&!I?.reboundFrom&&!_()&&!D(z.sessionID);if(w&&I&&(!l||A2())&&(!_()||D(z.sessionID))&&!V.sameAccountRetry){if(V.ended)await V.ended;if(V.limit)await V.limit.delivered;let M2=await N2(V.scope.sessionID,async()=>{O();let Y2=I.accountId,r=()=>B.has(V.id)&&V.accountId===Y2&&j1(z.sessionID)===V&&V.outputStarted===l&&(!l||A2())&&(!_()||D(z.sessionID))&&(!j||o.get(z.sessionID)===!0);if(!r()||V.sameAccountRetry)return!1;V.sameAccountRetry=!0;let V2={...V.scope,accountId:Y2,error:z.error,attempt:z.attempt,...V.limit?{limit:V.limit.signal}:{},...l?{continuation:"interrupted-read"}:{}},i;try{i=await w(V2)}catch(n){m("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:z.sessionID,error:p(n)})}if(!i)return O(),!1;let T2={accountId:i.accountId,input:V2,...l?{continuation:!0}:{}};try{O()}catch(n){throw await J2(T2),n}if(!r()||i.accountId!==Y2)return await J2(T2),!1;let I2=S.get(V.key);if(S.delete(V.key),I2)await t2(I2);try{O()}catch(n){throw await J2(T2),n}if(!r())return await J2(T2),!1;return S.set(V.key,{request:V.request,attemptId:V.id,sessionID:V.scope.sessionID,order:++q,accountId:Y2,sameAccount:T2}),V.judged=!0,z.decision=l?Q:{retry:!0,delay:0},!0});if(O(),M2){await m2({sessionID:z.sessionID,accountId:V.accountId,kind:V.scope.kind,attempt:z.attempt,reason:l?"continue-same-account":"same-account",hostDecision:Q,decision:z.decision,handle:V.attempt});return}}if(D(z.sessionID)){await W();return}V.judged=!0;let F2=V.attempt;if(F2&&!V.outputStarted){if(!V.limit){let M2=Z.limitFromError?.(z.error,F2);if(M2)B2(V,M2,"error")}if(V.ended)await V.ended;if(V.limit)await V.limit.delivered}O();let{decision:W2,reason:Y1}=await N2(V.scope.sessionID,async()=>{if(O(),D(z.sessionID))return{decision:Q,reason:"host-decides"};let M2=S.get(V.key);if(S.delete(V.key),M2)await t2(M2);if(O(),D(z.sessionID))return{decision:Q,reason:"host-decides"};let Y2=Q,r,V2,i,T2;if(V.accountId===void 0||!F2)Y2={retry:!1},r="no-account";else if(V.outputStarted)Y2={retry:!1},r="output-started";else if(_())Y2={retry:!1},r="adapter-veto";else if(V.limit){let I2={accountId:V.accountId,limit:V.limit.signal},n,d2={...V.scope,phase:"retry",...O2(V.request),hostAttempt:z.attempt,previousAccountId:V.accountId,rerouteFrom:I2};try{n=await Z.chooseAccount(d2)}catch(i1){m("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:V.scope.sessionID,error:p(i1)})}let l2=typeof n==="string"?n:typeof n==="object"&&("hold"in n)?V.accountId:void 0;if(x2(l2,d2,V.request)){if(l2!==void 0)await U2({accountId:l2,input:d2});n=void 0}let Z2=typeof n==="object"&&"hold"in n?n.hold:void 0,C2=typeof n==="object"&&"waitThenReselect"in n?n.waitThenReselect:void 0,H4=typeof n==="object"&&"hostRetry"in n?n.hostRetry:void 0,T1=typeof n==="string"?n:Z2?V.accountId:void 0;if(T1!==void 0)i={accountId:T1,input:d2};try{O()}catch(i1){if(i)await U2(i);throw i1}if(D(z.sessionID)){if(i)await U2(i);return{decision:Q,reason:"host-decides"}}if(_()||H4==="veto"){if(i)await U2(i);if(i=void 0,O(),D(z.sessionID))return{decision:Q,reason:"host-decides"};V.hostRetry="veto",Y2={retry:!1},r="adapter-veto"}else if(!(U-z.attempt>=1)){if(i)await U2(i);i=void 0,r="host-decides-last-account"}else if(C2&&Number.isFinite(C2.delayMs)&&C2.delayMs>=0&&C2.delayMs<=a2)Y2={retry:!0,delay:Math.ceil(C2.delayMs)},r="wait-then-reselect";else if(Z2&&Number.isFinite(Z2.delayMs)&&Z2.delayMs>=0&&Z2.delayMs<=a2){if(Y2={retry:!0,delay:Math.ceil(Z2.delayMs)},Z2.target!==void 0)T2={target:Z2.target,...Z2.checkpoint===void 0?{}:{checkpoint:Z2.checkpoint},...Z2.kind===void 0?{}:{kind:Z2.kind}};r="hold"}else if(!Z2&&T1!==void 0&&T1!==V.accountId)V.rerouted=!0,V.request.excluded.add(V.accountId),V2=I2,Y2={retry:!0,delay:0},r="reroute";else{if(Z2&&i)await U2(i),i=void 0;r="host-decides-last-account"}}else r="host-decides";if(z.decision=Y2,Y2.retry&&V.accountId!==void 0&&B.has(V.id))S.set(V.key,{request:V.request,attemptId:V.id,sessionID:V.scope.sessionID,order:++q,accountId:V.accountId,...V2===void 0?{}:{rerouteFrom:V2},...i===void 0?{}:{next:i},...T2===void 0?{}:{wake:T2}});else if(i)await U2(i);if(!Y2.retry)u(V.request);return{decision:Y2,reason:r}});O(),await m2({sessionID:z.sessionID,...V.accountId===void 0?{}:{accountId:V.accountId},kind:V.scope.kind,attempt:z.attempt,reason:Y1,hostDecision:Q,decision:W2,...F2===void 0?{}:{handle:F2}})})},j2));let q2=(z)=>{if(d(z),o.delete(z),!b.get(z)?.foreignSeen)b.delete(z);for(let Q of v)if(JSON.parse(Q)[0]===z)v.delete(Q);for(let Q of[...B.values()]){if(Q.scope.sessionID!==z)continue;C(Q,"its session was forgotten"),u(Q.request),B.delete(Q.id)}for(let[Q,W]of S)if(W.sessionID===z)D2(Q)},y2=new AbortController,g2=$.event;if(g2)(async()=>{try{for await(let z of g2.subscribe({signal:y2.signal}))if(z.type==="session.deleted")q2(z.data.sessionID);else if(z.type==="session.status"&&z.data.status.type==="idle"){let Q=z.data.sessionID,W=++q;N2(Q,async()=>{for(let[T,V]of S)if(V.sessionID===Q&&V.order<W)S.delete(T),u(V.request),await t2(V)})}}catch(z){if(!y2.signal.aborted)m("opencode2 auth stopped listening for session deletion",{error:p(z)})}})();return{on(z,Q){let W=E2.get(z);if(!W)W=new Set,E2.set(z,W);let T=Q;return W.add(T),()=>{W.delete(T)}},accountFor(z,Q){return R(i2(z,Q))?.accountId},forgetSession:q2,get size(){return B.size},async dispose(){if(t)return;t=!0;for(let z of y.keys())d(z);y2.abort();for(let z of B.values())C(z,"the installation was disposed");B.clear();for(let z of S.keys())D2(z);v.clear(),o.clear(),b.clear(),E2.clear(),await Promise.all(R2.values()),await Promise.all(L2.map(async(z)=>{try{await z.dispose()}catch(Q){m("opencode2 auth hook did not dispose cleanly",{error:p(Q)})}}))}}}import{randomUUID as p$}from"node:crypto";import{createHash as M4}from"node:crypto";var _4=1024,T4=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),S$=($)=>b$($,"user"),C4=($)=>T4($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function E4($){return M4("sha256").update(JSON.stringify($)).digest("hex")}class $1{runtime;maxSessions;#$=new Map;constructor($,Z=_4){this.runtime=$;this.maxSessions=Z}advance($,Z,J=this.runtime){let G=this.#$.get($),j=Array.isArray(Z.input)?Z.input:[],Y=j.filter(S$),K=j.findLastIndex(S$),L=K<0?void 0:E4(j[K]),U=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,H,B,M;if(U)H=Y.length>0,B=L??G?.fingerprint,M=G?.userCount===void 0?void 0:G.userCount+Y.length;else{B=L,M=Y.length;let q=K>=0&&K>j.findLastIndex(C4),v=G!==void 0&&!G.completed&&G.fingerprint===B&&G.userCount===M;H=q&&!v}let S=H||!G?{turnID:(J?.uuid??o2)(),turnStartedAt:(J?.now??Date.now)()}:{turnID:G.turnID,turnStartedAt:G.turnStartedAt};return this.#Z($,{...S,completed:!1,fingerprint:B,userCount:M}),S}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 o1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var R$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function O4(){let $=globalThis;return $[R$]??=crypto.randomUUID(),$[R$]}class W1{runtime;store;sessions;frameTurns;installationID;constructor($,Z,J){this.runtime=$;this.store=J;this.installationID=Z??O4(),this.sessions=J?.sessions??new Map,this.frameTurns=J?.frameTurns??new $1}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(E1(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var s1={version:D$,"user-agent":k$,originator:"codex_exec"};var x4=1024,q4=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,x1=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),I$=($)=>x1($)&&($.type==="message"||("role"in $))&&$.role==="user",f$=($)=>x1($)&&$.type==="configuration_update";class r1{http;#$=new Map;constructor($=new W1){this.http=$}apply($,Z,J){if(Z.kind!=="primary")return!1;let G=typeof $.model==="string"?$.model:"";if(!w$.has(G))return!1;if(q4.test(G))return!1;let j=x1($.reasoning)?$.reasoning:void 0,Y=typeof j?.effort==="string"?j.effort:void 0;if(!Y)return!1;let K=this.#$.get(Z.sessionID);if(K===void 0)return this.#Z(Z.sessionID,Y),!1;if(Y===K)return!1;let L=Array.isArray($.input)?$.input:void 0;if(!L||L.length===0)return!1;let U=L.findLastIndex(I$);if(U<0){if(J==="http")return!1;return $.reasoning={...j,effort:K},!0}if($.reasoning={...j,effort:K},!f$(L[U-1]))L.splice(U,0,{type:"configuration_update",reasoning:{effort:Y}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>x4){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function E1($){try{let Z=JSON.parse($);return x1(Z)?Z:void 0}catch{return}}async function v$($,Z,J,G,j=J.http,Y){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let K=await $.clone().text(),L=E1(K);if(L)delete L.max_output_tokens;let U=new Headers($.headers),H=O1({rewriteLite:y$,init:{body:L?JSON.stringify(L):$.body===null?void 0:K},headers:U,metadata:j.get(Z.sessionID),installationID:j.installationID,runtime:j.runtime,websocket:!1,responsesLite:G,applyEffort:(B)=>{if(J.apply(B,Z,"http"),Y&&typeof B.model==="string")Y(B.model)}});return new Request($,{headers:U,body:H.init?.body})}function h$($,Z,J,G){let j=G.sessions.get($.sessionID),Y=G.frameTurns.get($.sessionID);if(!j||!Y)return;let K=o1(j,Y),L=new Headers({"content-type":"application/json"});for(let H of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let B=J.get(H);if(B!==null)L.set(H,B)}O1({init:{body:$.bodyText},headers:L,metadata:K,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 A4($,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&&f$(Z[J])&&I$(Z[J+1])&&JSON.stringify(Z.slice(J+1))===JSON.stringify($.slice(J))}function g$($,Z,J,G){let j=E1($);if(j?.type!=="response.create")return;let Y=J.http.advanceFrame(Z.sessionID,j),K=J.http.get(Z.sessionID);delete j.max_output_tokens;let L=O1({rewriteLite:()=>{},init:{body:JSON.stringify(j)},headers:new Headers,metadata:o1(K,Y),installationID:J.http.installationID,runtime:J.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(H)=>{J.apply(H,Z,"ws")}}),U=E1(String(L.init?.body));if(!U)return;if(G&&typeof U.model==="string")G(U.model);if(!A4(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 S4($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function t1($,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(`${S4(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 m$}from"node:path";var b4=1024;class q1{accounts=new Map;limit;constructor($=b4){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 l$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),u$=globalThis,e1=u$[l$]??new Map;u$[l$]=e1;function $$($){let Z=JSON.stringify([m$($.configPath),m$($.statePath)]),J=e1.get(Z);if(!J)J=new q1,e1.set(Z,J);return J}var b2="openai",z1=10;var Z$=1,R4="request refused: no account with a usable credential",K2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function D4($){let Z=K2($)?$.counters:void 0,J=K2(Z)?Z.resetCredits:void 0,G=K2(J)?J.value:void 0;return typeof G==="number"&&Number.isFinite(G)?G:void 0}function U1($){try{return JSON.parse($)}catch{return}}function V1($){let Z=b1($);return Z?R1(Z):void 0}var k4=new Set(["usage_limit_reached","rate_limit_exceeded"]);function N1($,Z,J,G){return{reason:$.window,windows:GZ($,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 KZ($,Z,J){if($.type!=="response.failed"){let Y=S1($,Z),K=typeof $.status==="number"?$.status:void 0;return Y?N1(Y,Z,K,J):void 0}if(!K2($.response))return;let G=$.response.failed;if(K2(G)&&typeof G.rate_limit_reached_type==="string")return N1({window:G.rate_limit_reached_type},Z,void 0,J);let j=$.response.error;if(K2(j)){let Y=typeof j.code==="string"?j.code:typeof j.type==="string"?j.type:void 0;if(Y&&k4.has(Y)){let K=typeof $.status==="number"?$.status:void 0,L=S1({error:{...j,type:Y},status:K},Z);return N1(L??{window:Y},Z,K,J)}}return}function PZ($,Z,J){return LZ(U1($),Z,J)}function LZ($,Z,J){if(!K2($))return;let G=typeof $.type==="string"?$.type:void 0;if(G==="codex.rate_limits")return{quota:{snapshot:o$($),complete:!0}};let j=KZ($,Z,J);if(j)return{limit:j};if(G===void 0||G==="error")return;return HZ(G)?void 0:{outputStarted:!0}}function w4($){let Z=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:a$($),complete:n$($)}}function y4($){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 MZ($){let Z=new WeakMap,J=new WeakSet,G=new WeakMap,j=new Map,Y=(X)=>{if(X?.data?.kind!=="vault"||!X.data.receipt.credentialId||!S2())return;let N=X.data.receipt;return(C)=>{let F=`${X.sessionID}\x00${X.kind}`,R=(j.get(F)??0)+1;if(j.set(F,R),j.size>n2){let x=j.keys().next().value;if(x!==void 0)j.delete(x)}G.set(X,new k1(X.sessionID,N,X.kind,C,R,$.cacheWarming,X.data?.kind==="vault"&&X.data.freeQuota))}},{source:K,pins:L}=$,U=$.now??Date.now,H=$.log,B=$.vault,M=$.limits,S=p$(),q=new WeakMap,v=new Map,o=(X,N)=>s2(N?B?.routes().find((C)=>C.id===X)?.quota:K.peek().rows.find((C)=>C.id===X)?.quota),b=new r1($.codex),D=new Map,P2=(X)=>{for(let N of j.keys())if(N.startsWith(`${X}\x00`))j.delete(N);for(let[N,C]of D)if(C===X)D.delete(N)},Q2=new Map,h=new Map,a=(X)=>`${X.sessionID}\x00${X.kind}`,E2=new Map,z2=new Map,t=(X)=>{let N=z2.get(X);if(N)clearTimeout(N.timer);z2.delete(X)},y=(X,N,C)=>{let F=p({...X,accountId:N});t(F);let R={request:C,sessionID:X.sessionID,expiresAt:performance.now()+5000,timer:setTimeout(()=>{if(z2.get(F)===R)t(F)},5000)};if(R.timer.unref(),z2.set(F,R),z2.size>n2){let x=z2.keys().next().value;if(x!==void 0)t(x)}},m=(X)=>{let N=z2.get(X);return t(X),N&&performance.now()<N.expiresAt?N.request:void 0},p=(X)=>`${X.sessionID}\x00${X.kind}\x00${X.accountId}`,u=$.sessionAccounts??new q1,O2=new zZ,x2=(X,N,C)=>{let F=C?[]:FZ(K.peek().rows,X,N,B?.identities()??new Set),R=(B?.routes()??[]).filter((x)=>x.kind==="oauth"&&s$(s2(x.quota),X,N));return[...F.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota,row:x})),...R.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota}))]},R2=(X,N,C)=>{let F=$Z(X,N,C),R=X.map((f)=>({id:f.id,kind:"oauth",...H1(f.quota)?{quota:f.quota}:{}})),x=X.flatMap((f)=>f.row?[f.row]:[]),A=new Set(X.filter((f)=>!f.row).map((f)=>f.id)),k=M?.marks()??new Map;return{rows:R,now:C,rateLimitMarks:k,refreshBackoff:K.refreshBackoffFor(x),killswitch:F,requestPull:(f)=>A.has(f)?B?.requestReading(f):K.requestReading(f)}},N2=(X,N,C,F,R,x)=>{let A=F1({...X,rows:X.rows.filter((f)=>!C.has(f.id)),placement:j$(N),mainId:R});if(A.kind==="block"){H?.debug("pool admission refused the request",{reason:A.block.reason});return}let k=A.order.filter((f)=>!C.has(f));if(x)for(let f of k){let d=A.tiers[f];if(d)x.set(f,d)}if(F!==void 0&&k.includes(F))return F;return k[0]},u2=(X,N)=>{let C=new Map(X.map((F)=>[F.id,F.quota]));return{requestBytes:Z$,reservePercent:(F)=>J$(N,F===G$?void 0:F),resetCredits:(F)=>D4(C.get(F))}},U2=(X,N,C,F,R,x,A,k,f)=>{let d=u2(N,C),P=Y$(X),g=(H2,B2)=>D1(A,{sessionId:F,requestBytes:Z$,validPinnedAccountIds:X.rows.map((c)=>c.id).filter((c)=>!P.excluded.has(c)),excludeAccountIds:H2,quotaCheckedAtByAccount:Object.fromEntries(X.rows.map((c)=>[c.id,P.projections.get(c.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(N.map((c)=>[c.id,c.identity])),select:(c)=>{let $2=k?{accountId:k,source:"mode-fallback",quotaCheckedAt:P.projections.get(k)?.checkedAt}:JZ(X,d,new Set(H2),c);if($2&&"tier"in $2)f?.set($2.accountId,$2.tier);return $2},persist:B2},(c,$2)=>A.set(c,$2)),s=[...R],e=g(s,x);if(!e)return;let X2=e.accountId,G2=Q$(X,d,X2);if(G2.kind==="serve")f?.set(X2,G2.tier);else f?.delete(X2);if(G2.kind==="none")return;if(G2.kind==="move"){let H2=g([...s,X2],x);if(H2)return H2.accountId;return G2.reason==="killswitch"?void 0:X2}if(G2.kind==="detour")return g([...s,X2],!1)?.accountId;return X2},D2={providerID:b2,async retrySameAccount(X){if(X.continuation!=="interrupted-read")return;let N=h.get(a(X));if(h.delete(a(X)),!N||N.accountId!==X.accountId||N.modelID!==X.modelID||N.agent!==X.agent||X.limit)return;let C=B!==void 0&&await B.authority()!=="local",F=await $.storage();if(!C&&!(await K.current()).active)return;let R=U(),x=x2(F,R,C),A=x.find((P)=>P.id===X.accountId);if(!A)return;let k=R2(x,F,R),f=F?.routing?.mode??"main-first";if(f==="sticky-balanced"){let P=Q$(k,u2(x,F),X.accountId);if(P.kind!=="serve"&&P.kind!=="last-path")return}else{let P=F1({...k,placement:j$(f),...C?{mainId:X$(B?.routes()??[])}:{}});if(P.kind==="block"||!P.order.includes(X.accountId))return}let d=N.data;if(A.row){if(d?.kind!=="pool")return;let P=K.usableToken(A.row),g=A.row.identity??(P&&V1(P));if(!P||!d.identity||g!==d.identity)return}else{if(d?.kind!=="vault"||!B)return;let P=await B.authorize(X.accountId);if(!P||P.credentialId!==d.credentialId||P.accountIdentity!==d.accountIdentity||(P.accountIdentity??V1(P.accessToken))!==d.wireIdentity||A.identity!==void 0&&A.identity!==d.wireIdentity)return}return{accountId:X.accountId}},dropSameAccountRetry(){},dropChoice(X){let N=p(X);t(N),E2.get(N)?.drop(),E2.delete(N),Q2.delete(N)},chooseAccount:async(X)=>{let N,C=await B?.authority(),F=await $.storage(),R=C!==void 0&&C!=="local",x=()=>{throw new _2({kind:"no-account",providerID:b2,sessionID:X.sessionID,requestKind:X.kind,message:w1})};if(R){let _=performance.now()+y1;await $.awaitVaultRoster?.(),N=await M?.forRequest(_)}else{if(N=await M?.forRequest(),!(await K.current()).active){if(await $.slotPlaceholderWithoutMain?.())x();H?.warn("the account pool does not serve requests yet; refusing the request",{kind:X.kind});return}await K.prepareTokens(K.peek().rows,F)}let A=U(),k=x2(F,A,R),f=ZZ(R2(k.filter((_)=>_.id!==X.rerouteFrom?.accountId),F,A));if(f)await f,A=U(),k=x2(F,A,R);let d=new Map(k.map((_)=>[_.id,_])),P=R2(k,F,A),g=S2()?new Map:void 0,s=F?.routing?.maxSameAccountWait,e=JSON.stringify([X.sessionID,X.kind]),X2=[...D.values()].includes(X.sessionID),G2=M?.activity.get(X.sessionID),H2=G2&&M?.accountKey(G2.accountKey.accountId),B2=X.previousAccountId??X.rerouteFrom?.accountId,c=B2&&M?.accountKey(B2),$2=X.rerouteFrom?.limit,w2=k.flatMap((_)=>{let E=M?.accountKey(_.id);if(!E)return[];let O=s2(_.quota),w=XZ($2&&_.id===B2?{account:E,kind:"rate-limit",reason:$2.reason,scope:{kind:"pool"},windows:$2.windows??[],observedAt:$2.observedAt??A}:void 0,O,A),I=P.rateLimitMarks.get(_.id),l=P.refreshBackoff.get(_.id),A2=[...I&&I>A?[{kind:"hard",until:I,cause:"rate-limit"}]:[],...l&&l>A?[{kind:"cooldown",until:l}]:[]],F2=P.killswitch.get(_.id)!==!1&&!!(O?.primary||O?.secondary)&&!d$(c$(H1(_.quota)?_.quota:void 0),A)&&!(l&&l>A)&&(!_.row||!!K.usableToken(_.row));return[{account:E,admitted:F2,placementEligible:F2,ready:F2&&!A2.length&&!w.length,blockers:A2,confirmedBlockers:w}]}),p2={phase:X.phase==="retry"?"after-limit":"pre-send",host:"opencode2",hostPhase:X.phase,now:A,clockNow:A,sessionId:X.sessionID,requestScope:{kind:"pool"},history:i$({requestId:X.sessionID,originalUrl:"https://api.openai.com/v1/responses",clockNow:A}),delivery:{owned:!0,attributable:!0,replayable:!0},candidates:w2,...X.phase==="retry"&&c?{attempted:c}:{},...X.phase==="retry"&&c&&$2?{signal:{account:c,kind:"rate-limit",reason:$2.reason,scope:{kind:"pool"},windows:$2.windows??[],observedAt:$2.observedAt??A},status:$2.status}:{},remainingRetries:z1-(X.hostAttempt??z1)},j1=()=>{let _=M?.owner();return YZ({accounts:w2.flatMap((E)=>{let O=d.get(E.account.accountId);if(!O)return[];return[{account:E.account,reading:s2(O.quota),usable:!O.row||!!K.usableToken(O.row),confirmedBlockers:E.confirmedBlockers,floors:r$(F)?J$(F,O.id===G$?void 0:O.id):void 0,marks:_?.snapshot()?.marks.filter((w)=>w.key.window==="account"&&w.key.scope.kind==="pool"&&Z1(w.key.account,E.account)).flatMap((w)=>w.entries.map((I)=>({until:I.until,evidenceAt:I.evidenceAt})))}]}),now:A,effectiveModel:X.modelID,maxSameAccountWait:s,activity:G2,currentAccountKey:H2,provenance:_?.provenance})},j2=w2.find((_)=>c&&Z1(_.account,c));if(X.phase==="retry"&&$2&&j2){let _=B$({candidate:j2,activity:G2,maxSameAccountWait:s,now:A,maxDelayMs:a2}),E=W$({...p2,hold:_},{mode:"sticky"});if(E?.action==="hold"&&!X2)return D.set(e,X.sessionID),{hold:{delayMs:E.delayMs,target:E.target,checkpoint:E.checkpoint,kind:"hold"}};let O=k.filter((I)=>I.id!==B2);if(j2.confirmedBlockers?.some((I)=>I.confirmed)&&O.length>0&&O.every((I)=>{let l=w2.find((A2)=>A2.account.accountId===I.id);return l&&(!l.admitted||(P.rateLimitMarks.get(I.id)??0)>A)})){if(X2)return{hostRetry:"veto"};let I=V$(p2,j1());if(z$(s)===0)return{hostRetry:"veto"};let l="delayMs"in I?I.delayMs:("retryAfterMs"in I)?I.retryAfterMs:void 0;if((p2.remainingRetries??0)<1||l===void 0||l>a2)return{hostRetry:"leave"};if(I.action==="hold"&&Z1(I.account,j2.account))return D.set(e,X.sessionID),{hold:{delayMs:l,target:I.target,checkpoint:I.checkpoint,kind:"terminal"}};return D.set(e,X.sessionID),{waitThenReselect:{delayMs:l}}}}let L2;if(X.phase==="request"&&X.wake?.checkpoint&&j2&&(X.hostAttempt??z1)<z1&&z$(s)!==0&&Z1(j2.account,X.wake.checkpoint.accountKey)){let _=X.wake.checkpoint,E=new Map(_.blockers.map((l)=>[l.window,{...l,confirmed:!0,confirmedByReading:!1,observedAt:_.decidedAt,provenance:"provider"}]));for(let l of j2.confirmedBlockers??[])E.set(l.window,l);let O={...j2,confirmedBlockers:[...E.values()]},w=B$({candidate:O,activity:G2,maxSameAccountWait:s,now:A,maxDelayMs:a2});if(W$({...p2,attempted:j2.account,candidates:w2.map((l)=>l===j2?O:l),hold:w,wake:{...X.wake,checkpoint:_}},{mode:"sticky"})?.action==="retain")L2=j2.account.accountId}let c2=new Set(X.rerouteFrom?[X.rerouteFrom.accountId]:[]),q2=F?.routing?.mode??"main-first",y2=X.kind==="primary",g2=new Set,z,Q,W,T=!1,V=(_)=>{let E=Y$(P).projections.get(_)?.checkedAt,O=d.get(_)?.identity;return L.reserve(X.sessionID,{accountId:_,inputBytes:Z$,...E!==void 0?{quotaCheckedAt:E}:{},...O!==void 0?{wireIdentity:O}:{}})};try{for(;;){let _=new Set([...c2,...g2]);W=void 0,g?.clear(),z=void 0;let E=q2!=="sticky-balanced";if(L2&&!_.has(L2))W=L2,L2=void 0;else if(q2==="sticky-balanced"){let w=new Map(L.placementSnapshot(X.sessionID)),I=w.get(X.sessionID);if(E=I===void 0,W=U2(P,k,F,X.sessionID,_,y2&&g2.size===0,w,void 0,g),W!==void 0&&w.get(X.sessionID)!==I)z=w.get(X.sessionID)}if(W??=N2(P,q2,_,y2?void 0:u.activeAccount(X.sessionID),R?q2==="sticky-balanced"?null:X$(B?.routes()??[]):void 0,g),W===void 0||g2.has(W)){if(c2.size>0){let w=new Map(P.rateLimitMarks);for(let I of c2)w.delete(I);P={...P,rateLimitMarks:w},c2.clear();continue}if(P.rateLimitMarks.size>0){P={...P,rateLimitMarks:new Map};continue}W=void 0;break}if(y2&&q2==="sticky-balanced")Q=V(W);if(!T){T=!0;let w=X.wake?void 0:await VZ({vaultMode:R,fresh:E,sessionId:X.sessionID,request:{modelId:X.modelID,kind:X.kind,retry:X.phase==="retry"||X.rerouteFrom!==void 0},routes:B?.routes()??[],routing:P,wait:{activity:G2,accountKey:H2,maxSameAccountWait:s},eligibleIds:k.filter((I)=>!_.has(I.id)).map((I)=>I.id)});if(w&&w!==W){if(Q)L.rollback(Q);if(Q=void 0,q2==="sticky-balanced"){let I=new Map(L.placementSnapshot(X.sessionID));W=U2(P,k,F,X.sessionID,_,y2,I,w,g)??W,z=I.get(X.sessionID)??z}else W=w;if(y2&&q2==="sticky-balanced")Q=V(W)}}let O=d.get(W)?.row;if(O){if(K.usableToken(O)!==void 0)break;H?.debug("pool row holds no usable token; choosing again",{accountId:W})}else{if(!B)break;let w=await B.authorize(W);if(w){Q2.set(p({...X,accountId:W}),{receipt:w,freeQuota:g?.get(W)==="free"});break}H?.debug("the vault refused to serve an account; choosing again",{accountId:W})}if(Q)L.rollback(Q);Q=void 0,g2.add(W)}if(W===void 0&&!R&&k.length===0&&await $.slotPlaceholderWithoutMain?.())x();if(W===void 0&&R&&B&&(k.length===0||g2.size>0)){let _=g2.size>0?"vault-refused":e$(B);throw H?.warn("vault mode: no vault account can serve; refusing the request",{cause:_}),new _2({kind:"no-account",providerID:b2,sessionID:X.sessionID,requestKind:X.kind,message:t$(_,B.name)})}if(W!==void 0){if(N)y(X,W,N);let _=W,E=Q,O=z,w=()=>{if(E)L.finish(E,O);if(y2)u.record(X.sessionID,_),$.onRoute?.(X.sessionID,_,q2)};if(X.phase==="retry")E2.set(p({...X,accountId:W}),{commit:w,drop:()=>{if(E)L.rollback(E)}}),Q=void 0;else w();let I=H?.info;O2.served(P,W,H&&I?{info:(l,A2)=>I.call(H,l,A2)}:void 0)}if(W===void 0&&X.phase==="request"&&w2.length>0&&w2.every((_)=>!_.admitted)&&w2.some((_)=>P.killswitch.get(_.account.accountId)===!1||_.confirmedBlockers?.length)){let _=V$(p2,j1()),E=QZ({decision:_,now:A,host:"opencode2",requestThrow:!0,maxSameAccountWait:s});if(E.kind==="http"){let O=JSON.parse(E.body);throw new _2({kind:"no-account",providerID:b2,sessionID:X.sessionID,requestKind:X.kind,message:O.error.message})}}return H?.debug("pool account chosen",{kind:X.kind,accountId:W,mode:q2,...X.rerouteFrom?{rerouteFrom:X.rerouteFrom.accountId}:{}}),W}finally{if(Q)L.rollback(Q)}},accountHeaders:async(X)=>{let{accountId:N}=X;h.delete(a(X));let C=p(X),F=E2.get(C);E2.delete(C);let R=()=>{F?.commit()};try{let x=()=>new _2({kind:"no-account",providerID:b2,sessionID:X.sessionID,requestKind:X.kind,message:R4}),A=async(g)=>{if(!M)return;let s=m(C)??await M.forRequest();if(g.kind==="pool"){let c=K.peek().rows.find(($2)=>$2.id===N);if(!c||c.credentialEpoch!==g.credentialEpoch||K.usableToken(c)!==g.token)throw x()}let e=M.bindings().find((c)=>c.account.accountId===N),X2=await s?.beforeDispatch(e,()=>M.ownershipBindings(),N),G2=M.accountKey(N);if(X2&&X2.status!=="ready"||e&&(!G2||!Z1(e.account,G2)))throw x();let H2=M.owner(),B2=e?{sessionId:X.sessionID,accountKey:e.account,dispatchedAt:U(),ttlMs:BZ(JSON.stringify({model:X.modelID}))}:void 0;if(B2){if(v.delete(B2.sessionId),v.set(B2.sessionId,B2),v.size>n2){let c=v.keys().next().value;if(c!==void 0)v.delete(c)}}q.set(g,{owner:H2,probe:H2?.observe(e),dispatch:B2,failed:!1,completed:!1})},k=B&&await B.authority()!=="local"?void 0:K.peek().rows.find((g)=>g.id===N);if(!k&&B){let g=p(X),s=Q2.get(g),e=s?.receipt??await B.authorize(N);if(Q2.delete(g),!e)throw H?.warn("the vault refused to serve an account; refusing the request",{accountId:N}),x();let X2={kind:"vault",routeId:N,receipt:e,...s?.freeQuota?{freeQuota:!0}:{}};return await A(X2),R(),{headers:{...s1,"session-id":X.sessionID,authorization:`Bearer ${e.accessToken}`,"chatgpt-account-id":e.accountIdentity??V1(e.accessToken)??null},attempt:X2}}let f=k?K.usableToken(k):void 0;if(!k||!f)throw H?.warn("pool row holds no usable token; refusing the request",{accountId:N}),x();let d=k.identity??V1(f),P={kind:"pool",token:f,credentialEpoch:k.credentialEpoch,...d!==void 0?{identity:d}:{}};return await A(P),R(),{headers:{...s1,"session-id":X.sessionID,authorization:`Bearer ${f}`,"chatgpt-account-id":d??null},attempt:P}}finally{F?.drop()}},async rewriteRequest({request:X,sessionID:N,kind:C,attempt:F}){let R=$.codexEndpoint?t1(X.url,$.codexEndpoint()):X.url,x=R===X.url?X:new Request(R,X);return await v$(x,{sessionID:N,kind:C},b,$.responsesLite?.()??!1,void 0,Y(F))??x},rewriteHandshakeURL:({url:X})=>$.codexEndpoint?t1(X,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:X,sessionID:N,kind:C,attempt:F})=>g$(X,{sessionID:N,kind:C},b,Y(F)),quotaFromHeaders:(X,N,C)=>{if(C.data?.kind==="vault")B?.reportUsage(C.data.routeId,{headers:X},C.data.receipt);if(C.data?.kind==="vault"&&S2()&&N>=200&&N<300)Z.set(C,{status:N,headers:X});return w4(X)},async limitFromResponse({status:X,headers:N,body:C,attempt:F}){if(X<400)return;let R=U1(await C().catch(()=>"")),x=U(),A=S1({...K2(R)?R:{},status:X},x);if(F.data?.kind==="vault"&&S2())A1(F.sessionID,F.data.receipt,{status:X,headers:N,body:R,limit:A,quota:B?.routes().find((d)=>d.id===F.accountId)?.quota,now:U()});if(!A)return;let k=N1(A,x,X,o(F.accountId,F.data?.kind==="vault"));if(k.retryAfterMs!==void 0)return k;let f=y4(N);return f===void 0?k:{...k,retryAfterMs:f,resetAt:x+f,resetSource:"retry-after"}},inspectEvent:({data:X,transport:N,attempt:C})=>{let F=U1(X),R=!1,x=C.data&&q.get(C.data);if(x&&K2(F)&&(F.type==="response.failed"||F.type==="error"))x.failed=!0;if(x&&K2(F)&&F.type==="response.completed")x.completed=!0;if(C.data?.kind==="vault"&&X.includes("codex.rate_limits")){let k=U1(X);if(K2(k)&&k.type==="codex.rate_limits")B?.reportUsage(C.data.routeId,{frame:k},C.data.receipt)}if(C.data?.kind==="vault"&&S2()){let k=G.get(C);if(k)k.event(F),R=N==="ws"&&K2(F)&&(F.type==="response.incomplete"||F.type==="response.failed"||F.type==="error");if(NZ(X)||N==="ws"&&X.includes('"response.completed"')){if(UZ(F))J.add(C);if(N==="ws"&&K2(F)&&F.type==="response.completed")A1(C.sessionID,C.data.receipt,{status:200,headers:new Headers,failed:J.has(C)})}}let A=LZ(F,U(),o(C.accountId,C.data?.kind==="vault"));return R||N==="ws"&&K2(F)&&F.type==="response.completed"?{...A,done:!0}:A},limitFromError(X,N){let C=U1(X.message),F=U(),R=o(N.accountId,N.data?.kind==="vault");return KZ({...K2(C)?C:{},...X.status!==void 0?{status:X.status}:{}},F,R)??(X.message.includes("usage_limit_reached")?N1({window:"usage_limit_reached"},F,X.status,R):void 0)},async onAttemptEnd(X,N){let C=X.data?.kind==="vault"&&S2()?G.get(X):void 0;if(C)G.delete(X),C.end(N.outputStarted,!N.error,N.status,N.error?.reason==="cancelled");let F=X.data,R=F&&q.get(F);if(R){let A=!N.error&&!N.limit&&!R.failed&&(X.transport==="ws"?R.completed:N.status!==void 0&&N.status>=200&&N.status<300);if(A&&R.dispatch&&M){let k=v.get(R.dispatch.sessionId);WZ(M.activity,R.dispatch,k===R.dispatch?M.accountKey(X.accountId):void 0,X.transport==="ws"?{kind:"ws",event:"response.completed",aborted:!1}:{kind:"http",completed:!0,failed:!1,aborted:!1})}R.owner?.afterProbe(R.probe,A,Boolean(N.limit))}if(F&&N.outputStarted&&N.error?.reason==="failed"){if(h.set(a(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??V1(F.receipt.accessToken)}}),h.size>n2){let A=h.keys().next().value;if(A!==void 0)h.delete(A)}}let x=F?.kind==="vault"&&S2()?Z.get(X):void 0;if(Z.delete(X),F?.kind==="vault"&&x&&!N.error&&!N.limit)A1(X.sessionID,F.receipt,{...x,failed:J.has(X)});if(F?.kind!=="vault"||N.status!==401)return;H?.warn("a vault account answered 401; reporting it to the vault",{accountId:X.accountId}),await B?.reportFailure(F.receipt,401)}},h2=(X,N,C)=>{let F=C.data;if(F?.kind==="vault"){B?.recordSnapshot(X,N.snapshot,N.complete,F.receipt);return}if(F?.kind!=="pool")return;if(K.peek().rows.find((x)=>x.id===X)?.credentialEpoch!==F.credentialEpoch){H?.debug("quota reading dropped: the row holds another credential",{accountId:X});return}K.recordSnapshot(X,N.snapshot,F.token,N.complete)},m2=(X,N,C)=>{let F=U(),R=C.data?.kind==="vault";if(M){let x=C.data&&q.get(C.data),A=x?.owner??M.owner();if(!A)return;if(!x?.probe||A.registry!==x.probe.registry){A.dropSignal();return}let k=N,{command:f,provenance:d}=jZ({binding:x.probe.binding,baseRevision:x.probe.baseRevision,producerId:S,operationId:p$(),parsed:{window:N.reason,resetAt:k.resetAt??(N.retryAfterMs!==void 0?F+N.retryAfterMs:void 0)},reading:o(X,R),now:F,observedAt:k.observedAt??F,evidenceAt:F,resetSource:k.resetSource});A.enqueue(f,d);return}};return{adapter:D2,beginTurn:P2,dispose:()=>{D.clear(),j.clear()},attach(X){X.on("quota",(N)=>h2(N.accountId,N.quota,N.handle)),X.on("limit",(N)=>{m2(N.accountId,N.limit,N.handle),H?.debug("pool row refused the request",{accountId:N.accountId,via:N.via,reason:N.limit.reason,outputStarted:N.outputStarted})})},forgetSession(X){P2(X);for(let[N,C]of z2)if(C.sessionID===X)t(N);v.delete(X),M?.forget(X);for(let[N,C]of h)if(C.sessionID===X)h.delete(N);L.forget(X),u.forget(X),b.forget(X)},activeAccount:(X)=>u.activeAccount(X)}}import{resolve as v1}from"node:path";function _Z($,Z){if(!Z.ok||!Z.body)return $.end(!1,!0,Z.status),Z;let J=!1,j=Z.body.pipeThrough(B1((Y)=>{J||=PZ(Y.data,Date.now())?.outputStarted===!0;try{$.event(JSON.parse(Y.data))}catch{}},()=>{})).getReader();return new Response(new ReadableStream({async pull(Y){try{let K=await j.read();if(K.done)Y.close(),$.end(J,!0,Z.status);else Y.enqueue(K.value)}catch(K){Y.error(K),$.end(J,!1,Z.status)}},cancel(Y){return $.end(J,!1,Z.status),j.cancel(Y)}}),{status:Z.status,statusText:Z.statusText,headers:Z.headers})}import{Buffer as I4}from"node:buffer";import{resolve as TZ}from"node:path";function K1($){return I4.byteLength(JSON.stringify($))}function f4($){return $.reduce((Z,J)=>Z+K1(J),0)}function U$($,Z){return 2+$+Math.max(0,Z-1)}function v4($){let{head:Z,pending:J}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+U$(Z.inputBytes,Z.input.length)+1:0)+(J?20+U$(J.inputBytes,J.input.length)+10+U$(J.outputBytes,J.output.length)+(J.responseID===void 0?0:14+J.responseIDBytes)+1:0)}function CZ($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class EZ{enabled;caps=I1;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$){for(let Z of this.entries.keys())if(!r2(Z,$))this.forget(Z)}}send($,Z){if(!r2($,this.enabled)){this.forget($);return}let J=CZ(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($),Y=j?.head;if(G&&G!==Y?.responseID){this.forget($);return}let{type:K,previous_response_id:L,input:U,...H}=J;this.keep($,{fields:G&&j?j.fields:H,fieldsBytes:G&&j?j.fieldsBytes:K1(H),...G&&Y?{head:Y}:{},pending:{input:U,inputBytes:f4(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")||!r2($,this.enabled))return;let G=this.entries.get($);if(!G?.pending)return;let j=CZ(Z);if(!j)return;let Y=G.pending,K=j.response;if(j.type==="response.created"&&typeof K?.id==="string")Y.responseID=K.id,Y.responseIDBytes=K1(K.id),this.keep($,G);else if(j.type==="response.output_item.done"&&j.item){if(typeof j.response_id==="string"&&Y.responseID!==void 0&&j.response_id!==Y.responseID)return;Y.output.push(j.item),Y.outputBytes+=K1(j.item),this.keep($,G)}else if(j.type==="response.completed"&&typeof K?.id==="string"){if(K.id===G.head?.responseID||Y.responseID!==void 0&&K.id!==Y.responseID)return;let L={responseID:K.id,responseIDBytes:Y.responseID===K.id?Y.responseIDBytes:K1(K.id),input:[...G.head?.input??[],...Y.input,...Y.output],inputBytes:(G.head?.inputBytes??0)+Y.inputBytes+Y.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=v4(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 OZ=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),xZ=globalThis,N$=xZ[OZ]??new Map;xZ[OZ]=N$;function f1($){let Z=JSON.stringify([TZ($.configPath),TZ($.statePath)]),J=N$.get(Z);if(!J)J=new EZ,N$.set(Z,J);return J}var h4=5000,g4=["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"],m4=["x-opencode-parent-session-id","x-parent-session-id"];function bZ($){let Z=qZ($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:AZ($?{...$,cachekeep:Z}:$)}}var RZ=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),DZ=globalThis,J1=DZ[RZ]??new Map;DZ[RZ]=J1;function kZ($,Z){let J=JSON.stringify([v1($.configPath),v1($.statePath)]);return J1.get(J)?.manager.warming(Z)??{on:!1}}function l4($,Z){let J=[],G=()=>J.at(-1)?.location,j=()=>{let U=G();if(!U)throw Error("no location holds keep-warm");return U},Y=(U,H)=>{L.remove(U),G()?.log?.debug(`cachekeep dropped target (${H})`,{sessionKey:U})},K=async(U)=>{if(U.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let H=U.accountId??"main",B=j(),M=await B.source.accessFor(H,await B.storage());if(!M)throw Error(`pool row ${H} has no usable token`);return{token:M.token,identity:M.row.identity}},L=SZ({observeBillingSend(U,H,B,M){if(!B.credentialId||!S2())return;let S=U.meta.routingSessionId;if(!S)return;let q;try{q=JSON.parse(H).model}catch{return}if(typeof q!=="string")return;let v=j().vault.routes().find((D)=>D.id===U.accountId),o=F1({rows:v?[{id:v.id,kind:"oauth",...H1(v.quota)?{quota:v.quota}:{}}]:[],now:$.now(),placement:"roster",mainId:null,rateLimitMarks:new Map,refreshBackoff:new Map,killswitch:new Map,requestPull:()=>{}}),b=new k1(S,B,"keep_warm",q,M,(D)=>L.warming(D),v!==void 0&&o.kind==="send"&&o.tiers[v.id]==="free");return{response:(D)=>_Z(b,D),failed:()=>b.end(!1,!1)}},...I1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(U,H)=>j().fetch(U,H),logger:{debug:(U,H)=>G()?.log?.debug(U,H),warn:(U,H)=>G()?.log?.warn(U,H)},getWindow:()=>G()?.settings().window,getSustain:()=>G()?.settings().sustain===!0,resolveLocal:K,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 H=G(),B=U.meta.routingSessionId??U.sessionKey,M=U.accountId??"main";return H?.accounts.activeAccount(B)===M?H.limits?.accountKey(M):void 0}},vault:{owns:(U)=>G()?.vault.owns(U)===!0,authority:()=>j().vault.authority(),reportUsage:(...U)=>G()?.vault.reportUsage(...U),send:async(U,H,B)=>{let M=j(),S=await M.vault.authority();if(S!=="vault"&&S!=="host")return;return M.vault.send(U,H,B)}},activeAccount:(U)=>{if(U===void 0)throw Error("target has no session");let H=G(),B=H?.settings();if(!H||!B||!r2(U,B.enabled)){Y(U,"keep-warm is off");return}if(!B.subagents&&L.status().targets.some((S)=>S.sessionKey===U&&S.isSubagent)){Y(U,"subagent warming is off");return}let M=H.accounts.activeAccount(U);if(M===void 0){Y(U,"no account recorded for the session");return}return M},verifyCredential:({target:U,mode:H,identity:B})=>{if(U.meta.credentialMode!==H)throw Error(`a target captured in ${U.meta.credentialMode??"an unknown"} mode is not warmed with a ${H} credential`);if(B!==U.meta.chatgptAccountId)throw Y(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??h4}}function u4($){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 p4($){let Z={};for(let J of g4){let G=$.get(J);if(G)Z[J]=G}return Z}function wZ($,Z,J){let G=JSON.stringify([v1($.configPath),v1($.statePath)]),j=J1.get(G);if(!j)j=l4(J,Z.settings()),J1.set(G,j);let Y=j,K=f1($);K.setEnabled(Y.settings.enabled);let L={location:{...Z,settings:()=>Y.settings}};Y.holders.push(L);let U=!1,H=async(B)=>{try{let M=L.location.settings();if(U||!r2(B.sessionID,M.enabled))return;if(B.kind!=="primary"){if(B.kind==="generate"&&u4(await B.request.clone().text())){if(U)return;Y.manager.remove(B.sessionID)}return}let S=B.attempt.data,q=S?.kind==="pool"?"local":S?.kind==="vault"?"vault":void 0;if(!q)return;let v=B.request.headers,o=m4.some((P2)=>v.has(P2))||Z.parentOf!==void 0&&await Z.parentOf(B.sessionID)!==void 0;if(o&&!M.subagents)return;let b=await B.request.clone().text();if(U)return;let D=v.get("chatgpt-account-id")??void 0;Y.manager.track({sessionKey:B.sessionID,bodyText:b,accountId:B.attempt.accountId,isSubagent:o,meta:{replayHeaders:p4(v),...D?{chatgptAccountId:D}:{},routingSessionId:B.sessionID,url:B.request.url,credentialMode:q}})}catch(M){Z.log?.warn("cachekeep capture failed",{error:M instanceof Error?M.message:String(M)})}};return{manager:Y.manager,configure:(B)=>{Object.assign(Y.settings,B),K.setEnabled(Y.settings.enabled)},capture:H,forget:(B)=>Y.manager.remove(B),async release(){if(U)return;U=!0;let B=Y.holders.indexOf(L);if(B>=0)Y.holders.splice(B,1);if(Y.holders.length>0)return;if(J1.get(G)===Y)J1.delete(G);Y.manager.stop();let M;try{await Promise.race([Y.manager.tick().catch(()=>{}),new Promise((S)=>{M=setTimeout(S,Y.joinTimeoutMs),M.unref?.()})])}finally{clearTimeout(M)}}}}import{mkdirSync as c4}from"node:fs";import{dirname as d4,resolve as i4}from"node:path";function a4(){return yZ("opencode2")}var n4=2000;class gZ{path;options;sessions;frameTurns=new $1;#$=new Set;#Z=new Set;#J=new Set;#G=Promise.resolve();#X=!1;#z;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=vZ($,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??n4),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{$=H$(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(c4(d4(this.path),{recursive:!0}),J=await this.#B(),!J)return;let G;try{G=H$(this.path)}catch{G=new Map}await this.options.afterRead?.();let j=!1;for(let Y of Z)if(G.delete(Y))j=!0;for(let[Y,K]of $){if(G.get(Y)===K.threadID)continue;G.set(Y,K.threadID),j=!0}if(j)hZ(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 fZ(this.path,this.options.lockWaitMs??IZ)}}var mZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),lZ=globalThis,h1=lZ[mZ]??new Map;lZ[mZ]=h1;function o4($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.sessions instanceof Map&&typeof Z.get==="function"&&typeof Z.delete==="function"&&typeof Z.save==="function"&&typeof Z.settled==="function"&&(Z.frameTurns===void 0||Z.frameTurns!==null&&typeof Z.frameTurns.advance==="function"&&typeof Z.frameTurns.get==="function"&&typeof Z.frameTurns.completed==="function"&&typeof Z.frameTurns.forget==="function")}function uZ($=a4()){let Z=i4($),J=h1,G=h1.get(Z),j=h1;if(G!==void 0&&!o4(G))J.compatible??=new Map,j=J.compatible;let Y=j.get(Z);if(!Y)Y=new gZ(Z),j.set(Z,Y);let K=Y;return K.frameTurns??=new $1,Y}var F$=Symbol.for("cortexkit.openai-auth.v2.commands"),s4=v2("v2-command");function g1($){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 K$($){s4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function r4(){let $=globalThis;return $[F$]??={locations:new Map},$[F$].locations??=new Map,$[F$]}async function oZ($,Z){let J=r4(),G=$.location.directory,j={menu:Z,session:$.session,closed:new AbortController},Y=await cZ(G),K=await pZ(aZ,Y.dir,()=>nZ({...Y,drain:iZ,apply:(M)=>{let S=J.locations.get(G);if(!g1(S))throw Error("The OpenAI menu location was closed");return S.menu.apply(M)}})),L=J.locations.get(G);if(J.locations.set(G,j),g1(L))L.closed.abort(),await L.registration?.dispose();let U={name:"openai",description:"OpenAI account menu",async execute(M){let S=[...J.locations.values()].find(g1)?.session;if(!S)return K$("no live location");let q=await S.get({sessionID:M.sessionID}),v=J.locations.get(q.location.directory);if(!g1(v))return K$("location closed");let o=await dZ(M.sessionID,v.closed.signal);if(!o||J.locations.get(q.location.directory)!==v){if(!o&&!v.closed.signal.aborted)P$({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},M.sessionID);return K$(v.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let b=await v.menu.open(M.sessionID);P$(b,M.sessionID)}};J.command??=U,J.command.execute=U.execute;let H=J.command;try{j.registration=await $.command.transform((M)=>{M.add(H)})}catch(M){if(j.closed.abort(),J.locations.get(G)===j)J.locations.delete(G);throw await K.release(),M}let B=!1;return async()=>{if(B)return;if(B=!0,j.closed.abort(),J.locations.get(G)===j)J.locations.delete(G);await K.release(),await j.registration?.dispose()}}var t4="openai-auth-pool-browser",e4="openai-auth-pool-headless",$5="openai-auth-vault",Z5="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 P1($){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 J0($){return{method:{id:$5,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){let Z=await rZ($.paths,$.name);if(Z==="host"){let J=sZ(eZ);await Promise.resolve(J.close()).catch(()=>{return})}else if(Z!=="vault")throw Error(Z5)}}}function G0($){let Z=(J,G,j)=>({method:{id:J,type:"oauth",label:G},async authorize(){if($.vault)await P1($.vault);let Y=await $.beginLogin({version:$.version,headless:j});return{url:Y.url,instructions:Y.instructions,mode:"auto",callback:Y.completion}}});return[Z(t4,"ChatGPT (openai-auth pool, browser)",!1),Z(e4,"ChatGPT (openai-auth pool, headless)",!0)]}function L$($){let Z=(J)=>typeof J==="string"?J:"";return Q1({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===Z0||tZ($)}function z5($){if($.accountId)return $.accountId;let Z=$.access?b1($.access):void 0;return Z?R1(Z):void 0}async function X0($,Z,J,G={}){if(G.vault)await P1(G.vault);if(L$(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let j=$0($,{rowLocks:(q)=>z0(Z,q)}),Y=await j.read();if(Y.status!=="ready")throw Error(`the account pool cannot be read (${Y.status}); the login was not stored`);let K={type:"oauth",refresh:J.refresh,...J.access!==void 0?{access:J.access}:{},...J.expires!==void 0?{expires:J.expires}:{}},L=z5(J);if(G.vault)await P1(G.vault);let U=L!==void 0?{identity:L}:{};if(G.origin==="import"){let q=Y.rows.find((v)=>L!==void 0&&v.identity===L||v.credential?.type==="oauth"&&v.credential.refresh===J.refresh);if(q)return{id:q.id,operation:"kept"}}let H=Y.rows.filter((q)=>q.type==="oauth"&&!q.invalid),B=L?H.find((q)=>q.identity===L):void 0,M=Y.rows.find((q)=>q.id===m1);if(B)return{id:(await j.replace(B.id,K,U)).id,operation:"replaced"};if(!M){let q=await j.add({id:m1,credential:K,...U,...J.label!==void 0?{label:J.label}:{}});return{id:q.id,operation:q.outcome==="added-disabled"?"added-disabled":"added"}}if(!M.invalid&&!M.credential)return{id:(await j.replace(m1,K,U)).id,operation:"replaced"};let S=await j.add({id:J.id,credential:K,...U,...J.label!==void 0?{label:J.label}:{}});return{id:S.id,operation:S.outcome==="added-disabled"?"added-disabled":S.outcome==="rotated"?"replaced":"added"}}function J5($){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 Q0($){let Z={...$,allowAction:J5,unavailableSections:[]};return{open:(J)=>j0(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(([,Y])=>Y===null||["string","number","boolean"].includes(typeof Y))):void 0;return Y0(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 G5($,Z){if(!B0($.modelID??$.id)){$.enabled=!1;return}let J=W0($.id);if(J)$.limit={...J};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((G)=>[G.id,G])).values()]}function U0($){return $.model.transform((Z)=>{let J=Z.list(b2);for(let G of J){let j=V0(String(G.id)),Y=j?J.find((K)=>String(K.id)===j):void 0;Z.update(b2,String(G.id),(K)=>G5(K,Y?.variants?.map((L)=>({...L,id:String(L.id)}))))}})}class M${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(!N0())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(()=>l1({...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:Y}=Z.error,K=Y?`${j}: ${Y}`:j;await this.safely(()=>l1({...G,error:u1(K,J?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>l1({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 _${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 L0($){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 H0({accessToken:J.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,G),F0(G,$.now(),!0)}}function M0($){let{source:Z,counts:J,now:G}=$,j=async(H)=>{let B=await Z.rowAccess(H,await $.storage());if(!B?.row)throw new K0("unknown_account",`${H==="main"?"Main":"Fallback"} account ${H} was not found.`);return P0(H,B)},Y=async(H)=>{if($.authority&&await $.authority()!=="local")return{account:H,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[B]=await Z.pollRows(await $.storage(),{ids:[H]});if(!B)return{account:H,ok:!1,error:"targeted quota refresh returned no result"};return{account:B.id,ok:B.ok,...B.error!==void 0?{error:B.error}:{}}},K=(H)=>Z.peek().rows.find((B)=>B.id===H),L=(H)=>{let B=K(H);if(!B)return null;let M=s2(B.quota)??{},S=J.applicable(B),q=Math.max(0,...[M.primary?.checkedAt,M.secondary?.checkedAt].filter((v)=>typeof v==="number"));return{quota:{...M,...S!==void 0?{resetCreditsApplicable:S}:{}},checkedAt:q,refreshAfter:q,...B.identity!==void 0?{accountId:B.identity}:{}}};return{resolveResetTarget:j,refreshResetTargetQuota:Y,quotaManager:{isRateLimited:(H)=>{let B=K(H);if(!B)return!1;let M=$.rateLimitMarks().get(B.id);return M!==void 0&&M>G()},getMain:()=>L("main"),getFallback:(H)=>L(H)}}}import{resolve as _0}from"node:path";var X5=1024;class T${pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=X5){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 D1(this.placementSnapshot($.sessionId),$,(Z,J)=>this.set(Z,J))}}var T0=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),C0=globalThis,p1=C0[T0]??new Map;C0[T0]=p1;function j5($){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 E0($){let Z=JSON.stringify([_0($.configPath),_0($.statePath)]),J=p1,G=p1.get(Z);if(G!==void 0&&!j5(G)){let Y=p1;Y.compatibleV1??=new Map,J=Y.compatibleV1}let j=J.get(Z);if(!j)j=new T$,J.set(Z,j);return j}import{statSync as Y5}from"node:fs";import{resolve as Q5}from"node:path";function k0($){return $.map((Z)=>{try{let J=Y5(Z);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}function C$($){return k0([$.vault.paths.tokenPath,$.vault.paths.statePath])}function O0($){return k0([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+C$($)}class w0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;protocol=I0;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:O0($),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,Y)=>{let K=G.values().next().value;if(K)this.publish(K,{sessionId:j,pin:Y,accountId:Y?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,J)}return J.producers.add($),this.timer??=setInterval(()=>{for(let G of this.producers){let j={stamp:O0(G),roster:G.vault.snapshot()},Y=this.observations.get(G);if(j.stamp!==Y?.stamp||j.roster!==Y?.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??y0)(this.file,$,Z,()=>this.producers.has($))}).catch(()=>{v2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var y0=async($,Z,J,G)=>{let Y=await Z.vault.authority()!=="local",K=C$(Z),L=()=>G()&&Z.vault.enrolled()===Y&&C$(Z)===K,U=await(Y?M1(Z.paths):G1(Z.paths)),H=Y?R0(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((S)=>S.id)),U,Date.now()):D0((await Z.source.sidebarView()).rows,U,Date.now()),B={canWrite:L,vaultMode:Y};if(await q0(H,$,B),!L()||!J)return;let M=H.vaultAccounts??H.fallbacks;if(J.accountId===void 0){await S0(J.sessionId,M,$,B);return}if(J.pin){let S=Date.now();await b0({sessionId:J.sessionId,assignment:{accountId:J.pin.accountId,wireAccountId:J.pin.wireIdentity,inputBytes:J.pin.inputBytes??0,quotaCheckedAt:J.pin.quotaCheckedAt,assignedAt:S,lastSeenAt:S},validPinnedAccountIds:[...Y?[]:["main"],...M.filter((q)=>q.enabled).map((q)=>q.id)]},$,B)}await A0({sessionId:J.sessionId,activeId:J.accountId,route:J.route??H.route,updatedAt:Date.now()},M,$,B)},I0=2,f0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),v0=globalThis,L1=v0[f0]??new Map;v0[f0]=L1;function h0($,Z=x0(),J=2000){let G=Q5(Z),j=L1.get(G);if(j?.protocol!==I0)j=new w0(G,J),L1.set(G,j);let Y=j;$={...$,write:$.write??y0};let K=Y.add($),L=!1;for(let[U,H]of $.pins.snapshot())Y.publish($,{sessionId:U,pin:H,accountId:H.accountId,route:"sticky-balanced"});return{publish:()=>Y.publish($),route:(U,H,B)=>{Y.publish($,{sessionId:U,accountId:H,route:B})},async release(){if(L)return;if(L=!0,K(),await Y.settled(),Y.empty&&L1.get(G)===Y)L1.delete(G)}}}var d1="cortexkit-openai-auth",V5=5000;async function g0($,Z,J,G=new W1,j,Y,K){let L=new M$(J),U=new B5,H=new Map,B=new Map,M=(b)=>{B.delete(b);for(let D of H.keys())if(D.startsWith(`${b}:`))H.delete(D)},S=(b)=>{K?.(b.sessionID),Y?.send(b.sessionID,b.frame)},v=await n1({session:{hook:(b,D,P2)=>$.session.hook(b,async(Q2)=>{let h=b==="http.request"?Q2:void 0,a=b==="experimental.ws.handshake"?Q2:void 0,z2=(h?h.request.headers:a?new Headers(a.headers):void 0)?.get("authorization")===`Bearer ${f2(Z.providerID)}`,t={};if(a)H.delete(`${a.sessionID}:${a.kind}`);try{await U.run(t,()=>D(Q2))}catch(y){if(z2&&!(y instanceof _2))throw a0(y);throw y}if(h&&z2&&t.attempt){let y=h.request.headers.get("thread-id");if(y)h.request.headers.set("session-id",y)}if(h&&z2&&t.attempt)await L.captureHttp(h.request,t.attempt);if(h&&z2&&t.attempt)await j?.({sessionID:h.sessionID,kind:h.kind,request:h.request,attempt:t.attempt});if(a&&z2&&t.attempt)a.headers["session-id"]=G.get(a.sessionID).threadID;if(b==="experimental.ws.send"){let y=Q2,m=H.get(`${y.sessionID}:${y.kind}`);if(m)m.pending=!0;if(m)await L.frame(y.frame,m.attempt);if(m&&y.kind==="primary")S(y)}if(h||a){let y=h??a;if(!y)return;let p=(h?h.request.headers:new Headers(y.headers)).get("authorization")?.replace(/^Bearer /,"");if(z2&&p)B.set(y.sessionID,p);else B.delete(y.sessionID);if(a){let u=`${a.sessionID}:${a.kind}`;if(z2&&p&&t.attempt)H.set(u,{bearer:p,attempt:t.attempt,pending:!1,url:a.url,headers:new Headers(Object.entries(a.headers).filter(([O2])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(O2.toLowerCase())))});else H.delete(u)}if(B.size>512){let u=B.keys().next().value;if(u)B.delete(u)}if(H.size>512){let u=H.keys().next().value;if(u)H.delete(u)}}else if(b==="experimental.ws.receive"){let y=Q2,m=H.get(`${y.sessionID}:${y.kind}`);if(m){if(G.frameReceived(y.sessionID,y.frame),y.kind==="primary"){let p;if(Y?.receive(y.sessionID,y.frame,(u)=>{p=u}),p)try{let u=h$(p,m.url,m.headers,G);if(u)await j?.({sessionID:y.sessionID,kind:"primary",request:u,attempt:m.attempt})}catch(u){J.warn("cachekeep WebSocket capture failed",{error:u instanceof Error?u.message:String(u)})}}if(y.frame=n0(y.frame,m.bearer),y.kind==="primary"&&m.pending&&S2()&&(y.frame.includes('"response.completed"')||y.frame.includes('"response.failed"')||y.frame.includes('"response.incomplete"')||y.frame.includes('"error"')))try{let p=JSON.parse(y.frame);if(p.type==="response.completed")m.pending=!1,d0(y.sessionID,Date.now());else if(["response.failed","response.incomplete","error"].includes(p.type))m.pending=!1}catch{}}}else if(b==="retry"){let y=Q2,m=B.get(y.sessionID);if(m)Object.assign(y.error,{message:u1(y.error.message,m)})}},P2)},event:{subscribe:(b)=>async function*(){for await(let D of $.event.subscribe(b)){if(D.type==="session.deleted")M(D.data.sessionID);yield D}}()}},{...Z,rewriteRequest:async(b)=>{let D=U.getStore();if(D)D.attempt=b.attempt;return Z.rewriteRequest?.(b)},rewriteHandshakeURL:(b)=>{let D=U.getStore();if(D)D.attempt=b.attempt;return Z.rewriteHandshakeURL?.(b)},onAttemptEnd:async(b,D)=>{await L.end(b,D),await Z.onAttemptEnd?.(b,D)},rewriteResponse:async(b)=>{await L.response(b.request,b.response.status);let D=await Z.rewriteResponse?.(b)??b.response,P2=await o0(D,b.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream");return i0(P2,b.kind==="primary"?b.sessionID:void 0)}},{gateOnPlaceholder:{credential:(b)=>{let D=b.get("authorization");return D?.startsWith("Bearer ")?D.slice(7):void 0}},hostRetryLimit:z1,logger:{info:(b,D)=>J.info?.(b,{data:D}),warn:(b,D)=>J.warn(b,{data:D})}}),o=v.dispose;return{...v,dispose:async()=>{B.clear(),H.clear(),await o(),await L.settle(),L.clear()}}}function x$($={}){return{id:d1,setup:(Z)=>U5(Z,$)}}async function U5($,Z={}){let A=[];try{let J=v2("opencode2");let G=v2("quota");let j=Z.version??r0;await B4({version:j,...Z.runtimeLayout});let Y=Z.paths??(()=>e0(s0()));let K=await M1(Y());let L=K?.logging?.level;if(L&&typeof L==="string")l0(L);let U=Z.fetch??fetch;let H=Z.now??Date.now;let B=Z.poolMigration??V4;if(!B&&!X1(Y().configPath)){J.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let P=(s)=>{throw new _2({kind:"no-account",providerID:b2,sessionID:s.sessionID,requestKind:s.kind,message:w1})},g=await g0($,{providerID:b2,chooseAccount:P,accountHeaders:P},J);return()=>g.dispose()}let M=Z.vault?.firstRosterWaitMs??J4;let S=W4({host:"opencode",stateDir:Z.vault?.stateDir??c0(Y().statePath),reservedRouteIds:()=>h.peek().rows.map((P)=>P.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>U},Y());let q=S.vault;let v=async()=>await q.authority()==="local"?G1(Y()):M1(Y());let o=!1;let b=!1;const D=_1(A,{[Symbol.dispose](){if(!o)S.release()}},0);await q.authority();let P2=S.firstRoster;let Q2=new _$;let h=new G4({paths:Y,refreshProvider:async(P)=>{let g=await p0({refreshToken:P.refresh,fetchImpl:U,now:H}),s=u0({id_token:"",access_token:g.access,refresh_token:g.refresh});return{...g,...s?{identity:s}:{}}},pullQuota:L0({fetchImpl:U,now:H,counts:Q2,logger:G}),now:H,vaultIdentities:()=>q.identities(),vaultMode:()=>q.enrolled(),vaultAuthority:()=>q.authority(),vaultFirstRoster:P2,vaultFirstRosterBackgroundWaitMs:M,log:v2("pool")});if(await q.authority()==="local")await h.load();let a=new X4({pool:h,vault:q,log:(P)=>J.warn(P)});const E2=_1(A,{[Symbol.dispose](){if(!o)a.dispose()}},0);let z2=Z.heartbeat===!1?void 0:await Y4({version:j,logger:v2("heartbeat")});let t=Z.fence??(()=>t0({currentVersion:j}));let y=Z.slot??U4();let m=async()=>$4(Y(),await y.get({path:{id:"openai"}}));let p=!1;let u=B?j4({paths:Y,slot:y,version:j,fence:t,runDeps:{vaultServes:()=>q.serves()},paused:async()=>await q.authority()!=="local",migrate:async(P)=>{let g=await Z4(P);if(p=g.status==="refused",!b)await h.load();return g},adopt:async(P)=>{if(b)return{status:"retry",reason:"unsettled"};if(!await O$(P2,M))return{status:"retry",reason:"vault-roster-pending"};if(b)return{status:"retry",reason:"unsettled"};let g=await z4(P);if(!b)await h.load();return g}}):void 0;u?.start();S.start();let O2=E0(Y());let x2=h0({paths:Y(),source:h,pins:O2,vault:q},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const R2=_1(A,{[Symbol.dispose](){if(!o)x2.release()}},0);x2.publish();let N2=Z.codex??new W1(void 0,void 0,uZ());let u2=bZ(K);let U2=f1(Y());let J2=wZ(Y(),{source:h,limits:a,storage:v,vault:q,accounts:$$(Y()),settings:()=>u2,parentOf:async(P)=>(await $.session.get({sessionID:P}))?.parentID??void 0,fetch:U,log:v2("cachekeep")},{now:H,codexResponsesUrl:c1().codexApiEndpoint,...Z.cacheKeep});const t2=_1(A,{[Symbol.dispose](){if(!o)J2.release()}},0);let D2=MZ({cacheWarming:(P)=>kZ(Y(),P),limits:a,codex:N2,onRoute:x2.route,source:h,slotPlaceholderWithoutMain:m,storage:v,pins:O2,sessionAccounts:$$(Y()),vault:q,awaitVaultRoster:async()=>{await O$(q.awaitRequestRoster(),y1)},responsesLite:()=>c1().responsesLite,codexEndpoint:()=>c1().codexApiEndpoint,now:H,log:J});let h2=await g0($,D2.adapter,J,N2,(P)=>J2.capture(P),U2,(P)=>J2.forget(P));D2.attach(h2);let m2=await $.session.hook("prompt",(P)=>{D2.beginTurn(P.sessionID)});let X=async(P)=>{if(await P1(q),X1(Y().configPath))return;if(await u?.idle(),X1(Y().configPath))return;if(p&&!L$(P)&&(await t()).open){await h.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 N=async(P)=>{await X(P);let g=await X0(h.poolStore(),Y(),P,{vault:q});if(!X1(Y().configPath))await u?.requestAdoption();await h.load(),J.info("ChatGPT login stored in the account pool",g)};let C=await a1($,{integrationID:b2,methods:G0({beginLogin:Z.beginLogin??E$,version:j,vault:q}),onLogin:(P)=>N(P),label:"ChatGPT (openai-auth account pool)",vault:J0(q)});let F=await U0($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let R=$.command&&$.location?await oZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??Q0({...M0({rateLimitMarks:()=>a.marks(),source:h,storage:v,counts:Q2,now:H,authority:()=>q.authority()}),fetchImpl:U,now:H,randomUUID:W5,accountStoragePath:Y().configPath,accountStatePath:Y().statePath,packageVersion:j,layoutNotice:Q4,loadAccounts:G1,store:()=>h.poolStore(),migration:async()=>{if(X1(Y().configPath))return{migrated:!0};let P=await t();return{migrated:!1,blockers:P.open?[]:P.blockers}},beginAccountLogin:Z.beginLogin??E$,refreshAllQuota:async()=>(await h.pollRows(await G1(Y()))).map((P)=>({...P,account:P.id})),getStickyRouting:async(P)=>O2.get(P),cacheKeepManager:J2.manager,setCacheKeepEnabled:(P)=>J2.configure({enabled:P}),setCacheKeepSubagents:(P)=>J2.configure({subagents:P}),setCacheKeepSustain:(P)=>J2.configure({sustain:P}),setCacheKeepWindow:(P)=>J2.configure({window:P}),afterWrite:()=>h.load(),refreshSidebar:()=>x2.publish(),clearStickyRouting:async(P)=>{let g=O2.get(P)!==void 0;return O2.forget(P),g},vault:q})):void 0;let x=new AbortController;(async()=>{try{for await(let P of $.event.subscribe({signal:x.signal}))if(P.type==="session.deleted")D2.forgetSession(P.data.sessionID),J2.forget(P.data.sessionID),U2.forget(P.data.sessionID)}catch(P){if(!x.signal.aborted)J.warn("stopped listening for session deletion",{error:P instanceof Error?P.message:String(P)})}})();o=!0;return async()=>{b=!0,x.abort(),D2.dispose();let P=J2.release();await R?.(),u?.dispose(),await a.dispose(),await x2.release(),await Promise.allSettled([h2.dispose(),m2.dispose(),C.dispose(),F.dispose()]);let g;try{await Promise.race([Promise.all([u?.idle(),h.settled(),N2.store?.settled(),P]),new Promise((s)=>{g=setTimeout(s,V5),g.unref?.()})])}finally{clearTimeout(g),await S.release(),await z2?.release()}}}catch(k){var f=k,d=1}finally{m0(A,f,d)}}var N5=x$(),n7={id:d1,setup:N5.setup,server:N4.server};export{n7 as default,x$ as createOpenAIAuthPlugin,d1 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.14.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -66,17 +66,18 @@
|
|
|
66
66
|
},
|
|
67
67
|
"devDependencies": {
|
|
68
68
|
"@ai-sdk/openai": "3.0.88",
|
|
69
|
-
"@cortexkit/common-auth": "^0.
|
|
69
|
+
"@cortexkit/common-auth": "^0.44.0",
|
|
70
70
|
"@cortexkit/openai-auth-core": "workspace:*",
|
|
71
|
-
"@opencode
|
|
71
|
+
"@cortexkit/opencode-sidebar": "0.1.0",
|
|
72
|
+
"@opencode/plugin": "2.2.6"
|
|
72
73
|
},
|
|
73
74
|
"dependencies": {
|
|
74
|
-
"@cortexkit/claustrum-client": "^0.
|
|
75
|
+
"@cortexkit/claustrum-client": "^0.18.0",
|
|
75
76
|
"@cortexkit/private-files": "^0.2.2",
|
|
76
77
|
"@cortexkit/subc-client": "^0.24.0",
|
|
77
|
-
"@opentui/core": ">=0.
|
|
78
|
-
"@opentui/solid": ">=0.
|
|
79
|
-
"ai": "^7.0.
|
|
78
|
+
"@opentui/core": ">=0.8.3",
|
|
79
|
+
"@opentui/solid": ">=0.8.3",
|
|
80
|
+
"ai": "^7.0.165",
|
|
80
81
|
"jsonc-parser": "^3.3.1",
|
|
81
82
|
"solid-js": "1.9.18"
|
|
82
83
|
}
|