@cortexkit/opencode-openai-auth 1.9.6 → 1.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +8 -8
- package/dist/{codex-request-CZ16goZ6.d.ts → codex-request-BLzSBegI.d.ts} +4 -0
- package/dist/{index-x8qjasc7.js → index-2py81t0v.js} +2 -2
- package/dist/index-44b5y56b.js +64 -0
- package/dist/{index-se7mn1wg.js → index-4gkfz4zp.js} +2 -2
- package/dist/index-7fdcb97f.js +91 -0
- package/dist/{index-3mmdgz6r.js → index-7xqb1m44.js} +2 -2
- package/dist/index-8xgeh2zt.js +8 -0
- package/dist/{index-tcaef7wq.js → index-ct658ahq.js} +1 -1
- package/dist/{index-y4j7y8b8.js → index-dkhy2peg.js} +1 -1
- package/dist/{index-1kbr03m0.js → index-hq4gdm6f.js} +2 -2
- package/dist/{index-cf0mrvqj.js → index-mkda7acs.js} +1 -1
- package/dist/{index-7bv7pgy8.js → index-r0kv780p.js} +2 -2
- package/dist/index-vpjmexm5.js +76 -0
- package/dist/{index-s52j2h64.js → index-w37815v4.js} +1 -1
- package/dist/index.d.ts +2 -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-djwdynff.js → token-pd3t5f20.js} +1 -1
- package/dist/token-util-807rzwws.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.d.ts +1 -2
- package/dist/v2/server.js +3 -3
- package/package.json +4 -4
- package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +32 -8
- package/src/tui-compiled/raw/shared/5f8cc863449a6c85-limits-namespace.js +19 -7
- package/src/tui-compiled/raw/shared/92e38944b51b2405-file-read-cache.js +10 -5
- package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +1 -1
- package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +47 -3
- package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +32 -8
- package/src/tui-compiled/runtime/shared/5f8cc863449a6c85-limits-namespace.js +19 -7
- package/src/tui-compiled/runtime/shared/92e38944b51b2405-file-read-cache.js +10 -5
- package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +1 -1
- package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +47 -3
- package/dist/index-5xs8nfcx.js +0 -63
- package/dist/index-jqqeynjm.js +0 -91
- package/dist/index-qn927h9w.js +0 -76
- package/dist/index-t52k32ab.js +0 -8
- package/dist/token-util-0xt1ws82.js +0 -1
package/dist/v2/server.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{c as
|
|
2
|
-
`)}:{event:
|
|
3
|
-
`)}}function x1($,Z){let z=new TextDecoder,G="",X=(F)=>{let W=i0(F);if(!W)return;try{$(W)}catch(H){Z(H)}},Y=()=>{for(;;){let F=/\r?\n\r?\n/.exec(G);if(!F)return;let W=G.slice(0,F.index);G=G.slice(F.index+F[0].length),X(W)}};return new TransformStream({transform(F,W){W.enqueue(F),G+=z.decode(F,{stream:!0}),Y()},flush(){if(G+=z.decode(),Y(),G.trim()!=="")X(G);G=""}})}var Z1=512,S1=3621000,y2="x-common-auth-attempt",D2=($,Z)=>JSON.stringify([$,Z]),M2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function a0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function n0($,Z){let z=$.getReader();return new ReadableStream({async pull(G){let X;try{X=await z.read()}catch(Y){Z({reason:"failed",message:Y instanceof Error?Y.message:String(Y)}),G.error(Y);return}if(X.done)Z(),G.close();else G.enqueue(X.value)},async cancel(G){Z({reason:"cancelled",...G===void 0?{}:{message:String(G)}}),await z.cancel(G)}})}function $1($,Z){for(let[z,G]of Object.entries(Z)){let X=z.toLowerCase();for(let Y of Object.keys($))if(Y.toLowerCase()===X)delete $[Y];if(G!==null)$[z]=G}}function o0($,Z){for(let[z,G]of Object.entries(Z))if(G===null)$.delete(z);else $.set(z,G)}async function q1($,Z,z={}){let{providerID:G}=Z,X=z.gateOnPlaceholder,Y=(J)=>X===void 0||X.credential(J)===A2(G),F=z.logger,W=Math.max(1,z.maxRecords??Z1),H=z.hostRetryLimit??10,N=[...z.hostCredentials??[A2(G)],...X?[A2(G)]:[]].filter((J)=>J!==""),V=new Map,P=new WeakMap,C=new Map,E=0,h=new Set,a=new Map,A=new Map,k=(J)=>{let j=A.get(J);return j?.ownedSeen===!0&&j.foreignSeen},W2=(J,j)=>{a.set(J,j);let U=A.get(J)??{ownedSeen:!1,foreignSeen:!1};if(j)U.ownedSeen=!0;else U.foreignSeen=!0;A.set(J,U)},X2=(J,j)=>{let U=X?.refuseMisplaced,L=U?[...j].filter(([,I])=>I.includes(A2(G))):[],B=Y(j)&&(!U||L.length>0);if(U){if(L.length>0&&(L.length!==1||!B))throw W2(J.sessionID,!1),new F2({kind:"placement-refused",providerID:G,sessionID:J.sessionID,requestKind:J.kind,message:U(L[0]?.[0]??"")})}return W2(J.sessionID,B),B},v=!1,n=!1,K2=new Map,U2=0,j2=!1,b=new Map,g=(J,j)=>{try{F?.warn(J,j)}catch{}},p=(J)=>J instanceof Error?J.message:String(J),Q=(J)=>J.excluded.clear(),K=(J)=>J.excluded.size===0?{}:{excluded:[...J.excluded]},_=(J,j,U)=>{if(!z.enforceRequestExclusion||J===void 0||!U.excluded.has(J))return!1;return g("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:j.sessionID,kind:j.kind,phase:j.phase,accountId:J}),!0},M=new Map,D=(J,j)=>{let U=(M.get(J)??Promise.resolve()).then(j),L=U.then(()=>{},()=>{});return M.set(J,L),L.then(()=>{if(M.get(J)===L)M.delete(J)}),U},O=(J,j)=>{let U=M.get(J);return U?U.then(()=>O(J,j)):j()},R=async(J)=>{try{await Z.dropChoice?.({...J.input,accountId:J.accountId})}catch(j){g("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:J.input.sessionID,error:p(j)})}},f=async(J)=>{try{await Z.dropSameAccountRetry?.({...J.input,accountId:J.accountId})}catch(j){g("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:J.input.sessionID,error:p(j)})}},q=async(J)=>{if(J.next)await R(J.next);if(J.sameAccount)await f(J.sameAccount)},w=(J)=>{let j=C.get(J);if(C.delete(J),j)D(j.sessionID,()=>q(j))},y=async(J,j)=>{let U=K2.get(J);if(!U||U.size===0)return;await Promise.all([...U].map(async(L)=>{try{await L(j)}catch(B){g("opencode2 auth listener threw; the request is unaffected",{event:J,error:p(B)})}}))},J2=async(J,j)=>{try{await Z.onAttemptEnd?.(J,j)}catch(U){g("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:J.attemptId,error:p(U)})}},G2=(J,j)=>{if(J.ended||!J.attempt)return;let U={...J.status===void 0?{}:{status:J.status},outputStarted:J.outputStarted,...J.limit?{limit:J.limit.signal}:{},...j?{error:j}:{}};if(j)J.endError=j;if(j?.reason==="cancelled"||!j&&!J.limit&&(J.status===void 0||J.status<400))Q(J.request);J.ended=J2(J.attempt,U)},e=(J,j)=>G2(J,{reason:"abandoned",message:j}),s=(J)=>[...V.values()].filter((j)=>j.key===J),c=(J)=>s(J).at(-1),m=(J)=>{if(V.delete(J.id),C.get(J.key)?.attemptId===J.id||!s(J.key).length)w(J.key)},$2=(J)=>{V.set(J.id,J);while(V.size>W){let j=V.values().next().value;if(j===void 0)break;e(j,"dropped to keep the record bound"),m(j)}},T2=(J)=>J.accountId===void 0?void 0:{...J.scope,accountId:J.accountId},T=(J,j)=>new F2({kind:"no-account",providerID:G,sessionID:J.sessionID,requestKind:J.kind,...j===void 0?{}:{message:j}}),l=(J)=>{b.get(J)?.clear(),b.delete(J)},Z2=async(J,j)=>{let U=()=>T(J,`${G} ${J.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(j2)throw U();let L=b.get(J.sessionID);if(!L)L=new Set,b.set(J.sessionID,L);let B={};L.add(B);let I=()=>{if(!L.has(B))throw U()};try{return await j(I)}finally{if(L.delete(B),L.size===0&&b.get(J.sessionID)===L)b.delete(J.sessionID)}},t=(J,j)=>{for(let[U,L]of j)if(N.some((B)=>L.includes(B)))throw new F2({kind:"host-credential-on-wire",providerID:G,sessionID:J.sessionID,requestKind:J.kind,message:`${G} ${J.kind} request still carries the host's placeholder credential in ${U}; the adapter's account headers must replace it`})},B2=(J)=>{for(let j of s(J))if(j.ended||!j.attempt)m(j);else if(j.transport==="ws"||j.judged)e(j,"a newer attempt of its session and kind began"),m(j)},w2=async(J,j,U,L)=>{let B=D2(J.sessionID,J.kind),{input:I,accountId:x,sameAccountRetry:S,request:r}=await O(J.sessionID,async()=>{U();let Q2=C.get(B);C.delete(B);let g2=s(B);if(Q2&&g2.some((o)=>o.id!==Q2.attemptId&&o.attempt&&!o.ended))g("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:J.sessionID,kind:J.kind});if(!Q2){let o=new Set(g2.filter((N2)=>N2.attempt&&!N2.ended).map((N2)=>N2.request));for(let N2 of g2)if(!o.has(N2.request))Q(N2.request)}let V2=Q2?.request??{excluded:new Set},z2=Q2?.accountId??c(B)?.accountId;B2(B);let i=Q2?.next,Y2=Q2?.sameAccount,u=Y2!==void 0&&Y2.input.modelID===J.modelID&&Y2.input.agent===J.agent,H2=i!==void 0&&i.input.modelID===J.modelID&&i.input.agent===J.agent,O2=Q2?.wake,d={...J,phase:"request",...K(V2),...z2===void 0?{}:{previousAccountId:z2},...Q2?.rerouteFrom?{rerouteFrom:Q2.rerouteFrom}:{},...O2===void 0?{}:{wake:O2,hostAttempt:i?.input.hostAttempt}};if(i&&(!H2||O2!==void 0))await D(J.sessionID,()=>R(i)),U();if(Y2&&!u)await D(J.sessionID,()=>f(Y2)),U();if(Y2?.continuation&&(!u||k(J.sessionID))){if(u)await D(J.sessionID,()=>f(Y2));throw T(J)}let b2=u?Y2.accountId:H2&&O2===void 0?i.accountId:await Z.chooseAccount(d),S2=typeof b2==="string"?b2:void 0;if(_(S2,d,V2)){let o=S2;if(u&&Y2)await D(J.sessionID,()=>f(Y2));else if(o!==void 0)await D(J.sessionID,()=>R(H2&&i?i:{accountId:o,input:d}));S2=void 0,U()}return{input:d,accountId:S2,sameAccountRetry:u,request:V2}});U();let _2={},L2;if(x!==void 0){let Q2=await Z.accountHeaders({...J,accountId:x});if(U(),a0(Q2))_2=Q2.headers,L2=Q2.attempt;else _2=Q2}let h2=`attempt-${++U2}`,P2={id:h2,key:B,scope:J,request:r,accountId:x,headers:_2,attempt:x===void 0?void 0:{...J,accountId:x,attemptId:h2,transport:L,data:L2},...L===void 0?{}:{transport:L},outputStarted:!1,sameAccountRetry:S};if($2(P2),P2.attempt)y("select",{...J,accountId:P2.attempt.accountId,hook:j,...I.previousAccountId===void 0?{}:{previousAccountId:I.previousAccountId},...I.rerouteFrom===void 0?{}:{rerouteFrom:I.rerouteFrom},handle:P2.attempt});return P2},r2=async(J,j,U,L,B)=>{let I=D2(J.sessionID,J.kind),x=L===void 0?void 0:V.get(L);if(x?.key!==I)x=void 0;if(!x){if(x=c(I),s(I).filter((r)=>r.transport===void 0&&!r.ended).length>1&&!n)n=!0,g("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:J.sessionID,kind:J.kind})}if(!x||x.transport!==void 0||x.ended)x=await w2(J,j,B,U);else if(x.transport=U,x.attempt)x.attempt.transport=U;if(U==="ws"){for(let S of s(I))if(S!==x&&S.transport==="ws")e(S,"a newer attempt of its session and kind went out over WebSocket")}return x},C1=async(J,j)=>{try{return await j()}catch(U){throw G2(J,{reason:"failed",message:p(U)}),U}},Q$=(J,j)=>{let U=s(D2(J,j)).filter((L)=>L.transport==="ws").at(-1);return U?.attempt!==void 0&&!U.ended?U:void 0},t2=(J,j,U)=>{let L=T2(J);if(!L||!J.attempt||J.limit)return;J.limit={signal:j,delivered:y("limit",{...L,via:U,limit:j,outputStarted:J.outputStarted,handle:J.attempt})}},Y$=(J,j,U,L)=>{let B=T2(J);if(!B||!J.attempt)return;y("quota",{...B,transport:j,...L===void 0?{}:{status:L},quota:U,handle:J.attempt})},X$=(J,j,U,L)=>{let B=J.attempt;if(!B)return;let I=Z.inspectEvent?.(L===void 0?{transport:j,data:U,attempt:B}:{transport:j,data:U,event:L,attempt:B});if(!I)return;if(I.quota!==void 0)Y$(J,j,I.quota);if(I.outputStarted)J.outputStarted=!0;if(I.hostRetry==="veto")J.hostRetry="veto";if(I.limit)t2(J,I.limit,j);if(I.error!==void 0)G2(J,{reason:"failed",message:I.error});else if(I.done)G2(J)},p0=(J,j)=>{let U=J.attempt;if(!U||j.accountId===J.accountId)return;if(U.reboundFrom??=U.accountId,U.accountId=j.accountId,"data"in j)U.data=j.data;J.accountId=j.accountId},c0=(J)=>!J.attempt||J.endError!==void 0||J.status!==void 0&&J.status>=400,j$=(J)=>{let j=[...V.values()].filter((S)=>S.scope.sessionID===J),U=j.filter((S)=>S.limit&&!S.rerouted).at(-1);if(U)return U;let L=j.filter((S)=>S.scope.kind==="primary"),B=L.length>0?L:j;if(B.length<=1)return B[0];let I=B.filter((S)=>!S.judged&&c0(S)).at(-1);if(I)return I;let x=B.filter((S)=>S.attempt&&!S.ended);if(x.length>1)return"ambiguous";return x[0]??B.at(-1)},q2={providerID:G},x2=[];x2.push(await $.session.hook("model.request",(J)=>{if(X)return;return Z2(M2(J),async(j)=>{let U=await w2(M2(J),"model.request",j);if(j(),U.accountId===void 0)throw T(U.scope);$1(J.headers,{...U.headers,[y2]:U.id})})},q2)),x2.push(await $.session.hook("http.request",(J)=>{if(X){if(!X2(M2(J),J.request.headers))return}return Z2(M2(J),async(j)=>{let U=J.request.headers.get(y2)??void 0,L=X?await w2(M2(J),"http.request",j,"http"):await r2(M2(J),"http.request","http",U,j);j();let B=T2(L),I=L.attempt;if(!B||!I)throw T(L.scope);await C1(L,async()=>{let x=J.request;if(Z.rewriteRequest){if(U!==void 0){let _2=new Headers(x.headers);_2.delete(y2),x=new Request(x,{headers:_2})}x=await Z.rewriteRequest({...B,request:x,attempt:I})??x,j()}let S=new Headers(x.headers);S.delete(y2),o0(S,L.headers),t(L.scope,S.entries());let r=new Request(x,{headers:S});P.set(r,L),J.request=r})})},q2)),x2.push(await $.session.hook("http.response",async(J)=>{let j=P.get(J.request);if(!j){if(X)return;if(!v)v=!0,g("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:J.sessionID,kind:J.kind});return}let U=J.response;if(Z.answeredBy&&j.attempt){let S=j.attempt,r=await C1(j,async()=>Z.answeredBy?.({request:J.request,response:U,attempt:S}));if(r)p0(j,r)}let L=T2(j),B=j.attempt;if(!L||!B)return;j.status=U.status;let I=Z.quotaFromHeaders?.(U.headers,U.status,B);if(I!==void 0)Y$(j,"http",I,U.status);if(!U.ok&&Z.limitFromResponse){let S=await Z.limitFromResponse({status:U.status,headers:U.headers,body:()=>U.clone().text(),attempt:B});if(S)t2(j,S,"http")}if(!U.ok||!U.body)G2(j);let x=U;if(U.body&&(Z.inspectEvent||Z.onAttemptEnd)){let S=U.body;if(Z.inspectEvent)S=S.pipeThrough(x1((r)=>X$(j,"http",r.data,r.event),(r)=>g("opencode2 auth event inspection threw",{error:p(r)})));x=new Response(n0(S,(r)=>{if(r?.reason==="failed")j.httpReadFailed=!0;G2(j,r)}),{status:U.status,statusText:U.statusText,headers:U.headers})}if(Z.rewriteResponse)x=await Z.rewriteResponse({...L,request:J.request,response:x,attempt:B})??x;if(Z.responseRetry){if(await Z.responseRetry({...L,request:J.request,response:x,attempt:B})==="veto")j.hostRetry="veto"}if(x!==U)J.response=x},q2)),x2.push(await $.session.hook("experimental.ws.handshake",(J)=>{if(X){let j=D2(J.sessionID,J.kind);if(h.delete(j),!X2(M2(J),new Headers(J.headers)))return}return Z2(M2(J),async(j)=>{let U;for(let x of Object.keys(J.headers)){if(x.toLowerCase()!==y2)continue;U??=J.headers[x],delete J.headers[x]}let L=X?await w2(M2(J),"experimental.ws.handshake",j,"ws"):await r2(M2(J),"experimental.ws.handshake","ws",U,j);j();let B=T2(L),I=L.attempt;if(!B||!I)throw T(L.scope);await C1(L,async()=>{if(!X?.refuseMisplaced)$1(J.headers,L.headers);let x=Z.rewriteHandshakeURL?.({...B,url:J.url,attempt:I});if(x!==void 0)J.url=x;if(X?.refuseMisplaced)$1(J.headers,L.headers);if(t(L.scope,Object.entries(J.headers)),X)h.add(L.key)})})},q2));let B$=Z.rewriteWebSocketFrame?.bind(Z);if(B$)x2.push(await $.session.hook("experimental.ws.send",async(J)=>{let j=M2(J);if(X&&!h.has(D2(j.sessionID,j.kind)))return;let U=Q$(j.sessionID,j.kind),L=await B$({...j,attempt:U?.attempt,frame:J.frame});if(L!==void 0)J.frame=L},q2));x2.push(await $.session.hook("experimental.ws.receive",(J)=>{if(X&&!h.has(D2(J.sessionID,J.kind)))return;let j=Q$(J.sessionID,J.kind);if(!j)return;try{X$(j,"ws",J.frame)}catch(U){g("opencode2 auth frame inspection threw",{error:p(U)})}},q2)),x2.push(await $.session.hook("retry",async(J)=>{if(X&&a.get(J.sessionID)!==!0)return;let j=J.decision,U=()=>y("retry",{sessionID:J.sessionID,attempt:J.attempt,reason:"host-decides",hostDecision:j,decision:j});if(k(J.sessionID)&&!Z.retrySameAccount){await U();return}let L=j$(J.sessionID);if(!L)return;if(L==="ambiguous"){await y("retry",{sessionID:J.sessionID,attempt:J.attempt,reason:"host-decides",hostDecision:j,decision:j});return}let B=L,I=()=>B.hostRetry==="veto";await Z2(B.scope,async(x)=>{let S=x,r=Z.retrySameAccount?.bind(Z),_2=B.attempt,L2=B.outputStarted;if(L2&&B.httpReadFailed&&r&&_2&&!k(J.sessionID)){if(!B.limit){let V2=Z.limitFromError?.(J.error,_2);if(V2)t2(B,V2,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;S()}let h2=()=>B.httpReadFailed===!0&&J.error.type==="provider.transport"&&j.retry&&H-J.attempt>=1&&!B.limit&&!(B.status!==void 0&&B.status>=400)&&!(J.error.status!==void 0&&J.error.status>=400)&&!_2?.reboundFrom&&!I()&&!k(J.sessionID);if(r&&_2&&(!L2||h2())&&(!I()||k(J.sessionID))&&!B.sameAccountRetry){if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;let V2=await D(B.scope.sessionID,async()=>{S();let z2=_2.accountId,i=()=>V.has(B.id)&&B.accountId===z2&&j$(J.sessionID)===B&&B.outputStarted===L2&&(!L2||h2())&&(!I()||k(J.sessionID))&&(!X||a.get(J.sessionID)===!0);if(!i()||B.sameAccountRetry)return!1;B.sameAccountRetry=!0;let Y2={...B.scope,accountId:z2,error:J.error,attempt:J.attempt,...B.limit?{limit:B.limit.signal}:{},...L2?{continuation:"interrupted-read"}:{}},u;try{u=await r(Y2)}catch(d){g("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:J.sessionID,error:p(d)})}if(!u)return S(),!1;let H2={accountId:u.accountId,input:Y2,...L2?{continuation:!0}:{}};try{S()}catch(d){throw await f(H2),d}if(!i()||u.accountId!==z2)return await f(H2),!1;let O2=C.get(B.key);if(C.delete(B.key),O2)await q(O2);try{S()}catch(d){throw await f(H2),d}if(!i())return await f(H2),!1;return C.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++E,accountId:z2,sameAccount:H2}),B.judged=!0,J.decision=L2?j:{retry:!0,delay:0},!0});if(S(),V2){await y("retry",{sessionID:J.sessionID,accountId:B.accountId,kind:B.scope.kind,attempt:J.attempt,reason:L2?"continue-same-account":"same-account",hostDecision:j,decision:J.decision,handle:B.attempt});return}}if(k(J.sessionID)){await U();return}B.judged=!0;let P2=B.attempt;if(P2&&!B.outputStarted){if(!B.limit){let V2=Z.limitFromError?.(J.error,P2);if(V2)t2(B,V2,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered}S();let{decision:Q2,reason:g2}=await D(B.scope.sessionID,async()=>{if(S(),k(J.sessionID))return{decision:j,reason:"host-decides"};let V2=C.get(B.key);if(C.delete(B.key),V2)await q(V2);if(S(),k(J.sessionID))return{decision:j,reason:"host-decides"};let z2=j,i,Y2,u,H2;if(B.accountId===void 0||!P2)z2={retry:!1},i="no-account";else if(B.outputStarted)z2={retry:!1},i="output-started";else if(I())z2={retry:!1},i="adapter-veto";else if(B.limit){let O2={accountId:B.accountId,limit:B.limit.signal},d,b2={...B.scope,phase:"retry",...K(B.request),hostAttempt:J.attempt,previousAccountId:B.accountId,rerouteFrom:O2};try{d=await Z.chooseAccount(b2)}catch(A1){g("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:B.scope.sessionID,error:p(A1)})}let S2=typeof d==="string"?d:typeof d==="object"&&("hold"in d)?B.accountId:void 0;if(_(S2,b2,B.request)){if(S2!==void 0)await R({accountId:S2,input:b2});d=void 0}let o=typeof d==="object"&&"hold"in d?d.hold:void 0,N2=typeof d==="object"&&"waitThenReselect"in d?d.waitThenReselect:void 0,d0=typeof d==="object"&&"hostRetry"in d?d.hostRetry:void 0,e2=typeof d==="string"?d:o?B.accountId:void 0;if(e2!==void 0)u={accountId:e2,input:b2};try{S()}catch(A1){if(u)await R(u);throw A1}if(k(J.sessionID)){if(u)await R(u);return{decision:j,reason:"host-decides"}}if(I()||d0==="veto"){if(u)await R(u);if(u=void 0,S(),k(J.sessionID))return{decision:j,reason:"host-decides"};B.hostRetry="veto",z2={retry:!1},i="adapter-veto"}else if(!(H-J.attempt>=1)){if(u)await R(u);u=void 0,i="host-decides-last-account"}else if(N2&&Number.isFinite(N2.delayMs)&&N2.delayMs>=0&&N2.delayMs<=S1)z2={retry:!0,delay:Math.ceil(N2.delayMs)},i="wait-then-reselect";else if(o&&Number.isFinite(o.delayMs)&&o.delayMs>=0&&o.delayMs<=S1){if(z2={retry:!0,delay:Math.ceil(o.delayMs)},o.target!==void 0)H2={target:o.target,...o.checkpoint===void 0?{}:{checkpoint:o.checkpoint},...o.kind===void 0?{}:{kind:o.kind}};i="hold"}else if(!o&&e2!==void 0&&e2!==B.accountId)B.rerouted=!0,B.request.excluded.add(B.accountId),Y2=O2,z2={retry:!0,delay:0},i="reroute";else{if(o&&u)await R(u),u=void 0;i="host-decides-last-account"}}else i="host-decides";if(J.decision=z2,z2.retry&&B.accountId!==void 0&&V.has(B.id))C.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++E,accountId:B.accountId,...Y2===void 0?{}:{rerouteFrom:Y2},...u===void 0?{}:{next:u},...H2===void 0?{}:{wake:H2}});else if(u)await R(u);if(!z2.retry)Q(B.request);return{decision:z2,reason:i}});S(),await y("retry",{sessionID:J.sessionID,...B.accountId===void 0?{}:{accountId:B.accountId},kind:B.scope.kind,attempt:J.attempt,reason:g2,hostDecision:j,decision:Q2,...P2===void 0?{}:{handle:P2}})})},q2));let V$=(J)=>{if(l(J),a.delete(J),!A.get(J)?.foreignSeen)A.delete(J);for(let j of h)if(JSON.parse(j)[0]===J)h.delete(j);for(let j of[...V.values()]){if(j.scope.sessionID!==J)continue;e(j,"its session was forgotten"),Q(j.request),V.delete(j.id)}for(let[j,U]of C)if(U.sessionID===J)w(j)},O1=new AbortController,W$=$.event;if(W$)(async()=>{try{for await(let J of W$.subscribe({signal:O1.signal}))if(J.type==="session.deleted")V$(J.data.sessionID);else if(J.type==="session.status"&&J.data.status.type==="idle"){let j=J.data.sessionID,U=++E;D(j,async()=>{for(let[L,B]of C)if(B.sessionID===j&&B.order<U)C.delete(L),Q(B.request),await q(B)})}}catch(J){if(!O1.signal.aborted)g("opencode2 auth stopped listening for session deletion",{error:p(J)})}})();return{on(J,j){let U=K2.get(J);if(!U)U=new Set,K2.set(J,U);let L=j;return U.add(L),()=>{U.delete(L)}},accountFor(J,j){return c(D2(J,j))?.accountId},forgetSession:V$,get size(){return V.size},async dispose(){if(j2)return;j2=!0;for(let J of b.keys())l(J);O1.abort();for(let J of V.values())e(J,"the installation was disposed");V.clear();for(let J of C.keys())w(J);h.clear(),a.clear(),A.clear(),K2.clear(),await Promise.all(M.values()),await Promise.all(x2.map(async(J)=>{try{await J.dispose()}catch(j){g("opencode2 auth hook did not dispose cleanly",{error:p(j)})}}))}}}import{createHash as s0}from"node:crypto";var r0=1024,t0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),N$=($)=>F$($,"user"),e0=($)=>t0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function $4($){return s0("sha256").update(JSON.stringify($)).digest("hex")}class I2{runtime;maxSessions;#$=new Map;constructor($,Z=r0){this.runtime=$;this.maxSessions=Z}advance($,Z,z=this.runtime){let G=this.#$.get($),X=Array.isArray(Z.input)?Z.input:[],Y=X.filter(N$),F=X.findLastIndex(N$),W=F<0?void 0:$4(X[F]),H=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,N,V,P;if(H)N=Y.length>0,V=W??G?.fingerprint,P=G?.userCount===void 0?void 0:G.userCount+Y.length;else{V=W,P=Y.length;let E=F>=0&&F>X.findLastIndex(e0),h=G!==void 0&&!G.completed&&G.fingerprint===V&&G.userCount===P;N=E&&!h}let C=N||!G?{turnID:(z?.uuid??k2)(),turnStartedAt:(z?.now??Date.now)()}:{turnID:G.turnID,turnStartedAt:G.turnStartedAt};return this.#Z($,{...C,completed:!1,fingerprint:V,userCount:P}),C}completed($){let Z=this.#$.get($);if(Z)this.#Z($,{...Z,completed:!0})}get($){return this.#$.get($)}forget($){this.#$.delete($)}#Z($,Z){this.#$.delete($),this.#$.set($,Z);while(this.#$.size>this.maxSessions){let z=this.#$.keys().next().value;if(z===void 0)break;this.#$.delete(z)}}}function b1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var K$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function Z4(){let $=globalThis;return $[K$]??=crypto.randomUUID(),$[K$]}class l2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,z){this.runtime=$;this.store=z;this.installationID=Z??Z4(),this.sessions=z?.sessions??new Map,this.frameTurns=z?.frameTurns??new I2}get($){let Z=this.runtime?.uuid??k2;if(this.store)return this.store.get($,Z);let z=this.sessions.get($);if(!z){let G=Z();z={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,z)}return z}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(J1(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var D1={version:T$,"user-agent":_$,originator:"codex_exec"};var J4=1024,z4=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,G1=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),M$=($)=>G1($)&&($.type==="message"||("role"in $))&&$.role==="user",E$=($)=>G1($)&&$.type==="configuration_update";class k1{http;#$=new Map;constructor($=new l2){this.http=$}apply($,Z,z){if(Z.kind!=="primary")return!1;let G=typeof $.model==="string"?$.model:"";if(!L$.has(G))return!1;if(z4.test(G))return!1;let X=G1($.reasoning)?$.reasoning:void 0,Y=typeof X?.effort==="string"?X.effort:void 0;if(!Y)return!1;let F=this.#$.get(Z.sessionID);if(F===void 0)return this.#Z(Z.sessionID,Y),!1;if(Y===F)return!1;let W=Array.isArray($.input)?$.input:void 0;if(!W||W.length===0)return!1;let H=W.findLastIndex(M$);if(H<0){if(z==="http")return!1;return $.reasoning={...X,effort:F},!0}if($.reasoning={...X,effort:F},!E$(W[H-1]))W.splice(H,0,{type:"configuration_update",reasoning:{effort:Y}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>J4){let z=this.#$.keys().next().value;if(z===void 0)break;this.#$.delete(z)}}}function J1($){try{let Z=JSON.parse($);return G1(Z)?Z:void 0}catch{return}}async function C$($,Z,z,G,X=z.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Y=await $.clone().text(),F=J1(Y);if(F)delete F.max_output_tokens;let W=new Headers($.headers),H=z1({rewriteLite:P$,init:{body:F?JSON.stringify(F):$.body===null?void 0:Y},headers:W,metadata:X.get(Z.sessionID),installationID:X.installationID,runtime:X.runtime,websocket:!1,responsesLite:G,applyEffort:(N)=>{z.apply(N,Z,"http")}});return new Request($,{headers:W,body:H.init?.body})}function O$($,Z,z,G){let X=G.sessions.get($.sessionID),Y=G.frameTurns.get($.sessionID);if(!X||!Y)return;let F=b1(X,Y),W=new Headers({"content-type":"application/json"});for(let N of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let V=z.get(N);if(V!==null)W.set(N,V)}z1({init:{body:$.bodyText},headers:W,metadata:F,installationID:G.installationID,runtime:G.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let H=new URL(Z);if(H.protocol==="wss:")H.protocol="https:";if(H.protocol==="ws:")H.protocol="http:";return new Request(H,{method:"POST",headers:W,body:$.bodyText})}function G4($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let z=Z.findIndex((G,X)=>JSON.stringify(G)!==JSON.stringify($[X]));return z>=0&&E$(Z[z])&&M$(Z[z+1])&&JSON.stringify(Z.slice(z+1))===JSON.stringify($.slice(z))}function A$($,Z,z){let G=J1($);if(G?.type!=="response.create")return;let X=z.http.advanceFrame(Z.sessionID,G),Y=z.http.get(Z.sessionID);delete G.max_output_tokens;let F=z1({rewriteLite:()=>{},init:{body:JSON.stringify(G)},headers:new Headers,metadata:b1(Y,X),installationID:z.http.installationID,runtime:z.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(H)=>{z.apply(H,Z,"ws")}}),W=J1(String(F.init?.body));if(!W)return;if(!G4(G.input,W.input)){if("input"in G)W.input=G.input;else delete W.input;return JSON.stringify(W)}return String(F.init?.body)}function Q4($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function w1($,Z){let z=new URL($);if(z.origin!=="https://api.openai.com"&&z.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(z.pathname))return $;let G=new URL(`${Q4(Z)}/responses`);if(G.search=z.search,z.protocol==="ws:"||z.protocol==="wss:")G.protocol=G.protocol==="https:"?"wss:":"ws:";return G.href}import{resolve as y1}from"node:path";var R$=Symbol.for("@cortexkit/openai-auth/opencode2-rate-limits/v1"),x$=globalThis,I1=x$[R$]??new Map;x$[R$]=I1;function S$($){let Z=I1.get($);if(!Z)Z=new Map,I1.set($,Z);return Z}function q$($){return S$(JSON.stringify(["pool",y1($.configPath),y1($.statePath)]))}function b$($){return S$(JSON.stringify(["vault",y1($)]))}import{resolve as D$}from"node:path";var Y4=1024;class Q1{accounts=new Map;limit;constructor($=Y4){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let z=this.accounts.keys().next().value;if(z===void 0)break;this.accounts.delete(z)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var k$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),w$=globalThis,f1=w$[k$]??new Map;w$[k$]=f1;function v1($){let Z=JSON.stringify([D$($.configPath),D$($.statePath)]),z=f1.get(Z);if(!z)z=new Q1,f1.set(Z,z);return z}var E2="openai",X4=60000,h1=1,j4="request refused: no account with a usable credential",C2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function B4($){let Z=C2($)?$.counters:void 0,z=C2(Z)?Z.resetCredits:void 0,G=C2(z)?z.value:void 0;return typeof G==="number"&&Number.isFinite(G)?G:void 0}function c2($){try{return JSON.parse($)}catch{return}}function u2($){let Z=j1($);return Z?B1(Z):void 0}var V4=new Set(["usage_limit_reached","rate_limit_exceeded"]);function c1($,Z,z){return{reason:$.window,...z!==void 0?{status:z}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function W4($,Z){let z=X1($);if(z){let Y=typeof $.status==="number"?$.status:void 0;return c1(z,Z,Y)}if($.type!=="response.failed"||!C2($.response))return;let G=$.response.failed;if(C2(G)&&typeof G.rate_limit_reached_type==="string")return{reason:G.rate_limit_reached_type};let X=$.response.error;if(C2(X)){let Y=typeof X.code==="string"?X.code:typeof X.type==="string"?X.type:void 0;if(Y&&V4.has(Y))return{reason:Y}}return}function U4($,Z){let z=c2($);if(!C2(z))return;let G=typeof z.type==="string"?z.type:void 0;if(G==="codex.rate_limits")return{quota:{snapshot:v$(z),complete:!0}};let X=W4(z,Z);if(X)return{limit:X};if(G===void 0||G==="error")return;return r$(G)?void 0:{outputStarted:!0}}function H4($){let Z=!1;for(let z of $.keys())if(z.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:I$($),complete:f$($)}}function N4($){let Z=$.get("retry-after");if(Z===null)return;let z=Number(Z);return Number.isFinite(z)&&z>=0?z*1000:void 0}function e$($){let Z=new WeakMap,z=new WeakSet,{source:G,pins:X}=$,Y=$.now??Date.now,F=$.log,W=$.vault,H=new k1($.codex),N=new Map,V=new Map,P=(Q)=>`${Q.sessionID}\x00${Q.kind}`,C=new Map,E=(Q)=>`${Q.sessionID}\x00${Q.kind}\x00${Q.accountId}`,h=W?.paths?.rosterPath,a=h?b$(h):new Map,A=$.sessionAccounts??new Q1,k=new i$,W2=(Q,K,_)=>{let M=_?[]:t$(G.peek().rows,Q,K,W?.identities()??new Set),D=(W?.routes()??[]).filter((O)=>O.kind==="oauth"&&g$(d2(O.quota),Q,K));return[...M.map((O)=>({id:O.id,...O.identity!==void 0?{identity:O.identity}:{},quota:O.quota,row:O})),...D.map((O)=>({id:O.id,...O.identity!==void 0?{identity:O.identity}:{},quota:O.quota}))]},X2=(Q,K,_)=>{let M=c$(Q,K,_),D=Q.map((q)=>({id:q.id,kind:"oauth",...y$(q.quota)?{quota:q.quota}:{}})),O=Q.flatMap((q)=>q.row?[q.row]:[]),R=new Set(Q.filter((q)=>!q.row).map((q)=>q.id)),f=G.rateLimitMarks(O);for(let q of R){let w=a.get(q);if(w===void 0)continue;if(w<=_)a.delete(q);else f.set(q,w)}return{rows:D,now:_,rateLimitMarks:f,refreshBackoff:G.refreshBackoffFor(O),killswitch:M,requestPull:(q)=>R.has(q)?W?.requestReading(q):G.requestReading(q)}},v=(Q,K,_,M,D)=>{let O=l1({...Q,placement:m1(K),mainId:D});if(O.kind==="block"){F?.debug("pool admission refused the request",{reason:O.block.reason});return}let R=O.order.filter((f)=>!_.has(f));if(M!==void 0&&R.includes(M))return M;return R[0]},n=(Q,K)=>{let _=new Map(Q.map((M)=>[M.id,M.quota]));return{requestBytes:h1,reservePercent:(M)=>m$(K,M===p$?void 0:M),resetCredits:(M)=>B4(_.get(M))}},K2=(Q,K,_,M,D,O,R,f)=>{let q=n(K,_),w=u1(Q),y=(c,m)=>V1(R,{sessionId:M,requestBytes:h1,validPinnedAccountIds:Q.rows.map(($2)=>$2.id).filter(($2)=>!w.excluded.has($2)),excludeAccountIds:c,quotaCheckedAtByAccount:Object.fromEntries(Q.rows.map(($2)=>[$2.id,w.projections.get($2.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(K.map(($2)=>[$2.id,$2.identity])),select:($2)=>f?{accountId:f,source:"mode-fallback",quotaCheckedAt:w.projections.get(f)?.checkedAt}:a$(Q,q,new Set(c),$2),persist:m},($2,T2)=>R.set($2,T2)),J2=[...D],G2=y(J2,O);if(!G2)return;let e=G2.accountId,s=p1(Q,q,e);if(s.kind==="none")return;if(s.kind==="move"){let c=y([...J2,e],O);if(c)return c.accountId;return s.reason==="killswitch"?void 0:e}if(s.kind==="detour")return y([...J2,e],!1)?.accountId;return e},b={providerID:E2,async retrySameAccount(Q){if(Q.continuation!=="interrupted-read")return;let K=V.get(P(Q));if(V.delete(P(Q)),!K||K.accountId!==Q.accountId||K.modelID!==Q.modelID||K.agent!==Q.agent||Q.limit)return;let _=W!==void 0&&await W.authority()!=="local",M=await $.storage();if(!_&&!(await G.current()).active)return;let D=Y(),O=W2(M,D,_),R=O.find((y)=>y.id===Q.accountId);if(!R)return;let f=X2(O,M,D),q=M?.routing?.mode??"main-first";if(q==="sticky-balanced"){let y=p1(f,n(O,M),Q.accountId);if(y.kind!=="serve"&&y.kind!=="last-path")return}else{let y=l1({...f,placement:m1(q),..._?{mainId:g1(W?.routes()??[])}:{}});if(y.kind==="block"||!y.order.includes(Q.accountId))return}let w=K.data;if(R.row){if(w?.kind!=="pool")return;let y=G.usableToken(R.row),J2=R.row.identity??(y&&u2(y));if(!y||!w.identity||J2!==w.identity)return}else{if(w?.kind!=="vault"||!W)return;let y=await W.authorize(Q.accountId);if(!y||y.credentialId!==w.credentialId||y.accountIdentity!==w.accountIdentity||(y.accountIdentity??u2(y.accessToken))!==w.wireIdentity||R.identity!==void 0&&R.identity!==w.wireIdentity)return}return{accountId:Q.accountId}},dropSameAccountRetry(){},dropChoice(Q){let K=E(Q);C.get(K)?.drop(),C.delete(K),N.delete(K)},chooseAccount:async(Q)=>{let K=await W?.authority(),_=await $.storage(),M=K!==void 0&&K!=="local",D=()=>{throw new F2({kind:"no-account",providerID:E2,sessionID:Q.sessionID,requestKind:Q.kind,message:W1})};if(M)await $.awaitVaultRoster?.();else{if(!(await G.current()).active){if(await $.slotPlaceholderWithoutMain?.())D();F?.warn("the account pool does not serve requests yet; refusing the request",{kind:Q.kind});return}await G.prepareTokens(G.peek().rows,_)}let O=Y(),R=W2(_,O,M),f=d$(X2(R.filter((T)=>T.id!==Q.rerouteFrom?.accountId),_,O));if(f)await f,O=Y(),R=W2(_,O,M);let q=new Map(R.map((T)=>[T.id,T])),w=X2(R,_,O),y=new Set(Q.rerouteFrom?[Q.rerouteFrom.accountId]:[]),J2=_?.routing?.mode??"main-first",G2=Q.kind==="primary",e=new Set,s,c,m,$2=!1,T2=(T)=>{let l=u1(w).projections.get(T)?.checkedAt,Z2=q.get(T)?.identity;return X.reserve(Q.sessionID,{accountId:T,inputBytes:h1,...l!==void 0?{quotaCheckedAt:l}:{},...Z2!==void 0?{wireIdentity:Z2}:{}})};try{for(;;){let T=new Set([...y,...e]);m=void 0,s=void 0;let l=J2!=="sticky-balanced";if(J2==="sticky-balanced"){let t=new Map(X.placementSnapshot(Q.sessionID)),B2=t.get(Q.sessionID);if(l=B2===void 0,m=K2(w,R,_,Q.sessionID,T,G2&&e.size===0,t),m!==void 0&&t.get(Q.sessionID)!==B2)s=t.get(Q.sessionID)}if(m??=v(w,J2,T,G2?void 0:A.activeAccount(Q.sessionID),M?J2==="sticky-balanced"?null:g1(W?.routes()??[]):void 0),m===void 0||e.has(m)){if(y.size>0){let t=new Map(w.rateLimitMarks);for(let B2 of y)t.delete(B2);w={...w,rateLimitMarks:t},y.clear();continue}if(w.rateLimitMarks.size>0){w={...w,rateLimitMarks:new Map};continue}m=void 0;break}if(G2&&J2==="sticky-balanced")c=T2(m);if(!$2){$2=!0;let t=await n$({vaultMode:M,fresh:l,sessionId:Q.sessionID,request:{modelId:Q.modelID,kind:Q.kind,retry:Q.phase==="retry"||Q.rerouteFrom!==void 0},routes:W?.routes()??[],routing:w,eligibleIds:R.filter((B2)=>!T.has(B2.id)).map((B2)=>B2.id)});if(t&&t!==m){if(c)X.rollback(c);if(c=void 0,J2==="sticky-balanced"){let B2=new Map(X.placementSnapshot(Q.sessionID));m=K2(w,R,_,Q.sessionID,T,G2,B2,t)??m,s=B2.get(Q.sessionID)??s}else m=t;if(G2&&J2==="sticky-balanced")c=T2(m)}}let Z2=q.get(m)?.row;if(Z2){if(G.usableToken(Z2)!==void 0)break;F?.debug("pool row holds no usable token; choosing again",{accountId:m})}else{if(!W)break;let t=await W.authorize(m);if(t){N.set(E({...Q,accountId:m}),t);break}F?.debug("the vault refused to serve an account; choosing again",{accountId:m})}if(c)X.rollback(c);c=void 0,e.add(m)}if(m===void 0&&!M&&R.length===0&&await $.slotPlaceholderWithoutMain?.())D();if(m===void 0&&M&&W&&(R.length===0||e.size>0)){let T=e.size>0?"vault-refused":u$(W);throw F?.warn("vault mode: no vault account can serve; refusing the request",{cause:T}),new F2({kind:"no-account",providerID:E2,sessionID:Q.sessionID,requestKind:Q.kind,message:l$(T,W.name)})}if(m!==void 0){let T=m,l=c,Z2=s,t=()=>{if(l)X.finish(l,Z2);if(G2)A.record(Q.sessionID,T),$.onRoute?.(Q.sessionID,T,J2)};if(Q.phase==="retry")C.set(E({...Q,accountId:m}),{commit:t,drop:()=>{if(l)X.rollback(l)}}),c=void 0;else t();let B2=F?.info;k.served(w,m,F&&B2?{info:(w2,r2)=>B2.call(F,w2,r2)}:void 0)}return F?.debug("pool account chosen",{kind:Q.kind,accountId:m,mode:J2,...Q.rerouteFrom?{rerouteFrom:Q.rerouteFrom.accountId}:{}}),m}finally{if(c)X.rollback(c)}},accountHeaders:async(Q)=>{let{accountId:K}=Q;V.delete(P(Q));let _=E(Q),M=C.get(_);C.delete(_);let D=()=>{M?.commit()};try{let O=()=>new F2({kind:"no-account",providerID:E2,sessionID:Q.sessionID,requestKind:Q.kind,message:j4}),R=W&&await W.authority()!=="local"?void 0:G.peek().rows.find((w)=>w.id===K);if(!R&&W){let w=E(Q),y=N.get(w)??await W.authorize(K);if(N.delete(w),!y)throw F?.warn("the vault refused to serve an account; refusing the request",{accountId:K}),O();return D(),{headers:{...D1,"session-id":Q.sessionID,authorization:`Bearer ${y.accessToken}`,"chatgpt-account-id":y.accountIdentity??u2(y.accessToken)??null},attempt:{kind:"vault",routeId:K,receipt:y}}}let f=R?G.usableToken(R):void 0;if(!R||!f)throw F?.warn("pool row holds no usable token; refusing the request",{accountId:K}),O();let q=R.identity??u2(f);return D(),{headers:{...D1,"session-id":Q.sessionID,authorization:`Bearer ${f}`,"chatgpt-account-id":q??null},attempt:{kind:"pool",token:f,credentialEpoch:R.credentialEpoch,...q!==void 0?{identity:q}:{}}}}finally{M?.drop()}},async rewriteRequest({request:Q,sessionID:K,kind:_}){let M=$.codexEndpoint?w1(Q.url,$.codexEndpoint()):Q.url,D=M===Q.url?Q:new Request(M,Q);return await C$(D,{sessionID:K,kind:_},H,$.responsesLite?.()??!1)??D},rewriteHandshakeURL:({url:Q})=>$.codexEndpoint?w1(Q,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:Q,sessionID:K,kind:_})=>A$(Q,{sessionID:K,kind:_},H),quotaFromHeaders:(Q,K,_)=>{if(_.data?.kind==="vault")W?.reportUsage(_.data.routeId,{headers:Q},_.data.receipt);if(_.data?.kind==="vault"&&p2()&&K>=200&&K<300)Z.set(_,{status:K,headers:Q});return H4(Q)},async limitFromResponse({status:Q,headers:K,body:_,attempt:M}){if(Q<400)return;let D=c2(await _().catch(()=>"")),O=X1({...C2(D)?D:{},status:Q});if(M.data?.kind==="vault"&&p2())Y1(M.sessionID,M.data.receipt,{status:Q,headers:K,body:D,limit:O,quota:W?.routes().find((w)=>w.id===M.accountId)?.quota,now:Y()});if(!O)return;let R=Y(),f=c1(O,R,Q);if(f.retryAfterMs!==void 0)return f;let q=N4(K);return q===void 0?f:{...f,retryAfterMs:q}},inspectEvent:({data:Q,transport:K,attempt:_})=>{if(_.data?.kind==="vault"&&Q.includes("codex.rate_limits")){let M=c2(Q);if(C2(M)&&M.type==="codex.rate_limits")W?.reportUsage(_.data.routeId,{frame:M},_.data.receipt)}if(_.data?.kind==="vault"&&p2()&&(s$(Q)||K==="ws"&&Q.includes('"response.completed"'))){let M=c2(Q);if(o$(M))z.add(_);if(K==="ws"&&C2(M)&&M.type==="response.completed")Y1(_.sessionID,_.data.receipt,{status:200,headers:new Headers,failed:z.has(_)})}return U4(Q,Y())},limitFromError(Q){let K=c2(Q.message),_=X1({...C2(K)?K:{},...Q.status!==void 0?{status:Q.status}:{}})??(Q.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return _?c1(_,Y(),Q.status):void 0},async onAttemptEnd(Q,K){let _=Q.data;if(_&&K.outputStarted&&K.error?.reason==="failed"){if(V.set(P(Q),{accountId:Q.accountId,modelID:Q.modelID,agent:Q.agent,sessionID:Q.sessionID,data:_.kind==="pool"?{kind:"pool",identity:_.identity}:{kind:"vault",credentialId:_.receipt.credentialId,accountIdentity:_.receipt.accountIdentity,wireIdentity:_.receipt.accountIdentity??u2(_.receipt.accessToken)}}),V.size>Z1){let D=V.keys().next().value;if(D!==void 0)V.delete(D)}}let M=_?.kind==="vault"&&p2()?Z.get(Q):void 0;if(Z.delete(Q),_?.kind==="vault"&&M&&!K.error&&!K.limit)Y1(Q.sessionID,_.receipt,{...M,failed:z.has(Q)});if(_?.kind!=="vault"||K.status!==401)return;F?.warn("a vault account answered 401; reporting it to the vault",{accountId:Q.accountId}),await W?.reportFailure(_.receipt,401)}},g=(Q,K,_)=>{let M=_.data;if(M?.kind==="vault"){W?.recordSnapshot(Q,K.snapshot,K.complete,M.receipt);return}if(M?.kind!=="pool")return;if(G.peek().rows.find((O)=>O.id===Q)?.credentialEpoch!==M.credentialEpoch){F?.debug("quota reading dropped: the row holds another credential",{accountId:Q});return}G.recordSnapshot(Q,K.snapshot,M.token,K.complete)},p=(Q,K,_)=>{let M=Y(),D=_.data?.kind==="vault",O=D?W?.routes().find((q)=>q.id===Q)?.quota:G.peek().rows.find((q)=>q.id===Q)?.quota,R=h$(d2(O),K.reason,M,X4,K.retryAfterMs!==void 0?M+K.retryAfterMs:void 0);if(!D){G.markRateLimited(Q,R);return}let f=a.get(Q);if(f===void 0||f<R)a.set(Q,R)};return{adapter:b,attach(Q){Q.on("quota",(K)=>g(K.accountId,K.quota,K.handle)),Q.on("limit",(K)=>{p(K.accountId,K.limit,K.handle),F?.debug("pool row refused the request",{accountId:K.accountId,via:K.via,reason:K.limit.reason,outputStarted:K.outputStarted})})},forgetSession(Q){for(let[K,_]of V)if(_.sessionID===Q)V.delete(K);X.forget(Q),A.forget(Q),H.forget(Q)},activeAccount:(Q)=>A.activeAccount(Q)}}import{resolve as QZ}from"node:path";import{Buffer as F4}from"node:buffer";import{resolve as $Z}from"node:path";function i2($){return F4.byteLength(JSON.stringify($))}function K4($){return $.reduce((Z,z)=>Z+i2(z),0)}function d1($,Z){return 2+$+Math.max(0,Z-1)}function T4($){let{head:Z,pending:z}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+d1(Z.inputBytes,Z.input.length)+1:0)+(z?20+d1(z.inputBytes,z.input.length)+10+d1(z.outputBytes,z.output.length)+(z.responseID===void 0?0:14+z.responseIDBytes)+1:0)}function ZZ($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class JZ{enabled;caps=U1;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$)this.entries.clear(),this.bytes=0}send($,Z){if(!this.enabled)return;let z=ZZ(Z);if(z?.type!=="response.create")return;if(!Array.isArray(z.input)){this.forget($);return}let G=z.previous_response_id,X=this.entries.get($),Y=X?.head;if(G&&G!==Y?.responseID){this.forget($);return}let{type:F,previous_response_id:W,input:H,...N}=z;this.keep($,{fields:G&&X?X.fields:N,fieldsBytes:G&&X?X.fieldsBytes:i2(N),...G&&Y?{head:Y}:{},pending:{input:H,inputBytes:K4(H),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,z){if(!this.enabled||!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed"))return;let G=this.entries.get($);if(!G?.pending)return;let X=ZZ(Z);if(!X)return;let Y=G.pending,F=X.response;if(X.type==="response.created"&&typeof F?.id==="string")Y.responseID=F.id,Y.responseIDBytes=i2(F.id),this.keep($,G);else if(X.type==="response.output_item.done"&&X.item){if(typeof X.response_id==="string"&&Y.responseID!==void 0&&X.response_id!==Y.responseID)return;Y.output.push(X.item),Y.outputBytes+=i2(X.item),this.keep($,G)}else if(X.type==="response.completed"&&typeof F?.id==="string"){if(F.id===G.head?.responseID||Y.responseID!==void 0&&F.id!==Y.responseID)return;let W={responseID:F.id,responseIDBytes:Y.responseID===F.id?Y.responseIDBytes:i2(F.id),input:[...G.head?.input??[],...Y.input,...Y.output],inputBytes:(G.head?.inputBytes??0)+Y.inputBytes+Y.outputBytes},H={...G,head:W,pending:void 0};if(!this.keep($,H))return;z?.({sessionID:$,responseID:W.responseID,bodyText:this.body(G.fields,W)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let z=T4(Z);if(this.forget($),z>this.caps.maxBytes)return!1;Z.bytes=z,this.entries.set($,Z),this.bytes+=z;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let G=this.entries.keys().next().value;if(G===void 0)break;this.forget(G)}return this.entries.has($)}}var zZ=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),GZ=globalThis,i1=GZ[zZ]??new Map;GZ[zZ]=i1;function H1($){let Z=JSON.stringify([$Z($.configPath),$Z($.statePath)]),z=i1.get(Z);if(!z)z=new JZ,i1.set(Z,z);return z}var _4=5000,L4=["accept","originator","session-id","thread-id","user-agent","version","x-client-request-id","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-openai-internal-codex-responses-lite","x-opencode-parent-session-id","x-parent-session-id"],P4=["x-opencode-parent-session-id","x-parent-session-id"];function BZ($){let Z=YZ($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:XZ($?{...$,cachekeep:Z}:$)}}var VZ=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),WZ=globalThis,a2=WZ[VZ]??new Map;WZ[VZ]=a2;function M4($,Z){let z=[],G=()=>z.at(-1)?.location,X=()=>{let H=G();if(!H)throw Error("no location holds keep-warm");return H},Y=(H,N)=>{W.remove(H),G()?.log?.debug(`cachekeep dropped target (${N})`,{sessionKey:H})},F=async(H)=>{if(H.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let N=H.accountId??"main",V=X(),P=await V.source.accessFor(N,await V.storage());if(!P)throw Error(`pool row ${N} has no usable token`);return{token:P.token,identity:P.row.identity}},W=jZ({...U1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(H,N)=>X().fetch(H,N),logger:{debug:(H,N)=>G()?.log?.debug(H,N),warn:(H,N)=>G()?.log?.warn(H,N)},getWindow:()=>G()?.settings().window,getSustain:()=>G()?.settings().sustain===!0,resolveLocal:F,vault:{owns:(H)=>G()?.vault.owns(H)===!0,authority:()=>X().vault.authority(),reportUsage:(...H)=>G()?.vault.reportUsage(...H),send:async(H,N,V)=>{let P=X();if(await P.vault.authority()!=="vault")return;return P.vault.send(H,N,V)}},activeAccount:(H)=>{if(H===void 0)throw Error("target has no session");let N=G(),V=N?.settings();if(!N||!V?.enabled){Y(H,"keep-warm is off");return}if(!V.subagents&&W.status().targets.some((C)=>C.sessionKey===H&&C.isSubagent)){Y(H,"subagent warming is off");return}let P=N.accounts.activeAccount(H);if(P===void 0){Y(H,"no account recorded for the session");return}return P},verifyCredential:({target:H,mode:N,identity:V})=>{if(H.meta.credentialMode!==N)throw Error(`a target captured in ${H.meta.credentialMode??"an unknown"} mode is not warmed with a ${N} credential`);if(V!==H.meta.chatgptAccountId)throw Y(H.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:W,settings:Z,holders:z,joinTimeoutMs:$.joinTimeoutMs??_4}}function E4($){try{let Z=JSON.parse($),z=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(z?.role!=="user")return!1;return(typeof z.content==="string"?z.content:Array.isArray(z.content)?z.content.map((X)=>typeof X?.text==="string"?X.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function C4($){let Z={};for(let z of L4){let G=$.get(z);if(G)Z[z]=G}return Z}function UZ($,Z,z){let G=JSON.stringify([QZ($.configPath),QZ($.statePath)]),X=a2.get(G);if(!X)X=M4(z,Z.settings()),a2.set(G,X);let Y=X,F=H1($);F.setEnabled(Y.settings.enabled);let W={location:{...Z,settings:()=>Y.settings}};Y.holders.push(W);let H=!1,N=async(V)=>{try{let P=W.location.settings();if(H||!P.enabled)return;if(V.kind!=="primary"){if(V.kind==="generate"&&E4(await V.request.clone().text())){if(H)return;Y.manager.remove(V.sessionID)}return}let C=V.attempt.data,E=C?.kind==="pool"?"local":C?.kind==="vault"?"vault":void 0;if(!E)return;let h=V.request.headers,a=P4.some((W2)=>h.has(W2))||Z.parentOf!==void 0&&await Z.parentOf(V.sessionID)!==void 0;if(a&&!P.subagents)return;let A=await V.request.clone().text();if(H)return;let k=h.get("chatgpt-account-id")??void 0;Y.manager.track({sessionKey:V.sessionID,bodyText:A,accountId:V.attempt.accountId,isSubagent:a,meta:{replayHeaders:C4(h),...k?{chatgptAccountId:k}:{},routingSessionId:V.sessionID,url:V.request.url,credentialMode:E}})}catch(P){Z.log?.warn("cachekeep capture failed",{error:P instanceof Error?P.message:String(P)})}};return{manager:Y.manager,configure:(V)=>{Object.assign(Y.settings,V),F.setEnabled(Y.settings.enabled)},capture:N,forget:(V)=>Y.manager.remove(V),async release(){if(H)return;H=!0;let V=Y.holders.indexOf(W);if(V>=0)Y.holders.splice(V,1);if(Y.holders.length>0)return;if(a2.get(G)===Y)a2.delete(G);Y.manager.stop();let P;try{await Promise.race([Y.manager.tick().catch(()=>{}),new Promise((C)=>{P=setTimeout(C,Y.joinTimeoutMs),P.unref?.()})])}finally{clearTimeout(P)}}}}import{mkdirSync as O4}from"node:fs";import{dirname as A4,resolve as R4}from"node:path";function x4(){return HZ("opencode2")}var S4=2000;class _Z{path;options;sessions;frameTurns=new I2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Q=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=KZ($,Z.uuid??k2)}get($,Z=k2){let z=this.sessions.get($);if(!z){let G=Z();z={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,z),this.#Z.delete($),this.#z.delete($),this.#$.add($),this.#Y()}return z}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#z.add($);this.#Y()}#Y(){if(this.#J)return;this.#J=setTimeout(()=>{this.#J=void 0,this.save()},this.options.saveDelayMs??S4),this.#J.unref?.()}save(){if(clearTimeout(this.#J),this.#J=void 0,!this.#Q)this.#Q=!0,this.#G=this.#G.then(()=>{return this.#Q=!1,this.#j()});return this.#G}settled(){return this.#J?this.save():this.#G}#X(){if(this.#z.size===0)return;let $;try{$=a1(this.path)}catch{$=new Map}for(let Z of this.#z)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#z.clear()}async#j(){if(this.#X(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((G)=>{let X=this.sessions.get(G);return X?[[G,X]]:[]}),Z=[...this.#Z],z=null;try{if(O4(A4(this.path),{recursive:!0}),z=await this.#B(),!z)return;let G;try{G=a1(this.path)}catch{G=new Map}await this.options.afterRead?.();let X=!1;for(let Y of Z)if(G.delete(Y))X=!0;for(let[Y,F]of $){if(G.get(Y)===F.threadID)continue;G.set(Y,F.threadID),X=!0}if(X)TZ(this.path,G)}catch{return}finally{await z?.release().catch(()=>{})}for(let[G,X]of $)if(this.sessions.get(G)===X)this.#$.delete(G);for(let G of Z)if(!this.sessions.has(G))this.#Z.delete(G)}#B(){return FZ(this.path,this.options.lockWaitMs??NZ)}}var LZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),PZ=globalThis,N1=PZ[LZ]??new Map;PZ[LZ]=N1;function q4($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.sessions instanceof Map&&typeof Z.get==="function"&&typeof Z.delete==="function"&&typeof Z.save==="function"&&typeof Z.settled==="function"&&(Z.frameTurns===void 0||Z.frameTurns!==null&&typeof Z.frameTurns.advance==="function"&&typeof Z.frameTurns.get==="function"&&typeof Z.frameTurns.completed==="function"&&typeof Z.frameTurns.forget==="function")}function MZ($=x4()){let Z=R4($),z=N1,G=N1.get(Z),X=N1;if(G!==void 0&&!q4(G))z.compatible??=new Map,X=z.compatible;let Y=X.get(Z);if(!Y)Y=new _Z(Z),X.set(Z,Y);let F=Y;return F.frameTurns??=new I2,Y}var n1=Symbol.for("cortexkit.openai-auth.v2.commands"),b4=R2("v2-command");function F1($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.closed instanceof AbortController&&typeof Z.menu?.open==="function"&&typeof Z.menu?.apply==="function"&&typeof Z.session?.get==="function"&&(Z.registration===void 0||Z.registration!==null&&typeof Z.registration.dispose==="function")}function o1($){b4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function D4(){let $=globalThis;return $[n1]??={locations:new Map},$[n1].locations??=new Map,$[n1]}async function SZ($,Z){let z=D4(),G=$.location.directory,X={menu:Z,session:$.session,closed:new AbortController},Y=await CZ(G),F=await EZ(RZ,Y.dir,()=>xZ({...Y,drain:AZ,apply:(P)=>{let C=z.locations.get(G);if(!F1(C))throw Error("The OpenAI menu location was closed");return C.menu.apply(P)}})),W=z.locations.get(G);if(z.locations.set(G,X),F1(W))W.closed.abort(),await W.registration?.dispose();let H={name:"openai",description:"OpenAI account menu",async execute(P){let C=[...z.locations.values()].find(F1)?.session;if(!C)return o1("no live location");let E=await C.get({sessionID:P.sessionID}),h=z.locations.get(E.location.directory);if(!F1(h))return o1("location closed");let a=await OZ(P.sessionID,h.closed.signal);if(!a||z.locations.get(E.location.directory)!==h){if(!a&&!h.closed.signal.aborted)s1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},P.sessionID);return o1(h.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let A=await h.menu.open(P.sessionID);s1(A,P.sessionID)}};z.command??=H,z.command.execute=H.execute;let N=z.command;try{X.registration=await $.command.transform((P)=>{P.add(N)})}catch(P){if(X.closed.abort(),z.locations.get(G)===X)z.locations.delete(G);throw await F.release(),P}let V=!1;return async()=>{if(V)return;if(V=!0,X.closed.abort(),z.locations.get(G)===X)z.locations.delete(G);await F.release(),await X.registration?.dispose()}}var k4="openai-auth-pool-browser",w4="openai-auth-pool-headless",y4="openai-auth-vault",I4="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Run /openai → Vault → Connect and approve the request before trying again.";async function n2($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function yZ($){return{method:{id:y4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await qZ($.paths,$.name)!=="vault")throw Error(I4)}}}function IZ($){let Z=(z,G,X)=>({method:{id:z,type:"oauth",label:G},async authorize(){if($.vault)await n2($.vault);let Y=await $.beginLogin({version:$.version,headless:X});return{url:Y.url,instructions:Y.instructions,mode:"auto",callback:Y.completion}}});return[Z(k4,"ChatGPT (openai-auth pool, browser)",!1),Z(w4,"ChatGPT (openai-auth pool, headless)",!0)]}function r1($){let Z=(z)=>typeof z==="string"?z:"";return m2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===kZ||bZ($)}function f4($){if($.accountId)return $.accountId;let Z=$.access?j1($.access):void 0;return Z?B1(Z):void 0}async function fZ($,Z,z,G={}){if(G.vault)await n2(G.vault);if(r1(z))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let X=DZ($,{rowLocks:(E)=>wZ(Z,E)}),Y=await X.read();if(Y.status!=="ready")throw Error(`the account pool cannot be read (${Y.status}); the login was not stored`);let F={type:"oauth",refresh:z.refresh,...z.access!==void 0?{access:z.access}:{},...z.expires!==void 0?{expires:z.expires}:{}},W=f4(z);if(G.vault)await n2(G.vault);let H=W!==void 0?{identity:W}:{};if(G.origin==="import"){let E=Y.rows.find((h)=>W!==void 0&&h.identity===W||h.credential?.type==="oauth"&&h.credential.refresh===z.refresh);if(E)return{id:E.id,operation:"kept"}}let N=Y.rows.filter((E)=>E.type==="oauth"&&!E.invalid),V=W?N.find((E)=>E.identity===W):void 0,P=Y.rows.find((E)=>E.id===K1);if(V)return{id:(await X.replace(V.id,F,H)).id,operation:"replaced"};if(!P){let E=await X.add({id:K1,credential:F,...H,...z.label!==void 0?{label:z.label}:{}});return{id:E.id,operation:E.outcome==="added-disabled"?"added-disabled":"added"}}if(!P.invalid&&!P.credential)return{id:(await X.replace(K1,F,H)).id,operation:"replaced"};let C=await X.add({id:z.id,credential:F,...H,...z.label!==void 0?{label:z.label}:{}});return{id:C.id,operation:C.outcome==="added-disabled"?"added-disabled":C.outcome==="rotated"?"replaced":"added"}}function v4($){let Z=$.itemId!==void 0;switch($.sectionId){case"accounts":return Z?["enable","disable","remove","move"].includes($.actionId):$.actionId==="add";case"routing":return!Z&&["order","mode"].includes($.actionId);case"quota":return $.actionId==="check";case"limits":return Z?$.actionId==="floors":$.actionId==="killswitch";case"session":return!Z&&$.actionId==="clear-pin";case"vault":return Z?["enable","disable"].includes($.actionId):["connect","disconnect"].includes($.actionId);case"diagnostics":return!Z&&["logging","dump"].includes($.actionId);case"cache":return!Z&&["enabled","subagents","sustain","window"].includes($.actionId);case"reset":return Z&&["preview","spend","retry"].includes($.actionId);default:return!1}}function gZ($){let Z={...$,allowAction:v4,unavailableSections:[]};return{open:(z)=>vZ(Z,z),apply:(z)=>{let G=z!==null&&typeof z==="object"?z:{},X=G.values&&typeof G.values==="object"&&!Array.isArray(G.values)?Object.fromEntries(Object.entries(G.values).filter(([,Y])=>Y===null||["string","number","boolean"].includes(typeof Y))):void 0;return hZ(Z,{command:"openai",sectionId:typeof G.sectionId==="string"?G.sectionId:"",actionId:typeof G.actionId==="string"?G.actionId:"",...X?{values:X}:{},...G.confirmed===!0?{confirmed:!0}:{},...typeof G.itemId==="string"?{itemId:G.itemId}:{},...typeof G.sessionId==="string"?{sessionId:G.sessionId}:{}})}}}function h4($,Z){if(!mZ($.modelID??$.id)){$.enabled=!1;return}let z=lZ($.id);if(z)$.limit={...z};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((G)=>[G.id,G])).values()]}function pZ($){return $.model.transform((Z)=>{let z=Z.list(E2);for(let G of z){let X=uZ(String(G.id)),Y=X?z.find((F)=>String(F.id)===X):void 0;Z.update(E2,String(G.id),(F)=>h4(F,Y?.variants?.map((W)=>({...W,id:String(W.id)}))))}})}class t1{log;pending=new Map;requests=new Map;writing=new Set;constructor($){this.log=$}async safely($){let Z=(async()=>{try{await $()}catch{this.log.warn("request dump failed")}})();this.writing.add(Z);try{await Z}finally{this.writing.delete(Z)}}async captureHttp($,Z){if(!cZ())return;await this.safely(async()=>{let z={sessionID:Z.sessionID,accountId:Z.accountId,transport:"http",phase:"http",url:$.url,method:$.method,headers:new Headers($.headers),bodyText:await $.clone().text()};if(this.pending.set($,{attemptId:Z.attemptId,input:z}),this.requests.set(Z.attemptId,$),this.pending.size>512){let G=this.pending.keys().next().value;if(G)this.take(G)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let z=this.take($);if(z)await this.safely(()=>T1({...z,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let z=this.requests.get($.attemptId),G=z&&this.take(z);if(!G)return;let{reason:X,message:Y}=Z.error,F=Y?`${X}: ${Y}`:X;await this.safely(()=>T1({...G,error:_1(F,z?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>T1({sessionID:Z.sessionID,accountId:Z.accountId,transport:"websocket",phase:"observed",bodyText:$}))}clear(){this.pending.clear(),this.requests.clear()}async settle(){await Promise.all(this.writing)}}class e1{counts=new Map;record($,Z){let z=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof z==="number"&&Number.isFinite(z)?z:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function oZ($){return async(Z)=>{let z=Z.credential;if(z.type!=="oauth"||!z.access)throw Error("the row holds no access token to poll with");let G=await dZ({accessToken:z.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,G),iZ(G,$.now(),!0)}}function sZ($){let{source:Z,counts:z,now:G}=$,X=async(N)=>{let V=await Z.rowAccess(N,await $.storage());if(!V?.row)throw new aZ("unknown_account",`${N==="main"?"Main":"Fallback"} account ${N} was not found.`);return nZ(N,V)},Y=async(N)=>{if($.authority&&await $.authority()!=="local")return{account:N,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[V]=await Z.pollRows(await $.storage(),{ids:[N]});if(!V)return{account:N,ok:!1,error:"targeted quota refresh returned no result"};return{account:V.id,ok:V.ok,...V.error!==void 0?{error:V.error}:{}}},F=(N)=>Z.peek().rows.find((V)=>V.id===N),W=(N)=>{let V=F(N);if(!V)return null;let P=d2(V.quota)??{},C=z.applicable(V),E=Math.max(0,...[P.primary?.checkedAt,P.secondary?.checkedAt].filter((h)=>typeof h==="number"));return{quota:{...P,...C!==void 0?{resetCreditsApplicable:C}:{}},checkedAt:E,refreshAfter:E,...V.identity!==void 0?{accountId:V.identity}:{}}};return{resolveResetTarget:X,refreshResetTargetQuota:Y,quotaManager:{isRateLimited:(N)=>{let V=F(N);if(!V)return!1;let P=Z.rateLimitMarks([V]).get(V.id);return P!==void 0&&P>G()},getMain:()=>W("main"),getFallback:(N)=>W(N)}}}import{resolve as rZ}from"node:path";var g4=1024;class $${pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=g4){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.reservations.delete($),this.pins.delete($);for(let Z of this.listeners)Z($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}snapshot(){return new Map(this.pins)}placementSnapshot($){let Z=new Map(this.pins);for(let z of this.reservations.values())if(z.sessionId!==$)Z.set(z.sessionId,z.pin);return Z}reserve($,Z){let z={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,z),z}rollback($){if(this.reservations.get($.sessionId)===$)this.reservations.delete($.sessionId)}finish($,Z){if(this.reservations.get($.sessionId)!==$)return;if(this.rollback($),Z&&this.pins.get($.sessionId)===$.previous)this.set($.sessionId,Z)}get size(){return this.pins.size}set($,Z){this.reservations.delete($),this.pins.delete($),this.pins.set($,Z);for(let z of this.listeners)z($,Z);while(this.pins.size>this.limit){let z=this.pins.keys().next().value;if(z===void 0)break;this.forget(z)}}place($){return V1(this.placementSnapshot($.sessionId),$,(Z,z)=>this.set(Z,z))}}var tZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),eZ=globalThis,L1=eZ[tZ]??new Map;eZ[tZ]=L1;function m4($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.get==="function"&&typeof Z.forget==="function"&&typeof Z.subscribe==="function"&&typeof Z.snapshot==="function"&&typeof Z.place==="function"&&typeof Z.placementSnapshot==="function"&&typeof Z.reserve==="function"&&typeof Z.rollback==="function"&&typeof Z.finish==="function"}function $0($){let Z=JSON.stringify([rZ($.configPath),rZ($.statePath)]),z=L1,G=L1.get(Z);if(G!==void 0&&!m4(G)){let Y=L1;Y.compatibleV1??=new Map,z=Y.compatibleV1}let X=z.get(Z);if(!X)X=new $$,z.set(Z,X);return X}import{statSync as l4}from"node:fs";import{resolve as u4}from"node:path";function B0($){return $.map((Z)=>{try{let z=l4(Z);return`${z.ino}:${z.size}:${z.mtimeMs}:${z.ctimeMs}`}catch{return"?"}}).join("|")}function Z$($){return B0([$.vault.paths.tokenPath,$.vault.paths.statePath])}function Z0($){return B0([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+Z$($)}class V0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;protocol=U0;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:Z0($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),z=this.subscriptions.get($.pins);if(!z){let G=new Set;z={producers:G,stop:$.pins.subscribe((X,Y)=>{let F=G.values().next().value;if(F)this.publish(F,{sessionId:X,pin:Y,accountId:Y?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,z)}return z.producers.add($),this.timer??=setInterval(()=>{for(let G of this.producers){let X={stamp:Z0(G),roster:G.vault.snapshot()},Y=this.observations.get(G);if(X.stamp!==Y?.stamp||X.roster!==Y?.roster)this.observations.set(G,X),this.publish(G)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),z.producers.delete($),!z.producers.size)z.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;await($.write??W0)(this.file,$,Z,()=>this.producers.has($))}).catch(()=>{R2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var W0=async($,Z,z,G)=>{let Y=await Z.vault.authority()!=="local",F=Z$(Z),W=()=>G()&&Z.vault.enrolled()===Y&&Z$(Z)===F,H=await(Y?s2(Z.paths):f2(Z.paths)),N=Y?X0(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((C)=>C.id)),H,Date.now()):j0((await Z.source.sidebarView()).rows,H,Date.now()),V={canWrite:W,vaultMode:Y};if(await z0(N,$,V),!W()||!z)return;let P=N.vaultAccounts??N.fallbacks;if(z.accountId===void 0){await Q0(z.sessionId,P,$,V);return}if(z.pin){let C=Date.now();await Y0({sessionId:z.sessionId,assignment:{accountId:z.pin.accountId,wireAccountId:z.pin.wireIdentity,inputBytes:z.pin.inputBytes??0,quotaCheckedAt:z.pin.quotaCheckedAt,assignedAt:C,lastSeenAt:C},validPinnedAccountIds:[...Y?[]:["main"],...P.filter((E)=>E.enabled).map((E)=>E.id)]},$,V)}await G0({sessionId:z.sessionId,activeId:z.accountId,route:z.route??N.route,updatedAt:Date.now()},P,$,V)},U0=2,H0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),N0=globalThis,o2=N0[H0]??new Map;N0[H0]=o2;function F0($,Z=J0(),z=2000){let G=u4(Z),X=o2.get(G);if(X?.protocol!==U0)X=new V0(G,z),o2.set(G,X);let Y=X;$={...$,write:$.write??W0};let F=Y.add($),W=!1;for(let[H,N]of $.pins.snapshot())Y.publish($,{sessionId:H,pin:N,accountId:N.accountId,route:"sticky-balanced"});return{publish:()=>Y.publish($),route:(H,N,V)=>{Y.publish($,{sessionId:H,accountId:N,route:V})},async release(){if(W)return;if(W=!0,F(),await Y.settled(),Y.empty&&o2.get(G)===Y)o2.delete(G)}}}var E1="cortexkit-openai-auth",d4=5000;async function K0($,Z,z,G=new l2,X,Y,F){let W=new t1(z),H=new p4,N=new Map,V=new Map,P=(A)=>{V.delete(A);for(let k of N.keys())if(k.startsWith(`${A}:`))N.delete(k)},C=(A)=>{F?.(A.sessionID),Y?.send(A.sessionID,A.frame)},h=await q1({session:{hook:(A,k,W2)=>$.session.hook(A,async(X2)=>{let v=A==="http.request"?X2:void 0,n=A==="experimental.ws.handshake"?X2:void 0,U2=(v?v.request.headers:n?new Headers(n.headers):void 0)?.get("authorization")===`Bearer ${A2(Z.providerID)}`,j2={};if(n)N.delete(`${n.sessionID}:${n.kind}`);try{await H.run(j2,()=>k(X2))}catch(b){if(U2&&!(b instanceof F2))throw E0(b);throw b}if(v&&U2&&j2.attempt){let b=v.request.headers.get("thread-id");if(b)v.request.headers.set("session-id",b)}if(v&&U2&&j2.attempt)await W.captureHttp(v.request,j2.attempt);if(v&&U2&&j2.attempt)await X?.({sessionID:v.sessionID,kind:v.kind,request:v.request,attempt:j2.attempt});if(n&&U2&&j2.attempt)n.headers["session-id"]=G.get(n.sessionID).threadID;if(A==="experimental.ws.send"){let b=X2,g=N.get(`${b.sessionID}:${b.kind}`);if(g)await W.frame(b.frame,g.attempt);if(g&&b.kind==="primary")C(b)}if(v||n){let b=v??n;if(!b)return;let p=(v?v.request.headers:new Headers(b.headers)).get("authorization")?.replace(/^Bearer /,"");if(U2&&p)V.set(b.sessionID,p);else V.delete(b.sessionID);if(n){let Q=`${n.sessionID}:${n.kind}`;if(U2&&p&&j2.attempt)N.set(Q,{bearer:p,attempt:j2.attempt,url:n.url,headers:new Headers(Object.entries(n.headers).filter(([K])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(K.toLowerCase())))});else N.delete(Q)}if(V.size>512){let Q=V.keys().next().value;if(Q)V.delete(Q)}if(N.size>512){let Q=N.keys().next().value;if(Q)N.delete(Q)}}else if(A==="experimental.ws.receive"){let b=X2,g=N.get(`${b.sessionID}:${b.kind}`);if(g){if(G.frameReceived(b.sessionID,b.frame),b.kind==="primary"){let p;if(Y?.receive(b.sessionID,b.frame,(Q)=>{p=Q}),p)try{let Q=O$(p,g.url,g.headers,G);if(Q)await X?.({sessionID:b.sessionID,kind:"primary",request:Q,attempt:g.attempt})}catch(Q){z.warn("cachekeep WebSocket capture failed",{error:Q instanceof Error?Q.message:String(Q)})}}b.frame=C0(b.frame,g.bearer)}}else if(A==="retry"){let b=X2,g=V.get(b.sessionID);if(g)Object.assign(b.error,{message:_1(b.error.message,g)})}},W2)},event:{subscribe:(A)=>async function*(){for await(let k of $.event.subscribe(A)){if(k.type==="session.deleted")P(k.data.sessionID);yield k}}()}},{...Z,rewriteRequest:async(A)=>{let k=H.getStore();if(k)k.attempt=A.attempt;return Z.rewriteRequest?.(A)},rewriteHandshakeURL:(A)=>{let k=H.getStore();if(k)k.attempt=A.attempt;return Z.rewriteHandshakeURL?.(A)},onAttemptEnd:async(A,k)=>{await W.end(A,k),await Z.onAttemptEnd?.(A,k)},rewriteResponse:async(A)=>{await W.response(A.request,A.response.status);let k=await Z.rewriteResponse?.(A)??A.response;return O0(k,A.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(A)=>{let k=A.get("authorization");return k?.startsWith("Bearer ")?k.slice(7):void 0}},logger:{warn:(A,k)=>z.warn(A,{data:k})}}),a=h.dispose;return{...h,dispose:async()=>{V.clear(),N.clear(),await a(),await W.settle(),W.clear()}}}function G$($={}){return{id:E1,setup:(Z)=>i4(Z,$)}}async function i4($,Z={}){let c=[];try{let z=R2("opencode2");let G=R2("quota");let X=Z.version??R0;await h0({version:X,...Z.runtimeLayout});let Y=Z.paths??(()=>S0(A0()));let F=await s2(Y());let W=F?.logging?.level;if(W&&typeof W==="string")_0(W);let H=Z.fetch??fetch;let N=Z.now??Date.now;let V=Z.poolMigration??m0;if(!V&&!v2(Y().configPath)){z.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let T=(Z2)=>{throw new F2({kind:"no-account",providerID:E2,sessionID:Z2.sessionID,requestKind:Z2.kind,message:W1})},l=await K0($,{providerID:E2,chooseAccount:T,accountHeaders:T},z);return()=>l.dispose()}let P=Z.vault?.firstRosterWaitMs??w0;let C=g0({host:"opencode",stateDir:Z.vault?.stateDir??M0(Y().statePath),reservedRouteIds:()=>v.peek().rows.map((T)=>T.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>H},Y());let E=C.vault;let h=async()=>await E.authority()==="local"?f2(Y()):s2(Y());let a=!1;let A=!1;const k=P1(c,{[Symbol.dispose](){if(!a)C.release()}},0);await E.authority();let W2=C.firstRoster;let X2=new e1;let v=new y0({paths:Y,rateLimitMarks:q$(Y()),refreshProvider:async(T)=>{let l=await P0({refreshToken:T.refresh,fetchImpl:H,now:N}),Z2=L0({id_token:"",access_token:l.access,refresh_token:l.refresh});return{...l,...Z2?{identity:Z2}:{}}},pullQuota:oZ({fetchImpl:H,now:N,counts:X2,logger:G}),now:N,vaultIdentities:()=>E.identities(),vaultMode:()=>E.enrolled(),vaultAuthority:()=>E.authority(),vaultFirstRoster:W2,vaultFirstRosterBackgroundWaitMs:P,log:R2("pool")});if(await E.authority()==="local")await v.load();let n=Z.heartbeat===!1?void 0:await f0({version:X,logger:R2("heartbeat")});let K2=Z.fence??(()=>x0({currentVersion:X}));let U2=Z.slot??l0();let j2=async()=>q0(Y(),await U2.get({path:{id:"openai"}}));let b=!1;let g=V?I0({paths:Y,slot:U2,version:X,fence:K2,runDeps:{vaultServes:()=>E.serves()},paused:async()=>await E.authority()!=="local",migrate:async(T)=>{let l=await b0(T);if(b=l.status==="refused",!A)await v.load();return l},adopt:async(T)=>{if(A)return{status:"retry",reason:"unsettled"};if(!await z$(W2,P))return{status:"retry",reason:"vault-roster-pending"};if(A)return{status:"retry",reason:"unsettled"};let l=await D0(T);if(!A)await v.load();return l}}):void 0;g?.start();C.start();let p=$0(Y());let Q=F0({paths:Y(),source:v,pins:p,vault:E},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const K=P1(c,{[Symbol.dispose](){if(!a)Q.release()}},0);Q.publish();let _=Z.codex??new l2(void 0,void 0,MZ());let M=BZ(F);let D=H1(Y());let O=UZ(Y(),{source:v,storage:h,vault:E,accounts:v1(Y()),settings:()=>M,parentOf:async(T)=>(await $.session.get({sessionID:T}))?.parentID??void 0,fetch:H,log:R2("cachekeep")},{now:N,codexResponsesUrl:M1().codexApiEndpoint,...Z.cacheKeep});const R=P1(c,{[Symbol.dispose](){if(!a)O.release()}},0);let f=e$({codex:_,onRoute:Q.route,source:v,slotPlaceholderWithoutMain:j2,storage:h,pins:p,sessionAccounts:v1(Y()),vault:E,awaitVaultRoster:async()=>{await z$(E.awaitRequestRoster(),k0)},responsesLite:()=>M1().responsesLite,codexEndpoint:()=>M1().codexApiEndpoint,now:N,log:z});let q=await K0($,f.adapter,z,_,(T)=>O.capture(T),D,(T)=>O.forget(T));f.attach(q);let w=async(T)=>{if(await n2(E),v2(Y().configPath))return;if(await g?.idle(),v2(Y().configPath))return;if(b&&!r1(T)&&(await K2()).open){await v.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let y=async(T)=>{await w(T);let l=await fZ(v.poolStore(),Y(),T,{vault:E});if(!v2(Y().configPath))await g?.requestAdoption();await v.load(),z.info("ChatGPT login stored in the account pool",l)};let J2=await R1($,{integrationID:E2,methods:IZ({beginLogin:Z.beginLogin??J$,version:X,vault:E}),onLogin:(T)=>y(T),label:"ChatGPT (openai-auth account pool)",vault:yZ(E)});let G2=await pZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let e=$.command&&$.location?await SZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??gZ({...sZ({source:v,storage:h,counts:X2,now:N,authority:()=>E.authority()}),fetchImpl:H,now:N,randomUUID:c4,accountStoragePath:Y().configPath,accountStatePath:Y().statePath,packageVersion:X,layoutNotice:v0,loadAccounts:f2,store:()=>v.poolStore(),migration:async()=>{if(v2(Y().configPath))return{migrated:!0};let T=await K2();return{migrated:!1,blockers:T.open?[]:T.blockers}},beginAccountLogin:Z.beginLogin??J$,refreshAllQuota:async()=>(await v.pollRows(await f2(Y()))).map((T)=>({...T,account:T.id})),getStickyRouting:async(T)=>p.get(T),cacheKeepManager:O.manager,setCacheKeepEnabled:(T)=>O.configure({enabled:T}),setCacheKeepSubagents:(T)=>O.configure({subagents:T}),setCacheKeepSustain:(T)=>O.configure({sustain:T}),setCacheKeepWindow:(T)=>O.configure({window:T}),afterWrite:()=>v.load(),refreshSidebar:()=>Q.publish(),clearStickyRouting:async(T)=>{let l=p.get(T)!==void 0;return p.forget(T),l},vault:E})):void 0;let s=new AbortController;(async()=>{try{for await(let T of $.event.subscribe({signal:s.signal}))if(T.type==="session.deleted")f.forgetSession(T.data.sessionID),O.forget(T.data.sessionID),D.forget(T.data.sessionID)}catch(T){if(!s.signal.aborted)z.warn("stopped listening for session deletion",{error:T instanceof Error?T.message:String(T)})}})();a=!0;return async()=>{A=!0,s.abort();let T=O.release();await e?.(),g?.dispose(),await v.dispose(),await Q.release(),await Promise.allSettled([q.dispose(),J2.dispose(),G2.dispose()]);let l;try{await Promise.race([Promise.all([g?.idle(),v.settled(),_.store?.settled(),T]),new Promise((Z2)=>{l=setTimeout(Z2,d4),l.unref?.()})])}finally{clearTimeout(l),C.release(),await n?.release()}}}catch(m){var $2=m,T2=1}finally{T0(c,$2,T2)}}var a4=G$(),M7={id:E1,setup:a4.setup,server:u0.server};export{M7 as default,G$ as createOpenAIAuthPlugin,E1 as OPENAI_AUTH_PLUGIN_ID};
|
|
1
|
+
import{c as z4}from"../index-ct658ahq.js";import{$ as Z4,A as o0,B as s0,C as O1,D as VZ,E as UZ,F as _0,G as E0,H as $4,I as lZ,J as uZ,M as Z0,N as z0,O as G0,W as Q0,X as B0,d as m0,e as X0,f as h1,fa as R$,g as e2,ga as D$,h as S1,i as I1,ja as G4,k as S$,l as b$,m as A$,n as C1,o as gZ,p as H$,q as mZ,r as tZ,s as eZ,t as R1,u as _Z,v as EZ,w as b1,x as n0,y as T$,z as a0}from"../index-44b5y56b.js";import{Ab as B1,Cb as QZ,Db as E1,Eb as BZ,Fb as WZ,Hb as u0,Ib as SZ,Kb as p0,Lb as nZ,Ra as iZ,Ub as c0,Vb as d0,Wb as i0,Xb as aZ,ab as ZZ,cb as zZ,db as j$,dc as c2,eb as Y$,ec as bZ,fb as GZ,fc as RZ,gc as V$,hb as q1,hc as DZ,ic as kZ,lc as r0,mc as t0,na as s2,nc as e0,oa as p$,pb as JZ,qa as t1,qb as Q$,rb as XZ,ua as f0,ub as jZ,vb as YZ,wb as f1,xb as v0,ya as o$,yb as h0,za as s$,zb as g0}from"../index-vpjmexm5.js";import{Mc as P0,Nc as M0,Pc as C0,Tc as T0,xc as L0}from"../index-4gkfz4zp.js";import{$e as G$,Be as n$,Ce as a$,De as TZ,Ee as e1,Jd as x1,Kd as A1,Ke as y1,Ld as y0,Re as Y0,Sd as C$,Se as d2,Td as c$,Te as $$,Ud as d$,Ue as Z$,Vd as i$,Ve as r$,Xe as z$,Ye as t$,_e as e$,af as J$,be as cZ,bf as $Z,cf as X$,hd as r1,ie as dZ,ke as I0,le as j0,pd as l$,qd as u$,ve as t2,we as F1}from"../index-7fdcb97f.js";import"../index-8xgeh2zt.js";import{sf as vZ,tf as l0}from"../index-7xqb1m44.js";import"../index-r0kv780p.js";import{Ef as w0,Gf as I2}from"../index-2py81t0v.js";import"../index-hq4gdm6f.js";import{cg as hZ}from"../index-dkhy2peg.js";import{gg as K1,hg as k0}from"../index-mkda7acs.js";import{AsyncLocalStorage as $5}from"node:async_hooks";import{randomUUID as Z5}from"node:crypto";class L2 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 y2($){return`common-auth-placeholder.${$}`}function E$($){let Z=y2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function X1($,Z){if($?.type!=="oauth")return!1;let G=Z===void 0?void 0:y2(Z),J=(Q)=>G===void 0?Q.startsWith("common-auth-placeholder."):Q===G;return J($.access)&&J($.refresh)}var O$="No browser sign-in: this connects the plugin to the accounts in its vault.";async function l1($,Z){let G=Z.now??Date.now,{integrationID:J}=Z,Q=(N)=>E$({integrationID:J,methodID:N,now:G()}),Y=async(N,V)=>{return await Z.onLogin(N,{integrationID:J,methodID:V}),Q(V)},K=(N)=>async(V)=>{let L=N.method.id,U=await N.authorize(V),_={url:U.url,instructions:U.instructions,...U.expiresAt===void 0?{}:{expiresAt:U.expiresAt}};if(U.mode==="auto")return{..._,mode:"auto",callback:U.callback.then((A)=>Y(A,L))};let q=U.callback;return{..._,mode:"code",callback:async(A)=>Y(await q(A),L)}};return $.integration.transform((N)=>{let V=Z.label===void 0?{}:{label:()=>Z.label};for(let _ of Z.methods)N.method.update({integrationID:J,method:_.method,authorize:K(_),refresh:async(q)=>{if(!X1(q,J))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return Q(q.methodID)},...V});let L=Z.vault;if(L===void 0)return;let U=L.method.id;N.method.update({integrationID:J,method:L.method,authorize:async()=>({url:"",instructions:L.instructions??O$,mode:"auto",callback:Promise.resolve().then(()=>L.activate({integrationID:J,methodID:U})).then(()=>Q(U))}),refresh:async(_)=>{if(!X1(_,J)||_.methodID!==U)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return Q(U)},...V})})}function X4($){let Z=[],G;for(let J of $.split(/\r?\n/))if(J.startsWith("data:"))Z.push(J.slice(5).replace(/^ /,""));else if(J.startsWith("event:"))G=J.slice(6).trim();if(Z.length===0)return;return G===void 0?{data:Z.join(`
|
|
2
|
+
`)}:{event:G,data:Z.join(`
|
|
3
|
+
`)}}function u1($,Z){let G=new TextDecoder,J="",Q=(K)=>{let N=X4(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 a2=512,p2=3621000,n2="x-common-auth-attempt",u2=($,Z)=>JSON.stringify([$,Z]),R2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function j4($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function Y4($,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 P1($,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 Q4($,Z){for(let[G,J]of Object.entries(Z))if(J===null)$.delete(G);else $.set(G,J)}async function p1($,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??a2),V=G.hostRetryLimit??10,L=[...G.hostCredentials??[y2(J)],...Q?[y2(J)]:[]].filter((z)=>z!==""),U=new Map,_=new WeakMap,q=new Map,A=0,v=new Set,$2=new Map,S=new Map,D=(z)=>{let X=S.get(z);return X?.ownedSeen===!0&&X.foreignSeen},V2=(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(([,T])=>T.includes(y2(J))):[],B=Y(X)&&(!W||F.length>0);if(W){if(F.length>0&&(F.length!==1||!B))throw V2(z.sessionID,!1),new L2({kind:"placement-refused",providerID:J,sessionID:z.sessionID,requestKind:z.kind,message:W(F[0]?.[0]??"")})}return V2(z.sessionID,B),B},I=!1,p=!1,f2=new Map,M2=0,t=!1,w=new Map,l=(z,X)=>{try{K?.warn(z,X)}catch{}},a=(z)=>z instanceof Error?z.message:String(z),m=(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 l("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},$1=(z,X)=>{let W=D2.get(z);return W?W.then(()=>$1(z,X)):X()},Q2=async(z)=>{try{await Z.dropChoice?.({...z.input,accountId:z.accountId})}catch(X){l("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:z.input.sessionID,error:a(X)})}},z2=async(z)=>{try{await Z.dropSameAccountRetry?.({...z.input,accountId:z.accountId})}catch(X){l("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:z.input.sessionID,error:a(X)})}},g2=async(z)=>{if(z.next)await Q2(z.next);if(z.sameAccount)await z2(z.sameAccount)},j=(z)=>{let X=q.get(z);if(q.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){l("opencode2 auth listener threw; the request is unaffected",{event:z,error:a(B)})}}))},P=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"&&D(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){l("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:z.attemptId,error:a(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))m(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),q.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)}},k=(z)=>z.accountId===void 0?void 0:{...z.scope,accountId:z.accountId},c=(z,X)=>new L2({kind:"no-account",providerID:J,sessionID:z.sessionID,requestKind:z.kind,...X===void 0?{}:{message:X}}),G2=(z)=>{w.get(z)?.clear(),w.delete(z)},C=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=w.get(z.sessionID);if(!F)F=new Set,w.set(z.sessionID,F);let B={};F.add(B);let T=()=>{if(!F.has(B))throw W()};try{return await X(T)}finally{if(F.delete(B),F.size===0&&w.get(z.sessionID)===F)w.delete(z.sessionID)}},h=(z,X)=>{for(let[W,F]of X)if(L.some((B)=>F.includes(B)))throw new L2({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:T,accountId:E,sameAccountRetry:R,request:o}=await $1(z.sessionID,async()=>{W();let j2=q.get(B);q.delete(B);let J1=O(B);if(j2&&J1.some((e)=>e.id!==j2.attemptId&&e.attempt&&!e.ended))l("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))m(_2.request)}let K2=j2?.request??{excluded:new Set},J2=j2?.accountId??y(B)?.accountId;Z2(B);let r=j2?.next,Y2=j2?.sameAccount,d=Y2!==void 0&&Y2.input.modelID===z.modelID&&Y2.input.agent===z.agent,T2=r!==void 0&&r.input.modelID===z.modelID&&r.input.agent===z.agent,w2=j2?.wake,n={...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&&(!T2||w2!==void 0))await U2(z.sessionID,()=>Q2(r)),W();if(Y2&&!d)await U2(z.sessionID,()=>z2(Y2)),W();if(Y2?.continuation&&(!d||D(z.sessionID))){if(d)await U2(z.sessionID,()=>z2(Y2));throw c(z)}let l2=d?Y2.accountId:T2&&w2===void 0?r.accountId:await Z.chooseAccount(n),h2=typeof l2==="string"?l2:void 0;if(S2(h2,n,K2)){let e=h2;if(d&&Y2)await U2(z.sessionID,()=>z2(Y2));else if(e!==void 0)await U2(z.sessionID,()=>Q2(T2&&r?r:{accountId:e,input:n}));h2=void 0,W()}return{input:n,accountId:h2,sameAccountRetry:d,request:K2}});W();let x2={},A2;if(E!==void 0){let j2=await Z.accountHeaders({...z,accountId:E});if(W(),j4(j2))x2=j2.headers,A2=j2.attempt;else x2=j2}let G1=`attempt-${++M2}`,b2={id:G1,key:B,scope:z,request:o,accountId:E,headers:x2,attempt:E===void 0?void 0:{...z,accountId:E,attemptId:G1,transport:F,data:A2},...F===void 0?{}:{transport:F},outputStarted:!1,sameAccountRetry:R};if(u(b2),b2.attempt)H("select",{...z,accountId:b2.attempt.accountId,hook:X,...T.previousAccountId===void 0?{}:{previousAccountId:T.previousAccountId},...T.rerouteFrom===void 0?{}:{rerouteFrom:T.rerouteFrom},handle:b2.attempt});return b2},i=async(z,X,W,F,B)=>{let T=u2(z.sessionID,z.kind),E=F===void 0?void 0:U.get(F);if(E?.key!==T)E=void 0;if(!E){if(E=y(T),O(T).filter((o)=>o.transport===void 0&&!o.ended).length>1&&!p)p=!0,l("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 R of O(T))if(R!==E&&R.transport==="ws")x(R,"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:a(W)}),W}},C2=(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=k(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})}},Z1=(z,X,W,F)=>{let B=k(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 T=Z.inspectEvent?.(F===void 0?{transport:X,data:W,attempt:B}:{transport:X,data:W,event:F,attempt:B});if(!T)return;if(T.quota!==void 0)Z1(z,X,T.quota);if(T.outputStarted)z.outputStarted=!0;if(T.hostRetry==="veto")z.hostRetry="veto";if(T.limit)k2(z,T.limit,X);if(T.error!==void 0)b(z,{reason:"failed",message:T.error});else if(T.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},i2=(z)=>!z.attempt||z.endError!==void 0||z.status!==void 0&&z.status>=400,O2=(z)=>{let X=[...U.values()].filter((R)=>R.scope.sessionID===z),W=X.filter((R)=>R.limit&&!R.rerouted).at(-1);if(W)return W;let F=X.filter((R)=>R.scope.kind==="primary"),B=F.length>0?F:X;if(B.length<=1)return B[0];let T=B.filter((R)=>!R.judged&&i2(R)).at(-1);if(T)return T;let E=B.filter((R)=>R.attempt&&!R.ended);if(E.length>1)return"ambiguous";return E[0]??B.at(-1)},F2={providerID:J},B2=[];B2.push(await $.session.hook("model.request",(z)=>{if(Q)return;return C(R2(z),async(X)=>{let W=await N2(R2(z),"model.request",X);if(X(),W.accountId===void 0)throw c(W.scope);P1(z.headers,{...W.headers,[n2]:W.id})})},F2)),B2.push(await $.session.hook("http.request",(z)=>{if(Q){if(!X2(R2(z),z.request.headers))return}return C(R2(z),async(X)=>{let W=z.request.headers.get(n2)??void 0,F=Q?await N2(R2(z),"http.request",X,"http"):await i(R2(z),"http.request","http",W,X);X();let B=k(F),T=F.attempt;if(!B||!T)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(n2),E=new Request(E,{headers:x2})}E=await Z.rewriteRequest({...B,request:E,attempt:T})??E,X()}let R=new Headers(E.headers);R.delete(n2),Q4(R,F.headers),h(F.scope,R.entries());let o=new Request(E,{headers:R});_.set(o,F),z.request=o})})},F2)),B2.push(await $.session.hook("http.response",async(z)=>{let X=_.get(z.request);if(!X){if(Q)return;if(!I)I=!0,l("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 R=X.attempt,o=await s(X,async()=>Z.answeredBy?.({request:z.request,response:W,attempt:R}));if(o)m2(X,o)}let F=k(X),B=X.attempt;if(!F||!B)return;X.status=W.status;let T=Z.quotaFromHeaders?.(W.headers,W.status,B);if(T!==void 0)Z1(X,"http",T,W.status);if(!W.ok&&Z.limitFromResponse){let R=await Z.limitFromResponse({status:W.status,headers:W.headers,body:()=>W.clone().text(),attempt:B});if(R)k2(X,R,"http")}if(!W.ok||!W.body)b(X);let E=W;if(W.body&&(Z.inspectEvent||Z.onAttemptEnd)){let R=W.body;if(Z.inspectEvent)R=R.pipeThrough(u1((o)=>H2(X,"http",o.data,o.event),(o)=>l("opencode2 auth event inspection threw",{error:a(o)})));E=new Response(Y4(R,(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)),B2.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 C(R2(z),async(X)=>{let W;for(let E of Object.keys(z.headers)){if(E.toLowerCase()!==n2)continue;W??=z.headers[E],delete z.headers[E]}let F=Q?await N2(R2(z),"experimental.ws.handshake",X,"ws"):await i(R2(z),"experimental.ws.handshake","ws",W,X);X();let B=k(F),T=F.attempt;if(!B||!T)throw c(F.scope);await s(F,async()=>{if(!Q?.refuseMisplaced)P1(z.headers,F.headers);let E=Z.rewriteHandshakeURL?.({...B,url:z.url,attempt:T});if(E!==void 0)z.url=E;if(Q?.refuseMisplaced)P1(z.headers,F.headers);if(h(F.scope,Object.entries(z.headers)),Q)v.add(F.key)})})},F2));let v2=Z.rewriteWebSocketFrame?.bind(Z);if(v2)B2.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=C2(X.sessionID,X.kind),F=await v2({...X,attempt:W?.attempt,frame:z.frame});if(F!==void 0)z.frame=F},F2));B2.push(await $.session.hook("experimental.ws.receive",(z)=>{if(Q&&!v.has(u2(z.sessionID,z.kind)))return;let X=C2(z.sessionID,z.kind);if(!X)return;try{H2(X,"ws",z.frame)}catch(W){l("opencode2 auth frame inspection threw",{error:a(W)})}},F2)),B2.push(await $.session.hook("retry",async(z)=>{if(Q&&$2.get(z.sessionID)!==!0)return;let X=z.decision,W=()=>P({sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:X,decision:X});if(D(z.sessionID)&&!Z.retrySameAccount){await W();return}let F=O2(z.sessionID);if(!F)return;if(F==="ambiguous"){await P({sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:X,decision:X});return}let B=F,T=()=>B.hostRetry==="veto";await C(B.scope,async(E)=>{let R=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&&!D(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;R()}let G1=()=>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&&!T()&&!D(z.sessionID);if(o&&x2&&(!A2||G1())&&(!T()||D(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()=>{R();let J2=x2.accountId,r=()=>U.has(B.id)&&B.accountId===J2&&O2(z.sessionID)===B&&B.outputStarted===A2&&(!A2||G1())&&(!T()||D(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"}:{}},d;try{d=await o(Y2)}catch(n){l("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:z.sessionID,error:a(n)})}if(!d)return R(),!1;let T2={accountId:d.accountId,input:Y2,...A2?{continuation:!0}:{}};try{R()}catch(n){throw await z2(T2),n}if(!r()||d.accountId!==J2)return await z2(T2),!1;let w2=q.get(B.key);if(q.delete(B.key),w2)await g2(w2);try{R()}catch(n){throw await z2(T2),n}if(!r())return await z2(T2),!1;return q.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++A,accountId:J2,sameAccount:T2}),B.judged=!0,z.decision=A2?X:{retry:!0,delay:0},!0});if(R(),K2){await P({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(D(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}R();let{decision:j2,reason:J1}=await U2(B.scope.sessionID,async()=>{if(R(),D(z.sessionID))return{decision:X,reason:"host-decides"};let K2=q.get(B.key);if(q.delete(B.key),K2)await g2(K2);if(R(),D(z.sessionID))return{decision:X,reason:"host-decides"};let J2=X,r,Y2,d,T2;if(B.accountId===void 0||!b2)J2={retry:!1},r="no-account";else if(B.outputStarted)J2={retry:!1},r="output-started";else if(T())J2={retry:!1},r="adapter-veto";else if(B.limit){let w2={accountId:B.accountId,limit:B.limit.signal},n,l2={...B.scope,phase:"retry",...E2(B.request),hostAttempt:z.attempt,previousAccountId:B.accountId,rerouteFrom:w2};try{n=await Z.chooseAccount(l2)}catch(m1){l("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:B.scope.sessionID,error:a(m1)})}let h2=typeof n==="string"?n:typeof n==="object"&&("hold"in n)?B.accountId:void 0;if(S2(h2,l2,B.request)){if(h2!==void 0)await Q2({accountId:h2,input:l2});n=void 0}let e=typeof n==="object"&&"hold"in n?n.hold:void 0,_2=typeof n==="object"&&"waitThenReselect"in n?n.waitThenReselect:void 0,J4=typeof n==="object"&&"hostRetry"in n?n.hostRetry:void 0,L1=typeof n==="string"?n:e?B.accountId:void 0;if(L1!==void 0)d={accountId:L1,input:l2};try{R()}catch(m1){if(d)await Q2(d);throw m1}if(D(z.sessionID)){if(d)await Q2(d);return{decision:X,reason:"host-decides"}}if(T()||J4==="veto"){if(d)await Q2(d);if(d=void 0,R(),D(z.sessionID))return{decision:X,reason:"host-decides"};B.hostRetry="veto",J2={retry:!1},r="adapter-veto"}else if(!(V-z.attempt>=1)){if(d)await Q2(d);d=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)T2={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&&d)await Q2(d),d=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))q.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++A,accountId:B.accountId,...Y2===void 0?{}:{rerouteFrom:Y2},...d===void 0?{}:{next:d},...T2===void 0?{}:{wake:T2}});else if(d)await Q2(d);if(!J2.retry)m(B.request);return{decision:J2,reason:r}});R(),await P({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 W2=(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"),m(X.request),U.delete(X.id)}for(let[X,W]of q)if(W.sessionID===z)j(X)},g=new AbortController,z1=$.event;if(z1)(async()=>{try{for await(let z of z1.subscribe({signal:g.signal}))if(z.type==="session.deleted")W2(z.data.sessionID);else if(z.type==="session.status"&&z.data.status.type==="idle"){let X=z.data.sessionID,W=++A;U2(X,async()=>{for(let[F,B]of q)if(B.sessionID===X&&B.order<W)q.delete(F),m(B.request),await g2(B)})}}catch(z){if(!g.signal.aborted)l("opencode2 auth stopped listening for session deletion",{error:a(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:W2,get size(){return U.size},async dispose(){if(t)return;t=!0;for(let z of w.keys())G2(z);g.abort();for(let z of U.values())x(z,"the installation was disposed");U.clear();for(let z of q.keys())j(z);v.clear(),$2.clear(),S.clear(),f2.clear(),await Promise.all(D2.values()),await Promise.all(B2.map(async(z)=>{try{await z.dispose()}catch(X){l("opencode2 auth hook did not dispose cleanly",{error:a(X)})}}))}}}import{randomUUID as m$}from"node:crypto";import{createHash as B4}from"node:crypto";var W4=1024,V4=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),x$=($)=>A$($,"user"),U4=($)=>V4($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function N4($){return B4("sha256").update(JSON.stringify($)).digest("hex")}class o2{runtime;maxSessions;#$=new Map;constructor($,Z=W4){this.runtime=$;this.maxSessions=Z}advance($,Z,G=this.runtime){let J=this.#$.get($),Q=Array.isArray(Z.input)?Z.input:[],Y=Q.filter(x$),K=Q.findLastIndex(x$),N=K<0?void 0:N4(Q[K]),V=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,L,U,_;if(V)L=Y.length>0,U=N??J?.fingerprint,_=J?.userCount===void 0?void 0:J.userCount+Y.length;else{U=N,_=Y.length;let A=K>=0&&K>Q.findLastIndex(U4),v=J!==void 0&&!J.completed&&J.fingerprint===U&&J.userCount===_;L=A&&!v}let q=L||!J?{turnID:(G?.uuid??c2)(),turnStartedAt:(G?.now??Date.now)()}:{turnID:J.turnID,turnStartedAt:J.turnStartedAt};return this.#Z($,{...q,completed:!1,fingerprint:U,userCount:_}),q}completed($){let Z=this.#$.get($);if(Z)this.#Z($,{...Z,completed:!0})}get($){return this.#$.get($)}forget($){this.#$.delete($)}#Z($,Z){this.#$.delete($),this.#$.set($,Z);while(this.#$.size>this.maxSessions){let G=this.#$.keys().next().value;if(G===void 0)break;this.#$.delete(G)}}}function c1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var q$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function H4(){let $=globalThis;return $[q$]??=crypto.randomUUID(),$[q$]}class j1{runtime;store;sessions;frameTurns;installationID;constructor($,Z,G){this.runtime=$;this.store=G;this.installationID=Z??H4(),this.sessions=G?.sessions??new Map,this.frameTurns=G?.frameTurns??new o2}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(M1(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var d1={version:S$,"user-agent":b$,originator:"codex_exec"};var F4=1024,K4=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,T1=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),k$=($)=>T1($)&&($.type==="message"||("role"in $))&&$.role==="user",w$=($)=>T1($)&&$.type==="configuration_update";class i1{http;#$=new Map;constructor($=new j1){this.http=$}apply($,Z,G){if(Z.kind!=="primary")return!1;let J=typeof $.model==="string"?$.model:"";if(!R$.has(J))return!1;if(K4.test(J))return!1;let Q=T1($.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(k$);if(V<0){if(G==="http")return!1;return $.reasoning={...Q,effort:K},!0}if($.reasoning={...Q,effort:K},!w$(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>F4){let G=this.#$.keys().next().value;if(G===void 0)break;this.#$.delete(G)}}}function M1($){try{let Z=JSON.parse($);return T1(Z)?Z:void 0}catch{return}}async function y$($,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=M1(Y);if(K)delete K.max_output_tokens;let N=new Headers($.headers),V=C1({rewriteLite:D$,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:(L)=>{G.apply(L,Z,"http")}});return new Request($,{headers:N,body:V.init?.body})}function I$($,Z,G,J){let Q=J.sessions.get($.sessionID),Y=J.frameTurns.get($.sessionID);if(!Q||!Y)return;let K=c1(Q,Y),N=new Headers({"content-type":"application/json"});for(let L of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let U=G.get(L);if(U!==null)N.set(L,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 L4($,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&&w$(Z[G])&&k$(Z[G+1])&&JSON.stringify(Z.slice(G+1))===JSON.stringify($.slice(G))}function f$($,Z,G){let J=M1($);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:c1(Y,Q),installationID:G.http.installationID,runtime:G.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(V)=>{G.apply(V,Z,"ws")}}),N=M1(String(K.init?.body));if(!N)return;if(!L4(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 P4($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function n1($,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(`${P4(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 v$}from"node:path";var M4=1024;class _1{accounts=new Map;limit;constructor($=M4){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 h$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),g$=globalThis,a1=g$[h$]??new Map;g$[h$]=a1;function o1($){let Z=JSON.stringify([v$($.configPath),v$($.statePath)]),G=a1.get(Z);if(!G)G=new _1,a1.set(Z,G);return G}var q2="openai",r2=10;var s1=1,C4="request refused: no account with a usable credential",P2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function T4($){let Z=P2($)?$.counters:void 0,G=P2(Z)?Z.resetCredits:void 0,J=P2(G)?G.value:void 0;return typeof J==="number"&&Number.isFinite(J)?J:void 0}function Y1($){try{return JSON.parse($)}catch{return}}function Q1($){let Z=x1($);return Z?A1(Z):void 0}var _4=new Set(["usage_limit_reached","rate_limit_exceeded"]);function W1($,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 NZ($,Z,G){if($.type!=="response.failed"){let Y=O1($,Z),K=typeof $.status==="number"?$.status:void 0;return Y?W1(Y,Z,K,G):void 0}if(!P2($.response))return;let J=$.response.failed;if(P2(J)&&typeof J.rate_limit_reached_type==="string")return W1({window:J.rate_limit_reached_type},Z,void 0,G);let Q=$.response.error;if(P2(Q)){let Y=typeof Q.code==="string"?Q.code:typeof Q.type==="string"?Q.type:void 0;if(Y&&_4.has(Y)){let K=typeof $.status==="number"?$.status:void 0,N=O1({error:{...Q,type:Y},status:K},Z);return W1(N??{window:Y},Z,K,G)}}return}function E4($,Z,G){if(!P2($))return;let J=typeof $.type==="string"?$.type:void 0;if(J==="codex.rate_limits")return{quota:{snapshot:i$($),complete:!0}};let Q=NZ($,Z,G);if(Q)return{limit:Q};if(J===void 0||J==="error")return;return VZ(J)?void 0:{outputStarted:!0}}function O4($){let Z=!1;for(let G of $.keys())if(G.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:c$($),complete:d$($)}}function x4($){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 HZ($){let Z=new WeakMap,G=new WeakSet,{source:J,pins:Q}=$,Y=$.now??Date.now,K=$.log,N=$.vault,V=$.limits,L=m$(),U=new WeakMap,_=new Map,q=(j,H)=>d2(H?N?.routes().find((P)=>P.id===j)?.quota:J.peek().rows.find((P)=>P.id===j)?.quota),A=new i1($.codex),v=new Map,$2=(j)=>{for(let[H,P]of v)if(P===j)v.delete(H)},S=new Map,D=new Map,V2=(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,P)=>{let M=t({...j,accountId:H});p(M);let b={request:P,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>a2){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}`,w=$.sessionAccounts??new _1,l=new e$,a=(j,H,P)=>{let M=P?[]:UZ(J.peek().rows,j,H,N?.identities()??new Set),b=(N?.routes()??[]).filter((x)=>x.kind==="oauth"&&n$(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}))]},m=(j,H,P)=>{let M=r$(j,H,P),b=j.map((f)=>({id:f.id,kind:"oauth",...r1(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:P,rateLimitMarks:y,refreshBackoff:J.refreshBackoffFor(x),killswitch:M,requestPull:(f)=>O.has(f)?N?.requestReading(f):J.requestReading(f)}},E2=(j,H,P,M,b)=>{let x=G$({...j,rows:j.rows.filter((y)=>!P.has(y.id)),placement:z$(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)=>!P.has(y));if(M!==void 0&&O.includes(M))return M;return O[0]},S2=(j,H)=>{let P=new Map(j.map((M)=>[M.id,M.quota]));return{requestBytes:s1,reservePercent:(M)=>e1(H,M===$$?void 0:M),resetCredits:(M)=>T4(P.get(M))}},D2=(j,H,P,M,b,x,O,y)=>{let f=S2(H,P),u=J$(j),k=(Z2,N2)=>q1(O,{sessionId:M,requestBytes:s1,validPinnedAccountIds:j.rows.map((i)=>i.id).filter((i)=>!u.excluded.has(i)),excludeAccountIds:Z2,quotaCheckedAtByAccount:Object.fromEntries(j.rows.map((i)=>[i.id,u.projections.get(i.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(H.map((i)=>[i.id,i.identity])),select:(i)=>y?{accountId:y,source:"mode-fallback",quotaCheckedAt:u.projections.get(y)?.checkedAt}:$Z(j,f,new Set(Z2),i),persist:N2},(i,s)=>O.set(i,s)),c=[...b],G2=k(c,x);if(!G2)return;let C=G2.accountId,h=X$(j,f,C);if(h.kind==="none")return;if(h.kind==="move"){let Z2=k([...c,C],x);if(Z2)return Z2.accountId;return h.reason==="killswitch"?void 0:C}if(h.kind==="detour")return k([...c,C],!1)?.accountId;return C},Q2={providerID:q2,async retrySameAccount(j){if(j.continuation!=="interrupted-read")return;let H=D.get(V2(j));if(D.delete(V2(j)),!H||H.accountId!==j.accountId||H.modelID!==j.modelID||H.agent!==j.agent||j.limit)return;let P=N!==void 0&&await N.authority()!=="local",M=await $.storage();if(!P&&!(await J.current()).active)return;let b=Y(),x=a(M,b,P),O=x.find((k)=>k.id===j.accountId);if(!O)return;let y=m(x,M,b),f=M?.routing?.mode??"main-first";if(f==="sticky-balanced"){let k=X$(y,S2(x,M),j.accountId);if(k.kind!=="serve"&&k.kind!=="last-path")return}else{let k=G$({...y,placement:z$(f),...P?{mainId:Z$(N?.routes()??[])}:{}});if(k.kind==="block"||!k.order.includes(j.accountId))return}let u=H.data;if(O.row){if(u?.kind!=="pool")return;let k=J.usableToken(O.row),c=O.row.identity??(k&&Q1(k));if(!k||!u.identity||c!==u.identity)return}else{if(u?.kind!=="vault"||!N)return;let k=await N.authorize(j.accountId);if(!k||k.credentialId!==u.credentialId||k.accountIdentity!==u.accountIdentity||(k.accountIdentity??Q1(k.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,P=await N?.authority(),M=await $.storage(),b=P!==void 0&&P!=="local",x=()=>{throw new L2({kind:"no-account",providerID:q2,sessionID:j.sessionID,requestKind:j.kind,message:S1})};if(b){let X=performance.now()+b1;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=a(M,O,b),f=t$(m(y.filter((X)=>X.id!==j.rerouteFrom?.accountId),M,O));if(f)await f,O=Y(),y=a(M,O,b);let u=new Map(y.map((X)=>[X.id,X])),k=m(y,M,O),c=M?.routing?.maxSameAccountWait,G2=JSON.stringify([j.sessionID,j.kind]),C=[...v.values()].includes(j.sessionID),h=V?.activity.get(j.sessionID),Z2=h&&V?.accountKey(h.accountKey.accountId),N2=j.previousAccountId??j.rerouteFrom?.accountId,i=N2&&V?.accountKey(N2),s=j.rerouteFrom?.limit,C2=y.flatMap((X)=>{let W=V?.accountKey(X.id);if(!W)return[];let F=d2(X.quota),B=zZ(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),T=k.rateLimitMarks.get(X.id),E=k.refreshBackoff.get(X.id),R=[...T&&T>O?[{kind:"hard",until:T,cause:"rate-limit"}]:[],...E&&E>O?[{kind:"cooldown",until:E}]:[]],o=k.killswitch.get(X.id)!==!1&&!!(F?.primary||F?.secondary)&&!u$(l$(r1(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&&!R.length&&!B.length,blockers:R,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:p$({requestId:j.sessionID,originalUrl:"https://api.openai.com/v1/responses",clockNow:O}),delivery:{owned:!0,attributable:!0,replayable:!0},candidates:C2,...j.phase==="retry"&&i?{attempted:i}:{},...j.phase==="retry"&&i&&s?{signal:{account:i,kind:"rate-limit",reason:s.reason,scope:{kind:"pool"},windows:s.windows??[],observedAt:s.observedAt??O},status:s.status}:{},remainingRetries:r2-(j.hostAttempt??r2)},Z1=()=>{let X=V?.owner();return JZ({accounts:C2.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:a$(M)?e1(M,F.id===$$?void 0:F.id):void 0,marks:X?.snapshot()?.marks.filter((B)=>B.key.window==="account"&&B.key.scope.kind==="pool"&&s2(B.key.account,W.account)).flatMap((B)=>B.entries.map((T)=>({until:T.until,evidenceAt:T.evidenceAt})))}]}),now:O,effectiveModel:j.modelID,maxSameAccountWait:c,activity:h,currentAccountKey:Z2,provenance:X?.provenance})},H2=C2.find((X)=>i&&s2(X.account,i));if(j.phase==="retry"&&s&&H2){let X=j$({candidate:H2,activity:h,maxSameAccountWait:c,now:O,maxDelayMs:p2}),W=Y$({...k2,hold:X},{mode:"sticky"});if(W?.action==="hold"&&!C)return v.set(G2,j.sessionID),{hold:{delayMs:W.delayMs,target:W.target,checkpoint:W.checkpoint,kind:"hold"}};let F=y.filter((T)=>T.id!==N2);if(H2.confirmedBlockers?.some((T)=>T.confirmed)&&F.length>0&&F.every((T)=>{let E=C2.find((R)=>R.account.accountId===T.id);return E&&(!E.admitted||(k.rateLimitMarks.get(T.id)??0)>O)})){if(C)return{hostRetry:"veto"};let T=Q$(k2,Z1());if(t1(c)===0)return{hostRetry:"veto"};let E="delayMs"in T?T.delayMs:("retryAfterMs"in T)?T.retryAfterMs:void 0;if((k2.remainingRetries??0)<1||E===void 0||E>p2)return{hostRetry:"leave"};if(T.action==="hold"&&s2(T.account,H2.account))return v.set(G2,j.sessionID),{hold:{delayMs:E,target:T.target,checkpoint:T.checkpoint,kind:"terminal"}};return v.set(G2,j.sessionID),{waitThenReselect:{delayMs:E}}}}let m2;if(j.phase==="request"&&j.wake?.checkpoint&&H2&&(j.hostAttempt??r2)<r2&&t1(c)!==0&&s2(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=j$({candidate:F,activity:h,maxSameAccountWait:c,now:O,maxDelayMs:p2});if(Y$({...k2,attempted:H2.account,candidates:C2.map((E)=>E===H2?F:E),hold:B,wake:{...j.wake,checkpoint:X}},{mode:"sticky"})?.action==="retain")m2=H2.account.accountId}let i2=new Set(j.rerouteFrom?[j.rerouteFrom.accountId]:[]),O2=M?.routing?.mode??"main-first",F2=j.kind==="primary",B2=new Set,v2,W2,g,z1=!1,z=(X)=>{let W=J$(k).projections.get(X)?.checkedAt,F=u.get(X)?.identity;return Q.reserve(j.sessionID,{accountId:X,inputBytes:s1,...W!==void 0?{quotaCheckedAt:W}:{},...F!==void 0?{wireIdentity:F}:{}})};try{for(;;){let X=new Set([...i2,...B2]);g=void 0,v2=void 0;let W=O2!=="sticky-balanced";if(m2&&!X.has(m2))g=m2,m2=void 0;else if(O2==="sticky-balanced"){let B=new Map(Q.placementSnapshot(j.sessionID)),T=B.get(j.sessionID);if(W=T===void 0,g=D2(k,y,M,j.sessionID,X,F2&&B2.size===0,B),g!==void 0&&B.get(j.sessionID)!==T)v2=B.get(j.sessionID)}if(g??=E2(k,O2,X,F2?void 0:w.activeAccount(j.sessionID),b?O2==="sticky-balanced"?null:Z$(N?.routes()??[]):void 0),g===void 0||B2.has(g)){if(i2.size>0){let B=new Map(k.rateLimitMarks);for(let T of i2)B.delete(T);k={...k,rateLimitMarks:B},i2.clear();continue}if(k.rateLimitMarks.size>0){k={...k,rateLimitMarks:new Map};continue}g=void 0;break}if(F2&&O2==="sticky-balanced")W2=z(g);if(!z1){z1=!0;let B=j.wake?void 0:await QZ({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:k,wait:{activity:h,accountKey:Z2,maxSameAccountWait:c},eligibleIds:y.filter((T)=>!X.has(T.id)).map((T)=>T.id)});if(B&&B!==g){if(W2)Q.rollback(W2);if(W2=void 0,O2==="sticky-balanced"){let T=new Map(Q.placementSnapshot(j.sessionID));g=D2(k,y,M,j.sessionID,X,F2,T,B)??g,v2=T.get(j.sessionID)??v2}else g=B;if(F2&&O2==="sticky-balanced")W2=z(g)}}let F=u.get(g)?.row;if(F){if(J.usableToken(F)!==void 0)break;K?.debug("pool row holds no usable token; choosing again",{accountId:g})}else{if(!N)break;let B=await N.authorize(g);if(B){S.set(t({...j,accountId:g}),B);break}K?.debug("the vault refused to serve an account; choosing again",{accountId:g})}if(W2)Q.rollback(W2);W2=void 0,B2.add(g)}if(g===void 0&&!b&&y.length===0&&await $.slotPlaceholderWithoutMain?.())x();if(g===void 0&&b&&N&&(y.length===0||B2.size>0)){let X=B2.size>0?"vault-refused":s$(N);throw K?.warn("vault mode: no vault account can serve; refusing the request",{cause:X}),new L2({kind:"no-account",providerID:q2,sessionID:j.sessionID,requestKind:j.kind,message:o$(X,N.name)})}if(g!==void 0){if(H)f2(j,g,H);let X=g,W=W2,F=v2,B=()=>{if(W)Q.finish(W,F);if(F2)w.record(j.sessionID,X),$.onRoute?.(j.sessionID,X,O2)};if(j.phase==="retry")X2.set(t({...j,accountId:g}),{commit:B,drop:()=>{if(W)Q.rollback(W)}}),W2=void 0;else B();let T=K?.info;l.served(k,g,K&&T?{info:(E,R)=>T.call(K,E,R)}:void 0)}if(g===void 0&&j.phase==="request"&&C2.length>0&&C2.every((X)=>!X.admitted)&&C2.some((X)=>k.killswitch.get(X.account.accountId)===!1||X.confirmedBlockers?.length)){let X=Q$(k2,Z1()),W=XZ({decision:X,now:O,host:"opencode2",requestThrow:!0,maxSameAccountWait:c});if(W.kind==="http"){let F=JSON.parse(W.body);throw new L2({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:g,mode:O2,...j.rerouteFrom?{rerouteFrom:j.rerouteFrom.accountId}:{}}),g}finally{if(W2)Q.rollback(W2)}},accountHeaders:async(j)=>{let{accountId:H}=j;D.delete(V2(j));let P=t(j),M=X2.get(P);X2.delete(P);let b=()=>{M?.commit()};try{let x=()=>new L2({kind:"no-account",providerID:q2,sessionID:j.sessionID,requestKind:j.kind,message:C4}),O=async(c)=>{if(!V)return;let G2=M2(P)??await V.forRequest();if(c.kind==="pool"){let s=J.peek().rows.find((C2)=>C2.id===H);if(!s||s.credentialEpoch!==c.credentialEpoch||J.usableToken(s)!==c.token)throw x()}let C=V.bindings().find((s)=>s.account.accountId===H),h=await G2?.beforeDispatch(C,()=>V.ownershipBindings(),H),Z2=V.accountKey(H);if(h&&h.status!=="ready"||C&&(!Z2||!s2(C.account,Z2)))throw x();let N2=V.owner(),i=C?{sessionId:j.sessionID,accountKey:C.account,dispatchedAt:Y(),ttlMs:jZ(JSON.stringify({model:j.modelID}))}:void 0;if(i){if(_.delete(i.sessionId),_.set(i.sessionId,i),_.size>a2){let s=_.keys().next().value;if(s!==void 0)_.delete(s)}}U.set(c,{owner:N2,probe:N2?.observe(C),dispatch:i,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 C={kind:"vault",routeId:H,receipt:G2};return await O(C),b(),{headers:{...d1,"session-id":j.sessionID,authorization:`Bearer ${G2.accessToken}`,"chatgpt-account-id":G2.accountIdentity??Q1(G2.accessToken)??null},attempt:C}}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??Q1(f),k={kind:"pool",token:f,credentialEpoch:y.credentialEpoch,...u!==void 0?{identity:u}:{}};return await O(k),b(),{headers:{...d1,"session-id":j.sessionID,authorization:`Bearer ${f}`,"chatgpt-account-id":u??null},attempt:k}}finally{M?.drop()}},async rewriteRequest({request:j,sessionID:H,kind:P}){let M=$.codexEndpoint?n1(j.url,$.codexEndpoint()):j.url,b=M===j.url?j:new Request(M,j);return await y$(b,{sessionID:H,kind:P},A,$.responsesLite?.()??!1)??b},rewriteHandshakeURL:({url:j})=>$.codexEndpoint?n1(j,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:j,sessionID:H,kind:P})=>f$(j,{sessionID:H,kind:P},A),quotaFromHeaders:(j,H,P)=>{if(P.data?.kind==="vault")N?.reportUsage(P.data.routeId,{headers:j},P.data.receipt);if(P.data?.kind==="vault"&&B1()&&H>=200&&H<300)Z.set(P,{status:H,headers:j});return O4(j)},async limitFromResponse({status:j,headers:H,body:P,attempt:M}){if(j<400)return;let b=Y1(await P().catch(()=>"")),x=Y(),O=O1({...P2(b)?b:{},status:j},x);if(M.data?.kind==="vault"&&B1())E1(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=W1(O,x,j,q(M.accountId,M.data?.kind==="vault"));if(y.retryAfterMs!==void 0)return y;let f=x4(H);return f===void 0?y:{...y,retryAfterMs:f,resetAt:x+f,resetSource:"retry-after"}},inspectEvent:({data:j,transport:H,attempt:P})=>{let M=Y1(j),b=P.data&&U.get(P.data);if(b&&P2(M)&&(M.type==="response.failed"||M.type==="error"))b.failed=!0;if(b&&P2(M)&&M.type==="response.completed")b.completed=!0;if(P.data?.kind==="vault"&&j.includes("codex.rate_limits")){let O=Y1(j);if(P2(O)&&O.type==="codex.rate_limits")N?.reportUsage(P.data.routeId,{frame:O},P.data.receipt)}if(P.data?.kind==="vault"&&B1()&&(WZ(j)||H==="ws"&&j.includes('"response.completed"'))){let O=Y1(j);if(BZ(O))G.add(P);if(H==="ws"&&P2(O)&&O.type==="response.completed")E1(P.sessionID,P.data.receipt,{status:200,headers:new Headers,failed:G.has(P)})}let x=E4(M,Y(),q(P.accountId,P.data?.kind==="vault"));return H==="ws"&&P2(M)&&M.type==="response.completed"?{...x,done:!0}:x},limitFromError(j,H){let P=Y1(j.message),M=Y(),b=q(H.accountId,H.data?.kind==="vault");return NZ({...P2(P)?P:{},...j.status!==void 0?{status:j.status}:{}},M,b)??(j.message.includes("usage_limit_reached")?W1({window:"usage_limit_reached"},M,j.status,b):void 0)},async onAttemptEnd(j,H){let P=j.data,M=P&&U.get(P);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);YZ(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(P&&H.outputStarted&&H.error?.reason==="failed"){if(D.set(V2(j),{accountId:j.accountId,modelID:j.modelID,agent:j.agent,sessionID:j.sessionID,data:P.kind==="pool"?{kind:"pool",identity:P.identity}:{kind:"vault",credentialId:P.receipt.credentialId,accountIdentity:P.receipt.accountIdentity,wireIdentity:P.receipt.accountIdentity??Q1(P.receipt.accessToken)}}),D.size>a2){let x=D.keys().next().value;if(x!==void 0)D.delete(x)}}let b=P?.kind==="vault"&&B1()?Z.get(j):void 0;if(Z.delete(j),P?.kind==="vault"&&b&&!H.error&&!H.limit)E1(j.sessionID,P.receipt,{...b,failed:G.has(j)});if(P?.kind!=="vault"||H.status!==401)return;K?.warn("a vault account answered 401; reporting it to the vault",{accountId:j.accountId}),await N?.reportFailure(P.receipt,401)}},z2=(j,H,P)=>{let M=P.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,P)=>{let M=Y(),b=P.data?.kind==="vault";if(V){let x=P.data&&U.get(P.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}=GZ({binding:x.probe.binding,baseRevision:x.probe.baseRevision,producerId:L,operationId:m$(),parsed:{window:H.reason,resetAt:y.resetAt??(H.retryAfterMs!==void 0?M+H.retryAfterMs:void 0)},reading:q(j,b),now:M,observedAt:y.observedAt??M,evidenceAt:M,resetSource:y.resetSource});O.enqueue(f,u);return}};return{adapter:Q2,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,P]of I)if(P.sessionID===j)p(H);_.delete(j),V?.forget(j);for(let[H,P]of D)if(P.sessionID===j)D.delete(H);Q.forget(j),w.forget(j),A.forget(j)},activeAccount:(j)=>w.activeAccount(j)}}import{resolve as CZ}from"node:path";import{Buffer as A4}from"node:buffer";import{resolve as FZ}from"node:path";function V1($){return A4.byteLength(JSON.stringify($))}function q4($){return $.reduce((Z,G)=>Z+V1(G),0)}function B$($,Z){return 2+$+Math.max(0,Z-1)}function S4($){let{head:Z,pending:G}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+B$(Z.inputBytes,Z.input.length)+1:0)+(G?20+B$(G.inputBytes,G.input.length)+10+B$(G.outputBytes,G.output.length)+(G.responseID===void 0?0:14+G.responseIDBytes)+1:0)}function KZ($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class LZ{enabled;caps=R1;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$)this.entries.clear(),this.bytes=0}send($,Z){if(!this.enabled)return;let G=KZ(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,...L}=G;this.keep($,{fields:J&&Q?Q.fields:L,fieldsBytes:J&&Q?Q.fieldsBytes:V1(L),...J&&Y?{head:Y}:{},pending:{input:V,inputBytes:q4(V),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,G){if(!this.enabled||!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed"))return;let J=this.entries.get($);if(!J?.pending)return;let Q=KZ(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=V1(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+=V1(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:V1(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=S4(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 PZ=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),MZ=globalThis,W$=MZ[PZ]??new Map;MZ[PZ]=W$;function D1($){let Z=JSON.stringify([FZ($.configPath),FZ($.statePath)]),G=W$.get(Z);if(!G)G=new LZ,W$.set(Z,G);return G}var b4=5000,R4=["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"],D4=["x-opencode-parent-session-id","x-parent-session-id"];function OZ($){let Z=TZ($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:_Z($?{...$,cachekeep:Z}:$)}}var xZ=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),AZ=globalThis,U1=AZ[xZ]??new Map;AZ[xZ]=U1;function k4($,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,L)=>{N.remove(V),J()?.log?.debug(`cachekeep dropped target (${L})`,{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 L=V.accountId??"main",U=Q(),_=await U.source.accessFor(L,await U.storage());if(!_)throw Error(`pool row ${L} has no usable token`);return{token:_.token,identity:_.row.identity}},N=EZ({...R1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(V,L)=>Q().fetch(V,L),logger:{debug:(V,L)=>J()?.log?.debug(V,L),warn:(V,L)=>J()?.log?.warn(V,L)},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 L=J(),U=V.meta.routingSessionId??V.sessionKey,_=V.accountId??"main";return L?.accounts.activeAccount(U)===_?L.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,L,U)=>{let _=Q();if(await _.vault.authority()!=="vault")return;return _.vault.send(V,L,U)}},activeAccount:(V)=>{if(V===void 0)throw Error("target has no session");let L=J(),U=L?.settings();if(!L||!U?.enabled){Y(V,"keep-warm is off");return}if(!U.subagents&&N.status().targets.some((q)=>q.sessionKey===V&&q.isSubagent)){Y(V,"subagent warming is off");return}let _=L.accounts.activeAccount(V);if(_===void 0){Y(V,"no account recorded for the session");return}return _},verifyCredential:({target:V,mode:L,identity:U})=>{if(V.meta.credentialMode!==L)throw Error(`a target captured in ${V.meta.credentialMode??"an unknown"} mode is not warmed with a ${L} 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??b4}}function w4($){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 y4($){let Z={};for(let G of R4){let J=$.get(G);if(J)Z[G]=J}return Z}function qZ($,Z,G){let J=JSON.stringify([CZ($.configPath),CZ($.statePath)]),Q=U1.get(J);if(!Q)Q=k4(G,Z.settings()),U1.set(J,Q);let Y=Q,K=D1($);K.setEnabled(Y.settings.enabled);let N={location:{...Z,settings:()=>Y.settings}};Y.holders.push(N);let V=!1,L=async(U)=>{try{let _=N.location.settings();if(V||!_.enabled)return;if(U.kind!=="primary"){if(U.kind==="generate"&&w4(await U.request.clone().text())){if(V)return;Y.manager.remove(U.sessionID)}return}let q=U.attempt.data,A=q?.kind==="pool"?"local":q?.kind==="vault"?"vault":void 0;if(!A)return;let v=U.request.headers,$2=D4.some((V2)=>v.has(V2))||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 D=v.get("chatgpt-account-id")??void 0;Y.manager.track({sessionKey:U.sessionID,bodyText:S,accountId:U.attempt.accountId,isSubagent:$2,meta:{replayHeaders:y4(v),...D?{chatgptAccountId:D}:{},routingSessionId:U.sessionID,url:U.request.url,credentialMode:A}})}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:L,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(U1.get(J)===Y)U1.delete(J);Y.manager.stop();let _;try{await Promise.race([Y.manager.tick().catch(()=>{}),new Promise((q)=>{_=setTimeout(q,Y.joinTimeoutMs),_.unref?.()})])}finally{clearTimeout(_)}}}}import{mkdirSync as I4}from"node:fs";import{dirname as f4,resolve as v4}from"node:path";function h4(){return SZ("opencode2")}var g4=2000;class wZ{path;options;sessions;frameTurns=new o2;#$=new Set;#Z=new Set;#G=new Set;#J=Promise.resolve();#X=!1;#z;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=DZ($,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??g4),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{$=V$(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(I4(f4(this.path),{recursive:!0}),G=await this.#B(),!G)return;let J;try{J=V$(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)kZ(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 RZ(this.path,this.options.lockWaitMs??bZ)}}var yZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),IZ=globalThis,k1=IZ[yZ]??new Map;IZ[yZ]=k1;function m4($){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 fZ($=h4()){let Z=v4($),G=k1,J=k1.get(Z),Q=k1;if(J!==void 0&&!m4(J))G.compatible??=new Map,Q=G.compatible;let Y=Q.get(Z);if(!Y)Y=new wZ(Z),Q.set(Z,Y);let K=Y;return K.frameTurns??=new o2,Y}var U$=Symbol.for("cortexkit.openai-auth.v2.commands"),l4=I2("v2-command");function w1($){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 N$($){l4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function u4(){let $=globalThis;return $[U$]??={locations:new Map},$[U$].locations??=new Map,$[U$]}async function pZ($,Z){let G=u4(),J=$.location.directory,Q={menu:Z,session:$.session,closed:new AbortController},Y=await hZ(J),K=await vZ(lZ,Y.dir,()=>uZ({...Y,drain:mZ,apply:(_)=>{let q=G.locations.get(J);if(!w1(q))throw Error("The OpenAI menu location was closed");return q.menu.apply(_)}})),N=G.locations.get(J);if(G.locations.set(J,Q),w1(N))N.closed.abort(),await N.registration?.dispose();let V={name:"openai",description:"OpenAI account menu",async execute(_){let q=[...G.locations.values()].find(w1)?.session;if(!q)return N$("no live location");let A=await q.get({sessionID:_.sessionID}),v=G.locations.get(A.location.directory);if(!w1(v))return N$("location closed");let $2=await gZ(_.sessionID,v.closed.signal);if(!$2||G.locations.get(A.location.directory)!==v){if(!$2&&!v.closed.signal.aborted)H$({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},_.sessionID);return N$(v.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let S=await v.menu.open(_.sessionID);H$(S,_.sessionID)}};G.command??=V,G.command.execute=V.execute;let L=G.command;try{Q.registration=await $.command.transform((_)=>{_.add(L)})}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 p4="openai-auth-pool-browser",c4="openai-auth-pool-headless",d4="openai-auth-vault",i4="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Run /openai → Vault → Connect and approve the request before trying again.";async function N1($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function oZ($){return{method:{id:d4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await cZ($.paths,$.name)!=="vault")throw Error(i4)}}}function sZ($){let Z=(G,J,Q)=>({method:{id:G,type:"oauth",label:J},async authorize(){if($.vault)await N1($.vault);let Y=await $.beginLogin({version:$.version,headless:Q});return{url:Y.url,instructions:Y.instructions,mode:"auto",callback:Y.completion}}});return[Z(p4,"ChatGPT (openai-auth pool, browser)",!1),Z(c4,"ChatGPT (openai-auth pool, headless)",!0)]}function F$($){let Z=(G)=>typeof G==="string"?G:"";return X1({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===nZ||dZ($)}function n4($){if($.accountId)return $.accountId;let Z=$.access?x1($.access):void 0;return Z?A1(Z):void 0}async function rZ($,Z,G,J={}){if(J.vault)await N1(J.vault);if(F$(G))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Q=iZ($,{rowLocks:(A)=>aZ(Z,A)}),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=n4(G);if(J.vault)await N1(J.vault);let V=N!==void 0?{identity:N}:{};if(J.origin==="import"){let A=Y.rows.find((v)=>N!==void 0&&v.identity===N||v.credential?.type==="oauth"&&v.credential.refresh===G.refresh);if(A)return{id:A.id,operation:"kept"}}let L=Y.rows.filter((A)=>A.type==="oauth"&&!A.invalid),U=N?L.find((A)=>A.identity===N):void 0,_=Y.rows.find((A)=>A.id===y1);if(U)return{id:(await Q.replace(U.id,K,V)).id,operation:"replaced"};if(!_){let A=await Q.add({id:y1,credential:K,...V,...G.label!==void 0?{label:G.label}:{}});return{id:A.id,operation:A.outcome==="added-disabled"?"added-disabled":"added"}}if(!_.invalid&&!_.credential)return{id:(await Q.replace(y1,K,V)).id,operation:"replaced"};let q=await Q.add({id:G.id,credential:K,...V,...G.label!==void 0?{label:G.label}:{}});return{id:q.id,operation:q.outcome==="added-disabled"?"added-disabled":q.outcome==="rotated"?"replaced":"added"}}function a4($){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 $0($){let Z={...$,allowAction:a4,unavailableSections:[]};return{open:(G)=>tZ(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 eZ(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 o4($,Z){if(!Z0($.modelID??$.id)){$.enabled=!1;return}let G=z0($.id);if(G)$.limit={...G};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((J)=>[J.id,J])).values()]}function J0($){return $.model.transform((Z)=>{let G=Z.list(q2);for(let J of G){let Q=G0(String(J.id)),Y=Q?G.find((K)=>String(K.id)===Q):void 0;Z.update(q2,String(J.id),(K)=>o4(K,Y?.variants?.map((N)=>({...N,id:String(N.id)}))))}})}class K${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(!X0())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(()=>I1({...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(()=>I1({...J,error:f1(K,G?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>I1({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 W0($){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 j0({accessToken:G.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,J),Y0(J,$.now(),!0)}}function V0($){let{source:Z,counts:G,now:J}=$,Q=async(L)=>{let U=await Z.rowAccess(L,await $.storage());if(!U?.row)throw new Q0("unknown_account",`${L==="main"?"Main":"Fallback"} account ${L} was not found.`);return B0(L,U)},Y=async(L)=>{if($.authority&&await $.authority()!=="local")return{account:L,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[U]=await Z.pollRows(await $.storage(),{ids:[L]});if(!U)return{account:L,ok:!1,error:"targeted quota refresh returned no result"};return{account:U.id,ok:U.ok,...U.error!==void 0?{error:U.error}:{}}},K=(L)=>Z.peek().rows.find((U)=>U.id===L),N=(L)=>{let U=K(L);if(!U)return null;let _=d2(U.quota)??{},q=G.applicable(U),A=Math.max(0,...[_.primary?.checkedAt,_.secondary?.checkedAt].filter((v)=>typeof v==="number"));return{quota:{..._,...q!==void 0?{resetCreditsApplicable:q}:{}},checkedAt:A,refreshAfter:A,...U.identity!==void 0?{accountId:U.identity}:{}}};return{resolveResetTarget:Q,refreshResetTargetQuota:Y,quotaManager:{isRateLimited:(L)=>{let U=K(L);if(!U)return!1;let _=$.rateLimitMarks().get(U.id);return _!==void 0&&_>J()},getMain:()=>N("main"),getFallback:(L)=>N(L)}}}import{resolve as U0}from"node:path";var s4=1024;class P${pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=s4){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 q1(this.placementSnapshot($.sessionId),$,(Z,G)=>this.set(Z,G))}}var N0=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),H0=globalThis,v1=H0[N0]??new Map;H0[N0]=v1;function r4($){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 F0($){let Z=JSON.stringify([U0($.configPath),U0($.statePath)]),G=v1,J=v1.get(Z);if(J!==void 0&&!r4(J)){let Y=v1;Y.compatibleV1??=new Map,G=Y.compatibleV1}let Q=G.get(Z);if(!Q)Q=new P$,G.set(Z,Q);return Q}import{statSync as t4}from"node:fs";import{resolve as e4}from"node:path";function O0($){return $.map((Z)=>{try{let G=t4(Z);return`${G.ino}:${G.size}:${G.mtimeMs}:${G.ctimeMs}`}catch{return"?"}}).join("|")}function M$($){return O0([$.vault.paths.tokenPath,$.vault.paths.statePath])}function K0($){return O0([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+M$($)}class x0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;protocol=q0;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:K0($),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:K0(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??A0)(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 A0=async($,Z,G,J)=>{let Y=await Z.vault.authority()!=="local",K=M$(Z),N=()=>J()&&Z.vault.enrolled()===Y&&M$(Z)===K,V=await(Y?F1(Z.paths):t2(Z.paths)),L=Y?_0(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((q)=>q.id)),V,Date.now()):E0((await Z.source.sidebarView()).rows,V,Date.now()),U={canWrite:N,vaultMode:Y};if(await P0(L,$,U),!N()||!G)return;let _=L.vaultAccounts??L.fallbacks;if(G.accountId===void 0){await C0(G.sessionId,_,$,U);return}if(G.pin){let q=Date.now();await T0({sessionId:G.sessionId,assignment:{accountId:G.pin.accountId,wireAccountId:G.pin.wireIdentity,inputBytes:G.pin.inputBytes??0,quotaCheckedAt:G.pin.quotaCheckedAt,assignedAt:q,lastSeenAt:q},validPinnedAccountIds:[...Y?[]:["main"],..._.filter((A)=>A.enabled).map((A)=>A.id)]},$,U)}await M0({sessionId:G.sessionId,activeId:G.accountId,route:G.route??L.route,updatedAt:Date.now()},_,$,U)},q0=2,S0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),b0=globalThis,H1=b0[S0]??new Map;b0[S0]=H1;function R0($,Z=L0(),G=2000){let J=e4(Z),Q=H1.get(J);if(Q?.protocol!==q0)Q=new x0(J,G),H1.set(J,Q);let Y=Q;$={...$,write:$.write??A0};let K=Y.add($),N=!1;for(let[V,L]of $.pins.snapshot())Y.publish($,{sessionId:V,pin:L,accountId:L.accountId,route:"sticky-balanced"});return{publish:()=>Y.publish($),route:(V,L,U)=>{Y.publish($,{sessionId:V,accountId:L,route:U})},async release(){if(N)return;if(N=!0,K(),await Y.settled(),Y.empty&&H1.get(J)===Y)H1.delete(J)}}}var g1="cortexkit-openai-auth",z5=5000;async function D0($,Z,G,J=new j1,Q,Y,K){let N=new K$(G),V=new $5,L=new Map,U=new Map,_=(S)=>{U.delete(S);for(let D of L.keys())if(D.startsWith(`${S}:`))L.delete(D)},q=(S)=>{K?.(S.sessionID),Y?.send(S.sessionID,S.frame)},v=await p1({session:{hook:(S,D,V2)=>$.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)L.delete(`${p.sessionID}:${p.kind}`);try{await V.run(t,()=>D(X2))}catch(w){if(M2&&!(w instanceof L2))throw v0(w);throw w}if(I&&M2&&t.attempt){let w=I.request.headers.get("thread-id");if(w)I.request.headers.set("session-id",w)}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 w=X2,l=L.get(`${w.sessionID}:${w.kind}`);if(l)await N.frame(w.frame,l.attempt);if(l&&w.kind==="primary")q(w)}if(I||p){let w=I??p;if(!w)return;let a=(I?I.request.headers:new Headers(w.headers)).get("authorization")?.replace(/^Bearer /,"");if(M2&&a)U.set(w.sessionID,a);else U.delete(w.sessionID);if(p){let m=`${p.sessionID}:${p.kind}`;if(M2&&a&&t.attempt)L.set(m,{bearer:a,attempt:t.attempt,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 L.delete(m)}if(U.size>512){let m=U.keys().next().value;if(m)U.delete(m)}if(L.size>512){let m=L.keys().next().value;if(m)L.delete(m)}}else if(S==="experimental.ws.receive"){let w=X2,l=L.get(`${w.sessionID}:${w.kind}`);if(l){if(J.frameReceived(w.sessionID,w.frame),w.kind==="primary"){let a;if(Y?.receive(w.sessionID,w.frame,(m)=>{a=m}),a)try{let m=I$(a,l.url,l.headers,J);if(m)await Q?.({sessionID:w.sessionID,kind:"primary",request:m,attempt:l.attempt})}catch(m){G.warn("cachekeep WebSocket capture failed",{error:m instanceof Error?m.message:String(m)})}}w.frame=h0(w.frame,l.bearer)}}else if(S==="retry"){let w=X2,l=U.get(w.sessionID);if(l)Object.assign(w.error,{message:f1(w.error.message,l)})}},V2)},event:{subscribe:(S)=>async function*(){for await(let D of $.event.subscribe(S)){if(D.type==="session.deleted")_(D.data.sessionID);yield D}}()}},{...Z,rewriteRequest:async(S)=>{let D=V.getStore();if(D)D.attempt=S.attempt;return Z.rewriteRequest?.(S)},rewriteHandshakeURL:(S)=>{let D=V.getStore();if(D)D.attempt=S.attempt;return Z.rewriteHandshakeURL?.(S)},onAttemptEnd:async(S,D)=>{await N.end(S,D),await Z.onAttemptEnd?.(S,D)},rewriteResponse:async(S)=>{await N.response(S.request,S.response.status);let D=await Z.rewriteResponse?.(S)??S.response;return g0(D,S.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(S)=>{let D=S.get("authorization");return D?.startsWith("Bearer ")?D.slice(7):void 0}},hostRetryLimit:r2,logger:{info:(S,D)=>G.info?.(S,{data:D}),warn:(S,D)=>G.warn(S,{data:D})}}),$2=v.dispose;return{...v,dispose:async()=>{U.clear(),L.clear(),await $2(),await N.settle(),N.clear()}}}function _$($={}){return{id:g1,setup:(Z)=>G5(Z,$)}}async function G5($,Z={}){let u=[];try{let G=I2("opencode2");let J=I2("quota");let Q=Z.version??l0;await e0({version:Q,...Z.runtimeLayout});let Y=Z.paths??(()=>p0(m0()));let K=await F1(Y());let N=K?.logging?.level;if(N&&typeof N==="string")w0(N);let V=Z.fetch??fetch;let L=Z.now??Date.now;let U=Z.poolMigration??Z4;if(!U&&!e2(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 C=(Z2)=>{throw new L2({kind:"no-account",providerID:q2,sessionID:Z2.sessionID,requestKind:Z2.kind,message:S1})},h=await D0($,{providerID:q2,chooseAccount:C,accountHeaders:C},G);return()=>h.dispose()}let _=Z.vault?.firstRosterWaitMs??n0;let q=$4({host:"opencode",stateDir:Z.vault?.stateDir??f0(Y().statePath),reservedRouteIds:()=>I.peek().rows.map((C)=>C.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>V},Y());let A=q.vault;let v=async()=>await A.authority()==="local"?t2(Y()):F1(Y());let $2=!1;let S=!1;const D=K1(u,{[Symbol.dispose](){if(!$2)q.release()}},0);await A.authority();let V2=q.firstRoster;let X2=new L$;let I=new a0({paths:Y,refreshProvider:async(C)=>{let h=await I0({refreshToken:C.refresh,fetchImpl:V,now:L}),Z2=y0({id_token:"",access_token:h.access,refresh_token:h.refresh});return{...h,...Z2?{identity:Z2}:{}}},pullQuota:W0({fetchImpl:V,now:L,counts:X2,logger:J}),now:L,vaultIdentities:()=>A.identities(),vaultMode:()=>A.enrolled(),vaultAuthority:()=>A.authority(),vaultFirstRoster:V2,vaultFirstRosterBackgroundWaitMs:_,log:I2("pool")});if(await A.authority()==="local")await I.load();let p=new o0({pool:I,vault:A,log:(C)=>G.warn(C)});const f2=K1(u,{[Symbol.dispose](){if(!$2)p.dispose()}},0);let M2=Z.heartbeat===!1?void 0:await r0({version:Q,logger:I2("heartbeat")});let t=Z.fence??(()=>u0({currentVersion:Q}));let w=Z.slot??z4();let l=async()=>c0(Y(),await w.get({path:{id:"openai"}}));let a=!1;let m=U?s0({paths:Y,slot:w,version:Q,fence:t,runDeps:{vaultServes:()=>A.serves()},paused:async()=>await A.authority()!=="local",migrate:async(C)=>{let h=await d0(C);if(a=h.status==="refused",!S)await I.load();return h},adopt:async(C)=>{if(S)return{status:"retry",reason:"unsettled"};if(!await T$(V2,_))return{status:"retry",reason:"vault-roster-pending"};if(S)return{status:"retry",reason:"unsettled"};let h=await i0(C);if(!S)await I.load();return h}}):void 0;m?.start();q.start();let E2=F0(Y());let S2=R0({paths:Y(),source:I,pins:E2,vault:A},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const D2=K1(u,{[Symbol.dispose](){if(!$2)S2.release()}},0);S2.publish();let U2=Z.codex??new j1(void 0,void 0,fZ());let $1=OZ(K);let Q2=D1(Y());let z2=qZ(Y(),{source:I,limits:p,storage:v,vault:A,accounts:o1(Y()),settings:()=>$1,parentOf:async(C)=>(await $.session.get({sessionID:C}))?.parentID??void 0,fetch:V,log:I2("cachekeep")},{now:L,codexResponsesUrl:h1().codexApiEndpoint,...Z.cacheKeep});const g2=K1(u,{[Symbol.dispose](){if(!$2)z2.release()}},0);let j=HZ({limits:p,codex:U2,onRoute:S2.route,source:I,slotPlaceholderWithoutMain:l,storage:v,pins:E2,sessionAccounts:o1(Y()),vault:A,awaitVaultRoster:async()=>{await T$(A.awaitRequestRoster(),b1)},responsesLite:()=>h1().responsesLite,codexEndpoint:()=>h1().codexApiEndpoint,now:L,log:G});let H=await D0($,j.adapter,G,U2,(C)=>z2.capture(C),Q2,(C)=>z2.forget(C));j.attach(H);let P=await $.session.hook("prompt",(C)=>{j.beginTurn(C.sessionID)});let M=async(C)=>{if(await N1(A),e2(Y().configPath))return;if(await m?.idle(),e2(Y().configPath))return;if(a&&!F$(C)&&(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(C)=>{await M(C);let h=await rZ(I.poolStore(),Y(),C,{vault:A});if(!e2(Y().configPath))await m?.requestAdoption();await I.load(),G.info("ChatGPT login stored in the account pool",h)};let x=await l1($,{integrationID:q2,methods:sZ({beginLogin:Z.beginLogin??C$,version:Q,vault:A}),onLogin:(C)=>b(C),label:"ChatGPT (openai-auth account pool)",vault:oZ(A)});let O=await J0($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let y=$.command&&$.location?await pZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??$0({...V0({rateLimitMarks:()=>p.marks(),source:I,storage:v,counts:X2,now:L,authority:()=>A.authority()}),fetchImpl:V,now:L,randomUUID:Z5,accountStoragePath:Y().configPath,accountStatePath:Y().statePath,packageVersion:Q,layoutNotice:t0,loadAccounts:t2,store:()=>I.poolStore(),migration:async()=>{if(e2(Y().configPath))return{migrated:!0};let C=await t();return{migrated:!1,blockers:C.open?[]:C.blockers}},beginAccountLogin:Z.beginLogin??C$,refreshAllQuota:async()=>(await I.pollRows(await t2(Y()))).map((C)=>({...C,account:C.id})),getStickyRouting:async(C)=>E2.get(C),cacheKeepManager:z2.manager,setCacheKeepEnabled:(C)=>z2.configure({enabled:C}),setCacheKeepSubagents:(C)=>z2.configure({subagents:C}),setCacheKeepSustain:(C)=>z2.configure({sustain:C}),setCacheKeepWindow:(C)=>z2.configure({window:C}),afterWrite:()=>I.load(),refreshSidebar:()=>S2.publish(),clearStickyRouting:async(C)=>{let h=E2.get(C)!==void 0;return E2.forget(C),h},vault:A})):void 0;let f=new AbortController;(async()=>{try{for await(let C of $.event.subscribe({signal:f.signal}))if(C.type==="session.deleted")j.forgetSession(C.data.sessionID),z2.forget(C.data.sessionID),Q2.forget(C.data.sessionID)}catch(C){if(!f.signal.aborted)G.warn("stopped listening for session deletion",{error:C instanceof Error?C.message:String(C)})}})();$2=!0;return async()=>{S=!0,f.abort(),j.dispose();let C=z2.release();await y?.(),m?.dispose(),await p.dispose(),await S2.release(),await Promise.allSettled([H.dispose(),P.dispose(),x.dispose(),O.dispose()]);let h;try{await Promise.race([Promise.all([m?.idle(),I.settled(),U2.store?.settled(),C]),new Promise((Z2)=>{h=setTimeout(Z2,z5),h.unref?.()})])}finally{clearTimeout(h),await q.release(),await M2?.release()}}}catch(k){var c=k,G2=1}finally{k0(u,c,G2)}}var J5=_$(),k7={id:g1,setup:J5.setup,server:G4.server};export{k7 as default,_$ as createOpenAIAuthPlugin,g1 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.10.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -66,18 +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.39.2",
|
|
70
70
|
"@cortexkit/openai-auth-core": "workspace:*",
|
|
71
71
|
"@opencode/plugin": "2.2.5"
|
|
72
72
|
},
|
|
73
73
|
"dependencies": {
|
|
74
|
-
"@cortexkit/claustrum-client": "^0.
|
|
74
|
+
"@cortexkit/claustrum-client": "^0.15.0",
|
|
75
75
|
"@cortexkit/private-files": "^0.2.2",
|
|
76
76
|
"@cortexkit/subc-client": "^0.22.0",
|
|
77
77
|
"@opentui/core": ">=0.7.0",
|
|
78
78
|
"@opentui/solid": ">=0.7.0",
|
|
79
79
|
"ai": "^7.0.159",
|
|
80
80
|
"jsonc-parser": "^3.3.1",
|
|
81
|
-
"solid-js": "1.9.
|
|
81
|
+
"solid-js": "1.9.18"
|
|
82
82
|
}
|
|
83
83
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { stat } from "node:fs/promises";
|
|
3
3
|
import { resolve } from "node:path";
|
|
4
|
+
import { FileReadCache } from "./92e38944b51b2405-file-read-cache.js";
|
|
4
5
|
import { acquireRefreshFileLock, LockContentionError, LockOwnershipError, lockPathFor, PrivateFileError, withLock, writeJsonAtomic, } from "./ec971142548df90e-index.js";
|
|
5
6
|
import { readPrivateText, windowsPrivateFiles } from "./375d9cca2def037d-private-files.js";
|
|
6
7
|
import { decodeQuotaMap, isQuotaObservation, mergeQuotaObservation, } from "./d5a8f1061ee2f114-index.js";
|
|
@@ -333,7 +334,18 @@ function decodeRoster(value) {
|
|
|
333
334
|
export function decodedVaultRoster(roster) {
|
|
334
335
|
return decodeRoster(JSON.parse(JSON.stringify(roster)));
|
|
335
336
|
}
|
|
337
|
+
const rosterReadCache = new FileReadCache({
|
|
338
|
+
followSymlinks: true,
|
|
339
|
+
});
|
|
336
340
|
export async function readVaultRoster(path) {
|
|
341
|
+
// Windows permission, owner and ancestry checks must still run on every read.
|
|
342
|
+
if (windowsPrivateFiles)
|
|
343
|
+
return readFreshVaultRoster(path);
|
|
344
|
+
const roster = await rosterReadCache.read([path], ([resolvedPath = path]) => readFreshVaultRoster(resolvedPath));
|
|
345
|
+
// Callers edit rows and nested limits data; none may own the cached objects.
|
|
346
|
+
return structuredClone(roster);
|
|
347
|
+
}
|
|
348
|
+
async function readFreshVaultRoster(path) {
|
|
337
349
|
let text;
|
|
338
350
|
try {
|
|
339
351
|
text = await readPrivateText(path, windowsPrivateFiles);
|
|
@@ -366,7 +378,8 @@ const DISCOVERY_LEASE = { name: 'claustrum-roster', ttlMs: 30_000 };
|
|
|
366
378
|
*/
|
|
367
379
|
export async function mutateVaultRoster(path, change, options = {}) {
|
|
368
380
|
return withLock(path, { ...WRITE_LOCK, signal: options.signal }, async (lock) => {
|
|
369
|
-
|
|
381
|
+
// A read-modify-write always observes the file under its write lock.
|
|
382
|
+
const current = await readFreshVaultRoster(path);
|
|
370
383
|
const { next, result } = await change(current, {
|
|
371
384
|
assertOwned: () => lock.assertOwned(),
|
|
372
385
|
});
|
|
@@ -374,13 +387,24 @@ export async function mutateVaultRoster(path, change, options = {}) {
|
|
|
374
387
|
await lock.assertOwned();
|
|
375
388
|
// Staging the file takes several awaited steps; check both the caller's
|
|
376
389
|
// lease and this lock again at the last moment before the rename.
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
390
|
+
try {
|
|
391
|
+
await writeJsonAtomic(path, next, {
|
|
392
|
+
beforeRename: async () => {
|
|
393
|
+
await options.beforePublish?.();
|
|
394
|
+
options.signal?.throwIfAborted();
|
|
395
|
+
await lock.assertOwned();
|
|
396
|
+
},
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
catch (error) {
|
|
400
|
+
if (error &&
|
|
401
|
+
typeof error === 'object' &&
|
|
402
|
+
'published' in error &&
|
|
403
|
+
error.published === true)
|
|
404
|
+
options.onPublished?.();
|
|
405
|
+
throw error;
|
|
406
|
+
}
|
|
407
|
+
options.onPublished?.();
|
|
384
408
|
}
|
|
385
409
|
return result;
|
|
386
410
|
});
|
|
@@ -2,7 +2,7 @@ import { writeJsonAtomic } from "./7211cfec06a298bc-atomic-write.js";
|
|
|
2
2
|
import { assertLimitsWriteAllowed, runInsideHook } from "./9deae3c4da4fd63b-hooks.js";
|
|
3
3
|
import { notReadyError, readPool, runOperation } from "./458b934e92490331-mutate.js";
|
|
4
4
|
/** A namespace merge and its check of current row bindings share one locked config snapshot. */
|
|
5
|
-
export async function updatePoolLimitsNamespace(rt, mutator) {
|
|
5
|
+
export async function updatePoolLimitsNamespace(rt, mutator, options = {}) {
|
|
6
6
|
assertLimitsWriteAllowed();
|
|
7
7
|
const { ctx } = rt;
|
|
8
8
|
await runOperation(ctx, 'updateLimitsNamespace', undefined, undefined, async (locks, progress) => {
|
|
@@ -22,13 +22,25 @@ export async function updatePoolLimitsNamespace(rt, mutator) {
|
|
|
22
22
|
operation: 'updateLimitsNamespace',
|
|
23
23
|
rowId: undefined,
|
|
24
24
|
};
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
25
|
+
try {
|
|
26
|
+
await writeJsonAtomic(ctx.configPath, config, {
|
|
27
|
+
beforeRename: async () => {
|
|
28
|
+
await ctx.onStep?.('before-config-write', info);
|
|
29
|
+
await locks.assertAll();
|
|
30
|
+
options.beforePublish?.();
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
if (error &&
|
|
36
|
+
typeof error === 'object' &&
|
|
37
|
+
'published' in error &&
|
|
38
|
+
error.published === true)
|
|
39
|
+
options.onPublished?.();
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
31
42
|
progress.writes++;
|
|
43
|
+
options.onPublished?.();
|
|
32
44
|
await ctx.onStep?.('after-config-write', info);
|
|
33
45
|
});
|
|
34
46
|
}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { lstat } from "node:fs/promises";
|
|
1
|
+
import { lstat, stat } from "node:fs/promises";
|
|
2
2
|
import { resolve } from "node:path";
|
|
3
|
-
async function identity(path) {
|
|
3
|
+
async function identity(path, followSymlinks) {
|
|
4
4
|
try {
|
|
5
|
-
|
|
6
|
-
//
|
|
5
|
+
// Match the reader: private readers reject links, while readFile follows
|
|
6
|
+
// them and needs the target's identity, not the link's identity.
|
|
7
|
+
const metadata = await (followSymlinks ? stat(path) : lstat(path));
|
|
7
8
|
return metadata.isFile() ? metadata : undefined;
|
|
8
9
|
}
|
|
9
10
|
catch (error) {
|
|
@@ -23,11 +24,15 @@ function sameIdentity(left, right) {
|
|
|
23
24
|
}
|
|
24
25
|
/** Process-local reads, capped at 64 path sets with one value per resolved set. */
|
|
25
26
|
export class FileReadCache {
|
|
27
|
+
#followSymlinks;
|
|
26
28
|
#entries = new Map();
|
|
29
|
+
constructor(options = {}) {
|
|
30
|
+
this.#followSymlinks = options.followSymlinks ?? false;
|
|
31
|
+
}
|
|
27
32
|
async read(paths, read, validateHit) {
|
|
28
33
|
const resolvedPaths = paths.map((path) => resolve(path));
|
|
29
34
|
const key = JSON.stringify(resolvedPaths);
|
|
30
|
-
const probed = await Promise.all(resolvedPaths.map(identity));
|
|
35
|
+
const probed = await Promise.all(resolvedPaths.map((path) => identity(path, this.#followSymlinks)));
|
|
31
36
|
const identities = probed.every((entry) => entry !== undefined)
|
|
32
37
|
? probed
|
|
33
38
|
: undefined;
|