@cortexkit/opencode-openai-auth 1.9.4 → 1.9.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +2 -2
- package/dist/{codex-request-By530v1D.d.ts → codex-request-CZ16goZ6.d.ts} +20 -4
- package/dist/index-1nrre3d8.js +91 -0
- package/dist/index-41yn5c02.js +8 -0
- package/dist/{index-jej9cfk7.js → index-4gnwkw3a.js} +1 -1
- package/dist/{index-7bjgmbx4.js → index-7qxa018z.js} +1 -1
- package/dist/{index-4p45bmbz.js → index-8rj2xddq.js} +12 -12
- package/dist/{index-v1ztg103.js → index-cf0mrvqj.js} +1 -1
- package/dist/{index-rrtsaz80.js → index-f1cqptqa.js} +1 -1
- package/dist/index-h3vtzckv.js +76 -0
- package/dist/index-mcy24ej8.js +2 -0
- package/dist/index-npj40h62.js +12 -0
- package/dist/{index-cmybrjbd.js → index-s2vrkdj4.js} +1 -1
- package/dist/{index-2bf808fw.js → index-s52j2h64.js} +1 -1
- package/dist/{index-g3gbp1m4.js → index-y4j7y8b8.js} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/{port-file-DXCxv8tU.d.ts → port-file-CEjki7bM.d.ts} +6 -1
- package/dist/rpc/port-file.d.ts +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.d.ts +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/{rpc-client-CmaZW1by.d.ts → rpc-client-rWuV04C-.d.ts} +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-dcr3tgsk.js → token-djwdynff.js} +1 -1
- package/dist/token-util-0xt1ws82.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +1 -1
- package/dist/v2/server.d.ts +1 -1
- package/dist/v2/server.js +3 -3
- package/package.json +3 -3
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +74 -9
- package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +36 -0
- package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +2 -0
- package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +8 -0
- package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +7 -0
- package/src/tui-compiled/raw/shared/45bf5343bbbf9add-admission.js +17 -7
- package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +2 -5
- package/src/tui-compiled/raw/shared/4ede5af6a878a14e-usage.js +145 -0
- package/src/tui-compiled/raw/shared/5f8cc863449a6c85-limits-namespace.js +34 -0
- package/src/tui-compiled/raw/shared/754d6017f8e419cf-builtins.js +38 -0
- package/src/tui-compiled/raw/shared/836fc615de6afbd9-settings.js +11 -4
- package/src/tui-compiled/raw/shared/97484d9bb98c705b-provider-state.js +5 -5
- package/src/tui-compiled/raw/shared/9d3fc9e37456504e-refresh.js +1 -1
- package/src/tui-compiled/raw/shared/9deae3c4da4fd63b-hooks.js +20 -5
- package/src/tui-compiled/raw/shared/a62a27a204266acd-attribution.js +3 -2
- package/src/tui-compiled/raw/shared/c14988621dc60a75-port-file.js +46 -4
- package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +2 -0
- package/src/tui-compiled/raw/shared/cd94316a888b0a8e-schema.js +9 -4
- package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +142 -47
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +74 -9
- package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +36 -0
- package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +2 -0
- package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +8 -0
- package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +7 -0
- package/src/tui-compiled/runtime/shared/45bf5343bbbf9add-admission.js +17 -7
- package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +2 -5
- package/src/tui-compiled/runtime/shared/4ede5af6a878a14e-usage.js +145 -0
- package/src/tui-compiled/runtime/shared/5f8cc863449a6c85-limits-namespace.js +34 -0
- package/src/tui-compiled/runtime/shared/754d6017f8e419cf-builtins.js +38 -0
- package/src/tui-compiled/runtime/shared/836fc615de6afbd9-settings.js +11 -4
- package/src/tui-compiled/runtime/shared/97484d9bb98c705b-provider-state.js +5 -5
- package/src/tui-compiled/runtime/shared/9d3fc9e37456504e-refresh.js +1 -1
- package/src/tui-compiled/runtime/shared/9deae3c4da4fd63b-hooks.js +20 -5
- package/src/tui-compiled/runtime/shared/a62a27a204266acd-attribution.js +3 -2
- package/src/tui-compiled/runtime/shared/c14988621dc60a75-port-file.js +46 -4
- package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +2 -0
- package/src/tui-compiled/runtime/shared/cd94316a888b0a8e-schema.js +9 -4
- package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +142 -47
- package/dist/index-2esezxst.js +0 -12
- package/dist/index-6xz3n4qh.js +0 -91
- package/dist/index-81yvwra9.js +0 -8
- package/dist/index-hz6f9gpq.js +0 -2
- package/dist/index-xx3k2qbv.js +0 -76
- package/dist/token-util-gbd7jw6d.js +0 -1
package/dist/v2/server.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{c as
|
|
2
|
-
`)}:{event:
|
|
3
|
-
`)}}function F1($,Z){let J=new TextDecoder,G="",Y=(F)=>{let W=I0(F);if(!W)return;try{$(W)}catch(N){Z(N)}},Q=()=>{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),Y(W)}};return new TransformStream({transform(F,W){W.enqueue(F),G+=J.decode(F,{stream:!0}),Q()},flush(){if(G+=J.decode(),Q(),G.trim()!=="")Y(G);G=""}})}var r1=512,t1=1200000,R2="x-common-auth-attempt",O2=($,Z)=>JSON.stringify([$,Z]),N2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function f0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function v0($,Z){let J=$.getReader();return new ReadableStream({async pull(G){let Y;try{Y=await J.read()}catch(Q){Z({reason:"failed",message:Q instanceof Error?Q.message:String(Q)}),G.error(Q);return}if(Y.done)Z(),G.close();else G.enqueue(Y.value)},async cancel(G){Z({reason:"cancelled",...G===void 0?{}:{message:String(G)}}),await J.cancel(G)}})}function u2($,Z){for(let[J,G]of Object.entries(Z)){let Y=J.toLowerCase();for(let Q of Object.keys($))if(Q.toLowerCase()===Y)delete $[Q];if(G!==null)$[J]=G}}function h0($,Z){for(let[J,G]of Object.entries(Z))if(G===null)$.delete(J);else $.set(J,G)}async function K1($,Z,J={}){let{providerID:G}=Z,Y=J.gateOnPlaceholder,Q=(z)=>Y===void 0||Y.credential(z)===K2(G),F=J.logger,W=Math.max(1,J.maxRecords??r1),N=[...J.hostCredentials??[K2(G)],...Y?[K2(G)]:[]].filter((z)=>z!==""),B=new Map,H=new WeakMap,T=new Map,R=0,C=new Set,D=new Map,d=new Map,O=(z)=>{let j=d.get(z);return j?.ownedSeen===!0&&j.foreignSeen},f=(z,j)=>{D.set(z,j);let V=d.get(z)??{ownedSeen:!1,foreignSeen:!1};if(j)V.ownedSeen=!0;else V.foreignSeen=!0;d.set(z,V)},B2=(z,j)=>{let V=Y?.refuseMisplaced,P=V?[...j].filter(([,k])=>k.includes(K2(G))):[],U=Q(j)&&(!V||P.length>0);if(V){if(P.length>0&&(P.length!==1||!U))throw f(z.sessionID,!1),new Y2({kind:"placement-refused",providerID:G,sessionID:z.sessionID,requestKind:z.kind,message:V(P[0]?.[0]??"")})}return f(z.sessionID,U),U},J2=!1,w=!1,l=new Map,L2=0,Z2=!1,i=new Map,X=(z,j)=>{try{F?.warn(z,j)}catch{}},K=(z)=>z instanceof Error?z.message:String(z),M=new Map,_=(z,j)=>{let V=(M.get(z)??Promise.resolve()).then(j),P=V.then(()=>{},()=>{});return M.set(z,P),P.then(()=>{if(M.get(z)===P)M.delete(z)}),V},h=(z,j)=>{let V=M.get(z);return V?V.then(()=>h(z,j)):j()},A=async(z)=>{try{await Z.dropChoice?.({...z.input,accountId:z.accountId})}catch(j){X("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:z.input.sessionID,error:K(j)})}},S=async(z)=>{try{await Z.dropSameAccountRetry?.({...z.input,accountId:z.accountId})}catch(j){X("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:z.input.sessionID,error:K(j)})}},v=async(z)=>{if(z.next)await A(z.next);if(z.sameAccount)await S(z.sameAccount)},x=(z)=>{let j=T.get(z);if(T.delete(z),j)_(j.sessionID,()=>v(j))},I=async(z,j)=>{let V=l.get(z);if(!V||V.size===0)return;await Promise.all([...V].map(async(P)=>{try{await P(j)}catch(U){X("opencode2 auth listener threw; the request is unaffected",{event:z,error:K(U)})}}))},n=async(z,j)=>{try{await Z.onAttemptEnd?.(z,j)}catch(V){X("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:z.attemptId,error:K(V)})}},u=(z,j)=>{if(z.ended||!z.attempt)return;let V={...z.status===void 0?{}:{status:z.status},outputStarted:z.outputStarted,...z.limit?{limit:z.limit.signal}:{},...j?{error:j}:{}};if(j)z.endError=j;z.ended=n(z.attempt,V)},o=(z,j)=>u(z,{reason:"abandoned",message:j}),s=(z)=>[...B.values()].filter((j)=>j.key===z),e=(z)=>s(z).at(-1),p=(z)=>{if(B.delete(z.id),T.get(z.key)?.attemptId===z.id||!s(z.key).length)x(z.key)},q=(z)=>{B.set(z.id,z);while(B.size>W){let j=B.values().next().value;if(j===void 0)break;o(j,"dropped to keep the record bound"),p(j)}},G2=(z)=>z.accountId===void 0?void 0:{...z.scope,accountId:z.accountId},g=(z,j)=>new Y2({kind:"no-account",providerID:G,sessionID:z.sessionID,requestKind:z.kind,...j===void 0?{}:{message:j}}),m=(z)=>{i.get(z)?.clear(),i.delete(z)},$2=async(z,j)=>{let V=()=>g(z,`${G} ${z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(Z2)throw V();let P=i.get(z.sessionID);if(!P)P=new Set,i.set(z.sessionID,P);let U={};P.add(U);let k=()=>{if(!P.has(U))throw V()};try{return await j(k)}finally{if(P.delete(U),P.size===0&&i.get(z.sessionID)===P)i.delete(z.sessionID)}},X2=(z,j)=>{for(let[V,P]of j)if(N.some((U)=>P.includes(U)))throw new Y2({kind:"host-credential-on-wire",providerID:G,sessionID:z.sessionID,requestKind:z.kind,message:`${G} ${z.kind} request still carries the host's placeholder credential in ${V}; the adapter's account headers must replace it`})},L=(z)=>{for(let j of s(z))if(j.ended||!j.attempt)p(j);else if(j.transport==="ws"||j.judged)o(j,"a newer attempt of its session and kind began"),p(j)},b=async(z,j,V,P)=>{let U=O2(z.sessionID,z.kind),{input:k,accountId:E,sameAccountRetry:y}=await h(z.sessionID,async()=>{V();let r=T.get(U);T.delete(U);let z2=r?.accountId??e(U)?.accountId;L(U);let t=r?.next,Q2=r?.sameAccount,a=Q2!==void 0&&Q2.input.modelID===z.modelID&&Q2.input.agent===z.agent,W2=t!==void 0&&t.input.modelID===z.modelID&&t.input.agent===z.agent,U2={...z,phase:"request",...z2===void 0?{}:{previousAccountId:z2},...r?.rerouteFrom?{rerouteFrom:r.rerouteFrom}:{}};if(t&&!W2)await _(z.sessionID,()=>A(t)),V();if(Q2&&!a)await _(z.sessionID,()=>S(Q2)),V();let H2=a?Q2.accountId:W2?t.accountId:await Z.chooseAccount(U2);return{input:U2,accountId:typeof H2==="string"?H2:void 0,sameAccountRetry:a}});V();let c={},V2;if(E!==void 0){let r=await Z.accountHeaders({...z,accountId:E});if(V(),f0(r))c=r.headers,V2=r.attempt;else c=r}let g2=`attempt-${++L2}`,E2={id:g2,key:U,scope:z,accountId:E,headers:c,attempt:E===void 0?void 0:{...z,accountId:E,attemptId:g2,transport:P,data:V2},...P===void 0?{}:{transport:P},outputStarted:!1,sameAccountRetry:y};if(q(E2),E2.attempt)I("select",{...z,accountId:E2.attempt.accountId,hook:j,...k.previousAccountId===void 0?{}:{previousAccountId:k.previousAccountId},...k.rerouteFrom===void 0?{}:{rerouteFrom:k.rerouteFrom},handle:E2.attempt});return E2},j2=async(z,j,V,P,U)=>{let k=O2(z.sessionID,z.kind),E=P===void 0?void 0:B.get(P);if(E?.key!==k)E=void 0;if(!E){if(E=e(k),s(k).filter((c)=>c.transport===void 0&&!c.ended).length>1&&!w)w=!0,X("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:z.sessionID,kind:z.kind})}if(!E||E.transport!==void 0||E.ended)E=await b(z,j,U,V);else if(E.transport=V,E.attempt)E.attempt.transport=V;if(V==="ws"){for(let y of s(k))if(y!==E&&y.transport==="ws")o(y,"a newer attempt of its session and kind went out over WebSocket")}return E},b2=async(z,j)=>{try{return await j()}catch(V){throw u(z,{reason:"failed",message:K(V)}),V}},u1=(z,j)=>{let V=s(O2(z,j)).filter((P)=>P.transport==="ws").at(-1);return V?.attempt!==void 0&&!V.ended?V:void 0},W1=(z,j,V)=>{let P=G2(z);if(!P||!z.attempt||z.limit)return;z.limit={signal:j,delivered:I("limit",{...P,via:V,limit:j,outputStarted:z.outputStarted,handle:z.attempt})}},p1=(z,j,V,P)=>{let U=G2(z);if(!U||!z.attempt)return;I("quota",{...U,transport:j,...P===void 0?{}:{status:P},quota:V,handle:z.attempt})},c1=(z,j,V,P)=>{let U=z.attempt;if(!U)return;let k=Z.inspectEvent?.(P===void 0?{transport:j,data:V,attempt:U}:{transport:j,data:V,event:P,attempt:U});if(!k)return;if(k.quota!==void 0)p1(z,j,k.quota);if(k.outputStarted)z.outputStarted=!0;if(k.limit)W1(z,k.limit,j);if(k.error!==void 0)u(z,{reason:"failed",message:k.error});else if(k.done)u(z)},w0=(z,j)=>{let V=z.attempt;if(!V||j.accountId===z.accountId)return;if(V.reboundFrom??=V.accountId,V.accountId=j.accountId,"data"in j)V.data=j.data;z.accountId=j.accountId},y0=(z)=>!z.attempt||z.endError!==void 0||z.status!==void 0&&z.status>=400,d1=(z)=>{let j=[...B.values()].filter((y)=>y.scope.sessionID===z),V=j.filter((y)=>y.limit&&!y.rerouted).at(-1);if(V)return V;let P=j.filter((y)=>y.scope.kind==="primary"),U=P.length>0?P:j;if(U.length<=1)return U[0];let k=U.filter((y)=>!y.judged&&y0(y)).at(-1);if(k)return k;let E=U.filter((y)=>y.attempt&&!y.ended);if(E.length>1)return"ambiguous";return E[0]??U.at(-1)},C2={providerID:G},P2=[];P2.push(await $.session.hook("model.request",(z)=>{if(Y)return;return $2(N2(z),async(j)=>{let V=await b(N2(z),"model.request",j);if(j(),V.accountId===void 0)throw g(V.scope);u2(z.headers,{...V.headers,[R2]:V.id})})},C2)),P2.push(await $.session.hook("http.request",(z)=>{if(Y){if(!B2(N2(z),z.request.headers))return}return $2(N2(z),async(j)=>{let V=z.request.headers.get(R2)??void 0,P=Y?await b(N2(z),"http.request",j,"http"):await j2(N2(z),"http.request","http",V,j);j();let U=G2(P),k=P.attempt;if(!U||!k)throw g(P.scope);await b2(P,async()=>{let E=z.request;if(Z.rewriteRequest){if(V!==void 0){let V2=new Headers(E.headers);V2.delete(R2),E=new Request(E,{headers:V2})}E=await Z.rewriteRequest({...U,request:E,attempt:k})??E,j()}let y=new Headers(E.headers);y.delete(R2),h0(y,P.headers),X2(P.scope,y.entries());let c=new Request(E,{headers:y});H.set(c,P),z.request=c})})},C2)),P2.push(await $.session.hook("http.response",async(z)=>{let j=H.get(z.request);if(!j){if(Y)return;if(!J2)J2=!0,X("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:z.sessionID,kind:z.kind});return}let V=z.response;if(Z.answeredBy&&j.attempt){let y=j.attempt,c=await b2(j,async()=>Z.answeredBy?.({request:z.request,response:V,attempt:y}));if(c)w0(j,c)}let P=G2(j),U=j.attempt;if(!P||!U)return;j.status=V.status;let k=Z.quotaFromHeaders?.(V.headers,V.status,U);if(k!==void 0)p1(j,"http",k,V.status);if(!V.ok&&Z.limitFromResponse){let y=await Z.limitFromResponse({status:V.status,headers:V.headers,body:()=>V.clone().text(),attempt:U});if(y)W1(j,y,"http")}if(!V.ok||!V.body)u(j);let E=V;if(V.body&&(Z.inspectEvent||Z.onAttemptEnd)){let y=V.body;if(Z.inspectEvent)y=y.pipeThrough(F1((c)=>c1(j,"http",c.data,c.event),(c)=>X("opencode2 auth event inspection threw",{error:K(c)})));E=new Response(v0(y,(c)=>u(j,c)),{status:V.status,statusText:V.statusText,headers:V.headers})}if(Z.rewriteResponse)E=await Z.rewriteResponse({...P,request:z.request,response:E,attempt:U})??E;if(E!==V)z.response=E},C2)),P2.push(await $.session.hook("experimental.ws.handshake",(z)=>{if(Y){let j=O2(z.sessionID,z.kind);if(C.delete(j),!B2(N2(z),new Headers(z.headers)))return}return $2(N2(z),async(j)=>{let V;for(let E of Object.keys(z.headers)){if(E.toLowerCase()!==R2)continue;V??=z.headers[E],delete z.headers[E]}let P=Y?await b(N2(z),"experimental.ws.handshake",j,"ws"):await j2(N2(z),"experimental.ws.handshake","ws",V,j);j();let U=G2(P),k=P.attempt;if(!U||!k)throw g(P.scope);await b2(P,async()=>{if(!Y?.refuseMisplaced)u2(z.headers,P.headers);let E=Z.rewriteHandshakeURL?.({...U,url:z.url,attempt:k});if(E!==void 0)z.url=E;if(Y?.refuseMisplaced)u2(z.headers,P.headers);if(X2(P.scope,Object.entries(z.headers)),Y)C.add(P.key)})})},C2));let i1=Z.rewriteWebSocketFrame?.bind(Z);if(i1)P2.push(await $.session.hook("experimental.ws.send",async(z)=>{let j=N2(z);if(Y&&!C.has(O2(j.sessionID,j.kind)))return;let V=u1(j.sessionID,j.kind),P=await i1({...j,attempt:V?.attempt,frame:z.frame});if(P!==void 0)z.frame=P},C2));P2.push(await $.session.hook("experimental.ws.receive",(z)=>{if(Y&&!C.has(O2(z.sessionID,z.kind)))return;let j=u1(z.sessionID,z.kind);if(!j)return;try{c1(j,"ws",z.frame)}catch(V){X("opencode2 auth frame inspection threw",{error:K(V)})}},C2)),P2.push(await $.session.hook("retry",async(z)=>{if(Y&&D.get(z.sessionID)!==!0)return;let j=z.decision,V=()=>I("retry",{sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:j,decision:j});if(O(z.sessionID)&&!Z.retrySameAccount){await V();return}let P=d1(z.sessionID);if(!P)return;if(P==="ambiguous"){await I("retry",{sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:j,decision:j});return}let U=P;await $2(U.scope,async(k)=>{let E=k,y=Z.retrySameAccount?.bind(Z),c=U.attempt;if(y&&c&&!U.outputStarted&&!U.sameAccountRetry){if(U.ended)await U.ended;if(U.limit)await U.limit.delivered;let r=await _(U.scope.sessionID,async()=>{E();let z2=c.accountId,t=()=>B.has(U.id)&&U.accountId===z2&&d1(z.sessionID)===U&&!U.outputStarted&&(!Y||D.get(z.sessionID)===!0);if(!t()||U.sameAccountRetry)return!1;U.sameAccountRetry=!0;let Q2={...U.scope,accountId:z2,error:z.error,attempt:z.attempt,...U.limit?{limit:U.limit.signal}:{}},a;try{a=await y(Q2)}catch(H2){X("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:z.sessionID,error:K(H2)})}if(!a)return E(),!1;let W2={accountId:a.accountId,input:Q2};try{E()}catch(H2){throw await S(W2),H2}if(!t()||a.accountId!==z2)return await S(W2),!1;let U2=T.get(U.key);if(T.delete(U.key),U2)await v(U2);try{E()}catch(H2){throw await S(W2),H2}if(!t())return await S(W2),!1;return T.set(U.key,{attemptId:U.id,sessionID:U.scope.sessionID,order:++R,accountId:z2,sameAccount:W2}),U.judged=!0,z.decision={retry:!0,delay:0},!0});if(E(),r){await I("retry",{sessionID:z.sessionID,accountId:U.accountId,kind:U.scope.kind,attempt:z.attempt,reason:"same-account",hostDecision:j,decision:z.decision,handle:U.attempt});return}}if(O(z.sessionID)){await V();return}U.judged=!0;let V2=U.attempt;if(V2&&!U.outputStarted){if(!U.limit){let r=Z.limitFromError?.(z.error,V2);if(r)W1(U,r,"error")}if(U.ended)await U.ended;if(U.limit)await U.limit.delivered}E();let{decision:g2,reason:E2}=await _(U.scope.sessionID,async()=>{if(E(),O(z.sessionID))return{decision:j,reason:"host-decides"};let r=T.get(U.key);if(T.delete(U.key),r)await v(r);if(E(),O(z.sessionID))return{decision:j,reason:"host-decides"};let z2=j,t,Q2,a;if(U.accountId===void 0||!V2)z2={retry:!1},t="no-account";else if(U.outputStarted)z2={retry:!1},t="output-started";else if(U.limit){let W2={accountId:U.accountId,limit:U.limit.signal},U2,H2={...U.scope,phase:"retry",previousAccountId:U.accountId,rerouteFrom:W2};try{U2=await Z.chooseAccount(H2)}catch(H1){X("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:U.scope.sessionID,error:K(H1)})}let M2=typeof U2==="object"?U2.hold:void 0,l2=typeof U2==="string"?U2:M2?U.accountId:void 0;if(l2!==void 0)a={accountId:l2,input:H2};try{E()}catch(H1){if(a)await A(a);throw H1}if(O(z.sessionID)){if(a)await A(a);return{decision:j,reason:"host-decides"}}if(M2&&Number.isFinite(M2.delayMs)&&M2.delayMs>=0)z2={retry:!0,delay:Math.min(M2.delayMs,t1)},t="hold";else if(!M2&&l2!==void 0&&l2!==U.accountId)U.rerouted=!0,Q2=W2,z2={retry:!0,delay:0},t="reroute";else{if(M2&&a)await A(a),a=void 0;t="host-decides-last-account"}}else t="host-decides";if(z.decision=z2,z2.retry&&U.accountId!==void 0&&B.has(U.id))T.set(U.key,{attemptId:U.id,sessionID:U.scope.sessionID,order:++R,accountId:U.accountId,...Q2===void 0?{}:{rerouteFrom:Q2},...a===void 0?{}:{next:a}});else if(a)await A(a);return{decision:z2,reason:t}});E(),await I("retry",{sessionID:z.sessionID,...U.accountId===void 0?{}:{accountId:U.accountId},kind:U.scope.kind,attempt:z.attempt,reason:E2,hostDecision:j,decision:g2,...V2===void 0?{}:{handle:V2}})})},C2));let a1=(z)=>{if(m(z),D.delete(z),!d.get(z)?.foreignSeen)d.delete(z);for(let j of C)if(JSON.parse(j)[0]===z)C.delete(j);for(let j of[...B.values()]){if(j.scope.sessionID!==z)continue;o(j,"its session was forgotten"),B.delete(j.id)}for(let[j,V]of T)if(V.sessionID===z)x(j)},U1=new AbortController,n1=$.event;if(n1)(async()=>{try{for await(let z of n1.subscribe({signal:U1.signal}))if(z.type==="session.deleted")a1(z.data.sessionID);else if(z.type==="session.status"&&z.data.status.type==="idle"){let j=z.data.sessionID,V=++R;_(j,async()=>{for(let[P,U]of T)if(U.sessionID===j&&U.order<V)T.delete(P),await v(U)})}}catch(z){if(!U1.signal.aborted)X("opencode2 auth stopped listening for session deletion",{error:K(z)})}})();return{on(z,j){let V=l.get(z);if(!V)V=new Set,l.set(z,V);let P=j;return V.add(P),()=>{V.delete(P)}},accountFor(z,j){return e(O2(z,j))?.accountId},forgetSession:a1,get size(){return B.size},async dispose(){if(Z2)return;Z2=!0;for(let z of i.keys())m(z);U1.abort();for(let z of B.values())o(z,"the installation was disposed");B.clear();for(let z of T.keys())x(z);C.clear(),D.clear(),d.clear(),l.clear(),await Promise.all(M.values()),await Promise.all(P2.map(async(z)=>{try{await z.dispose()}catch(j){X("opencode2 auth hook did not dispose cleanly",{error:K(j)})}}))}}}import{createHash as m0}from"node:crypto";var g0=1024,l0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),e1=($)=>$$($,"user"),u0=($)=>l0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function p0($){return m0("sha256").update(JSON.stringify($)).digest("hex")}class x2{runtime;maxSessions;#$=new Map;constructor($,Z=g0){this.runtime=$;this.maxSessions=Z}advance($,Z,J=this.runtime){let G=this.#$.get($),Y=Array.isArray(Z.input)?Z.input:[],Q=Y.filter(e1),F=Y.findLastIndex(e1),W=F<0?void 0:p0(Y[F]),N=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,B,H,T;if(N)B=Q.length>0,H=W??G?.fingerprint,T=G?.userCount===void 0?void 0:G.userCount+Q.length;else{H=W,T=Q.length;let C=F>=0&&F>Y.findLastIndex(u0),D=G!==void 0&&!G.completed&&G.fingerprint===H&&G.userCount===T;B=C&&!D}let R=B||!G?{turnID:(J?.uuid??A2)(),turnStartedAt:(J?.now??Date.now)()}:{turnID:G.turnID,turnStartedAt:G.turnStartedAt};return this.#Z($,{...R,completed:!1,fingerprint:H,userCount:T}),R}completed($){let Z=this.#$.get($);if(Z)this.#Z($,{...Z,completed:!0})}get($){return this.#$.get($)}forget($){this.#$.delete($)}#Z($,Z){this.#$.delete($),this.#$.set($,Z);while(this.#$.size>this.maxSessions){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function T1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var Z$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function c0(){let $=globalThis;return $[Z$]??=crypto.randomUUID(),$[Z$]}class D2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,J){this.runtime=$;this.store=J;this.installationID=Z??c0(),this.sessions=J?.sessions??new Map,this.frameTurns=J?.frameTurns??new x2}get($){let Z=this.runtime?.uuid??A2;if(this.store)return this.store.get($,Z);let J=this.sessions.get($);if(!J){let G=Z();J={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,J)}return J}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(p2(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var _1={version:J$,"user-agent":z$,originator:"codex_exec"};var d0=1024,i0=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,d2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),Y$=($)=>d2($)&&($.type==="message"||("role"in $))&&$.role==="user",X$=($)=>d2($)&&$.type==="configuration_update";class L1{http;#$=new Map;constructor($=new D2){this.http=$}apply($,Z,J){if(Z.kind!=="primary")return!1;let G=typeof $.model==="string"?$.model:"";if(!G$.has(G))return!1;if(i0.test(G))return!1;let Y=d2($.reasoning)?$.reasoning:void 0,Q=typeof Y?.effort==="string"?Y.effort:void 0;if(!Q)return!1;let F=this.#$.get(Z.sessionID);if(F===void 0)return this.#Z(Z.sessionID,Q),!1;if(Q===F)return!1;let W=Array.isArray($.input)?$.input:void 0;if(!W||W.length===0)return!1;let N=W.findLastIndex(Y$);if(N<0){if(J==="http")return!1;return $.reasoning={...Y,effort:F},!0}if($.reasoning={...Y,effort:F},!X$(W[N-1]))W.splice(N,0,{type:"configuration_update",reasoning:{effort:Q}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>d0){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function p2($){try{let Z=JSON.parse($);return d2(Z)?Z:void 0}catch{return}}async function j$($,Z,J,G,Y=J.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Q=await $.clone().text(),F=p2(Q);if(F)delete F.max_output_tokens;let W=new Headers($.headers),N=c2({rewriteLite:Q$,init:{body:F?JSON.stringify(F):$.body===null?void 0:Q},headers:W,metadata:Y.get(Z.sessionID),installationID:Y.installationID,runtime:Y.runtime,websocket:!1,responsesLite:G,applyEffort:(B)=>{J.apply(B,Z,"http")}});return new Request($,{headers:W,body:N.init?.body})}function B$($,Z,J,G){let Y=G.sessions.get($.sessionID),Q=G.frameTurns.get($.sessionID);if(!Y||!Q)return;let F=T1(Y,Q),W=new Headers({"content-type":"application/json"});for(let B of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let H=J.get(B);if(H!==null)W.set(B,H)}c2({init:{body:$.bodyText},headers:W,metadata:F,installationID:G.installationID,runtime:G.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let N=new URL(Z);if(N.protocol==="wss:")N.protocol="https:";if(N.protocol==="ws:")N.protocol="http:";return new Request(N,{method:"POST",headers:W,body:$.bodyText})}function a0($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let J=Z.findIndex((G,Y)=>JSON.stringify(G)!==JSON.stringify($[Y]));return J>=0&&X$(Z[J])&&Y$(Z[J+1])&&JSON.stringify(Z.slice(J+1))===JSON.stringify($.slice(J))}function V$($,Z,J){let G=p2($);if(G?.type!=="response.create")return;let Y=J.http.advanceFrame(Z.sessionID,G),Q=J.http.get(Z.sessionID);delete G.max_output_tokens;let F=c2({rewriteLite:()=>{},init:{body:JSON.stringify(G)},headers:new Headers,metadata:T1(Q,Y),installationID:J.http.installationID,runtime:J.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(N)=>{J.apply(N,Z,"ws")}}),W=p2(String(F.init?.body));if(!W)return;if(!a0(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 n0($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function P1($,Z){let J=new URL($);if(J.origin!=="https://api.openai.com"&&J.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(J.pathname))return $;let G=new URL(`${n0(Z)}/responses`);if(G.search=J.search,J.protocol==="ws:"||J.protocol==="wss:")G.protocol=G.protocol==="https:"?"wss:":"ws:";return G.href}import{resolve as M1}from"node:path";var W$=Symbol.for("@cortexkit/openai-auth/opencode2-rate-limits/v1"),U$=globalThis,C1=U$[W$]??new Map;U$[W$]=C1;function H$($){let Z=C1.get($);if(!Z)Z=new Map,C1.set($,Z);return Z}function N$($){return H$(JSON.stringify(["pool",M1($.configPath),M1($.statePath)]))}function F$($){return H$(JSON.stringify(["vault",M1($)]))}import{resolve as K$}from"node:path";var o0=1024;class i2{accounts=new Map;limit;constructor($=o0){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let J=this.accounts.keys().next().value;if(J===void 0)break;this.accounts.delete(J)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var T$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),_$=globalThis,E1=_$[T$]??new Map;_$[T$]=E1;function O1($){let Z=JSON.stringify([K$($.configPath),K$($.statePath)]),J=E1.get(Z);if(!J)J=new i2,E1.set(Z,J);return J}var F2="openai",s0=60000,A1=1,r0="request refused: no account with a usable credential",T2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function t0($){let Z=T2($)?$.counters:void 0,J=T2(Z)?Z.resetCredits:void 0,G=T2(J)?J.value:void 0;return typeof G==="number"&&Number.isFinite(G)?G:void 0}function n2($){try{return JSON.parse($)}catch{return}}function L$($){let Z=s2($);return Z?r2(Z):void 0}var e0=new Set(["usage_limit_reached","rate_limit_exceeded"]);function x1($,Z,J){return{reason:$.window,...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function $4($,Z){let J=o2($);if(J){let Q=typeof $.status==="number"?$.status:void 0;return x1(J,Z,Q)}if($.type!=="response.failed"||!T2($.response))return;let G=$.response.failed;if(T2(G)&&typeof G.rate_limit_reached_type==="string")return{reason:G.rate_limit_reached_type};let Y=$.response.error;if(T2(Y)){let Q=typeof Y.code==="string"?Y.code:typeof Y.type==="string"?Y.type:void 0;if(Q&&e0.has(Q))return{reason:Q}}return}function Z4($,Z){let J=n2($);if(!T2(J))return;let G=typeof J.type==="string"?J.type:void 0;if(G==="codex.rate_limits")return{quota:{snapshot:E$(J),complete:!0}};let Y=$4(J,Z);if(Y)return{limit:Y};if(G===void 0||G==="error")return;return l$(G)?void 0:{outputStarted:!0}}function J4($){let Z=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:M$($),complete:C$($)}}function z4($){let Z=$.get("retry-after");if(Z===null)return;let J=Number(Z);return Number.isFinite(J)&&J>=0?J*1000:void 0}function p$($){let Z=new WeakMap,J=new WeakSet,{source:G,pins:Y}=$,Q=$.now??Date.now,F=$.log,W=$.vault,N=new L1($.codex),B=new Map,H=new Map,T=(X)=>`${X.sessionID}\x00${X.kind}\x00${X.accountId}`,R=W?.paths?.rosterPath,C=R?F$(R):new Map,D=$.sessionAccounts??new i2,d=new y$,O=(X,K,M)=>{let _=M?[]:u$(G.peek().rows,X,K,W?.identities()??new Set),h=(W?.routes()??[]).filter((A)=>A.kind==="oauth"&&A$(y2(A.quota),X,K));return[..._.map((A)=>({id:A.id,...A.identity!==void 0?{identity:A.identity}:{},quota:A.quota,row:A})),...h.map((A)=>({id:A.id,...A.identity!==void 0?{identity:A.identity}:{},quota:A.quota}))]},f=(X,K,M)=>{let _=k$(X,K,M),h=X.map((x)=>({id:x.id,kind:"oauth",...P$(x.quota)?{quota:x.quota}:{}})),A=X.flatMap((x)=>x.row?[x.row]:[]),S=new Set(X.filter((x)=>!x.row).map((x)=>x.id)),v=G.rateLimitMarks(A);for(let x of S){let I=C.get(x);if(I===void 0)continue;if(I<=M)C.delete(x);else v.set(x,I)}return{rows:h,now:M,rateLimitMarks:v,refreshBackoff:G.refreshBackoffFor(A),killswitch:_,requestPull:(x)=>S.has(x)?W?.requestReading(x):G.requestReading(x)}},B2=(X,K,M,_,h)=>{let A=I$({...X,placement:D$(K),mainId:h});if(A.kind==="block"){F?.debug("pool admission refused the request",{reason:A.block.reason});return}let S=A.order.filter((v)=>!M.has(v));if(_!==void 0&&S.includes(_))return _;return S[0]},J2=(X,K,M,_,h,A,S,v)=>{let x=new Map(K.map((q)=>[q.id,q.quota])),I={requestBytes:A1,reservePercent:(q)=>R$(M,q===S$?void 0:q),resetCredits:(q)=>t0(x.get(q))},n=R1(X),u=(q,G2)=>t2(S,{sessionId:_,requestBytes:A1,validPinnedAccountIds:X.rows.map((g)=>g.id).filter((g)=>!n.excluded.has(g)),excludeAccountIds:q,quotaCheckedAtByAccount:Object.fromEntries(X.rows.map((g)=>[g.id,n.projections.get(g.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(K.map((g)=>[g.id,g.identity])),select:(g)=>v?{accountId:v,source:"mode-fallback",quotaCheckedAt:n.projections.get(v)?.checkedAt}:f$(X,I,new Set(q),g),persist:G2},(g,m)=>S.set(g,m)),o=[...h],s=u(o,A);if(!s)return;let e=s.accountId,p=v$(X,I,e);if(p.kind==="none")return;if(p.kind==="move"){let q=u([...o,e],A);if(q)return q.accountId;return p.reason==="killswitch"?void 0:e}if(p.kind==="detour")return u([...o,e],!1)?.accountId;return e},L2={providerID:F2,dropChoice(X){let K=T(X);H.get(K)?.drop(),H.delete(K),B.delete(K)},chooseAccount:async(X)=>{let K=await W?.authority(),M=await $.storage(),_=K!==void 0&&K!=="local",h=()=>{throw new Y2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:e2})};if(_)await $.awaitVaultRoster?.();else{if(!(await G.current()).active){if(await $.slotPlaceholderWithoutMain?.())h();F?.warn("the account pool does not serve requests yet; refusing the request",{kind:X.kind});return}await G.prepareTokens(G.peek().rows,M)}let A=Q(),S=O(M,A,_),v=w$(f(S.filter((m)=>m.id!==X.rerouteFrom?.accountId),M,A));if(v)await v,A=Q(),S=O(M,A,_);let x=new Map(S.map((m)=>[m.id,m])),I=f(S,M,A),n=new Set(X.rerouteFrom?[X.rerouteFrom.accountId]:[]),u=M?.routing?.mode??"main-first",o=X.kind==="primary",s=new Set,e,p,q,G2=!1,g=(m)=>{let $2=R1(I).projections.get(m)?.checkedAt,X2=x.get(m)?.identity;return Y.reserve(X.sessionID,{accountId:m,inputBytes:A1,...$2!==void 0?{quotaCheckedAt:$2}:{},...X2!==void 0?{wireIdentity:X2}:{}})};try{for(;;){let m=new Set([...n,...s]);q=void 0,e=void 0;let $2=u!=="sticky-balanced";if(u==="sticky-balanced"){let L=new Map(Y.placementSnapshot(X.sessionID)),b=L.get(X.sessionID);if($2=b===void 0,q=J2(I,S,M,X.sessionID,m,o&&s.size===0,L),q!==void 0&&L.get(X.sessionID)!==b)e=L.get(X.sessionID)}if(q??=B2(I,u,m,o?void 0:D.activeAccount(X.sessionID),_?u==="sticky-balanced"?null:b$(W?.routes()??[]):void 0),q===void 0||s.has(q)){if(n.size>0){let L=new Map(I.rateLimitMarks);for(let b of n)L.delete(b);I={...I,rateLimitMarks:L},n.clear();continue}if(I.rateLimitMarks.size>0){I={...I,rateLimitMarks:new Map};continue}q=void 0;break}if(o&&u==="sticky-balanced")p=g(q);if(!G2){G2=!0;let L=await h$({vaultMode:_,fresh:$2,sessionId:X.sessionID,request:{modelId:X.modelID,kind:X.kind,retry:X.phase==="retry"||X.rerouteFrom!==void 0},routes:W?.routes()??[],routing:I,eligibleIds:S.filter((b)=>!m.has(b.id)).map((b)=>b.id)});if(L&&L!==q){if(p)Y.rollback(p);if(p=void 0,u==="sticky-balanced"){let b=new Map(Y.placementSnapshot(X.sessionID));q=J2(I,S,M,X.sessionID,m,o,b,L)??q,e=b.get(X.sessionID)??e}else q=L;if(o&&u==="sticky-balanced")p=g(q)}}let X2=x.get(q)?.row;if(X2){if(G.usableToken(X2)!==void 0)break;F?.debug("pool row holds no usable token; choosing again",{accountId:q})}else{if(!W)break;let L=await W.authorize(q);if(L){B.set(T({...X,accountId:q}),L);break}F?.debug("the vault refused to serve an account; choosing again",{accountId:q})}if(p)Y.rollback(p);p=void 0,s.add(q)}if(q===void 0&&!_&&S.length===0&&await $.slotPlaceholderWithoutMain?.())h();if(q===void 0&&_&&W&&(S.length===0||s.size>0)){let m=s.size>0?"vault-refused":q$(W);throw F?.warn("vault mode: no vault account can serve; refusing the request",{cause:m}),new Y2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:x$(m,W.name)})}if(q!==void 0){let m=q,$2=p,X2=e,L=()=>{if($2)Y.finish($2,X2);if(o)D.record(X.sessionID,m),$.onRoute?.(X.sessionID,m,u)};if(X.phase==="retry")H.set(T({...X,accountId:q}),{commit:L,drop:()=>{if($2)Y.rollback($2)}}),p=void 0;else L();let b=F?.info;d.served(I,q,F&&b?{info:(j2,b2)=>b.call(F,j2,b2)}:void 0)}return F?.debug("pool account chosen",{kind:X.kind,accountId:q,mode:u,...X.rerouteFrom?{rerouteFrom:X.rerouteFrom.accountId}:{}}),q}finally{if(p)Y.rollback(p)}},accountHeaders:async(X)=>{let{accountId:K}=X,M=T(X),_=H.get(M);H.delete(M);let h=()=>{_?.commit()};try{let A=()=>new Y2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:r0}),S=W&&await W.authority()!=="local"?void 0:G.peek().rows.find((I)=>I.id===K);if(!S&&W){let I=T(X),n=B.get(I)??await W.authorize(K);if(B.delete(I),!n)throw F?.warn("the vault refused to serve an account; refusing the request",{accountId:K}),A();return h(),{headers:{..._1,"session-id":X.sessionID,authorization:`Bearer ${n.accessToken}`,"chatgpt-account-id":n.accountIdentity??L$(n.accessToken)??null},attempt:{kind:"vault",routeId:K,receipt:n}}}let v=S?G.usableToken(S):void 0;if(!S||!v)throw F?.warn("pool row holds no usable token; refusing the request",{accountId:K}),A();let x=S.identity??L$(v);return h(),{headers:{..._1,"session-id":X.sessionID,authorization:`Bearer ${v}`,"chatgpt-account-id":x??null},attempt:{kind:"pool",token:v,credentialEpoch:S.credentialEpoch}}}finally{_?.drop()}},async rewriteRequest({request:X,sessionID:K,kind:M}){let _=$.codexEndpoint?P1(X.url,$.codexEndpoint()):X.url,h=_===X.url?X:new Request(_,X);return await j$(h,{sessionID:K,kind:M},N,$.responsesLite?.()??!1)??h},rewriteHandshakeURL:({url:X})=>$.codexEndpoint?P1(X,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:X,sessionID:K,kind:M})=>V$(X,{sessionID:K,kind:M},N),quotaFromHeaders:(X,K,M)=>{if(M.data?.kind==="vault"&&w2()&&K>=200&&K<300)Z.set(M,{status:K,headers:X});return J4(X)},async limitFromResponse({status:X,headers:K,body:M,attempt:_}){if(X<400)return;let h=n2(await M().catch(()=>"")),A=o2({...T2(h)?h:{},status:X});if(_.data?.kind==="vault"&&w2())a2(_.sessionID,_.data.receipt,{status:X,headers:K,body:h,limit:A,quota:W?.routes().find((I)=>I.id===_.accountId)?.quota,now:Q()});if(!A)return;let S=Q(),v=x1(A,S,X);if(v.retryAfterMs!==void 0)return v;let x=z4(K);return x===void 0?v:{...v,retryAfterMs:x}},inspectEvent:({data:X,transport:K,attempt:M})=>{if(M.data?.kind==="vault"&&w2()&&(g$(X)||K==="ws"&&X.includes('"response.completed"'))){let _=n2(X);if(m$(_))J.add(M);if(K==="ws"&&T2(_)&&_.type==="response.completed")a2(M.sessionID,M.data.receipt,{status:200,headers:new Headers,failed:J.has(M)})}return Z4(X,Q())},limitFromError(X){let K=n2(X.message),M=o2({...T2(K)?K:{},...X.status!==void 0?{status:X.status}:{}})??(X.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return M?x1(M,Q(),X.status):void 0},async onAttemptEnd(X,K){let M=X.data,_=M?.kind==="vault"&&w2()?Z.get(X):void 0;if(Z.delete(X),M?.kind==="vault"&&_&&!K.error&&!K.limit)a2(X.sessionID,M.receipt,{..._,failed:J.has(X)});if(M?.kind!=="vault"||K.status!==401)return;F?.warn("a vault account answered 401; reporting it to the vault",{accountId:X.accountId}),await W?.reportFailure(M.receipt,401)}},Z2=(X,K,M)=>{let _=M.data;if(_?.kind==="vault"){W?.recordSnapshot(X,K.snapshot,K.complete,_.receipt);return}if(_?.kind!=="pool")return;if(G.peek().rows.find((A)=>A.id===X)?.credentialEpoch!==_.credentialEpoch){F?.debug("quota reading dropped: the row holds another credential",{accountId:X});return}G.recordSnapshot(X,K.snapshot,_.token,K.complete)},i=(X,K,M)=>{let _=Q(),h=M.data?.kind==="vault",A=h?W?.routes().find((x)=>x.id===X)?.quota:G.peek().rows.find((x)=>x.id===X)?.quota,S=O$(y2(A),K.reason,_,s0,K.retryAfterMs!==void 0?_+K.retryAfterMs:void 0);if(!h){G.markRateLimited(X,S);return}let v=C.get(X);if(v===void 0||v<S)C.set(X,S)};return{adapter:L2,attach(X){X.on("quota",(K)=>Z2(K.accountId,K.quota,K.handle)),X.on("limit",(K)=>{i(K.accountId,K.limit,K.handle),F?.debug("pool row refused the request",{accountId:K.accountId,via:K.via,reason:K.limit.reason,outputStarted:K.outputStarted})})},forgetSession(X){Y.forget(X),D.forget(X),N.forget(X)},activeAccount:(X)=>D.activeAccount(X)}}import{resolve as o$}from"node:path";import{Buffer as G4}from"node:buffer";import{resolve as c$}from"node:path";function I2($){return G4.byteLength(JSON.stringify($))}function Q4($){return $.reduce((Z,J)=>Z+I2(J),0)}function q1($,Z){return 2+$+Math.max(0,Z-1)}function Y4($){let{head:Z,pending:J}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+q1(Z.inputBytes,Z.input.length)+1:0)+(J?20+q1(J.inputBytes,J.input.length)+10+q1(J.outputBytes,J.output.length)+(J.responseID===void 0?0:14+J.responseIDBytes)+1:0)}function d$($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class i${enabled;caps=$1;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$)this.entries.clear(),this.bytes=0}send($,Z){if(!this.enabled)return;let J=d$(Z);if(J?.type!=="response.create")return;if(!Array.isArray(J.input)){this.forget($);return}let G=J.previous_response_id,Y=this.entries.get($),Q=Y?.head;if(G&&G!==Q?.responseID){this.forget($);return}let{type:F,previous_response_id:W,input:N,...B}=J;this.keep($,{fields:G&&Y?Y.fields:B,fieldsBytes:G&&Y?Y.fieldsBytes:I2(B),...G&&Q?{head:Q}:{},pending:{input:N,inputBytes:Q4(N),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,J){if(!this.enabled||!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed"))return;let G=this.entries.get($);if(!G?.pending)return;let Y=d$(Z);if(!Y)return;let Q=G.pending,F=Y.response;if(Y.type==="response.created"&&typeof F?.id==="string")Q.responseID=F.id,Q.responseIDBytes=I2(F.id),this.keep($,G);else if(Y.type==="response.output_item.done"&&Y.item){if(typeof Y.response_id==="string"&&Q.responseID!==void 0&&Y.response_id!==Q.responseID)return;Q.output.push(Y.item),Q.outputBytes+=I2(Y.item),this.keep($,G)}else if(Y.type==="response.completed"&&typeof F?.id==="string"){if(F.id===G.head?.responseID||Q.responseID!==void 0&&F.id!==Q.responseID)return;let W={responseID:F.id,responseIDBytes:Q.responseID===F.id?Q.responseIDBytes:I2(F.id),input:[...G.head?.input??[],...Q.input,...Q.output],inputBytes:(G.head?.inputBytes??0)+Q.inputBytes+Q.outputBytes},N={...G,head:W,pending:void 0};if(!this.keep($,N))return;J?.({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 J=Y4(Z);if(this.forget($),J>this.caps.maxBytes)return!1;Z.bytes=J,this.entries.set($,Z),this.bytes+=J;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let G=this.entries.keys().next().value;if(G===void 0)break;this.forget(G)}return this.entries.has($)}}var a$=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),n$=globalThis,S1=n$[a$]??new Map;n$[a$]=S1;function Z1($){let Z=JSON.stringify([c$($.configPath),c$($.statePath)]),J=S1.get(Z);if(!J)J=new i$,S1.set(Z,J);return J}var X4=5000,j4=["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"],B4=["x-opencode-parent-session-id","x-parent-session-id"];function e$($){let Z=s$($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:r$($?{...$,cachekeep:Z}:$)}}var $Z=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),ZZ=globalThis,f2=ZZ[$Z]??new Map;ZZ[$Z]=f2;function V4($,Z){let J=[],G=()=>J.at(-1)?.location,Y=()=>{let N=G();if(!N)throw Error("no location holds keep-warm");return N},Q=(N,B)=>{W.remove(N),G()?.log?.debug(`cachekeep dropped target (${B})`,{sessionKey:N})},F=async(N)=>{if(N.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let B=N.accountId??"main",H=Y(),T=await H.source.accessFor(B,await H.storage());if(!T)throw Error(`pool row ${B} has no usable token`);return{token:T.token,identity:T.row.identity}},W=t$({...$1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(N,B)=>Y().fetch(N,B),logger:{debug:(N,B)=>G()?.log?.debug(N,B),warn:(N,B)=>G()?.log?.warn(N,B)},getWindow:()=>G()?.settings().window,getSustain:()=>G()?.settings().sustain===!0,resolveLocal:F,vault:{owns:(N)=>G()?.vault.owns(N)===!0,authority:()=>Y().vault.authority(),send:async(N,B,H)=>{let T=Y();if(await T.vault.authority()!=="vault")return;return T.vault.send(N,B,H)}},activeAccount:(N)=>{if(N===void 0)throw Error("target has no session");let B=G(),H=B?.settings();if(!B||!H?.enabled){Q(N,"keep-warm is off");return}if(!H.subagents&&W.status().targets.some((R)=>R.sessionKey===N&&R.isSubagent)){Q(N,"subagent warming is off");return}let T=B.accounts.activeAccount(N);if(T===void 0){Q(N,"no account recorded for the session");return}return T},verifyCredential:({target:N,mode:B,identity:H})=>{if(N.meta.credentialMode!==B)throw Error(`a target captured in ${N.meta.credentialMode??"an unknown"} mode is not warmed with a ${B} credential`);if(H!==N.meta.chatgptAccountId)throw Q(N.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:W,settings:Z,holders:J,joinTimeoutMs:$.joinTimeoutMs??X4}}function W4($){try{let Z=JSON.parse($),J=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(J?.role!=="user")return!1;return(typeof J.content==="string"?J.content:Array.isArray(J.content)?J.content.map((Y)=>typeof Y?.text==="string"?Y.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function U4($){let Z={};for(let J of j4){let G=$.get(J);if(G)Z[J]=G}return Z}function JZ($,Z,J){let G=JSON.stringify([o$($.configPath),o$($.statePath)]),Y=f2.get(G);if(!Y)Y=V4(J,Z.settings()),f2.set(G,Y);let Q=Y,F=Z1($);F.setEnabled(Q.settings.enabled);let W={location:{...Z,settings:()=>Q.settings}};Q.holders.push(W);let N=!1,B=async(H)=>{try{let T=W.location.settings();if(N||!T.enabled)return;if(H.kind!=="primary"){if(H.kind==="generate"&&W4(await H.request.clone().text())){if(N)return;Q.manager.remove(H.sessionID)}return}let R=H.attempt.data,C=R?.kind==="pool"?"local":R?.kind==="vault"?"vault":void 0;if(!C)return;let D=H.request.headers,d=B4.some((B2)=>D.has(B2))||Z.parentOf!==void 0&&await Z.parentOf(H.sessionID)!==void 0;if(d&&!T.subagents)return;let O=await H.request.clone().text();if(N)return;let f=D.get("chatgpt-account-id")??void 0;Q.manager.track({sessionKey:H.sessionID,bodyText:O,accountId:H.attempt.accountId,isSubagent:d,meta:{replayHeaders:U4(D),...f?{chatgptAccountId:f}:{},routingSessionId:H.sessionID,url:H.request.url,credentialMode:C}})}catch(T){Z.log?.warn("cachekeep capture failed",{error:T instanceof Error?T.message:String(T)})}};return{manager:Q.manager,configure:(H)=>{Object.assign(Q.settings,H),F.setEnabled(Q.settings.enabled)},capture:B,forget:(H)=>Q.manager.remove(H),async release(){if(N)return;N=!0;let H=Q.holders.indexOf(W);if(H>=0)Q.holders.splice(H,1);if(Q.holders.length>0)return;if(f2.get(G)===Q)f2.delete(G);Q.manager.stop();let T;try{await Promise.race([Q.manager.tick().catch(()=>{}),new Promise((R)=>{T=setTimeout(R,Q.joinTimeoutMs),T.unref?.()})])}finally{clearTimeout(T)}}}}import{mkdirSync as H4}from"node:fs";import{dirname as N4,resolve as F4}from"node:path";function K4(){return zZ("opencode2")}var T4=2000;class jZ{path;options;sessions;frameTurns=new x2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Q=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=YZ($,Z.uuid??A2)}get($,Z=A2){let J=this.sessions.get($);if(!J){let G=Z();J={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,J),this.#Z.delete($),this.#z.delete($),this.#$.add($),this.#Y()}return J}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#z.add($);this.#Y()}#Y(){if(this.#J)return;this.#J=setTimeout(()=>{this.#J=void 0,this.save()},this.options.saveDelayMs??T4),this.#J.unref?.()}save(){if(clearTimeout(this.#J),this.#J=void 0,!this.#Q)this.#Q=!0,this.#G=this.#G.then(()=>{return this.#Q=!1,this.#j()});return this.#G}settled(){return this.#J?this.save():this.#G}#X(){if(this.#z.size===0)return;let $;try{$=b1(this.path)}catch{$=new Map}for(let Z of this.#z)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#z.clear()}async#j(){if(this.#X(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((G)=>{let Y=this.sessions.get(G);return Y?[[G,Y]]:[]}),Z=[...this.#Z],J=null;try{if(H4(N4(this.path),{recursive:!0}),J=await this.#B(),!J)return;let G;try{G=b1(this.path)}catch{G=new Map}await this.options.afterRead?.();let Y=!1;for(let Q of Z)if(G.delete(Q))Y=!0;for(let[Q,F]of $){if(G.get(Q)===F.threadID)continue;G.set(Q,F.threadID),Y=!0}if(Y)XZ(this.path,G)}catch{return}finally{await J?.release().catch(()=>{})}for(let[G,Y]of $)if(this.sessions.get(G)===Y)this.#$.delete(G);for(let G of Z)if(!this.sessions.has(G))this.#Z.delete(G)}#B(){return QZ(this.path,this.options.lockWaitMs??GZ)}}var BZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),VZ=globalThis,J1=VZ[BZ]??new Map;VZ[BZ]=J1;function _4($){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 WZ($=K4()){let Z=F4($),J=J1,G=J1.get(Z),Y=J1;if(G!==void 0&&!_4(G))J.compatible??=new Map,Y=J.compatible;let Q=Y.get(Z);if(!Q)Q=new jZ(Z),Y.set(Z,Q);let F=Q;return F.frameTurns??=new x2,Q}var k1=Symbol.for("cortexkit.openai-auth.v2.commands"),L4=_2("v2-command");function z1($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.closed instanceof AbortController&&typeof Z.menu?.open==="function"&&typeof Z.menu?.apply==="function"&&typeof Z.session?.get==="function"&&(Z.registration===void 0||Z.registration!==null&&typeof Z.registration.dispose==="function")}function D1($){L4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function P4(){let $=globalThis;return $[k1]??={locations:new Map},$[k1].locations??=new Map,$[k1]}async function _Z($,Z){let J=P4(),G=$.location.directory,Y={menu:Z,session:$.session,closed:new AbortController},Q=await HZ(G),F=await UZ(KZ,Q.dir,()=>TZ({...Q,drain:FZ,apply:(T)=>{let R=J.locations.get(G);if(!z1(R))throw Error("The OpenAI menu location was closed");return R.menu.apply(T)}})),W=J.locations.get(G);if(J.locations.set(G,Y),z1(W))W.closed.abort(),await W.registration?.dispose();let N={name:"openai",description:"OpenAI account menu",async execute(T){let R=[...J.locations.values()].find(z1)?.session;if(!R)return D1("no live location");let C=await R.get({sessionID:T.sessionID}),D=J.locations.get(C.location.directory);if(!z1(D))return D1("location closed");let d=await NZ(T.sessionID,D.closed.signal);if(!d||J.locations.get(C.location.directory)!==D){if(!d&&!D.closed.signal.aborted)w1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},T.sessionID);return D1(D.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let O=await D.menu.open(T.sessionID);w1(O,T.sessionID)}};J.command??=N,J.command.execute=N.execute;let B=J.command;try{Y.registration=await $.command.transform((T)=>{T.add(B)})}catch(T){if(Y.closed.abort(),J.locations.get(G)===Y)J.locations.delete(G);throw await F.release(),T}let H=!1;return async()=>{if(H)return;if(H=!0,Y.closed.abort(),J.locations.get(G)===Y)J.locations.delete(G);await F.release(),await Y.registration?.dispose()}}var M4="openai-auth-pool-browser",C4="openai-auth-pool-headless",E4="openai-auth-vault",O4="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Run /openai → Vault → Connect and approve the request before trying again.";async function v2($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function OZ($){return{method:{id:E4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await LZ($.paths,$.name)!=="vault")throw Error(O4)}}}function AZ($){let Z=(J,G,Y)=>({method:{id:J,type:"oauth",label:G},async authorize(){if($.vault)await v2($.vault);let Q=await $.beginLogin({version:$.version,headless:Y});return{url:Q.url,instructions:Q.instructions,mode:"auto",callback:Q.completion}}});return[Z(M4,"ChatGPT (openai-auth pool, browser)",!1),Z(C4,"ChatGPT (openai-auth pool, headless)",!0)]}function y1($){let Z=(J)=>typeof J==="string"?J:"";return k2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===CZ||PZ($)}function A4($){if($.accountId)return $.accountId;let Z=$.access?s2($.access):void 0;return Z?r2(Z):void 0}async function RZ($,Z,J,G={}){if(G.vault)await v2(G.vault);if(y1(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Y=MZ($,{rowLocks:(C)=>EZ(Z,C)}),Q=await Y.read();if(Q.status!=="ready")throw Error(`the account pool cannot be read (${Q.status}); the login was not stored`);let F={type:"oauth",refresh:J.refresh,...J.access!==void 0?{access:J.access}:{},...J.expires!==void 0?{expires:J.expires}:{}},W=A4(J);if(G.vault)await v2(G.vault);let N=W!==void 0?{identity:W}:{};if(G.origin==="import"){let C=Q.rows.find((D)=>W!==void 0&&D.identity===W||D.credential?.type==="oauth"&&D.credential.refresh===J.refresh);if(C)return{id:C.id,operation:"kept"}}let B=Q.rows.filter((C)=>C.type==="oauth"&&!C.invalid),H=W?B.find((C)=>C.identity===W):void 0,T=Q.rows.find((C)=>C.id===G1);if(H)return{id:(await Y.replace(H.id,F,N)).id,operation:"replaced"};if(!T){let C=await Y.add({id:G1,credential:F,...N,...J.label!==void 0?{label:J.label}:{}});return{id:C.id,operation:C.outcome==="added-disabled"?"added-disabled":"added"}}if(!T.invalid&&!T.credential)return{id:(await Y.replace(G1,F,N)).id,operation:"replaced"};let R=await Y.add({id:J.id,credential:F,...N,...J.label!==void 0?{label:J.label}:{}});return{id:R.id,operation:R.outcome==="added-disabled"?"added-disabled":R.outcome==="rotated"?"replaced":"added"}}function R4($){let Z=$.itemId!==void 0;switch($.sectionId){case"accounts":return Z?["enable","disable","remove","move"].includes($.actionId):$.actionId==="add";case"routing":return!Z&&["order","mode"].includes($.actionId);case"quota":return $.actionId==="check";case"limits":return Z?$.actionId==="floors":$.actionId==="killswitch";case"session":return!Z&&$.actionId==="clear-pin";case"vault":return Z?["enable","disable"].includes($.actionId):["connect","disconnect"].includes($.actionId);case"diagnostics":return!Z&&["logging","dump"].includes($.actionId);case"cache":return!Z&&["enabled","subagents","sustain","window"].includes($.actionId);case"reset":return Z&&["preview","spend","retry"].includes($.actionId);default:return!1}}function SZ($){let Z={...$,allowAction:R4,unavailableSections:[]};return{open:(J)=>xZ(Z,J),apply:(J)=>{let G=J!==null&&typeof J==="object"?J:{},Y=G.values&&typeof G.values==="object"&&!Array.isArray(G.values)?Object.fromEntries(Object.entries(G.values).filter(([,Q])=>Q===null||["string","number","boolean"].includes(typeof Q))):void 0;return qZ(Z,{command:"openai",sectionId:typeof G.sectionId==="string"?G.sectionId:"",actionId:typeof G.actionId==="string"?G.actionId:"",...Y?{values:Y}:{},...G.confirmed===!0?{confirmed:!0}:{},...typeof G.itemId==="string"?{itemId:G.itemId}:{},...typeof G.sessionId==="string"?{sessionId:G.sessionId}:{}})}}}function x4($,Z){if(!bZ($.modelID??$.id)){$.enabled=!1;return}let J=kZ($.id);if(J)$.limit={...J};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((G)=>[G.id,G])).values()]}function wZ($){return $.model.transform((Z)=>{let J=Z.list(F2);for(let G of J){let Y=DZ(String(G.id)),Q=Y?J.find((F)=>String(F.id)===Y):void 0;Z.update(F2,String(G.id),(F)=>x4(F,Q?.variants?.map((W)=>({...W,id:String(W.id)}))))}})}class I1{log;pending=new Map;requests=new Map;writing=new Set;constructor($){this.log=$}async safely($){let Z=(async()=>{try{await $()}catch{this.log.warn("request dump failed")}})();this.writing.add(Z);try{await Z}finally{this.writing.delete(Z)}}async captureHttp($,Z){if(!yZ())return;await this.safely(async()=>{let J={sessionID:Z.sessionID,accountId:Z.accountId,transport:"http",phase:"http",url:$.url,method:$.method,headers:new Headers($.headers),bodyText:await $.clone().text()};if(this.pending.set($,{attemptId:Z.attemptId,input:J}),this.requests.set(Z.attemptId,$),this.pending.size>512){let G=this.pending.keys().next().value;if(G)this.take(G)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let J=this.take($);if(J)await this.safely(()=>Q1({...J,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let J=this.requests.get($.attemptId),G=J&&this.take(J);if(!G)return;let{reason:Y,message:Q}=Z.error,F=Q?`${Y}: ${Q}`:Y;await this.safely(()=>Q1({...G,error:Y1(F,J?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>Q1({sessionID:Z.sessionID,accountId:Z.accountId,transport:"websocket",phase:"observed",bodyText:$}))}clear(){this.pending.clear(),this.requests.clear()}async settle(){await Promise.all(this.writing)}}class f1{counts=new Map;record($,Z){let J=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof J==="number"&&Number.isFinite(J)?J:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function mZ($){return async(Z)=>{let J=Z.credential;if(J.type!=="oauth"||!J.access)throw Error("the row holds no access token to poll with");let G=await IZ({accessToken:J.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,G),fZ(G,$.now(),!0)}}function gZ($){let{source:Z,counts:J,now:G}=$,Y=async(B)=>{let H=await Z.rowAccess(B,await $.storage());if(!H?.row)throw new vZ("unknown_account",`${B==="main"?"Main":"Fallback"} account ${B} was not found.`);return hZ(B,H)},Q=async(B)=>{if($.authority&&await $.authority()!=="local")return{account:B,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[H]=await Z.pollRows(await $.storage(),{ids:[B]});if(!H)return{account:B,ok:!1,error:"targeted quota refresh returned no result"};return{account:H.id,ok:H.ok,...H.error!==void 0?{error:H.error}:{}}},F=(B)=>Z.peek().rows.find((H)=>H.id===B),W=(B)=>{let H=F(B);if(!H)return null;let T=y2(H.quota)??{},R=J.applicable(H),C=Math.max(0,...[T.primary?.checkedAt,T.secondary?.checkedAt].filter((D)=>typeof D==="number"));return{quota:{...T,...R!==void 0?{resetCreditsApplicable:R}:{}},checkedAt:C,refreshAfter:C,...H.identity!==void 0?{accountId:H.identity}:{}}};return{resolveResetTarget:Y,refreshResetTargetQuota:Q,quotaManager:{isRateLimited:(B)=>{let H=F(B);if(!H)return!1;let T=Z.rateLimitMarks([H]).get(H.id);return T!==void 0&&T>G()},getMain:()=>W("main"),getFallback:(B)=>W(B)}}}import{resolve as lZ}from"node:path";var q4=1024;class v1{pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=q4){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.reservations.delete($),this.pins.delete($);for(let Z of this.listeners)Z($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}snapshot(){return new Map(this.pins)}placementSnapshot($){let Z=new Map(this.pins);for(let J of this.reservations.values())if(J.sessionId!==$)Z.set(J.sessionId,J.pin);return Z}reserve($,Z){let J={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,J),J}rollback($){if(this.reservations.get($.sessionId)===$)this.reservations.delete($.sessionId)}finish($,Z){if(this.reservations.get($.sessionId)!==$)return;if(this.rollback($),Z&&this.pins.get($.sessionId)===$.previous)this.set($.sessionId,Z)}get size(){return this.pins.size}set($,Z){this.reservations.delete($),this.pins.delete($),this.pins.set($,Z);for(let J of this.listeners)J($,Z);while(this.pins.size>this.limit){let J=this.pins.keys().next().value;if(J===void 0)break;this.forget(J)}}place($){return t2(this.placementSnapshot($.sessionId),$,(Z,J)=>this.set(Z,J))}}var uZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),pZ=globalThis,X1=pZ[uZ]??new Map;pZ[uZ]=X1;function S4($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.get==="function"&&typeof Z.forget==="function"&&typeof Z.subscribe==="function"&&typeof Z.snapshot==="function"&&typeof Z.place==="function"&&typeof Z.placementSnapshot==="function"&&typeof Z.reserve==="function"&&typeof Z.rollback==="function"&&typeof Z.finish==="function"}function cZ($){let Z=JSON.stringify([lZ($.configPath),lZ($.statePath)]),J=X1,G=X1.get(Z);if(G!==void 0&&!S4(G)){let Q=X1;Q.compatibleV1??=new Map,J=Q.compatibleV1}let Y=J.get(Z);if(!Y)Y=new v1,J.set(Z,Y);return Y}import{statSync as b4}from"node:fs";import{resolve as k4}from"node:path";function eZ($){return $.map((Z)=>{try{let J=b4(Z);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}function h1($){return eZ([$.vault.paths.tokenPath,$.vault.paths.statePath])}function dZ($){return eZ([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+h1($)}class $0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;protocol=J0;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:dZ($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),J=this.subscriptions.get($.pins);if(!J){let G=new Set;J={producers:G,stop:$.pins.subscribe((Y,Q)=>{let F=G.values().next().value;if(F)this.publish(F,{sessionId:Y,pin:Q,accountId:Q?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,J)}return J.producers.add($),this.timer??=setInterval(()=>{for(let G of this.producers){let Y={stamp:dZ(G),roster:G.vault.snapshot()},Q=this.observations.get(G);if(Y.stamp!==Q?.stamp||Y.roster!==Q?.roster)this.observations.set(G,Y),this.publish(G)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),J.producers.delete($),!J.producers.size)J.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;await($.write??Z0)(this.file,$,Z,()=>this.producers.has($))}).catch(()=>{_2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var Z0=async($,Z,J,G)=>{let Q=await Z.vault.authority()!=="local",F=h1(Z),W=()=>G()&&Z.vault.enrolled()===Q&&h1(Z)===F,N=await(Q?m2(Z.paths):q2(Z.paths)),B=Q?rZ(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((R)=>R.id)),N,Date.now()):tZ((await Z.source.sidebarView()).rows,N,Date.now()),H={canWrite:W,vaultMode:Q};if(await aZ(B,$,H),!W()||!J)return;let T=B.vaultAccounts??B.fallbacks;if(J.accountId===void 0){await oZ(J.sessionId,T,$,H);return}if(J.pin){let R=Date.now();await sZ({sessionId:J.sessionId,assignment:{accountId:J.pin.accountId,wireAccountId:J.pin.wireIdentity,inputBytes:J.pin.inputBytes??0,quotaCheckedAt:J.pin.quotaCheckedAt,assignedAt:R,lastSeenAt:R},validPinnedAccountIds:[...Q?[]:["main"],...T.filter((C)=>C.enabled).map((C)=>C.id)]},$,H)}await nZ({sessionId:J.sessionId,activeId:J.accountId,route:J.route??B.route,updatedAt:Date.now()},T,$,H)},J0=2,z0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),G0=globalThis,h2=G0[z0]??new Map;G0[z0]=h2;function Q0($,Z=iZ(),J=2000){let G=k4(Z),Y=h2.get(G);if(Y?.protocol!==J0)Y=new $0(G,J),h2.set(G,Y);let Q=Y;$={...$,write:$.write??Z0};let F=Q.add($),W=!1;for(let[N,B]of $.pins.snapshot())Q.publish($,{sessionId:N,pin:B,accountId:B.accountId,route:"sticky-balanced"});return{publish:()=>Q.publish($),route:(N,B,H)=>{Q.publish($,{sessionId:N,accountId:B,route:H})},async release(){if(W)return;if(W=!0,F(),await Q.settled(),Q.empty&&h2.get(G)===Q)h2.delete(G)}}}var V1="cortexkit-openai-auth",y4=5000;async function Y0($,Z,J,G=new D2,Y,Q,F){let W=new I1(J),N=new D4,B=new Map,H=new Map,T=(O)=>{H.delete(O);for(let f of B.keys())if(f.startsWith(`${O}:`))B.delete(f)},R=(O)=>{F?.(O.sessionID),Q?.send(O.sessionID,O.frame)},D=await K1({session:{hook:(O,f,B2)=>$.session.hook(O,async(J2)=>{let w=O==="http.request"?J2:void 0,l=O==="experimental.ws.handshake"?J2:void 0,Z2=(w?w.request.headers:l?new Headers(l.headers):void 0)?.get("authorization")===`Bearer ${K2(Z.providerID)}`,i={};if(l)B.delete(`${l.sessionID}:${l.kind}`);try{await N.run(i,()=>f(J2))}catch(X){if(Z2&&!(X instanceof Y2))throw U0(X);throw X}if(w&&Z2&&i.attempt){let X=w.request.headers.get("thread-id");if(X)w.request.headers.set("session-id",X)}if(w&&Z2&&i.attempt)await W.captureHttp(w.request,i.attempt);if(w&&Z2&&i.attempt)await Y?.({sessionID:w.sessionID,kind:w.kind,request:w.request,attempt:i.attempt});if(l&&Z2&&i.attempt)l.headers["session-id"]=G.get(l.sessionID).threadID;if(O==="experimental.ws.send"){let X=J2,K=B.get(`${X.sessionID}:${X.kind}`);if(K)await W.frame(X.frame,K.attempt);if(K&&X.kind==="primary")R(X)}if(w||l){let X=w??l;if(!X)return;let M=(w?w.request.headers:new Headers(X.headers)).get("authorization")?.replace(/^Bearer /,"");if(Z2&&M)H.set(X.sessionID,M);else H.delete(X.sessionID);if(l){let _=`${l.sessionID}:${l.kind}`;if(Z2&&M&&i.attempt)B.set(_,{bearer:M,attempt:i.attempt,url:l.url,headers:new Headers(Object.entries(l.headers).filter(([h])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(h.toLowerCase())))});else B.delete(_)}if(H.size>512){let _=H.keys().next().value;if(_)H.delete(_)}if(B.size>512){let _=B.keys().next().value;if(_)B.delete(_)}}else if(O==="experimental.ws.receive"){let X=J2,K=B.get(`${X.sessionID}:${X.kind}`);if(K){if(G.frameReceived(X.sessionID,X.frame),X.kind==="primary"){let M;if(Q?.receive(X.sessionID,X.frame,(_)=>{M=_}),M)try{let _=B$(M,K.url,K.headers,G);if(_)await Y?.({sessionID:X.sessionID,kind:"primary",request:_,attempt:K.attempt})}catch(_){J.warn("cachekeep WebSocket capture failed",{error:_ instanceof Error?_.message:String(_)})}}X.frame=H0(X.frame,K.bearer)}}else if(O==="retry"){let X=J2,K=H.get(X.sessionID);if(K)Object.assign(X.error,{message:Y1(X.error.message,K)})}},B2)},event:{subscribe:(O)=>async function*(){for await(let f of $.event.subscribe(O)){if(f.type==="session.deleted")T(f.data.sessionID);yield f}}()}},{...Z,rewriteRequest:async(O)=>{let f=N.getStore();if(f)f.attempt=O.attempt;return Z.rewriteRequest?.(O)},rewriteHandshakeURL:(O)=>{let f=N.getStore();if(f)f.attempt=O.attempt;return Z.rewriteHandshakeURL?.(O)},onAttemptEnd:async(O,f)=>{await W.end(O,f),await Z.onAttemptEnd?.(O,f)},rewriteResponse:async(O)=>{await W.response(O.request,O.response.status);let f=await Z.rewriteResponse?.(O)??O.response;return N0(f,O.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(O)=>{let f=O.get("authorization");return f?.startsWith("Bearer ")?f.slice(7):void 0}},logger:{warn:(O,f)=>J.warn(O,{data:f})}}),d=D.dispose;return{...D,dispose:async()=>{H.clear(),B.clear(),await d(),await W.settle(),W.clear()}}}function l1($={}){return{id:V1,setup:(Z)=>I4(Z,$)}}async function I4($,Z={}){let g=[];try{let J=_2("opencode2");let G=_2("quota");let Y=Z.version??K0;await q0({version:Y,...Z.runtimeLayout});let Q=Z.paths??(()=>_0(F0()));let F=await m2(Q());let W=F?.logging?.level;if(W&&typeof W==="string")j0(W);let N=Z.fetch??fetch;let B=Z.now??Date.now;let H=Z.poolMigration??b0;if(!H&&!S2(Q().configPath)){J.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let L=(j2)=>{throw new Y2({kind:"no-account",providerID:F2,sessionID:j2.sessionID,requestKind:j2.kind,message:e2})},b=await Y0($,{providerID:F2,chooseAccount:L,accountHeaders:L},J);return()=>b.dispose()}let T=Z.vault?.firstRosterWaitMs??E0;let R=S0({host:"opencode",stateDir:Z.vault?.stateDir??W0(Q().statePath),reservedRouteIds:()=>w.peek().rows.map((L)=>L.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>N},Q());let C=R.vault;let D=async()=>await C.authority()==="local"?q2(Q()):m2(Q());let d=!1;let O=!1;const f=j1(g,{[Symbol.dispose](){if(!d)R.release()}},0);await C.authority();let B2=R.firstRoster;let J2=new f1;let w=new O0({paths:Q,rateLimitMarks:N$(Q()),refreshProvider:async(L)=>{let b=await V0({refreshToken:L.refresh,fetchImpl:N,now:B}),j2=B0({id_token:"",access_token:b.access,refresh_token:b.refresh});return{...b,...j2?{identity:j2}:{}}},pullQuota:mZ({fetchImpl:N,now:B,counts:J2,logger:G}),now:B,vaultIdentities:()=>C.identities(),vaultMode:()=>C.enrolled(),vaultAuthority:()=>C.authority(),vaultFirstRoster:B2,vaultFirstRosterBackgroundWaitMs:T,log:_2("pool")});if(await C.authority()==="local")await w.load();let l=Z.heartbeat===!1?void 0:await R0({version:Y,logger:_2("heartbeat")});let L2=Z.fence??(()=>T0({currentVersion:Y}));let Z2=Z.slot??k0();let i=async()=>L0(Q(),await Z2.get({path:{id:"openai"}}));let X=!1;let K=H?A0({paths:Q,slot:Z2,version:Y,fence:L2,runDeps:{vaultServes:()=>C.serves()},paused:async()=>await C.authority()!=="local",migrate:async(L)=>{let b=await P0(L);if(X=b.status==="refused",!O)await w.load();return b},adopt:async(L)=>{if(O)return{status:"retry",reason:"unsettled"};if(!await g1(B2,T))return{status:"retry",reason:"vault-roster-pending"};if(O)return{status:"retry",reason:"unsettled"};let b=await M0(L);if(!O)await w.load();return b}}):void 0;K?.start();R.start();let M=cZ(Q());let _=Q0({paths:Q(),source:w,pins:M,vault:C},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const h=j1(g,{[Symbol.dispose](){if(!d)_.release()}},0);_.publish();let A=Z.codex??new D2(void 0,void 0,WZ());let S=e$(F);let v=Z1(Q());let x=JZ(Q(),{source:w,storage:D,vault:C,accounts:O1(Q()),settings:()=>S,parentOf:async(L)=>(await $.session.get({sessionID:L}))?.parentID??void 0,fetch:N,log:_2("cachekeep")},{now:B,codexResponsesUrl:B1().codexApiEndpoint,...Z.cacheKeep});const I=j1(g,{[Symbol.dispose](){if(!d)x.release()}},0);let n=p$({codex:A,onRoute:_.route,source:w,slotPlaceholderWithoutMain:i,storage:D,pins:M,sessionAccounts:O1(Q()),vault:C,awaitVaultRoster:async()=>{await g1(C.awaitRequestRoster(),C0)},responsesLite:()=>B1().responsesLite,codexEndpoint:()=>B1().codexApiEndpoint,now:B,log:J});let u=await Y0($,n.adapter,J,A,(L)=>x.capture(L),v,(L)=>x.forget(L));n.attach(u);let o=async(L)=>{if(await v2(C),S2(Q().configPath))return;if(await K?.idle(),S2(Q().configPath))return;if(X&&!y1(L)&&(await L2()).open){await w.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let s=async(L)=>{await o(L);let b=await RZ(w.poolStore(),Q(),L,{vault:C});if(!S2(Q().configPath))await K?.requestAdoption();await w.load(),J.info("ChatGPT login stored in the account pool",b)};let e=await N1($,{integrationID:F2,methods:AZ({beginLogin:Z.beginLogin??m1,version:Y,vault:C}),onLogin:(L)=>s(L),label:"ChatGPT (openai-auth account pool)",vault:OZ(C)});let p=await wZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let q=$.command&&$.location?await _Z({session:$.session,command:$.command,location:$.location},Z.controlPlane??SZ({...gZ({source:w,storage:D,counts:J2,now:B,authority:()=>C.authority()}),fetchImpl:N,now:B,randomUUID:w4,accountStoragePath:Q().configPath,accountStatePath:Q().statePath,packageVersion:Y,layoutNotice:x0,loadAccounts:q2,store:()=>w.poolStore(),migration:async()=>{if(S2(Q().configPath))return{migrated:!0};let L=await L2();return{migrated:!1,blockers:L.open?[]:L.blockers}},beginAccountLogin:Z.beginLogin??m1,refreshAllQuota:async()=>(await w.pollRows(await q2(Q()))).map((L)=>({...L,account:L.id})),getStickyRouting:async(L)=>M.get(L),cacheKeepManager:x.manager,setCacheKeepEnabled:(L)=>x.configure({enabled:L}),setCacheKeepSubagents:(L)=>x.configure({subagents:L}),setCacheKeepSustain:(L)=>x.configure({sustain:L}),setCacheKeepWindow:(L)=>x.configure({window:L}),afterWrite:()=>w.load(),refreshSidebar:()=>_.publish(),clearStickyRouting:async(L)=>{let b=M.get(L)!==void 0;return M.forget(L),b},vault:C})):void 0;let G2=new AbortController;(async()=>{try{for await(let L of $.event.subscribe({signal:G2.signal}))if(L.type==="session.deleted")n.forgetSession(L.data.sessionID),x.forget(L.data.sessionID),v.forget(L.data.sessionID)}catch(L){if(!G2.signal.aborted)J.warn("stopped listening for session deletion",{error:L instanceof Error?L.message:String(L)})}})();d=!0;return async()=>{O=!0,G2.abort();let L=x.release();await q?.(),K?.dispose(),await w.dispose(),await _.release(),await Promise.allSettled([u.dispose(),e.dispose(),p.dispose()]);let b;try{await Promise.race([Promise.all([K?.idle(),w.settled(),A.store?.settled(),L]),new Promise((j2)=>{b=setTimeout(j2,y4),b.unref?.()})])}finally{clearTimeout(b),R.release(),await l?.release()}}}catch(m){var $2=m,X2=1}finally{X0(g,$2,X2)}}var f4=l1(),V7={id:V1,setup:f4.setup,server:D0.server};export{V7 as default,l1 as createOpenAIAuthPlugin,V1 as OPENAI_AUTH_PLUGIN_ID};
|
|
1
|
+
import{c as g0}from"../index-4gnwkw3a.js";import{A as w0,B as Z1,C as o$,D as s$,E as Q0,F as Y0,G as v0,H as OZ,I as AZ,L as hZ,M as gZ,N as mZ,V as dZ,W as iZ,_ as h0,d as C0,e as uZ,ea as U$,f as F1,fa as H$,g as I2,h as Q1,i as W1,ia as m0,k as V$,l as W$,m as j$,n as r2,o as EZ,p as l1,q as CZ,r as IZ,s as fZ,t as Y1,u as QZ,v as YZ,w as b0,x as D0,y as n1,z as k0}from"../index-8rj2xddq.js";import{Ab as q0,Bb as S0,Cb as DZ,Kb as D2,Lb as UZ,Ma as SZ,Mb as HZ,Nb as h1,Ob as NZ,Pb as FZ,Rb as y0,Sb as I0,Ta as G1,Tb as f0,bb as U1,cb as P0,db as M0,eb as E0,fb as h2,hb as i$,ib as $1,jb as a$,kb as n$,mb as A0,nb as WZ,pa as _0,pb as R0,qb as bZ,ta as I$,ua as f$,zb as x0}from"../index-h3vtzckv.js";import{bc as $0,qc as Z0,rc as J0,tc as z0,xc as G0}from"../index-7qxa018z.js";import{Ae as l$,Ce as u$,De as p$,Ee as y1,Fe as c$,Gd as xZ,Ge as d$,Md as qZ,Nc as q$,Od as L0,Pd as pZ,Qd as k$,Zd as y2,_d as d2,de as w$,fe as GZ,ge as y$,md as J1,me as V1,nd as z1,od as T0,te as cZ,ue as m2,vd as a1,ve as v$,wd as S$,we as h$,xd as b$,xe as g$,yd as D$,ze as m$}from"../index-1nrre3d8.js";import"../index-41yn5c02.js";import{We as PZ,Xe as O0}from"../index-f1cqptqa.js";import"../index-npj40h62.js";import{gf as K0,if as M2}from"../index-s2vrkdj4.js";import"../index-mcy24ej8.js";import{Gf as MZ}from"../index-y4j7y8b8.js";import{Kf as N1,Lf as F0}from"../index-cf0mrvqj.js";import{AsyncLocalStorage as l4}from"node:async_hooks";import{randomUUID as u4}from"node:crypto";class V2 extends Error{kind;providerID;sessionID;requestKind;constructor($){super($.message??`${$.providerID} ${$.requestKind} request refused (${$.kind})`);this.name="OpenCode2AuthError",this.kind=$.kind,this.providerID=$.providerID,this.sessionID=$.sessionID,this.requestKind=$.requestKind}}function P2($){return`common-auth-placeholder.${$}`}function G$($){let Z=P2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function f2($,Z){if($?.type!=="oauth")return!1;let z=Z===void 0?void 0:P2(Z),G=(Y)=>z===void 0?Y.startsWith("common-auth-placeholder."):Y===z;return G($.access)&&G($.refresh)}var Q$="No browser sign-in: this connects the plugin to the accounts in its vault.";async function M1($,Z){let z=Z.now??Date.now,{integrationID:G}=Z,Y=(U)=>G$({integrationID:G,methodID:U,now:z()}),Q=async(U,H)=>{return await Z.onLogin(U,{integrationID:G,methodID:H}),Y(H)},K=(U)=>async(H)=>{let N=U.method.id,V=await U.authorize(H),P={url:V.url,instructions:V.instructions,...V.expiresAt===void 0?{}:{expiresAt:V.expiresAt}};if(V.mode==="auto")return{...P,mode:"auto",callback:V.callback.then((E)=>Q(E,N))};let C=V.callback;return{...P,mode:"code",callback:async(E)=>Q(await C(E),N)}};return $.integration.transform((U)=>{let H=Z.label===void 0?{}:{label:()=>Z.label};for(let P of Z.methods)U.method.update({integrationID:G,method:P.method,authorize:K(P),refresh:async(C)=>{if(!f2(C,G))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return Y(C.methodID)},...H});let N=Z.vault;if(N===void 0)return;let V=N.method.id;U.method.update({integrationID:G,method:N.method,authorize:async()=>({url:"",instructions:N.instructions??Q$,mode:"auto",callback:Promise.resolve().then(()=>N.activate({integrationID:G,methodID:V})).then(()=>Y(V))}),refresh:async(P)=>{if(!f2(P,G)||P.methodID!==V)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return Y(V)},...H})})}function c0($){let Z=[],z;for(let G of $.split(/\r?\n/))if(G.startsWith("data:"))Z.push(G.slice(5).replace(/^ /,""));else if(G.startsWith("event:"))z=G.slice(6).trim();if(Z.length===0)return;return z===void 0?{data:Z.join(`
|
|
2
|
+
`)}:{event:z,data:Z.join(`
|
|
3
|
+
`)}}function E1($,Z){let z=new TextDecoder,G="",Y=(K)=>{let U=c0(K);if(!U)return;try{$(U)}catch(H){Z(H)}},Q=()=>{for(;;){let K=/\r?\n\r?\n/.exec(G);if(!K)return;let U=G.slice(0,K.index);G=G.slice(K.index+K[0].length),Y(U)}};return new TransformStream({transform(K,U){U.enqueue(K),G+=z.decode(K,{stream:!0}),Q()},flush(){if(G+=z.decode(),Q(),G.trim()!=="")Y(G);G=""}})}var Y$=512,C1=3621000,k2="x-common-auth-attempt",b2=($,Z)=>JSON.stringify([$,Z]),N2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function d0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function i0($,Z){let z=$.getReader();return new ReadableStream({async pull(G){let Y;try{Y=await z.read()}catch(Q){Z({reason:"failed",message:Q instanceof Error?Q.message:String(Q)}),G.error(Q);return}if(Y.done)Z(),G.close();else G.enqueue(Y.value)},async cancel(G){Z({reason:"cancelled",...G===void 0?{}:{message:String(G)}}),await z.cancel(G)}})}function o2($,Z){for(let[z,G]of Object.entries(Z)){let Y=z.toLowerCase();for(let Q of Object.keys($))if(Q.toLowerCase()===Y)delete $[Q];if(G!==null)$[z]=G}}function a0($,Z){for(let[z,G]of Object.entries(Z))if(G===null)$.delete(z);else $.set(z,G)}async function O1($,Z,z={}){let{providerID:G}=Z,Y=z.gateOnPlaceholder,Q=(J)=>Y===void 0||Y.credential(J)===P2(G),K=z.logger,U=Math.max(1,z.maxRecords??Y$),H=z.hostRetryLimit??10,N=[...z.hostCredentials??[P2(G)],...Y?[P2(G)]:[]].filter((J)=>J!==""),V=new Map,P=new WeakMap,C=new Map,E=0,w=new Set,n=new Map,O=new Map,D=(J)=>{let j=O.get(J);return j?.ownedSeen===!0&&j.foreignSeen},U2=(J,j)=>{n.set(J,j);let W=O.get(J)??{ownedSeen:!1,foreignSeen:!1};if(j)W.ownedSeen=!0;else W.foreignSeen=!0;O.set(J,W)},G2=(J,j)=>{let W=Y?.refuseMisplaced,M=W?[...j].filter(([,b])=>b.includes(P2(G))):[],B=Q(j)&&(!W||M.length>0);if(W){if(M.length>0&&(M.length!==1||!B))throw U2(J.sessionID,!1),new V2({kind:"placement-refused",providerID:G,sessionID:J.sessionID,requestKind:J.kind,message:W(M[0]?.[0]??"")})}return U2(J.sessionID,B),B},I=!1,i=!1,H2=new Map,X2=0,$2=!1,X=new Map,F=(J,j)=>{try{K?.warn(J,j)}catch{}},T=(J)=>J instanceof Error?J.message:String(J),L=(J)=>J.excluded.clear(),g=(J)=>J.excluded.size===0?{}:{excluded:[...J.excluded]},x=(J,j,W)=>{if(!z.enforceRequestExclusion||J===void 0||!W.excluded.has(J))return!1;return F("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:j.sessionID,kind:j.kind,phase:j.phase,accountId:J}),!0},k=new Map,f=(J,j)=>{let W=(k.get(J)??Promise.resolve()).then(j),M=W.then(()=>{},()=>{});return k.set(J,M),M.then(()=>{if(k.get(J)===M)k.delete(J)}),W},S=(J,j)=>{let W=k.get(J);return W?W.then(()=>S(J,j)):j()},y=async(J)=>{try{await Z.dropChoice?.({...J.input,accountId:J.accountId})}catch(j){F("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:J.input.sessionID,error:T(j)})}},u=async(J)=>{try{await Z.dropSameAccountRetry?.({...J.input,accountId:J.accountId})}catch(j){F("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:J.input.sessionID,error:T(j)})}},a=async(J)=>{if(J.next)await y(J.next);if(J.sameAccount)await u(J.sameAccount)},J2=(J)=>{let j=C.get(J);if(C.delete(J),j)f(j.sessionID,()=>a(j))},r=async(J,j)=>{let W=H2.get(J);if(!W||W.size===0)return;await Promise.all([...W].map(async(M)=>{try{await M(j)}catch(B){F("opencode2 auth listener threw; the request is unaffected",{event:J,error:T(B)})}}))},Q2=async(J,j)=>{try{await Z.onAttemptEnd?.(J,j)}catch(W){F("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:J.attemptId,error:T(W)})}},p=(J,j)=>{if(J.ended||!J.attempt)return;let W={...J.status===void 0?{}:{status:J.status},outputStarted:J.outputStarted,...J.limit?{limit:J.limit.signal}:{},...j?{error:j}:{}};if(j)J.endError=j;if(j?.reason==="cancelled"||!j&&!J.limit&&(J.status===void 0||J.status<400))L(J.request);J.ended=Q2(J.attempt,W)},A=(J,j)=>p(J,{reason:"abandoned",message:j}),z2=(J)=>[...V.values()].filter((j)=>j.key===J),c=(J)=>z2(J).at(-1),m=(J)=>{if(V.delete(J.id),C.get(J.key)?.attemptId===J.id||!z2(J.key).length)J2(J.key)},j2=(J)=>{V.set(J.id,J);while(V.size>U){let j=V.values().next().value;if(j===void 0)break;A(j,"dropped to keep the record bound"),m(j)}},Y2=(J)=>J.accountId===void 0?void 0:{...J.scope,accountId:J.accountId},_=(J,j)=>new V2({kind:"no-account",providerID:G,sessionID:J.sessionID,requestKind:J.kind,...j===void 0?{}:{message:j}}),v=(J)=>{X.get(J)?.clear(),X.delete(J)},B2=async(J,j)=>{let W=()=>_(J,`${G} ${J.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if($2)throw W();let M=X.get(J.sessionID);if(!M)M=new Set,X.set(J.sessionID,M);let B={};M.add(B);let b=()=>{if(!M.has(B))throw W()};try{return await j(b)}finally{if(M.delete(B),M.size===0&&X.get(J.sessionID)===M)X.delete(J.sessionID)}},i2=(J,j)=>{for(let[W,M]of j)if(N.some((B)=>M.includes(B)))throw new V2({kind:"host-credential-on-wire",providerID:G,sessionID:J.sessionID,requestKind:J.kind,message:`${G} ${J.kind} request still carries the host's placeholder credential in ${W}; the adapter's account headers must replace it`})},l0=(J)=>{for(let j of z2(J))if(j.ended||!j.attempt)m(j);else if(j.transport==="ws"||j.judged)A(j,"a newer attempt of its session and kind began"),m(j)},a2=async(J,j,W,M)=>{let B=b2(J.sessionID,J.kind),{input:b,accountId:R,sameAccountRetry:q,request:o}=await S(J.sessionID,async()=>{W();let d=C.get(B);C.delete(B);let s=z2(B);if(d&&s.some((_2)=>_2.id!==d.attemptId&&_2.attempt&&!_2.ended))F("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:J.sessionID,kind:J.kind});if(!d){let _2=new Set(s.filter((W2)=>W2.attempt&&!W2.ended).map((W2)=>W2.request));for(let W2 of s)if(!_2.has(W2.request))L(W2.request)}let t=d?.request??{excluded:new Set},C2=d?.accountId??c(B)?.accountId;l0(B);let h=d?.next,e=d?.sameAccount,T2=e!==void 0&&e.input.modelID===J.modelID&&e.input.agent===J.agent,l=h!==void 0&&h.input.modelID===J.modelID&&h.input.agent===J.agent,O2=d?.wake,x2={...J,phase:"request",...g(t),...C2===void 0?{}:{previousAccountId:C2},...d?.rerouteFrom?{rerouteFrom:d.rerouteFrom}:{},...O2===void 0?{}:{wake:O2,hostAttempt:h?.input.hostAttempt}};if(h&&(!l||O2!==void 0))await f(J.sessionID,()=>y(h)),W();if(e&&!T2)await f(J.sessionID,()=>u(e)),W();let Z2=T2?e.accountId:l&&O2===void 0?h.accountId:await Z.chooseAccount(x2),L2=typeof Z2==="string"?Z2:void 0;if(x(L2,x2,t)){let _2=L2;if(T2&&e)await f(J.sessionID,()=>u(e));else if(_2!==void 0)await f(J.sessionID,()=>y(l&&h?h:{accountId:_2,input:x2}));L2=void 0,W()}return{input:x2,accountId:L2,sameAccountRetry:T2,request:t}});W();let E2={},R2;if(R!==void 0){let d=await Z.accountHeaders({...J,accountId:R});if(W(),d0(d))E2=d.headers,R2=d.attempt;else E2=d}let n2=`attempt-${++X2}`,S2={id:n2,key:B,scope:J,request:o,accountId:R,headers:E2,attempt:R===void 0?void 0:{...J,accountId:R,attemptId:n2,transport:M,data:R2},...M===void 0?{}:{transport:M},outputStarted:!1,sameAccountRetry:q};if(j2(S2),S2.attempt)r("select",{...J,accountId:S2.attempt.accountId,hook:j,...b.previousAccountId===void 0?{}:{previousAccountId:b.previousAccountId},...b.rerouteFrom===void 0?{}:{rerouteFrom:b.rerouteFrom},handle:S2.attempt});return S2},s1=async(J,j,W,M,B)=>{let b=b2(J.sessionID,J.kind),R=M===void 0?void 0:V.get(M);if(R?.key!==b)R=void 0;if(!R){if(R=c(b),z2(b).filter((o)=>o.transport===void 0&&!o.ended).length>1&&!i)i=!0,F("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:J.sessionID,kind:J.kind})}if(!R||R.transport!==void 0||R.ended)R=await a2(J,j,B,W);else if(R.transport=W,R.attempt)R.attempt.transport=W;if(W==="ws"){for(let q of z2(b))if(q!==R&&q.transport==="ws")A(q,"a newer attempt of its session and kind went out over WebSocket")}return R},T1=async(J,j)=>{try{return await j()}catch(W){throw p(J,{reason:"failed",message:T(W)}),W}},r1=(J,j)=>{let W=z2(b2(J,j)).filter((M)=>M.transport==="ws").at(-1);return W?.attempt!==void 0&&!W.ended?W:void 0},L1=(J,j,W)=>{let M=Y2(J);if(!M||!J.attempt||J.limit)return;J.limit={signal:j,delivered:r("limit",{...M,via:W,limit:j,outputStarted:J.outputStarted,handle:J.attempt})}},t1=(J,j,W,M)=>{let B=Y2(J);if(!B||!J.attempt)return;r("quota",{...B,transport:j,...M===void 0?{}:{status:M},quota:W,handle:J.attempt})},e1=(J,j,W,M)=>{let B=J.attempt;if(!B)return;let b=Z.inspectEvent?.(M===void 0?{transport:j,data:W,attempt:B}:{transport:j,data:W,event:M,attempt:B});if(!b)return;if(b.quota!==void 0)t1(J,j,b.quota);if(b.outputStarted)J.outputStarted=!0;if(b.hostRetry==="veto")J.hostRetry="veto";if(b.limit)L1(J,b.limit,j);if(b.error!==void 0)p(J,{reason:"failed",message:b.error});else if(b.done)p(J)},u0=(J,j)=>{let W=J.attempt;if(!W||j.accountId===J.accountId)return;if(W.reboundFrom??=W.accountId,W.accountId=j.accountId,"data"in j)W.data=j.data;J.accountId=j.accountId},p0=(J)=>!J.attempt||J.endError!==void 0||J.status!==void 0&&J.status>=400,$$=(J)=>{let j=[...V.values()].filter((q)=>q.scope.sessionID===J),W=j.filter((q)=>q.limit&&!q.rerouted).at(-1);if(W)return W;let M=j.filter((q)=>q.scope.kind==="primary"),B=M.length>0?M:j;if(B.length<=1)return B[0];let b=B.filter((q)=>!q.judged&&p0(q)).at(-1);if(b)return b;let R=B.filter((q)=>q.attempt&&!q.ended);if(R.length>1)return"ambiguous";return R[0]??B.at(-1)},q2={providerID:G},A2=[];A2.push(await $.session.hook("model.request",(J)=>{if(Y)return;return B2(N2(J),async(j)=>{let W=await a2(N2(J),"model.request",j);if(j(),W.accountId===void 0)throw _(W.scope);o2(J.headers,{...W.headers,[k2]:W.id})})},q2)),A2.push(await $.session.hook("http.request",(J)=>{if(Y){if(!G2(N2(J),J.request.headers))return}return B2(N2(J),async(j)=>{let W=J.request.headers.get(k2)??void 0,M=Y?await a2(N2(J),"http.request",j,"http"):await s1(N2(J),"http.request","http",W,j);j();let B=Y2(M),b=M.attempt;if(!B||!b)throw _(M.scope);await T1(M,async()=>{let R=J.request;if(Z.rewriteRequest){if(W!==void 0){let E2=new Headers(R.headers);E2.delete(k2),R=new Request(R,{headers:E2})}R=await Z.rewriteRequest({...B,request:R,attempt:b})??R,j()}let q=new Headers(R.headers);q.delete(k2),a0(q,M.headers),i2(M.scope,q.entries());let o=new Request(R,{headers:q});P.set(o,M),J.request=o})})},q2)),A2.push(await $.session.hook("http.response",async(J)=>{let j=P.get(J.request);if(!j){if(Y)return;if(!I)I=!0,F("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:J.sessionID,kind:J.kind});return}let W=J.response;if(Z.answeredBy&&j.attempt){let q=j.attempt,o=await T1(j,async()=>Z.answeredBy?.({request:J.request,response:W,attempt:q}));if(o)u0(j,o)}let M=Y2(j),B=j.attempt;if(!M||!B)return;j.status=W.status;let b=Z.quotaFromHeaders?.(W.headers,W.status,B);if(b!==void 0)t1(j,"http",b,W.status);if(!W.ok&&Z.limitFromResponse){let q=await Z.limitFromResponse({status:W.status,headers:W.headers,body:()=>W.clone().text(),attempt:B});if(q)L1(j,q,"http")}if(!W.ok||!W.body)p(j);let R=W;if(W.body&&(Z.inspectEvent||Z.onAttemptEnd)){let q=W.body;if(Z.inspectEvent)q=q.pipeThrough(E1((o)=>e1(j,"http",o.data,o.event),(o)=>F("opencode2 auth event inspection threw",{error:T(o)})));R=new Response(i0(q,(o)=>p(j,o)),{status:W.status,statusText:W.statusText,headers:W.headers})}if(Z.rewriteResponse)R=await Z.rewriteResponse({...M,request:J.request,response:R,attempt:B})??R;if(Z.responseRetry){if(await Z.responseRetry({...M,request:J.request,response:R,attempt:B})==="veto")j.hostRetry="veto"}if(R!==W)J.response=R},q2)),A2.push(await $.session.hook("experimental.ws.handshake",(J)=>{if(Y){let j=b2(J.sessionID,J.kind);if(w.delete(j),!G2(N2(J),new Headers(J.headers)))return}return B2(N2(J),async(j)=>{let W;for(let R of Object.keys(J.headers)){if(R.toLowerCase()!==k2)continue;W??=J.headers[R],delete J.headers[R]}let M=Y?await a2(N2(J),"experimental.ws.handshake",j,"ws"):await s1(N2(J),"experimental.ws.handshake","ws",W,j);j();let B=Y2(M),b=M.attempt;if(!B||!b)throw _(M.scope);await T1(M,async()=>{if(!Y?.refuseMisplaced)o2(J.headers,M.headers);let R=Z.rewriteHandshakeURL?.({...B,url:J.url,attempt:b});if(R!==void 0)J.url=R;if(Y?.refuseMisplaced)o2(J.headers,M.headers);if(i2(M.scope,Object.entries(J.headers)),Y)w.add(M.key)})})},q2));let Z$=Z.rewriteWebSocketFrame?.bind(Z);if(Z$)A2.push(await $.session.hook("experimental.ws.send",async(J)=>{let j=N2(J);if(Y&&!w.has(b2(j.sessionID,j.kind)))return;let W=r1(j.sessionID,j.kind),M=await Z$({...j,attempt:W?.attempt,frame:J.frame});if(M!==void 0)J.frame=M},q2));A2.push(await $.session.hook("experimental.ws.receive",(J)=>{if(Y&&!w.has(b2(J.sessionID,J.kind)))return;let j=r1(J.sessionID,J.kind);if(!j)return;try{e1(j,"ws",J.frame)}catch(W){F("opencode2 auth frame inspection threw",{error:T(W)})}},q2)),A2.push(await $.session.hook("retry",async(J)=>{if(Y&&n.get(J.sessionID)!==!0)return;let j=J.decision,W=()=>r("retry",{sessionID:J.sessionID,attempt:J.attempt,reason:"host-decides",hostDecision:j,decision:j});if(D(J.sessionID)&&!Z.retrySameAccount){await W();return}let M=$$(J.sessionID);if(!M)return;if(M==="ambiguous"){await r("retry",{sessionID:J.sessionID,attempt:J.attempt,reason:"host-decides",hostDecision:j,decision:j});return}let B=M,b=()=>B.hostRetry==="veto";await B2(B.scope,async(R)=>{let q=R,o=Z.retrySameAccount?.bind(Z),E2=B.attempt;if(o&&E2&&!B.outputStarted&&(!b()||D(J.sessionID))&&!B.sameAccountRetry){if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;let d=await f(B.scope.sessionID,async()=>{q();let s=E2.accountId,t=()=>V.has(B.id)&&B.accountId===s&&$$(J.sessionID)===B&&!B.outputStarted&&(!b()||D(J.sessionID))&&(!Y||n.get(J.sessionID)===!0);if(!t()||B.sameAccountRetry)return!1;B.sameAccountRetry=!0;let C2={...B.scope,accountId:s,error:J.error,attempt:J.attempt,...B.limit?{limit:B.limit.signal}:{}},h;try{h=await o(C2)}catch(l){F("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:J.sessionID,error:T(l)})}if(!h)return q(),!1;let e={accountId:h.accountId,input:C2};try{q()}catch(l){throw await u(e),l}if(!t()||h.accountId!==s)return await u(e),!1;let T2=C.get(B.key);if(C.delete(B.key),T2)await a(T2);try{q()}catch(l){throw await u(e),l}if(!t())return await u(e),!1;return C.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++E,accountId:s,sameAccount:e}),B.judged=!0,J.decision={retry:!0,delay:0},!0});if(q(),d){await r("retry",{sessionID:J.sessionID,accountId:B.accountId,kind:B.scope.kind,attempt:J.attempt,reason:"same-account",hostDecision:j,decision:J.decision,handle:B.attempt});return}}if(D(J.sessionID)){await W();return}B.judged=!0;let R2=B.attempt;if(R2&&!B.outputStarted){if(!B.limit){let d=Z.limitFromError?.(J.error,R2);if(d)L1(B,d,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered}q();let{decision:n2,reason:S2}=await f(B.scope.sessionID,async()=>{if(q(),D(J.sessionID))return{decision:j,reason:"host-decides"};let d=C.get(B.key);if(C.delete(B.key),d)await a(d);if(q(),D(J.sessionID))return{decision:j,reason:"host-decides"};let s=j,t,C2,h,e;if(B.accountId===void 0||!R2)s={retry:!1},t="no-account";else if(B.outputStarted)s={retry:!1},t="output-started";else if(b())s={retry:!1},t="adapter-veto";else if(B.limit){let T2={accountId:B.accountId,limit:B.limit.signal},l,O2={...B.scope,phase:"retry",...g(B.request),hostAttempt:J.attempt,previousAccountId:B.accountId,rerouteFrom:T2};try{l=await Z.chooseAccount(O2)}catch(P1){F("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:B.scope.sessionID,error:T(P1)})}let x2=typeof l==="string"?l:typeof l==="object"&&("hold"in l)?B.accountId:void 0;if(x(x2,O2,B.request)){if(x2!==void 0)await y({accountId:x2,input:O2});l=void 0}let Z2=typeof l==="object"&&"hold"in l?l.hold:void 0,L2=typeof l==="object"&&"waitThenReselect"in l?l.waitThenReselect:void 0,_2=typeof l==="object"&&"hostRetry"in l?l.hostRetry:void 0,W2=typeof l==="string"?l:Z2?B.accountId:void 0;if(W2!==void 0)h={accountId:W2,input:O2};try{q()}catch(P1){if(h)await y(h);throw P1}if(D(J.sessionID)){if(h)await y(h);return{decision:j,reason:"host-decides"}}if(b()||_2==="veto"){if(h)await y(h);if(h=void 0,q(),D(J.sessionID))return{decision:j,reason:"host-decides"};B.hostRetry="veto",s={retry:!1},t="adapter-veto"}else if(!(H-J.attempt>=1)){if(h)await y(h);h=void 0,t="host-decides-last-account"}else if(L2&&Number.isFinite(L2.delayMs)&&L2.delayMs>=0&&L2.delayMs<=C1)s={retry:!0,delay:Math.ceil(L2.delayMs)},t="wait-then-reselect";else if(Z2&&Number.isFinite(Z2.delayMs)&&Z2.delayMs>=0&&Z2.delayMs<=C1){if(s={retry:!0,delay:Math.ceil(Z2.delayMs)},Z2.target!==void 0)e={target:Z2.target,...Z2.checkpoint===void 0?{}:{checkpoint:Z2.checkpoint},...Z2.kind===void 0?{}:{kind:Z2.kind}};t="hold"}else if(!Z2&&W2!==void 0&&W2!==B.accountId)B.rerouted=!0,B.request.excluded.add(B.accountId),C2=T2,s={retry:!0,delay:0},t="reroute";else{if(Z2&&h)await y(h),h=void 0;t="host-decides-last-account"}}else t="host-decides";if(J.decision=s,s.retry&&B.accountId!==void 0&&V.has(B.id))C.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++E,accountId:B.accountId,...C2===void 0?{}:{rerouteFrom:C2},...h===void 0?{}:{next:h},...e===void 0?{}:{wake:e}});else if(h)await y(h);if(!s.retry)L(B.request);return{decision:s,reason:t}});q(),await r("retry",{sessionID:J.sessionID,...B.accountId===void 0?{}:{accountId:B.accountId},kind:B.scope.kind,attempt:J.attempt,reason:S2,hostDecision:j,decision:n2,...R2===void 0?{}:{handle:R2}})})},q2));let J$=(J)=>{if(v(J),n.delete(J),!O.get(J)?.foreignSeen)O.delete(J);for(let j of w)if(JSON.parse(j)[0]===J)w.delete(j);for(let j of[...V.values()]){if(j.scope.sessionID!==J)continue;A(j,"its session was forgotten"),L(j.request),V.delete(j.id)}for(let[j,W]of C)if(W.sessionID===J)J2(j)},_1=new AbortController,z$=$.event;if(z$)(async()=>{try{for await(let J of z$.subscribe({signal:_1.signal}))if(J.type==="session.deleted")J$(J.data.sessionID);else if(J.type==="session.status"&&J.data.status.type==="idle"){let j=J.data.sessionID,W=++E;f(j,async()=>{for(let[M,B]of C)if(B.sessionID===j&&B.order<W)C.delete(M),L(B.request),await a(B)})}}catch(J){if(!_1.signal.aborted)F("opencode2 auth stopped listening for session deletion",{error:T(J)})}})();return{on(J,j){let W=H2.get(J);if(!W)W=new Set,H2.set(J,W);let M=j;return W.add(M),()=>{W.delete(M)}},accountFor(J,j){return c(b2(J,j))?.accountId},forgetSession:J$,get size(){return V.size},async dispose(){if($2)return;$2=!0;for(let J of X.keys())v(J);_1.abort();for(let J of V.values())A(J,"the installation was disposed");V.clear();for(let J of C.keys())J2(J);w.clear(),n.clear(),O.clear(),H2.clear(),await Promise.all(k.values()),await Promise.all(A2.map(async(J)=>{try{await J.dispose()}catch(j){F("opencode2 auth hook did not dispose cleanly",{error:T(j)})}}))}}}import{createHash as n0}from"node:crypto";var o0=1024,s0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),X$=($)=>j$($,"user"),r0=($)=>s0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function t0($){return n0("sha256").update(JSON.stringify($)).digest("hex")}class w2{runtime;maxSessions;#$=new Map;constructor($,Z=o0){this.runtime=$;this.maxSessions=Z}advance($,Z,z=this.runtime){let G=this.#$.get($),Y=Array.isArray(Z.input)?Z.input:[],Q=Y.filter(X$),K=Y.findLastIndex(X$),U=K<0?void 0:t0(Y[K]),H=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,N,V,P;if(H)N=Q.length>0,V=U??G?.fingerprint,P=G?.userCount===void 0?void 0:G.userCount+Q.length;else{V=U,P=Q.length;let E=K>=0&&K>Y.findLastIndex(r0),w=G!==void 0&&!G.completed&&G.fingerprint===V&&G.userCount===P;N=E&&!w}let C=N||!G?{turnID:(z?.uuid??D2)(),turnStartedAt:(z?.now??Date.now)()}:{turnID:G.turnID,turnStartedAt:G.turnStartedAt};return this.#Z($,{...C,completed:!1,fingerprint:V,userCount:P}),C}completed($){let Z=this.#$.get($);if(Z)this.#Z($,{...Z,completed:!0})}get($){return this.#$.get($)}forget($){this.#$.delete($)}#Z($,Z){this.#$.delete($),this.#$.set($,Z);while(this.#$.size>this.maxSessions){let z=this.#$.keys().next().value;if(z===void 0)break;this.#$.delete(z)}}}function A1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var B$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function e0(){let $=globalThis;return $[B$]??=crypto.randomUUID(),$[B$]}class v2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,z){this.runtime=$;this.store=z;this.installationID=Z??e0(),this.sessions=z?.sessions??new Map,this.frameTurns=z?.frameTurns??new w2}get($){let Z=this.runtime?.uuid??D2;if(this.store)return this.store.get($,Z);let z=this.sessions.get($);if(!z){let G=Z();z={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,z)}return z}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(s2(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var R1={version:V$,"user-agent":W$,originator:"codex_exec"};var $4=1024,Z4=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,t2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),N$=($)=>t2($)&&($.type==="message"||("role"in $))&&$.role==="user",F$=($)=>t2($)&&$.type==="configuration_update";class x1{http;#$=new Map;constructor($=new v2){this.http=$}apply($,Z,z){if(Z.kind!=="primary")return!1;let G=typeof $.model==="string"?$.model:"";if(!U$.has(G))return!1;if(Z4.test(G))return!1;let Y=t2($.reasoning)?$.reasoning:void 0,Q=typeof Y?.effort==="string"?Y.effort:void 0;if(!Q)return!1;let K=this.#$.get(Z.sessionID);if(K===void 0)return this.#Z(Z.sessionID,Q),!1;if(Q===K)return!1;let U=Array.isArray($.input)?$.input:void 0;if(!U||U.length===0)return!1;let H=U.findLastIndex(N$);if(H<0){if(z==="http")return!1;return $.reasoning={...Y,effort:K},!0}if($.reasoning={...Y,effort:K},!F$(U[H-1]))U.splice(H,0,{type:"configuration_update",reasoning:{effort:Q}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>$4){let z=this.#$.keys().next().value;if(z===void 0)break;this.#$.delete(z)}}}function s2($){try{let Z=JSON.parse($);return t2(Z)?Z:void 0}catch{return}}async function K$($,Z,z,G,Y=z.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Q=await $.clone().text(),K=s2(Q);if(K)delete K.max_output_tokens;let U=new Headers($.headers),H=r2({rewriteLite:H$,init:{body:K?JSON.stringify(K):$.body===null?void 0:Q},headers:U,metadata:Y.get(Z.sessionID),installationID:Y.installationID,runtime:Y.runtime,websocket:!1,responsesLite:G,applyEffort:(N)=>{z.apply(N,Z,"http")}});return new Request($,{headers:U,body:H.init?.body})}function T$($,Z,z,G){let Y=G.sessions.get($.sessionID),Q=G.frameTurns.get($.sessionID);if(!Y||!Q)return;let K=A1(Y,Q),U=new Headers({"content-type":"application/json"});for(let N of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let V=z.get(N);if(V!==null)U.set(N,V)}r2({init:{body:$.bodyText},headers:U,metadata:K,installationID:G.installationID,runtime:G.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let H=new URL(Z);if(H.protocol==="wss:")H.protocol="https:";if(H.protocol==="ws:")H.protocol="http:";return new Request(H,{method:"POST",headers:U,body:$.bodyText})}function J4($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let z=Z.findIndex((G,Y)=>JSON.stringify(G)!==JSON.stringify($[Y]));return z>=0&&F$(Z[z])&&N$(Z[z+1])&&JSON.stringify(Z.slice(z+1))===JSON.stringify($.slice(z))}function L$($,Z,z){let G=s2($);if(G?.type!=="response.create")return;let Y=z.http.advanceFrame(Z.sessionID,G),Q=z.http.get(Z.sessionID);delete G.max_output_tokens;let K=r2({rewriteLite:()=>{},init:{body:JSON.stringify(G)},headers:new Headers,metadata:A1(Q,Y),installationID:z.http.installationID,runtime:z.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(H)=>{z.apply(H,Z,"ws")}}),U=s2(String(K.init?.body));if(!U)return;if(!J4(G.input,U.input)){if("input"in G)U.input=G.input;else delete U.input;return JSON.stringify(U)}return String(K.init?.body)}function z4($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function q1($,Z){let z=new URL($);if(z.origin!=="https://api.openai.com"&&z.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(z.pathname))return $;let G=new URL(`${z4(Z)}/responses`);if(G.search=z.search,z.protocol==="ws:"||z.protocol==="wss:")G.protocol=G.protocol==="https:"?"wss:":"ws:";return G.href}import{resolve as S1}from"node:path";var _$=Symbol.for("@cortexkit/openai-auth/opencode2-rate-limits/v1"),P$=globalThis,b1=P$[_$]??new Map;P$[_$]=b1;function M$($){let Z=b1.get($);if(!Z)Z=new Map,b1.set($,Z);return Z}function E$($){return M$(JSON.stringify(["pool",S1($.configPath),S1($.statePath)]))}function C$($){return M$(JSON.stringify(["vault",S1($)]))}import{resolve as O$}from"node:path";var G4=1024;class e2{accounts=new Map;limit;constructor($=G4){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let z=this.accounts.keys().next().value;if(z===void 0)break;this.accounts.delete(z)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var A$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),R$=globalThis,D1=R$[A$]??new Map;R$[A$]=D1;function k1($){let Z=JSON.stringify([O$($.configPath),O$($.statePath)]),z=D1.get(Z);if(!z)z=new e2,D1.set(Z,z);return z}var F2="openai",Q4=60000,w1=1,Y4="request refused: no account with a usable credential",K2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function X4($){let Z=K2($)?$.counters:void 0,z=K2(Z)?Z.resetCredits:void 0,G=K2(z)?z.value:void 0;return typeof G==="number"&&Number.isFinite(G)?G:void 0}function g2($){try{return JSON.parse($)}catch{return}}function x$($){let Z=J1($);return Z?z1(Z):void 0}var j4=new Set(["usage_limit_reached","rate_limit_exceeded"]);function I1($,Z,z){return{reason:$.window,...z!==void 0?{status:z}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function B4($,Z){let z=Z1($);if(z){let Q=typeof $.status==="number"?$.status:void 0;return I1(z,Z,Q)}if($.type!=="response.failed"||!K2($.response))return;let G=$.response.failed;if(K2(G)&&typeof G.rate_limit_reached_type==="string")return{reason:G.rate_limit_reached_type};let Y=$.response.error;if(K2(Y)){let Q=typeof Y.code==="string"?Y.code:typeof Y.type==="string"?Y.type:void 0;if(Q&&j4.has(Q))return{reason:Q}}return}function V4($,Z){let z=g2($);if(!K2(z))return;let G=typeof z.type==="string"?z.type:void 0;if(G==="codex.rate_limits")return{quota:{snapshot:D$(z),complete:!0}};let Y=B4(z,Z);if(Y)return{limit:Y};if(G===void 0||G==="error")return;return o$(G)?void 0:{outputStarted:!0}}function W4($){let Z=!1;for(let z of $.keys())if(z.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:S$($),complete:b$($)}}function U4($){let Z=$.get("retry-after");if(Z===null)return;let z=Number(Z);return Number.isFinite(z)&&z>=0?z*1000:void 0}function r$($){let Z=new WeakMap,z=new WeakSet,{source:G,pins:Y}=$,Q=$.now??Date.now,K=$.log,U=$.vault,H=new x1($.codex),N=new Map,V=new Map,P=(X)=>`${X.sessionID}\x00${X.kind}\x00${X.accountId}`,C=U?.paths?.rosterPath,E=C?C$(C):new Map,w=$.sessionAccounts??new e2,n=new u$,O=(X,F,T)=>{let L=T?[]:s$(G.peek().rows,X,F,U?.identities()??new Set),g=(U?.routes()??[]).filter((x)=>x.kind==="oauth"&&w$(m2(x.quota),X,F));return[...L.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota,row:x})),...g.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota}))]},D=(X,F,T)=>{let L=g$(X,F,T),g=X.map((S)=>({id:S.id,kind:"oauth",...q$(S.quota)?{quota:S.quota}:{}})),x=X.flatMap((S)=>S.row?[S.row]:[]),k=new Set(X.filter((S)=>!S.row).map((S)=>S.id)),f=G.rateLimitMarks(x);for(let S of k){let y=E.get(S);if(y===void 0)continue;if(y<=T)E.delete(S);else f.set(S,y)}return{rows:g,now:T,rateLimitMarks:f,refreshBackoff:G.refreshBackoffFor(x),killswitch:L,requestPull:(S)=>k.has(S)?U?.requestReading(S):G.requestReading(S)}},U2=(X,F,T,L,g)=>{let x=p$({...X,placement:m$(F),mainId:g});if(x.kind==="block"){K?.debug("pool admission refused the request",{reason:x.block.reason});return}let k=x.order.filter((f)=>!T.has(f));if(L!==void 0&&k.includes(L))return L;return k[0]},G2=(X,F,T,L,g,x,k,f)=>{let S=new Map(F.map((A)=>[A.id,A.quota])),y={requestBytes:w1,reservePercent:(A)=>y$(T,A===v$?void 0:A),resetCredits:(A)=>X4(S.get(A))},u=y1(X),a=(A,z2)=>G1(k,{sessionId:L,requestBytes:w1,validPinnedAccountIds:X.rows.map((c)=>c.id).filter((c)=>!u.excluded.has(c)),excludeAccountIds:A,quotaCheckedAtByAccount:Object.fromEntries(X.rows.map((c)=>[c.id,u.projections.get(c.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(F.map((c)=>[c.id,c.identity])),select:(c)=>f?{accountId:f,source:"mode-fallback",quotaCheckedAt:u.projections.get(f)?.checkedAt}:c$(X,y,new Set(A),c),persist:z2},(c,m)=>k.set(c,m)),J2=[...g],r=a(J2,x);if(!r)return;let Q2=r.accountId,p=d$(X,y,Q2);if(p.kind==="none")return;if(p.kind==="move"){let A=a([...J2,Q2],x);if(A)return A.accountId;return p.reason==="killswitch"?void 0:Q2}if(p.kind==="detour")return a([...J2,Q2],!1)?.accountId;return Q2},H2={providerID:F2,dropChoice(X){let F=P(X);V.get(F)?.drop(),V.delete(F),N.delete(F)},chooseAccount:async(X)=>{let F=await U?.authority(),T=await $.storage(),L=F!==void 0&&F!=="local",g=()=>{throw new V2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:Q1})};if(L)await $.awaitVaultRoster?.();else{if(!(await G.current()).active){if(await $.slotPlaceholderWithoutMain?.())g();K?.warn("the account pool does not serve requests yet; refusing the request",{kind:X.kind});return}await G.prepareTokens(G.peek().rows,T)}let x=Q(),k=O(T,x,L),f=l$(D(k.filter((m)=>m.id!==X.rerouteFrom?.accountId),T,x));if(f)await f,x=Q(),k=O(T,x,L);let S=new Map(k.map((m)=>[m.id,m])),y=D(k,T,x),u=new Set(X.rerouteFrom?[X.rerouteFrom.accountId]:[]),a=T?.routing?.mode??"main-first",J2=X.kind==="primary",r=new Set,Q2,p,A,z2=!1,c=(m)=>{let j2=y1(y).projections.get(m)?.checkedAt,Y2=S.get(m)?.identity;return Y.reserve(X.sessionID,{accountId:m,inputBytes:w1,...j2!==void 0?{quotaCheckedAt:j2}:{},...Y2!==void 0?{wireIdentity:Y2}:{}})};try{for(;;){let m=new Set([...u,...r]);A=void 0,Q2=void 0;let j2=a!=="sticky-balanced";if(a==="sticky-balanced"){let _=new Map(Y.placementSnapshot(X.sessionID)),v=_.get(X.sessionID);if(j2=v===void 0,A=G2(y,k,T,X.sessionID,m,J2&&r.size===0,_),A!==void 0&&_.get(X.sessionID)!==v)Q2=_.get(X.sessionID)}if(A??=U2(y,a,m,J2?void 0:w.activeAccount(X.sessionID),L?a==="sticky-balanced"?null:h$(U?.routes()??[]):void 0),A===void 0||r.has(A)){if(u.size>0){let _=new Map(y.rateLimitMarks);for(let v of u)_.delete(v);y={...y,rateLimitMarks:_},u.clear();continue}if(y.rateLimitMarks.size>0){y={...y,rateLimitMarks:new Map};continue}A=void 0;break}if(J2&&a==="sticky-balanced")p=c(A);if(!z2){z2=!0;let _=await i$({vaultMode:L,fresh:j2,sessionId:X.sessionID,request:{modelId:X.modelID,kind:X.kind,retry:X.phase==="retry"||X.rerouteFrom!==void 0},routes:U?.routes()??[],routing:y,eligibleIds:k.filter((v)=>!m.has(v.id)).map((v)=>v.id)});if(_&&_!==A){if(p)Y.rollback(p);if(p=void 0,a==="sticky-balanced"){let v=new Map(Y.placementSnapshot(X.sessionID));A=G2(y,k,T,X.sessionID,m,J2,v,_)??A,Q2=v.get(X.sessionID)??Q2}else A=_;if(J2&&a==="sticky-balanced")p=c(A)}}let Y2=S.get(A)?.row;if(Y2){if(G.usableToken(Y2)!==void 0)break;K?.debug("pool row holds no usable token; choosing again",{accountId:A})}else{if(!U)break;let _=await U.authorize(A);if(_){N.set(P({...X,accountId:A}),_);break}K?.debug("the vault refused to serve an account; choosing again",{accountId:A})}if(p)Y.rollback(p);p=void 0,r.add(A)}if(A===void 0&&!L&&k.length===0&&await $.slotPlaceholderWithoutMain?.())g();if(A===void 0&&L&&U&&(k.length===0||r.size>0)){let m=r.size>0?"vault-refused":f$(U);throw K?.warn("vault mode: no vault account can serve; refusing the request",{cause:m}),new V2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:I$(m,U.name)})}if(A!==void 0){let m=A,j2=p,Y2=Q2,_=()=>{if(j2)Y.finish(j2,Y2);if(J2)w.record(X.sessionID,m),$.onRoute?.(X.sessionID,m,a)};if(X.phase==="retry")V.set(P({...X,accountId:A}),{commit:_,drop:()=>{if(j2)Y.rollback(j2)}}),p=void 0;else _();let v=K?.info;n.served(y,A,K&&v?{info:(B2,i2)=>v.call(K,B2,i2)}:void 0)}return K?.debug("pool account chosen",{kind:X.kind,accountId:A,mode:a,...X.rerouteFrom?{rerouteFrom:X.rerouteFrom.accountId}:{}}),A}finally{if(p)Y.rollback(p)}},accountHeaders:async(X)=>{let{accountId:F}=X,T=P(X),L=V.get(T);V.delete(T);let g=()=>{L?.commit()};try{let x=()=>new V2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:Y4}),k=U&&await U.authority()!=="local"?void 0:G.peek().rows.find((y)=>y.id===F);if(!k&&U){let y=P(X),u=N.get(y)??await U.authorize(F);if(N.delete(y),!u)throw K?.warn("the vault refused to serve an account; refusing the request",{accountId:F}),x();return g(),{headers:{...R1,"session-id":X.sessionID,authorization:`Bearer ${u.accessToken}`,"chatgpt-account-id":u.accountIdentity??x$(u.accessToken)??null},attempt:{kind:"vault",routeId:F,receipt:u}}}let f=k?G.usableToken(k):void 0;if(!k||!f)throw K?.warn("pool row holds no usable token; refusing the request",{accountId:F}),x();let S=k.identity??x$(f);return g(),{headers:{...R1,"session-id":X.sessionID,authorization:`Bearer ${f}`,"chatgpt-account-id":S??null},attempt:{kind:"pool",token:f,credentialEpoch:k.credentialEpoch}}}finally{L?.drop()}},async rewriteRequest({request:X,sessionID:F,kind:T}){let L=$.codexEndpoint?q1(X.url,$.codexEndpoint()):X.url,g=L===X.url?X:new Request(L,X);return await K$(g,{sessionID:F,kind:T},H,$.responsesLite?.()??!1)??g},rewriteHandshakeURL:({url:X})=>$.codexEndpoint?q1(X,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:X,sessionID:F,kind:T})=>L$(X,{sessionID:F,kind:T},H),quotaFromHeaders:(X,F,T)=>{if(T.data?.kind==="vault")U?.reportUsage(T.data.routeId,{headers:X},T.data.receipt);if(T.data?.kind==="vault"&&h2()&&F>=200&&F<300)Z.set(T,{status:F,headers:X});return W4(X)},async limitFromResponse({status:X,headers:F,body:T,attempt:L}){if(X<400)return;let g=g2(await T().catch(()=>"")),x=Z1({...K2(g)?g:{},status:X});if(L.data?.kind==="vault"&&h2())$1(L.sessionID,L.data.receipt,{status:X,headers:F,body:g,limit:x,quota:U?.routes().find((y)=>y.id===L.accountId)?.quota,now:Q()});if(!x)return;let k=Q(),f=I1(x,k,X);if(f.retryAfterMs!==void 0)return f;let S=U4(F);return S===void 0?f:{...f,retryAfterMs:S}},inspectEvent:({data:X,transport:F,attempt:T})=>{if(T.data?.kind==="vault"&&X.includes("codex.rate_limits")){let L=g2(X);if(K2(L)&&L.type==="codex.rate_limits")U?.reportUsage(T.data.routeId,{frame:L},T.data.receipt)}if(T.data?.kind==="vault"&&h2()&&(n$(X)||F==="ws"&&X.includes('"response.completed"'))){let L=g2(X);if(a$(L))z.add(T);if(F==="ws"&&K2(L)&&L.type==="response.completed")$1(T.sessionID,T.data.receipt,{status:200,headers:new Headers,failed:z.has(T)})}return V4(X,Q())},limitFromError(X){let F=g2(X.message),T=Z1({...K2(F)?F:{},...X.status!==void 0?{status:X.status}:{}})??(X.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return T?I1(T,Q(),X.status):void 0},async onAttemptEnd(X,F){let T=X.data,L=T?.kind==="vault"&&h2()?Z.get(X):void 0;if(Z.delete(X),T?.kind==="vault"&&L&&!F.error&&!F.limit)$1(X.sessionID,T.receipt,{...L,failed:z.has(X)});if(T?.kind!=="vault"||F.status!==401)return;K?.warn("a vault account answered 401; reporting it to the vault",{accountId:X.accountId}),await U?.reportFailure(T.receipt,401)}},X2=(X,F,T)=>{let L=T.data;if(L?.kind==="vault"){U?.recordSnapshot(X,F.snapshot,F.complete,L.receipt);return}if(L?.kind!=="pool")return;if(G.peek().rows.find((x)=>x.id===X)?.credentialEpoch!==L.credentialEpoch){K?.debug("quota reading dropped: the row holds another credential",{accountId:X});return}G.recordSnapshot(X,F.snapshot,L.token,F.complete)},$2=(X,F,T)=>{let L=Q(),g=T.data?.kind==="vault",x=g?U?.routes().find((S)=>S.id===X)?.quota:G.peek().rows.find((S)=>S.id===X)?.quota,k=k$(m2(x),F.reason,L,Q4,F.retryAfterMs!==void 0?L+F.retryAfterMs:void 0);if(!g){G.markRateLimited(X,k);return}let f=E.get(X);if(f===void 0||f<k)E.set(X,k)};return{adapter:H2,attach(X){X.on("quota",(F)=>X2(F.accountId,F.quota,F.handle)),X.on("limit",(F)=>{$2(F.accountId,F.limit,F.handle),K?.debug("pool row refused the request",{accountId:F.accountId,via:F.via,reason:F.limit.reason,outputStarted:F.outputStarted})})},forgetSession(X){Y.forget(X),w.forget(X),H.forget(X)},activeAccount:(X)=>w.activeAccount(X)}}import{resolve as zZ}from"node:path";import{Buffer as H4}from"node:buffer";import{resolve as t$}from"node:path";function l2($){return H4.byteLength(JSON.stringify($))}function N4($){return $.reduce((Z,z)=>Z+l2(z),0)}function f1($,Z){return 2+$+Math.max(0,Z-1)}function F4($){let{head:Z,pending:z}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+f1(Z.inputBytes,Z.input.length)+1:0)+(z?20+f1(z.inputBytes,z.input.length)+10+f1(z.outputBytes,z.output.length)+(z.responseID===void 0?0:14+z.responseIDBytes)+1:0)}function e$($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class $Z{enabled;caps=Y1;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$)this.entries.clear(),this.bytes=0}send($,Z){if(!this.enabled)return;let z=e$(Z);if(z?.type!=="response.create")return;if(!Array.isArray(z.input)){this.forget($);return}let G=z.previous_response_id,Y=this.entries.get($),Q=Y?.head;if(G&&G!==Q?.responseID){this.forget($);return}let{type:K,previous_response_id:U,input:H,...N}=z;this.keep($,{fields:G&&Y?Y.fields:N,fieldsBytes:G&&Y?Y.fieldsBytes:l2(N),...G&&Q?{head:Q}:{},pending:{input:H,inputBytes:N4(H),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,z){if(!this.enabled||!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed"))return;let G=this.entries.get($);if(!G?.pending)return;let Y=e$(Z);if(!Y)return;let Q=G.pending,K=Y.response;if(Y.type==="response.created"&&typeof K?.id==="string")Q.responseID=K.id,Q.responseIDBytes=l2(K.id),this.keep($,G);else if(Y.type==="response.output_item.done"&&Y.item){if(typeof Y.response_id==="string"&&Q.responseID!==void 0&&Y.response_id!==Q.responseID)return;Q.output.push(Y.item),Q.outputBytes+=l2(Y.item),this.keep($,G)}else if(Y.type==="response.completed"&&typeof K?.id==="string"){if(K.id===G.head?.responseID||Q.responseID!==void 0&&K.id!==Q.responseID)return;let U={responseID:K.id,responseIDBytes:Q.responseID===K.id?Q.responseIDBytes:l2(K.id),input:[...G.head?.input??[],...Q.input,...Q.output],inputBytes:(G.head?.inputBytes??0)+Q.inputBytes+Q.outputBytes},H={...G,head:U,pending:void 0};if(!this.keep($,H))return;z?.({sessionID:$,responseID:U.responseID,bodyText:this.body(G.fields,U)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let z=F4(Z);if(this.forget($),z>this.caps.maxBytes)return!1;Z.bytes=z,this.entries.set($,Z),this.bytes+=z;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let G=this.entries.keys().next().value;if(G===void 0)break;this.forget(G)}return this.entries.has($)}}var ZZ=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),JZ=globalThis,v1=JZ[ZZ]??new Map;JZ[ZZ]=v1;function X1($){let Z=JSON.stringify([t$($.configPath),t$($.statePath)]),z=v1.get(Z);if(!z)z=new $Z,v1.set(Z,z);return z}var K4=5000,T4=["accept","originator","session-id","thread-id","user-agent","version","x-client-request-id","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-openai-internal-codex-responses-lite","x-opencode-parent-session-id","x-parent-session-id"],L4=["x-opencode-parent-session-id","x-parent-session-id"];function XZ($){let Z=GZ($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:QZ($?{...$,cachekeep:Z}:$)}}var jZ=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),BZ=globalThis,u2=BZ[jZ]??new Map;BZ[jZ]=u2;function _4($,Z){let z=[],G=()=>z.at(-1)?.location,Y=()=>{let H=G();if(!H)throw Error("no location holds keep-warm");return H},Q=(H,N)=>{U.remove(H),G()?.log?.debug(`cachekeep dropped target (${N})`,{sessionKey:H})},K=async(H)=>{if(H.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let N=H.accountId??"main",V=Y(),P=await V.source.accessFor(N,await V.storage());if(!P)throw Error(`pool row ${N} has no usable token`);return{token:P.token,identity:P.row.identity}},U=YZ({...Y1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(H,N)=>Y().fetch(H,N),logger:{debug:(H,N)=>G()?.log?.debug(H,N),warn:(H,N)=>G()?.log?.warn(H,N)},getWindow:()=>G()?.settings().window,getSustain:()=>G()?.settings().sustain===!0,resolveLocal:K,vault:{owns:(H)=>G()?.vault.owns(H)===!0,authority:()=>Y().vault.authority(),reportUsage:(...H)=>G()?.vault.reportUsage(...H),send:async(H,N,V)=>{let P=Y();if(await P.vault.authority()!=="vault")return;return P.vault.send(H,N,V)}},activeAccount:(H)=>{if(H===void 0)throw Error("target has no session");let N=G(),V=N?.settings();if(!N||!V?.enabled){Q(H,"keep-warm is off");return}if(!V.subagents&&U.status().targets.some((C)=>C.sessionKey===H&&C.isSubagent)){Q(H,"subagent warming is off");return}let P=N.accounts.activeAccount(H);if(P===void 0){Q(H,"no account recorded for the session");return}return P},verifyCredential:({target:H,mode:N,identity:V})=>{if(H.meta.credentialMode!==N)throw Error(`a target captured in ${H.meta.credentialMode??"an unknown"} mode is not warmed with a ${N} credential`);if(V!==H.meta.chatgptAccountId)throw Q(H.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:U,settings:Z,holders:z,joinTimeoutMs:$.joinTimeoutMs??K4}}function P4($){try{let Z=JSON.parse($),z=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(z?.role!=="user")return!1;return(typeof z.content==="string"?z.content:Array.isArray(z.content)?z.content.map((Y)=>typeof Y?.text==="string"?Y.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function M4($){let Z={};for(let z of T4){let G=$.get(z);if(G)Z[z]=G}return Z}function VZ($,Z,z){let G=JSON.stringify([zZ($.configPath),zZ($.statePath)]),Y=u2.get(G);if(!Y)Y=_4(z,Z.settings()),u2.set(G,Y);let Q=Y,K=X1($);K.setEnabled(Q.settings.enabled);let U={location:{...Z,settings:()=>Q.settings}};Q.holders.push(U);let H=!1,N=async(V)=>{try{let P=U.location.settings();if(H||!P.enabled)return;if(V.kind!=="primary"){if(V.kind==="generate"&&P4(await V.request.clone().text())){if(H)return;Q.manager.remove(V.sessionID)}return}let C=V.attempt.data,E=C?.kind==="pool"?"local":C?.kind==="vault"?"vault":void 0;if(!E)return;let w=V.request.headers,n=L4.some((U2)=>w.has(U2))||Z.parentOf!==void 0&&await Z.parentOf(V.sessionID)!==void 0;if(n&&!P.subagents)return;let O=await V.request.clone().text();if(H)return;let D=w.get("chatgpt-account-id")??void 0;Q.manager.track({sessionKey:V.sessionID,bodyText:O,accountId:V.attempt.accountId,isSubagent:n,meta:{replayHeaders:M4(w),...D?{chatgptAccountId:D}:{},routingSessionId:V.sessionID,url:V.request.url,credentialMode:E}})}catch(P){Z.log?.warn("cachekeep capture failed",{error:P instanceof Error?P.message:String(P)})}};return{manager:Q.manager,configure:(V)=>{Object.assign(Q.settings,V),K.setEnabled(Q.settings.enabled)},capture:N,forget:(V)=>Q.manager.remove(V),async release(){if(H)return;H=!0;let V=Q.holders.indexOf(U);if(V>=0)Q.holders.splice(V,1);if(Q.holders.length>0)return;if(u2.get(G)===Q)u2.delete(G);Q.manager.stop();let P;try{await Promise.race([Q.manager.tick().catch(()=>{}),new Promise((C)=>{P=setTimeout(C,Q.joinTimeoutMs),P.unref?.()})])}finally{clearTimeout(P)}}}}import{mkdirSync as E4}from"node:fs";import{dirname as C4,resolve as O4}from"node:path";function A4(){return WZ("opencode2")}var R4=2000;class KZ{path;options;sessions;frameTurns=new w2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Q=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=NZ($,Z.uuid??D2)}get($,Z=D2){let z=this.sessions.get($);if(!z){let G=Z();z={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,z),this.#Z.delete($),this.#z.delete($),this.#$.add($),this.#Y()}return z}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#z.add($);this.#Y()}#Y(){if(this.#J)return;this.#J=setTimeout(()=>{this.#J=void 0,this.save()},this.options.saveDelayMs??R4),this.#J.unref?.()}save(){if(clearTimeout(this.#J),this.#J=void 0,!this.#Q)this.#Q=!0,this.#G=this.#G.then(()=>{return this.#Q=!1,this.#j()});return this.#G}settled(){return this.#J?this.save():this.#G}#X(){if(this.#z.size===0)return;let $;try{$=h1(this.path)}catch{$=new Map}for(let Z of this.#z)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#z.clear()}async#j(){if(this.#X(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((G)=>{let Y=this.sessions.get(G);return Y?[[G,Y]]:[]}),Z=[...this.#Z],z=null;try{if(E4(C4(this.path),{recursive:!0}),z=await this.#B(),!z)return;let G;try{G=h1(this.path)}catch{G=new Map}await this.options.afterRead?.();let Y=!1;for(let Q of Z)if(G.delete(Q))Y=!0;for(let[Q,K]of $){if(G.get(Q)===K.threadID)continue;G.set(Q,K.threadID),Y=!0}if(Y)FZ(this.path,G)}catch{return}finally{await z?.release().catch(()=>{})}for(let[G,Y]of $)if(this.sessions.get(G)===Y)this.#$.delete(G);for(let G of Z)if(!this.sessions.has(G))this.#Z.delete(G)}#B(){return HZ(this.path,this.options.lockWaitMs??UZ)}}var TZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),LZ=globalThis,j1=LZ[TZ]??new Map;LZ[TZ]=j1;function x4($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.sessions instanceof Map&&typeof Z.get==="function"&&typeof Z.delete==="function"&&typeof Z.save==="function"&&typeof Z.settled==="function"&&(Z.frameTurns===void 0||Z.frameTurns!==null&&typeof Z.frameTurns.advance==="function"&&typeof Z.frameTurns.get==="function"&&typeof Z.frameTurns.completed==="function"&&typeof Z.frameTurns.forget==="function")}function _Z($=A4()){let Z=O4($),z=j1,G=j1.get(Z),Y=j1;if(G!==void 0&&!x4(G))z.compatible??=new Map,Y=z.compatible;let Q=Y.get(Z);if(!Q)Q=new KZ(Z),Y.set(Z,Q);let K=Q;return K.frameTurns??=new w2,Q}var g1=Symbol.for("cortexkit.openai-auth.v2.commands"),q4=M2("v2-command");function B1($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.closed instanceof AbortController&&typeof Z.menu?.open==="function"&&typeof Z.menu?.apply==="function"&&typeof Z.session?.get==="function"&&(Z.registration===void 0||Z.registration!==null&&typeof Z.registration.dispose==="function")}function m1($){q4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function S4(){let $=globalThis;return $[g1]??={locations:new Map},$[g1].locations??=new Map,$[g1]}async function RZ($,Z){let z=S4(),G=$.location.directory,Y={menu:Z,session:$.session,closed:new AbortController},Q=await MZ(G),K=await PZ(OZ,Q.dir,()=>AZ({...Q,drain:CZ,apply:(P)=>{let C=z.locations.get(G);if(!B1(C))throw Error("The OpenAI menu location was closed");return C.menu.apply(P)}})),U=z.locations.get(G);if(z.locations.set(G,Y),B1(U))U.closed.abort(),await U.registration?.dispose();let H={name:"openai",description:"OpenAI account menu",async execute(P){let C=[...z.locations.values()].find(B1)?.session;if(!C)return m1("no live location");let E=await C.get({sessionID:P.sessionID}),w=z.locations.get(E.location.directory);if(!B1(w))return m1("location closed");let n=await EZ(P.sessionID,w.closed.signal);if(!n||z.locations.get(E.location.directory)!==w){if(!n&&!w.closed.signal.aborted)l1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},P.sessionID);return m1(w.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let O=await w.menu.open(P.sessionID);l1(O,P.sessionID)}};z.command??=H,z.command.execute=H.execute;let N=z.command;try{Y.registration=await $.command.transform((P)=>{P.add(N)})}catch(P){if(Y.closed.abort(),z.locations.get(G)===Y)z.locations.delete(G);throw await K.release(),P}let V=!1;return async()=>{if(V)return;if(V=!0,Y.closed.abort(),z.locations.get(G)===Y)z.locations.delete(G);await K.release(),await Y.registration?.dispose()}}var b4="openai-auth-pool-browser",D4="openai-auth-pool-headless",k4="openai-auth-vault",w4="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Run /openai → Vault → Connect and approve the request before trying again.";async function p2($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function kZ($){return{method:{id:k4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await xZ($.paths,$.name)!=="vault")throw Error(w4)}}}function wZ($){let Z=(z,G,Y)=>({method:{id:z,type:"oauth",label:G},async authorize(){if($.vault)await p2($.vault);let Q=await $.beginLogin({version:$.version,headless:Y});return{url:Q.url,instructions:Q.instructions,mode:"auto",callback:Q.completion}}});return[Z(b4,"ChatGPT (openai-auth pool, browser)",!1),Z(D4,"ChatGPT (openai-auth pool, headless)",!0)]}function u1($){let Z=(z)=>typeof z==="string"?z:"";return f2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===bZ||qZ($)}function y4($){if($.accountId)return $.accountId;let Z=$.access?J1($.access):void 0;return Z?z1(Z):void 0}async function yZ($,Z,z,G={}){if(G.vault)await p2(G.vault);if(u1(z))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Y=SZ($,{rowLocks:(E)=>DZ(Z,E)}),Q=await Y.read();if(Q.status!=="ready")throw Error(`the account pool cannot be read (${Q.status}); the login was not stored`);let K={type:"oauth",refresh:z.refresh,...z.access!==void 0?{access:z.access}:{},...z.expires!==void 0?{expires:z.expires}:{}},U=y4(z);if(G.vault)await p2(G.vault);let H=U!==void 0?{identity:U}:{};if(G.origin==="import"){let E=Q.rows.find((w)=>U!==void 0&&w.identity===U||w.credential?.type==="oauth"&&w.credential.refresh===z.refresh);if(E)return{id:E.id,operation:"kept"}}let N=Q.rows.filter((E)=>E.type==="oauth"&&!E.invalid),V=U?N.find((E)=>E.identity===U):void 0,P=Q.rows.find((E)=>E.id===V1);if(V)return{id:(await Y.replace(V.id,K,H)).id,operation:"replaced"};if(!P){let E=await Y.add({id:V1,credential:K,...H,...z.label!==void 0?{label:z.label}:{}});return{id:E.id,operation:E.outcome==="added-disabled"?"added-disabled":"added"}}if(!P.invalid&&!P.credential)return{id:(await Y.replace(V1,K,H)).id,operation:"replaced"};let C=await Y.add({id:z.id,credential:K,...H,...z.label!==void 0?{label:z.label}:{}});return{id:C.id,operation:C.outcome==="added-disabled"?"added-disabled":C.outcome==="rotated"?"replaced":"added"}}function I4($){let Z=$.itemId!==void 0;switch($.sectionId){case"accounts":return Z?["enable","disable","remove","move"].includes($.actionId):$.actionId==="add";case"routing":return!Z&&["order","mode"].includes($.actionId);case"quota":return $.actionId==="check";case"limits":return Z?$.actionId==="floors":$.actionId==="killswitch";case"session":return!Z&&$.actionId==="clear-pin";case"vault":return Z?["enable","disable"].includes($.actionId):["connect","disconnect"].includes($.actionId);case"diagnostics":return!Z&&["logging","dump"].includes($.actionId);case"cache":return!Z&&["enabled","subagents","sustain","window"].includes($.actionId);case"reset":return Z&&["preview","spend","retry"].includes($.actionId);default:return!1}}function vZ($){let Z={...$,allowAction:I4,unavailableSections:[]};return{open:(z)=>IZ(Z,z),apply:(z)=>{let G=z!==null&&typeof z==="object"?z:{},Y=G.values&&typeof G.values==="object"&&!Array.isArray(G.values)?Object.fromEntries(Object.entries(G.values).filter(([,Q])=>Q===null||["string","number","boolean"].includes(typeof Q))):void 0;return fZ(Z,{command:"openai",sectionId:typeof G.sectionId==="string"?G.sectionId:"",actionId:typeof G.actionId==="string"?G.actionId:"",...Y?{values:Y}:{},...G.confirmed===!0?{confirmed:!0}:{},...typeof G.itemId==="string"?{itemId:G.itemId}:{},...typeof G.sessionId==="string"?{sessionId:G.sessionId}:{}})}}}function f4($,Z){if(!hZ($.modelID??$.id)){$.enabled=!1;return}let z=gZ($.id);if(z)$.limit={...z};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((G)=>[G.id,G])).values()]}function lZ($){return $.model.transform((Z)=>{let z=Z.list(F2);for(let G of z){let Y=mZ(String(G.id)),Q=Y?z.find((K)=>String(K.id)===Y):void 0;Z.update(F2,String(G.id),(K)=>f4(K,Q?.variants?.map((U)=>({...U,id:String(U.id)}))))}})}class p1{log;pending=new Map;requests=new Map;writing=new Set;constructor($){this.log=$}async safely($){let Z=(async()=>{try{await $()}catch{this.log.warn("request dump failed")}})();this.writing.add(Z);try{await Z}finally{this.writing.delete(Z)}}async captureHttp($,Z){if(!uZ())return;await this.safely(async()=>{let z={sessionID:Z.sessionID,accountId:Z.accountId,transport:"http",phase:"http",url:$.url,method:$.method,headers:new Headers($.headers),bodyText:await $.clone().text()};if(this.pending.set($,{attemptId:Z.attemptId,input:z}),this.requests.set(Z.attemptId,$),this.pending.size>512){let G=this.pending.keys().next().value;if(G)this.take(G)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let z=this.take($);if(z)await this.safely(()=>W1({...z,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let z=this.requests.get($.attemptId),G=z&&this.take(z);if(!G)return;let{reason:Y,message:Q}=Z.error,K=Q?`${Y}: ${Q}`:Y;await this.safely(()=>W1({...G,error:U1(K,z?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>W1({sessionID:Z.sessionID,accountId:Z.accountId,transport:"websocket",phase:"observed",bodyText:$}))}clear(){this.pending.clear(),this.requests.clear()}async settle(){await Promise.all(this.writing)}}class c1{counts=new Map;record($,Z){let z=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof z==="number"&&Number.isFinite(z)?z:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function aZ($){return async(Z)=>{let z=Z.credential;if(z.type!=="oauth"||!z.access)throw Error("the row holds no access token to poll with");let G=await pZ({accessToken:z.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,G),cZ(G,$.now(),!0)}}function nZ($){let{source:Z,counts:z,now:G}=$,Y=async(N)=>{let V=await Z.rowAccess(N,await $.storage());if(!V?.row)throw new dZ("unknown_account",`${N==="main"?"Main":"Fallback"} account ${N} was not found.`);return iZ(N,V)},Q=async(N)=>{if($.authority&&await $.authority()!=="local")return{account:N,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[V]=await Z.pollRows(await $.storage(),{ids:[N]});if(!V)return{account:N,ok:!1,error:"targeted quota refresh returned no result"};return{account:V.id,ok:V.ok,...V.error!==void 0?{error:V.error}:{}}},K=(N)=>Z.peek().rows.find((V)=>V.id===N),U=(N)=>{let V=K(N);if(!V)return null;let P=m2(V.quota)??{},C=z.applicable(V),E=Math.max(0,...[P.primary?.checkedAt,P.secondary?.checkedAt].filter((w)=>typeof w==="number"));return{quota:{...P,...C!==void 0?{resetCreditsApplicable:C}:{}},checkedAt:E,refreshAfter:E,...V.identity!==void 0?{accountId:V.identity}:{}}};return{resolveResetTarget:Y,refreshResetTargetQuota:Q,quotaManager:{isRateLimited:(N)=>{let V=K(N);if(!V)return!1;let P=Z.rateLimitMarks([V]).get(V.id);return P!==void 0&&P>G()},getMain:()=>U("main"),getFallback:(N)=>U(N)}}}import{resolve as oZ}from"node:path";var v4=1024;class d1{pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=v4){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.reservations.delete($),this.pins.delete($);for(let Z of this.listeners)Z($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}snapshot(){return new Map(this.pins)}placementSnapshot($){let Z=new Map(this.pins);for(let z of this.reservations.values())if(z.sessionId!==$)Z.set(z.sessionId,z.pin);return Z}reserve($,Z){let z={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,z),z}rollback($){if(this.reservations.get($.sessionId)===$)this.reservations.delete($.sessionId)}finish($,Z){if(this.reservations.get($.sessionId)!==$)return;if(this.rollback($),Z&&this.pins.get($.sessionId)===$.previous)this.set($.sessionId,Z)}get size(){return this.pins.size}set($,Z){this.reservations.delete($),this.pins.delete($),this.pins.set($,Z);for(let z of this.listeners)z($,Z);while(this.pins.size>this.limit){let z=this.pins.keys().next().value;if(z===void 0)break;this.forget(z)}}place($){return G1(this.placementSnapshot($.sessionId),$,(Z,z)=>this.set(Z,z))}}var sZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),rZ=globalThis,H1=rZ[sZ]??new Map;rZ[sZ]=H1;function h4($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.get==="function"&&typeof Z.forget==="function"&&typeof Z.subscribe==="function"&&typeof Z.snapshot==="function"&&typeof Z.place==="function"&&typeof Z.placementSnapshot==="function"&&typeof Z.reserve==="function"&&typeof Z.rollback==="function"&&typeof Z.finish==="function"}function tZ($){let Z=JSON.stringify([oZ($.configPath),oZ($.statePath)]),z=H1,G=H1.get(Z);if(G!==void 0&&!h4(G)){let Q=H1;Q.compatibleV1??=new Map,z=Q.compatibleV1}let Y=z.get(Z);if(!Y)Y=new d1,z.set(Z,Y);return Y}import{statSync as g4}from"node:fs";import{resolve as m4}from"node:path";function X0($){return $.map((Z)=>{try{let z=g4(Z);return`${z.ino}:${z.size}:${z.mtimeMs}:${z.ctimeMs}`}catch{return"?"}}).join("|")}function i1($){return X0([$.vault.paths.tokenPath,$.vault.paths.statePath])}function eZ($){return X0([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+i1($)}class j0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;protocol=V0;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:eZ($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),z=this.subscriptions.get($.pins);if(!z){let G=new Set;z={producers:G,stop:$.pins.subscribe((Y,Q)=>{let K=G.values().next().value;if(K)this.publish(K,{sessionId:Y,pin:Q,accountId:Q?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,z)}return z.producers.add($),this.timer??=setInterval(()=>{for(let G of this.producers){let Y={stamp:eZ(G),roster:G.vault.snapshot()},Q=this.observations.get(G);if(Y.stamp!==Q?.stamp||Y.roster!==Q?.roster)this.observations.set(G,Y),this.publish(G)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),z.producers.delete($),!z.producers.size)z.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;await($.write??B0)(this.file,$,Z,()=>this.producers.has($))}).catch(()=>{M2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var B0=async($,Z,z,G)=>{let Q=await Z.vault.authority()!=="local",K=i1(Z),U=()=>G()&&Z.vault.enrolled()===Q&&i1(Z)===K,H=await(Q?d2(Z.paths):y2(Z.paths)),N=Q?Q0(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((C)=>C.id)),H,Date.now()):Y0((await Z.source.sidebarView()).rows,H,Date.now()),V={canWrite:U,vaultMode:Q};if(await Z0(N,$,V),!U()||!z)return;let P=N.vaultAccounts??N.fallbacks;if(z.accountId===void 0){await z0(z.sessionId,P,$,V);return}if(z.pin){let C=Date.now();await G0({sessionId:z.sessionId,assignment:{accountId:z.pin.accountId,wireAccountId:z.pin.wireIdentity,inputBytes:z.pin.inputBytes??0,quotaCheckedAt:z.pin.quotaCheckedAt,assignedAt:C,lastSeenAt:C},validPinnedAccountIds:[...Q?[]:["main"],...P.filter((E)=>E.enabled).map((E)=>E.id)]},$,V)}await J0({sessionId:z.sessionId,activeId:z.accountId,route:z.route??N.route,updatedAt:Date.now()},P,$,V)},V0=2,W0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),U0=globalThis,c2=U0[W0]??new Map;U0[W0]=c2;function H0($,Z=$0(),z=2000){let G=m4(Z),Y=c2.get(G);if(Y?.protocol!==V0)Y=new j0(G,z),c2.set(G,Y);let Q=Y;$={...$,write:$.write??B0};let K=Q.add($),U=!1;for(let[H,N]of $.pins.snapshot())Q.publish($,{sessionId:H,pin:N,accountId:N.accountId,route:"sticky-balanced"});return{publish:()=>Q.publish($),route:(H,N,V)=>{Q.publish($,{sessionId:H,accountId:N,route:V})},async release(){if(U)return;if(U=!0,K(),await Q.settled(),Q.empty&&c2.get(G)===Q)c2.delete(G)}}}var K1="cortexkit-openai-auth",p4=5000;async function N0($,Z,z,G=new v2,Y,Q,K){let U=new p1(z),H=new l4,N=new Map,V=new Map,P=(O)=>{V.delete(O);for(let D of N.keys())if(D.startsWith(`${O}:`))N.delete(D)},C=(O)=>{K?.(O.sessionID),Q?.send(O.sessionID,O.frame)},w=await O1({session:{hook:(O,D,U2)=>$.session.hook(O,async(G2)=>{let I=O==="http.request"?G2:void 0,i=O==="experimental.ws.handshake"?G2:void 0,X2=(I?I.request.headers:i?new Headers(i.headers):void 0)?.get("authorization")===`Bearer ${P2(Z.providerID)}`,$2={};if(i)N.delete(`${i.sessionID}:${i.kind}`);try{await H.run($2,()=>D(G2))}catch(X){if(X2&&!(X instanceof V2))throw P0(X);throw X}if(I&&X2&&$2.attempt){let X=I.request.headers.get("thread-id");if(X)I.request.headers.set("session-id",X)}if(I&&X2&&$2.attempt)await U.captureHttp(I.request,$2.attempt);if(I&&X2&&$2.attempt)await Y?.({sessionID:I.sessionID,kind:I.kind,request:I.request,attempt:$2.attempt});if(i&&X2&&$2.attempt)i.headers["session-id"]=G.get(i.sessionID).threadID;if(O==="experimental.ws.send"){let X=G2,F=N.get(`${X.sessionID}:${X.kind}`);if(F)await U.frame(X.frame,F.attempt);if(F&&X.kind==="primary")C(X)}if(I||i){let X=I??i;if(!X)return;let T=(I?I.request.headers:new Headers(X.headers)).get("authorization")?.replace(/^Bearer /,"");if(X2&&T)V.set(X.sessionID,T);else V.delete(X.sessionID);if(i){let L=`${i.sessionID}:${i.kind}`;if(X2&&T&&$2.attempt)N.set(L,{bearer:T,attempt:$2.attempt,url:i.url,headers:new Headers(Object.entries(i.headers).filter(([g])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(g.toLowerCase())))});else N.delete(L)}if(V.size>512){let L=V.keys().next().value;if(L)V.delete(L)}if(N.size>512){let L=N.keys().next().value;if(L)N.delete(L)}}else if(O==="experimental.ws.receive"){let X=G2,F=N.get(`${X.sessionID}:${X.kind}`);if(F){if(G.frameReceived(X.sessionID,X.frame),X.kind==="primary"){let T;if(Q?.receive(X.sessionID,X.frame,(L)=>{T=L}),T)try{let L=T$(T,F.url,F.headers,G);if(L)await Y?.({sessionID:X.sessionID,kind:"primary",request:L,attempt:F.attempt})}catch(L){z.warn("cachekeep WebSocket capture failed",{error:L instanceof Error?L.message:String(L)})}}X.frame=M0(X.frame,F.bearer)}}else if(O==="retry"){let X=G2,F=V.get(X.sessionID);if(F)Object.assign(X.error,{message:U1(X.error.message,F)})}},U2)},event:{subscribe:(O)=>async function*(){for await(let D of $.event.subscribe(O)){if(D.type==="session.deleted")P(D.data.sessionID);yield D}}()}},{...Z,rewriteRequest:async(O)=>{let D=H.getStore();if(D)D.attempt=O.attempt;return Z.rewriteRequest?.(O)},rewriteHandshakeURL:(O)=>{let D=H.getStore();if(D)D.attempt=O.attempt;return Z.rewriteHandshakeURL?.(O)},onAttemptEnd:async(O,D)=>{await U.end(O,D),await Z.onAttemptEnd?.(O,D)},rewriteResponse:async(O)=>{await U.response(O.request,O.response.status);let D=await Z.rewriteResponse?.(O)??O.response;return E0(D,O.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(O)=>{let D=O.get("authorization");return D?.startsWith("Bearer ")?D.slice(7):void 0}},logger:{warn:(O,D)=>z.warn(O,{data:D})}}),n=w.dispose;return{...w,dispose:async()=>{V.clear(),N.clear(),await n(),await U.settle(),U.clear()}}}function o1($={}){return{id:K1,setup:(Z)=>c4(Z,$)}}async function c4($,Z={}){let c=[];try{let z=M2("opencode2");let G=M2("quota");let Y=Z.version??O0;await f0({version:Y,...Z.runtimeLayout});let Q=Z.paths??(()=>R0(C0()));let K=await d2(Q());let U=K?.logging?.level;if(U&&typeof U==="string")K0(U);let H=Z.fetch??fetch;let N=Z.now??Date.now;let V=Z.poolMigration??h0;if(!V&&!I2(Q().configPath)){z.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let _=(B2)=>{throw new V2({kind:"no-account",providerID:F2,sessionID:B2.sessionID,requestKind:B2.kind,message:Q1})},v=await N0($,{providerID:F2,chooseAccount:_,accountHeaders:_},z);return()=>v.dispose()}let P=Z.vault?.firstRosterWaitMs??D0;let C=v0({host:"opencode",stateDir:Z.vault?.stateDir??_0(Q().statePath),reservedRouteIds:()=>I.peek().rows.map((_)=>_.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>H},Q());let E=C.vault;let w=async()=>await E.authority()==="local"?y2(Q()):d2(Q());let n=!1;let O=!1;const D=N1(c,{[Symbol.dispose](){if(!n)C.release()}},0);await E.authority();let U2=C.firstRoster;let G2=new c1;let I=new k0({paths:Q,rateLimitMarks:E$(Q()),refreshProvider:async(_)=>{let v=await L0({refreshToken:_.refresh,fetchImpl:H,now:N}),B2=T0({id_token:"",access_token:v.access,refresh_token:v.refresh});return{...v,...B2?{identity:B2}:{}}},pullQuota:aZ({fetchImpl:H,now:N,counts:G2,logger:G}),now:N,vaultIdentities:()=>E.identities(),vaultMode:()=>E.enrolled(),vaultAuthority:()=>E.authority(),vaultFirstRoster:U2,vaultFirstRosterBackgroundWaitMs:P,log:M2("pool")});if(await E.authority()==="local")await I.load();let i=Z.heartbeat===!1?void 0:await y0({version:Y,logger:M2("heartbeat")});let H2=Z.fence??(()=>A0({currentVersion:Y}));let X2=Z.slot??g0();let $2=async()=>x0(Q(),await X2.get({path:{id:"openai"}}));let X=!1;let F=V?w0({paths:Q,slot:X2,version:Y,fence:H2,runDeps:{vaultServes:()=>E.serves()},paused:async()=>await E.authority()!=="local",migrate:async(_)=>{let v=await q0(_);if(X=v.status==="refused",!O)await I.load();return v},adopt:async(_)=>{if(O)return{status:"retry",reason:"unsettled"};if(!await n1(U2,P))return{status:"retry",reason:"vault-roster-pending"};if(O)return{status:"retry",reason:"unsettled"};let v=await S0(_);if(!O)await I.load();return v}}):void 0;F?.start();C.start();let T=tZ(Q());let L=H0({paths:Q(),source:I,pins:T,vault:E},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const g=N1(c,{[Symbol.dispose](){if(!n)L.release()}},0);L.publish();let x=Z.codex??new v2(void 0,void 0,_Z());let k=XZ(K);let f=X1(Q());let S=VZ(Q(),{source:I,storage:w,vault:E,accounts:k1(Q()),settings:()=>k,parentOf:async(_)=>(await $.session.get({sessionID:_}))?.parentID??void 0,fetch:H,log:M2("cachekeep")},{now:N,codexResponsesUrl:F1().codexApiEndpoint,...Z.cacheKeep});const y=N1(c,{[Symbol.dispose](){if(!n)S.release()}},0);let u=r$({codex:x,onRoute:L.route,source:I,slotPlaceholderWithoutMain:$2,storage:w,pins:T,sessionAccounts:k1(Q()),vault:E,awaitVaultRoster:async()=>{await n1(E.awaitRequestRoster(),b0)},responsesLite:()=>F1().responsesLite,codexEndpoint:()=>F1().codexApiEndpoint,now:N,log:z});let a=await N0($,u.adapter,z,x,(_)=>S.capture(_),f,(_)=>S.forget(_));u.attach(a);let J2=async(_)=>{if(await p2(E),I2(Q().configPath))return;if(await F?.idle(),I2(Q().configPath))return;if(X&&!u1(_)&&(await H2()).open){await I.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let r=async(_)=>{await J2(_);let v=await yZ(I.poolStore(),Q(),_,{vault:E});if(!I2(Q().configPath))await F?.requestAdoption();await I.load(),z.info("ChatGPT login stored in the account pool",v)};let Q2=await M1($,{integrationID:F2,methods:wZ({beginLogin:Z.beginLogin??a1,version:Y,vault:E}),onLogin:(_)=>r(_),label:"ChatGPT (openai-auth account pool)",vault:kZ(E)});let p=await lZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let A=$.command&&$.location?await RZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??vZ({...nZ({source:I,storage:w,counts:G2,now:N,authority:()=>E.authority()}),fetchImpl:H,now:N,randomUUID:u4,accountStoragePath:Q().configPath,accountStatePath:Q().statePath,packageVersion:Y,layoutNotice:I0,loadAccounts:y2,store:()=>I.poolStore(),migration:async()=>{if(I2(Q().configPath))return{migrated:!0};let _=await H2();return{migrated:!1,blockers:_.open?[]:_.blockers}},beginAccountLogin:Z.beginLogin??a1,refreshAllQuota:async()=>(await I.pollRows(await y2(Q()))).map((_)=>({..._,account:_.id})),getStickyRouting:async(_)=>T.get(_),cacheKeepManager:S.manager,setCacheKeepEnabled:(_)=>S.configure({enabled:_}),setCacheKeepSubagents:(_)=>S.configure({subagents:_}),setCacheKeepSustain:(_)=>S.configure({sustain:_}),setCacheKeepWindow:(_)=>S.configure({window:_}),afterWrite:()=>I.load(),refreshSidebar:()=>L.publish(),clearStickyRouting:async(_)=>{let v=T.get(_)!==void 0;return T.forget(_),v},vault:E})):void 0;let z2=new AbortController;(async()=>{try{for await(let _ of $.event.subscribe({signal:z2.signal}))if(_.type==="session.deleted")u.forgetSession(_.data.sessionID),S.forget(_.data.sessionID),f.forget(_.data.sessionID)}catch(_){if(!z2.signal.aborted)z.warn("stopped listening for session deletion",{error:_ instanceof Error?_.message:String(_)})}})();n=!0;return async()=>{O=!0,z2.abort();let _=S.release();await A?.(),F?.dispose(),await I.dispose(),await L.release(),await Promise.allSettled([a.dispose(),Q2.dispose(),p.dispose()]);let v;try{await Promise.race([Promise.all([F?.idle(),I.settled(),x.store?.settled(),_]),new Promise((B2)=>{v=setTimeout(B2,p4),v.unref?.()})])}finally{clearTimeout(v),C.release(),await i?.release()}}}catch(m){var j2=m,Y2=1}finally{F0(c,j2,Y2)}}var d4=o1(),_7={id:K1,setup:d4.setup,server:m0.server};export{_7 as default,o1 as createOpenAIAuthPlugin,K1 as OPENAI_AUTH_PLUGIN_ID};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-openai-auth",
|
|
3
|
-
"version": "1.9.
|
|
3
|
+
"version": "1.9.5",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -66,12 +66,12 @@
|
|
|
66
66
|
},
|
|
67
67
|
"devDependencies": {
|
|
68
68
|
"@ai-sdk/openai": "3.0.88",
|
|
69
|
-
"@cortexkit/common-auth": "^0.
|
|
69
|
+
"@cortexkit/common-auth": "^0.34.0",
|
|
70
70
|
"@cortexkit/openai-auth-core": "workspace:*",
|
|
71
71
|
"@opencode/plugin": "2.2.0"
|
|
72
72
|
},
|
|
73
73
|
"dependencies": {
|
|
74
|
-
"@cortexkit/claustrum-client": "^0.
|
|
74
|
+
"@cortexkit/claustrum-client": "^0.14.0",
|
|
75
75
|
"@cortexkit/private-files": "^0.2.2",
|
|
76
76
|
"@cortexkit/subc-client": "^0.22.0",
|
|
77
77
|
"@opentui/core": ">=0.7.0",
|
|
@@ -6,6 +6,7 @@ import { readClaustrumEnrollmentToken } from "./b9588ad4725c1d10-enrollment.js";
|
|
|
6
6
|
import { ClaustrumConsumerError } from "./ca0fccaba1d87af4-errors.js";
|
|
7
7
|
import { CUSTODY_PLACEHOLDER_PREFIX } from "./d9d2892a4c371301-host-slot.js";
|
|
8
8
|
import { drainShutdown, shutdownWarning } from "./a670cb7f5987bc1b-shutdown.js";
|
|
9
|
+
import { ScopedUsageReporter, } from "./4ede5af6a878a14e-usage.js";
|
|
9
10
|
import { ScopedRosterWatch, } from "./dc9290c2a7552ba6-watch.js";
|
|
10
11
|
/** Only a new version of the same account may replace an in-flight 401. */
|
|
11
12
|
export function isScopedCredentialRotation(served, current) {
|
|
@@ -28,6 +29,14 @@ function scopedRetryReason(served, current) {
|
|
|
28
29
|
return 'rotated';
|
|
29
30
|
}
|
|
30
31
|
const defaultLogger = createLogger('claustrum');
|
|
32
|
+
function checkedEnrollmentToken(value) {
|
|
33
|
+
if (!/^[0-9a-f]{64}$/.test(value.token) ||
|
|
34
|
+
!Number.isSafeInteger(value.token_generation) ||
|
|
35
|
+
value.token_generation < 1) {
|
|
36
|
+
throw new ClaustrumConsumerError('invalid-token', 'Invalid Claustrum enrollment token');
|
|
37
|
+
}
|
|
38
|
+
return value.token;
|
|
39
|
+
}
|
|
31
40
|
// Opt-in diagnostics let tests retain wait phases without logging each vault read.
|
|
32
41
|
const phaseDiagnostics = channel('common-auth.claustrum.phases');
|
|
33
42
|
/**
|
|
@@ -183,6 +192,8 @@ export class ClaustrumScopedCustody {
|
|
|
183
192
|
#reports = new WeakMap();
|
|
184
193
|
#kept = new Map();
|
|
185
194
|
#keptAttempts = new WeakMap();
|
|
195
|
+
#usage;
|
|
196
|
+
#usageServed = new Map();
|
|
186
197
|
#setTimeout;
|
|
187
198
|
#clearTimeout;
|
|
188
199
|
#outage = false;
|
|
@@ -197,6 +208,7 @@ export class ClaustrumScopedCustody {
|
|
|
197
208
|
#watches = new Set();
|
|
198
209
|
#tokenReads = new Set();
|
|
199
210
|
#warnShutdown;
|
|
211
|
+
#onDrainTimeout;
|
|
200
212
|
#disposing;
|
|
201
213
|
constructor(options) {
|
|
202
214
|
const tokenPath = options.tokenPath;
|
|
@@ -218,6 +230,14 @@ export class ClaustrumScopedCustody {
|
|
|
218
230
|
this.#warnShutdown = shutdownWarning(this.#logger);
|
|
219
231
|
this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
|
|
220
232
|
this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
|
|
233
|
+
this.#usage = new ScopedUsageReporter({
|
|
234
|
+
client: this.#client,
|
|
235
|
+
owns: (id) => this.#usageServed.has(id),
|
|
236
|
+
token: async () => checkedEnrollmentToken(await this.#readToken()),
|
|
237
|
+
logger: this.#logger,
|
|
238
|
+
setTimeout: this.#setTimeout,
|
|
239
|
+
clearTimeout: this.#clearTimeout,
|
|
240
|
+
});
|
|
221
241
|
}
|
|
222
242
|
/** A watch losing its transport is the same outage as an unreachable read. */
|
|
223
243
|
transportLost(error) {
|
|
@@ -303,12 +323,7 @@ export class ClaustrumScopedCustody {
|
|
|
303
323
|
});
|
|
304
324
|
}
|
|
305
325
|
this.#check(signal);
|
|
306
|
-
|
|
307
|
-
!Number.isSafeInteger(value.token_generation) ||
|
|
308
|
-
value.token_generation < 1) {
|
|
309
|
-
throw new ClaustrumConsumerError('invalid-token', 'Invalid Claustrum enrollment token');
|
|
310
|
-
}
|
|
311
|
-
return value.token;
|
|
326
|
+
return checkedEnrollmentToken(value);
|
|
312
327
|
}
|
|
313
328
|
async #call(operation, signal) {
|
|
314
329
|
this.#check(signal);
|
|
@@ -370,6 +385,7 @@ export class ClaustrumScopedCustody {
|
|
|
370
385
|
}
|
|
371
386
|
catch (error) {
|
|
372
387
|
this.#kept.clear();
|
|
388
|
+
this.#clearUsageOwnership();
|
|
373
389
|
throw error;
|
|
374
390
|
}
|
|
375
391
|
if (phaseDiagnostics.hasSubscribers)
|
|
@@ -473,11 +489,19 @@ export class ClaustrumScopedCustody {
|
|
|
473
489
|
else {
|
|
474
490
|
this.reachable();
|
|
475
491
|
this.#kept.clear();
|
|
492
|
+
this.#clearUsageOwnership();
|
|
476
493
|
}
|
|
477
494
|
}
|
|
478
495
|
/** Discard bearer material when a route is removed, declined or rebound. */
|
|
479
496
|
forget(credentialId) {
|
|
480
497
|
this.#kept.delete(credentialId);
|
|
498
|
+
this.#usageServed.delete(credentialId);
|
|
499
|
+
this.#usage.forget(credentialId);
|
|
500
|
+
}
|
|
501
|
+
#clearUsageOwnership() {
|
|
502
|
+
for (const id of this.#usageServed.keys())
|
|
503
|
+
this.#usage.forget(id);
|
|
504
|
+
this.#usageServed.clear();
|
|
481
505
|
}
|
|
482
506
|
/** Apply an already-held roster; this never fetches credentials or writes it. */
|
|
483
507
|
retain(identities) {
|
|
@@ -490,6 +514,14 @@ export class ClaustrumScopedCustody {
|
|
|
490
514
|
identity.accountIdentity !== kept.attempt.expectedAccountIdentity)
|
|
491
515
|
this.forget(id);
|
|
492
516
|
}
|
|
517
|
+
for (const [id, served] of this.#usageServed) {
|
|
518
|
+
const identity = current.get(id);
|
|
519
|
+
if (!identity?.enabled ||
|
|
520
|
+
identity.state !== 'active' ||
|
|
521
|
+
identity.credentialType !== served.credentialType ||
|
|
522
|
+
identity.accountIdentity !== served.accountIdentity)
|
|
523
|
+
this.forget(id);
|
|
524
|
+
}
|
|
493
525
|
}
|
|
494
526
|
/** A frozen, non-secret summary for a plugin's status display. */
|
|
495
527
|
keptReceiptState() {
|
|
@@ -527,6 +559,7 @@ export class ClaustrumScopedCustody {
|
|
|
527
559
|
}
|
|
528
560
|
catch (error) {
|
|
529
561
|
this.#kept.clear();
|
|
562
|
+
this.#clearUsageOwnership();
|
|
530
563
|
throw error;
|
|
531
564
|
}
|
|
532
565
|
if (this.#outage && kept) {
|
|
@@ -536,6 +569,7 @@ export class ClaustrumScopedCustody {
|
|
|
536
569
|
try {
|
|
537
570
|
const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
|
|
538
571
|
this.#kept.set(credentialId, { attempt, routeId, since: null });
|
|
572
|
+
this.#usageServed.set(credentialId, { ...identity });
|
|
539
573
|
return attempt;
|
|
540
574
|
}
|
|
541
575
|
catch (error) {
|
|
@@ -750,6 +784,25 @@ export class ClaustrumScopedCustody {
|
|
|
750
784
|
},
|
|
751
785
|
};
|
|
752
786
|
}
|
|
787
|
+
/**
|
|
788
|
+
* Queue reply quota metadata and return synchronously. Pass rate-limit
|
|
789
|
+
* headers only, never tokens: the library does not filter header names.
|
|
790
|
+
* Only credentials served by this custody and retained in its roster report.
|
|
791
|
+
* Hosts managing their own roster must call retain() when that roster changes.
|
|
792
|
+
*/
|
|
793
|
+
reportUsage(input) {
|
|
794
|
+
if (this.#closed)
|
|
795
|
+
return;
|
|
796
|
+
try {
|
|
797
|
+
this.#usage.report(input.credentialId, input.reading);
|
|
798
|
+
}
|
|
799
|
+
catch {
|
|
800
|
+
// Quota bookkeeping must never reject a provider request.
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
usageReportState() {
|
|
804
|
+
return this.#usage.state();
|
|
805
|
+
}
|
|
753
806
|
close() {
|
|
754
807
|
if (this.#closed)
|
|
755
808
|
return;
|
|
@@ -761,12 +814,24 @@ export class ClaustrumScopedCustody {
|
|
|
761
814
|
watch.stop();
|
|
762
815
|
this.#watches.clear();
|
|
763
816
|
this.#kept.clear();
|
|
764
|
-
this.#
|
|
817
|
+
const usage = this.#usage.close();
|
|
818
|
+
if (usage) {
|
|
819
|
+
this.#tokenReads.add(usage);
|
|
820
|
+
void usage.then(() => this.#tokenReads.delete(usage));
|
|
821
|
+
}
|
|
822
|
+
else
|
|
823
|
+
this.#client.close();
|
|
824
|
+
this.#disposing = drainShutdown(this.#tokenReads, (count) => (this.#onDrainTimeout ?? this.#warnShutdown)(count)).finally(() => {
|
|
825
|
+
this.#usage.drop();
|
|
826
|
+
this.#usageServed.clear();
|
|
827
|
+
if (usage)
|
|
828
|
+
this.#client.close();
|
|
829
|
+
});
|
|
765
830
|
}
|
|
766
|
-
/** Stop
|
|
831
|
+
/** Stop accepting work; give token reads and reply reports one shared 2 s drain. */
|
|
767
832
|
async dispose(onTimeout = this.#warnShutdown) {
|
|
833
|
+
this.#onDrainTimeout = onTimeout;
|
|
768
834
|
this.close();
|
|
769
|
-
this.#disposing ??= drainShutdown(this.#tokenReads, onTimeout);
|
|
770
835
|
await this.#disposing;
|
|
771
836
|
}
|
|
772
837
|
}
|