@cortexkit/opencode-openai-auth 1.0.1 → 1.0.2

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/index.js CHANGED
@@ -1 +1 @@
1
- import{Aa as u,Ba as v,Ca as w,Da as x,Ea as y,Fa as z,Ga as A,Ha as B,Ia as C,Ja as D,Ka as E,e as a,f as b,ia as c,ja as d,ka as e,la as f,ma as g,na as h,oa as i,pa as j,qa as k,ra as l,sa as m,ta as n,ua as o,va as p,wa as q,xa as r,ya as s,za as t}from"./index-ww91hyzr.js";import"./index-eqh53k8v.js";import"./index-jyr8y8k4.js";import"./index-rv08jmd4.js";import"./index-8kj7sa1p.js";import"./index-bmd7x5aq.js";import"./index-766sfrh5.js";import"./index-b3q3j39x.js";export{B as rewriteResponsesLiteBody,z as resolveSidebarSessionId,a as parseJwtClaims,w as mergePushedQuotaMetadata,k as getMainRefreshLockName,v as findCachekeepFallbackAccount,b as extractAccountIdFromClaims,E as default,r as createResetTargetResolver,e as codexOAuthModelListed,f as codexOAuthModelLimit,y as buildSidebarState,x as buildSidebarMachineState,s as buildResetRedemptionDeps,o as __resetBootQuotaSeedForTest,t as __menuContextForTest,n as __bootQuotaSeedPromiseForTest,q as ResetTargetResolutionError,h as RESPONSES_LITE_MODELS,u as POOL_MIGRATION_ENABLED,D as OpenAIAuthPlugin,A as MID_CONVERSATION_EFFORT_MODELS,l as MAIN_REFRESH_LOCK_TTL_MS,m as MAIN_REFRESH_LEASE_TTL_MS,g as EMPTY_BEARER_MESSAGE,d as DISALLOWED_MODELS,C as CodexAuthPlugin,i as CODEX_VERSION,j as CODEX_USER_AGENT,p as AuthPersistError,c as ALLOWED_MODELS};
1
+ import{Aa as u,Ba as v,Ca as w,Da as x,Ea as y,Fa as z,Ga as A,Ha as B,Ia as C,Ja as D,Ka as E,e as a,f as b,ia as c,ja as d,ka as e,la as f,ma as g,na as h,oa as i,pa as j,qa as k,ra as l,sa as m,ta as n,ua as o,va as p,wa as q,xa as r,ya as s,za as t}from"./index-m9d2bfkn.js";import"./index-eqh53k8v.js";import"./index-jyr8y8k4.js";import"./index-rv08jmd4.js";import"./index-8kj7sa1p.js";import"./index-bmd7x5aq.js";import"./index-766sfrh5.js";import"./index-b3q3j39x.js";export{B as rewriteResponsesLiteBody,z as resolveSidebarSessionId,a as parseJwtClaims,w as mergePushedQuotaMetadata,k as getMainRefreshLockName,v as findCachekeepFallbackAccount,b as extractAccountIdFromClaims,E as default,r as createResetTargetResolver,e as codexOAuthModelListed,f as codexOAuthModelLimit,y as buildSidebarState,x as buildSidebarMachineState,s as buildResetRedemptionDeps,o as __resetBootQuotaSeedForTest,t as __menuContextForTest,n as __bootQuotaSeedPromiseForTest,q as ResetTargetResolutionError,h as RESPONSES_LITE_MODELS,u as POOL_MIGRATION_ENABLED,D as OpenAIAuthPlugin,A as MID_CONVERSATION_EFFORT_MODELS,l as MAIN_REFRESH_LOCK_TTL_MS,m as MAIN_REFRESH_LEASE_TTL_MS,g as EMPTY_BEARER_MESSAGE,d as DISALLOWED_MODELS,C as CodexAuthPlugin,i as CODEX_VERSION,j as CODEX_USER_AGENT,p as AuthPersistError,c as ALLOWED_MODELS};
package/dist/v2/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import{$ as F1,A as N1,Aa as W$,B as D1,C as a1,D as o1,E as r1,F as t1,G as e1,Ga as t2,H as I2,Ha as e2,I as $$,J as A1,K as Y$,Ka as H$,L as Z$,M as K$,N as O1,O as x1,P as k2,Q as j2,R as U2,S as z$,T as X$,U as J$,V as j$,W as v2,X as Q$,Y as G$,Z as R2,_ as C1,aa as P1,ba as T1,c as h1,ca as M1,d as f1,da as L1,e as W2,ea as B$,f as H2,fa as V$,g as l1,ga as V2,h as p1,ha as _1,i as J1,j as j1,k as Q1,ka as w1,l as E1,la as I1,m as R1,n as c1,na as a2,o as d1,oa as o2,p as G1,pa as r2,q as i1,r as B1,s as V1,t as W1,u as H1,v as N2,w as n1,x as B2,y as s1,z as U1}from"../index-ww91hyzr.js";import{Na as X1}from"../index-eqh53k8v.js";import"../index-jyr8y8k4.js";import"../index-rv08jmd4.js";import"../index-8kj7sa1p.js";import{gc as J2}from"../index-bmd7x5aq.js";import"../index-766sfrh5.js";import{wc as g1,xc as u1}from"../index-b3q3j39x.js";class d 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 s($){return`common-auth-placeholder.${$}`}function i2($){let Z=s($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function z2($,Z){if($?.type!=="oauth")return!1;let X=Z===void 0?void 0:s(Z),z=(j)=>X===void 0?j.startsWith("common-auth-placeholder."):j===X;return z($.access)&&z($.refresh)}var n2="No browser sign-in: this connects the plugin to the accounts in its vault.";async function M2($,Z){let X=Z.now??Date.now,{integrationID:z}=Z,j=(P)=>i2({integrationID:z,methodID:P,now:X()}),B=async(P,A)=>{return await Z.onLogin(P,{integrationID:z,methodID:A}),j(A)},F=(P)=>async(A)=>{let H=P.method.id,W=await P.authorize(A),O={url:W.url,instructions:W.instructions,...W.expiresAt===void 0?{}:{expiresAt:W.expiresAt}};if(W.mode==="auto")return{...O,mode:"auto",callback:W.callback.then((x)=>B(x,H))};let w=W.callback;return{...O,mode:"code",callback:async(x)=>B(await w(x),H)}};return $.integration.transform((P)=>{let A=Z.label===void 0?{}:{label:()=>Z.label};for(let O of Z.methods)P.method.update({integrationID:z,method:O.method,authorize:F(O),refresh:async(w)=>{if(!z2(w,z))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return j(w.methodID)},...A});let H=Z.vault;if(H===void 0)return;let W=H.method.id;P.method.update({integrationID:z,method:H.method,authorize:async()=>({url:"",instructions:H.instructions??n2,mode:"auto",callback:Promise.resolve().then(()=>H.activate({integrationID:z,methodID:W})).then(()=>j(W))}),refresh:async(O)=>{if(!z2(O,z)||O.methodID!==W)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return j(W)},...A})})}function F$($){let Z=[],X;for(let z of $.split(/\r?\n/))if(z.startsWith("data:"))Z.push(z.slice(5).replace(/^ /,""));else if(z.startsWith("event:"))X=z.slice(6).trim();if(Z.length===0)return;return X===void 0?{data:Z.join(`
1
+ import{$ as F1,A as N1,Aa as W$,B as D1,C as a1,D as o1,E as r1,F as t1,G as e1,Ga as t2,H as I2,Ha as e2,I as $$,J as A1,K as Y$,Ka as H$,L as Z$,M as K$,N as O1,O as x1,P as k2,Q as j2,R as U2,S as z$,T as X$,U as J$,V as j$,W as v2,X as Q$,Y as G$,Z as R2,_ as C1,aa as P1,ba as T1,c as h1,ca as M1,d as f1,da as L1,e as W2,ea as B$,f as H2,fa as V$,g as l1,ga as V2,h as p1,ha as _1,i as J1,j as j1,k as Q1,ka as w1,l as E1,la as I1,m as R1,n as c1,na as a2,o as d1,oa as o2,p as G1,pa as r2,q as i1,r as B1,s as V1,t as W1,u as H1,v as N2,w as n1,x as B2,y as s1,z as U1}from"../index-m9d2bfkn.js";import{Na as X1}from"../index-eqh53k8v.js";import"../index-jyr8y8k4.js";import"../index-rv08jmd4.js";import"../index-8kj7sa1p.js";import{gc as J2}from"../index-bmd7x5aq.js";import"../index-766sfrh5.js";import{wc as g1,xc as u1}from"../index-b3q3j39x.js";class d 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 s($){return`common-auth-placeholder.${$}`}function i2($){let Z=s($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function z2($,Z){if($?.type!=="oauth")return!1;let X=Z===void 0?void 0:s(Z),z=(j)=>X===void 0?j.startsWith("common-auth-placeholder."):j===X;return z($.access)&&z($.refresh)}var n2="No browser sign-in: this connects the plugin to the accounts in its vault.";async function M2($,Z){let X=Z.now??Date.now,{integrationID:z}=Z,j=(P)=>i2({integrationID:z,methodID:P,now:X()}),B=async(P,A)=>{return await Z.onLogin(P,{integrationID:z,methodID:A}),j(A)},F=(P)=>async(A)=>{let H=P.method.id,W=await P.authorize(A),O={url:W.url,instructions:W.instructions,...W.expiresAt===void 0?{}:{expiresAt:W.expiresAt}};if(W.mode==="auto")return{...O,mode:"auto",callback:W.callback.then((x)=>B(x,H))};let w=W.callback;return{...O,mode:"code",callback:async(x)=>B(await w(x),H)}};return $.integration.transform((P)=>{let A=Z.label===void 0?{}:{label:()=>Z.label};for(let O of Z.methods)P.method.update({integrationID:z,method:O.method,authorize:F(O),refresh:async(w)=>{if(!z2(w,z))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return j(w.methodID)},...A});let H=Z.vault;if(H===void 0)return;let W=H.method.id;P.method.update({integrationID:z,method:H.method,authorize:async()=>({url:"",instructions:H.instructions??n2,mode:"auto",callback:Promise.resolve().then(()=>H.activate({integrationID:z,methodID:W})).then(()=>j(W))}),refresh:async(O)=>{if(!z2(O,z)||O.methodID!==W)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return j(W)},...A})})}function F$($){let Z=[],X;for(let z of $.split(/\r?\n/))if(z.startsWith("data:"))Z.push(z.slice(5).replace(/^ /,""));else if(z.startsWith("event:"))X=z.slice(6).trim();if(Z.length===0)return;return X===void 0?{data:Z.join(`
2
2
  `)}:{event:X,data:Z.join(`
3
3
  `)}}function L2($,Z){let X=new TextDecoder,z="",j=(F)=>{let P=F$(F);if(!P)return;try{$(P)}catch(A){Z(A)}},B=()=>{for(;;){let F=/\r?\n\r?\n/.exec(z);if(!F)return;let P=z.slice(0,F.index);z=z.slice(F.index+F[0].length),j(P)}};return new TransformStream({transform(F,P){P.enqueue(F),z+=X.decode(F,{stream:!0}),B()},flush(){if(z+=X.decode(),B(),z.trim()!=="")j(z);z=""}})}var s2=512,$2="x-common-auth-attempt",e=($,Z)=>JSON.stringify([$,Z]),a=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function P$($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function T$($,Z){let X=$.getReader();return new ReadableStream({async pull(z){let j;try{j=await X.read()}catch(B){Z({reason:"failed",message:B instanceof Error?B.message:String(B)}),z.error(B);return}if(j.done)Z(),z.close();else z.enqueue(j.value)},async cancel(z){Z({reason:"cancelled",...z===void 0?{}:{message:String(z)}}),await X.cancel(z)}})}function _2($,Z){for(let[X,z]of Object.entries(Z)){let j=X.toLowerCase();for(let B of Object.keys($))if(B.toLowerCase()===j)delete $[B];if(z!==null)$[X]=z}}function M$($,Z){for(let[X,z]of Object.entries(Z))if(z===null)$.delete(X);else $.set(X,z)}async function q2($,Z,X={}){let{providerID:z}=Z,j=X.gateOnPlaceholder,B=(Y)=>j===void 0||j.credential(Y)===s(z),F=X.logger,P=Math.max(1,X.maxRecords??s2),A=[...X.hostCredentials??[s(z)],...j?[s(z)]:[]].filter((Y)=>Y!==""),H=new Map,W=new WeakMap,O=new Map,w=new Set,x=new Map,b=!1,r=!1,c=new Map,v=0,u=!1,m=new Map,I=(Y,K)=>{try{F?.warn(Y,K)}catch{}},J=(Y)=>Y instanceof Error?Y.message:String(Y),V=async(Y,K)=>{let Q=c.get(Y);if(!Q||Q.size===0)return;await Promise.all([...Q].map(async(G)=>{try{await G(K)}catch(_){I("opencode2 auth listener threw; the request is unaffected",{event:Y,error:J(_)})}}))},M=async(Y,K)=>{try{await Z.onAttemptEnd?.(Y,K)}catch(Q){I("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:Y.attemptId,error:J(Q)})}},T=(Y,K)=>{if(Y.ended||!Y.attempt)return;let Q={...Y.status===void 0?{}:{status:Y.status},outputStarted:Y.outputStarted,...Y.limit?{limit:Y.limit.signal}:{},...K?{error:K}:{}};if(K)Y.endError=K;Y.ended=M(Y.attempt,Q)},R=(Y,K)=>T(Y,{reason:"abandoned",message:K}),L=(Y)=>[...H.values()].filter((K)=>K.key===Y),D=(Y)=>L(Y).at(-1),k=(Y)=>{if(H.delete(Y.id),!L(Y.key).length)O.delete(Y.key)},S=(Y)=>{H.set(Y.id,Y);while(H.size>P){let K=H.values().next().value;if(K===void 0)break;R(K,"dropped to keep the record bound"),k(K)}},g=(Y)=>Y.accountId===void 0?void 0:{...Y.scope,accountId:Y.accountId},p=(Y,K)=>new d({kind:"no-account",providerID:z,sessionID:Y.sessionID,requestKind:Y.kind,...K===void 0?{}:{message:K}}),l=(Y)=>{m.get(Y)?.clear(),m.delete(Y)},U=async(Y,K)=>{let Q=()=>p(Y,`${z} ${Y.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(u)throw Q();let G=m.get(Y.sessionID);if(!G)G=new Set,m.set(Y.sessionID,G);let _={};G.add(_);let E=()=>{if(!G.has(_))throw Q()};try{return await K(E)}finally{if(G.delete(_),G.size===0&&m.get(Y.sessionID)===G)m.delete(Y.sessionID)}},N=(Y,K)=>{for(let[Q,G]of K)if(A.some((_)=>G.includes(_)))throw new d({kind:"host-credential-on-wire",providerID:z,sessionID:Y.sessionID,requestKind:Y.kind,message:`${z} ${Y.kind} request still carries the host's placeholder credential in ${Q}; the adapter's account headers must replace it`})},h=(Y)=>{for(let K of L(Y))if(K.ended||!K.attempt)k(K);else if(K.transport==="ws"||K.judged)R(K,"a newer attempt of its session and kind began"),k(K)},f=async(Y,K,Q,G)=>{let _=e(Y.sessionID,Y.kind),E=O.get(_);O.delete(_);let C=E?.accountId??D(_)?.accountId;h(_);let q={...Y,...C===void 0?{}:{previousAccountId:C},...E?.rerouteFrom===void 0?{}:{rerouteFrom:E.rerouteFrom}},y=await Z.chooseAccount(q);Q();let n={},c2;if(y!==void 0){let Q2=await Z.accountHeaders({...Y,accountId:y});if(Q(),P$(Q2))n=Q2.headers,c2=Q2.attempt;else n=Q2}let d2=`attempt-${++v}`,K2={id:d2,key:_,scope:Y,accountId:y,headers:n,attempt:y===void 0?void 0:{...Y,accountId:y,attemptId:d2,transport:G,data:c2},...G===void 0?{}:{transport:G},outputStarted:!1};if(S(K2),K2.attempt)V("select",{...Y,accountId:K2.attempt.accountId,hook:K,...q.previousAccountId===void 0?{}:{previousAccountId:q.previousAccountId},...q.rerouteFrom===void 0?{}:{rerouteFrom:q.rerouteFrom},handle:K2.attempt});return K2},Z2=async(Y,K,Q,G,_)=>{let E=e(Y.sessionID,Y.kind),C=G===void 0?void 0:H.get(G);if(C?.key!==E)C=void 0;if(!C){if(C=D(E),L(E).filter((y)=>y.transport===void 0&&!y.ended).length>1&&!r)r=!0,I("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:Y.sessionID,kind:Y.kind})}if(!C||C.transport!==void 0||C.ended)C=await f(Y,K,_,Q);else if(C.transport=Q,C.attempt)C.attempt.transport=Q;if(Q==="ws"){for(let q of L(E))if(q!==C&&q.transport==="ws")R(q,"a newer attempt of its session and kind went out over WebSocket")}return C},F2=async(Y,K)=>{try{return await K()}catch(Q){throw T(Y,{reason:"failed",message:J(Q)}),Q}},f2=(Y,K)=>{let Q=L(e(Y,K)).filter((G)=>G.transport==="ws").at(-1);return Q?.attempt!==void 0&&!Q.ended?Q:void 0},P2=(Y,K,Q)=>{let G=g(Y);if(!G||!Y.attempt||Y.limit)return;Y.limit={signal:K,delivered:V("limit",{...G,via:Q,limit:K,outputStarted:Y.outputStarted,handle:Y.attempt})}},m2=(Y,K,Q,G)=>{let _=g(Y);if(!_||!Y.attempt)return;V("quota",{..._,transport:K,...G===void 0?{}:{status:G},quota:Q,handle:Y.attempt})},g2=(Y,K,Q,G)=>{let _=Y.attempt;if(!_)return;let E=Z.inspectEvent?.(G===void 0?{transport:K,data:Q,attempt:_}:{transport:K,data:Q,event:G,attempt:_});if(!E)return;if(E.quota!==void 0)m2(Y,K,E.quota);if(E.outputStarted)Y.outputStarted=!0;if(E.limit)P2(Y,E.limit,K);if(E.error!==void 0)T(Y,{reason:"failed",message:E.error});else if(E.done)T(Y)},U$=(Y,K)=>{let Q=Y.attempt;if(!Q||K.accountId===Y.accountId)return;if(Q.reboundFrom??=Q.accountId,Q.accountId=K.accountId,"data"in K)Q.data=K.data;Y.accountId=K.accountId},N$=(Y)=>!Y.attempt||Y.endError!==void 0||Y.status!==void 0&&Y.status>=400,C$=(Y)=>{let K=[...H.values()].filter((q)=>q.scope.sessionID===Y),Q=K.filter((q)=>q.limit&&!q.rerouted).at(-1);if(Q)return Q;let G=K.filter((q)=>q.scope.kind==="primary"),_=G.length>0?G:K;if(_.length<=1)return _[0];let E=_.filter((q)=>!q.judged&&N$(q)).at(-1);if(E)return E;let C=_.filter((q)=>q.attempt&&!q.ended);if(C.length>1)return"ambiguous";return C[0]??_.at(-1)},t={providerID:z},o=[];o.push(await $.session.hook("model.request",(Y)=>{if(j)return;return U(a(Y),async(K)=>{let Q=await f(a(Y),"model.request",K);if(K(),Q.accountId===void 0)throw p(Q.scope);_2(Y.headers,{...Q.headers,[$2]:Q.id})})},t)),o.push(await $.session.hook("http.request",(Y)=>{if(j){let K=B(Y.request.headers);if(x.set(Y.sessionID,K),!K)return}return U(a(Y),async(K)=>{let Q=Y.request.headers.get($2)??void 0,G=j?await f(a(Y),"http.request",K,"http"):await Z2(a(Y),"http.request","http",Q,K);K();let _=g(G),E=G.attempt;if(!_||!E)throw p(G.scope);await F2(G,async()=>{let C=Y.request;if(Z.rewriteRequest){if(Q!==void 0){let n=new Headers(C.headers);n.delete($2),C=new Request(C,{headers:n})}C=await Z.rewriteRequest({..._,request:C,attempt:E})??C,K()}let q=new Headers(C.headers);q.delete($2),M$(q,G.headers),N(G.scope,q.entries());let y=new Request(C,{headers:q});W.set(y,G),Y.request=y})})},t)),o.push(await $.session.hook("http.response",async(Y)=>{let K=W.get(Y.request);if(!K){if(j)return;if(!b)b=!0,I("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:Y.sessionID,kind:Y.kind});return}let Q=Y.response;if(Z.answeredBy&&K.attempt){let q=K.attempt,y=await F2(K,async()=>Z.answeredBy?.({request:Y.request,response:Q,attempt:q}));if(y)U$(K,y)}let G=g(K),_=K.attempt;if(!G||!_)return;K.status=Q.status;let E=Z.quotaFromHeaders?.(Q.headers,Q.status,_);if(E!==void 0)m2(K,"http",E,Q.status);if(!Q.ok&&Z.limitFromResponse){let q=await Z.limitFromResponse({status:Q.status,headers:Q.headers,body:()=>Q.clone().text(),attempt:_});if(q)P2(K,q,"http")}if(!Q.ok||!Q.body)T(K);let C=Q;if(Q.body&&(Z.inspectEvent||Z.onAttemptEnd)){let q=Q.body;if(Z.inspectEvent)q=q.pipeThrough(L2((y)=>g2(K,"http",y.data,y.event),(y)=>I("opencode2 auth event inspection threw",{error:J(y)})));C=new Response(T$(q,(y)=>T(K,y)),{status:Q.status,statusText:Q.statusText,headers:Q.headers})}if(Z.rewriteResponse)C=await Z.rewriteResponse({...G,request:Y.request,response:C,attempt:_})??C;if(C!==Q)Y.response=C},t)),o.push(await $.session.hook("experimental.ws.handshake",(Y)=>{if(j){let K=B(new Headers(Y.headers)),Q=e(Y.sessionID,Y.kind);if(x.set(Y.sessionID,K),w.delete(Q),!K)return}return U(a(Y),async(K)=>{let Q;for(let C of Object.keys(Y.headers)){if(C.toLowerCase()!==$2)continue;Q??=Y.headers[C],delete Y.headers[C]}let G=j?await f(a(Y),"experimental.ws.handshake",K,"ws"):await Z2(a(Y),"experimental.ws.handshake","ws",Q,K);K();let _=g(G),E=G.attempt;if(!_||!E)throw p(G.scope);await F2(G,async()=>{_2(Y.headers,G.headers);let C=Z.rewriteHandshakeURL?.({..._,url:Y.url,attempt:E});if(C!==void 0)Y.url=C;if(N(G.scope,Object.entries(Y.headers)),j)w.add(G.key)})})},t));let u2=Z.rewriteWebSocketFrame?.bind(Z);if(u2)o.push(await $.session.hook("experimental.ws.send",async(Y)=>{let K=a(Y);if(j&&!w.has(e(K.sessionID,K.kind)))return;let Q=f2(K.sessionID,K.kind),G=await u2({...K,attempt:Q?.attempt,frame:Y.frame});if(G!==void 0)Y.frame=G},t));o.push(await $.session.hook("experimental.ws.receive",(Y)=>{if(j&&!w.has(e(Y.sessionID,Y.kind)))return;let K=f2(Y.sessionID,Y.kind);if(!K)return;try{g2(K,"ws",Y.frame)}catch(Q){I("opencode2 auth frame inspection threw",{error:J(Q)})}},t)),o.push(await $.session.hook("retry",async(Y)=>{if(j&&x.get(Y.sessionID)!==!0)return;let K=C$(Y.sessionID);if(!K)return;let Q=Y.decision;if(K==="ambiguous"){await V("retry",{sessionID:Y.sessionID,attempt:Y.attempt,reason:"host-decides",hostDecision:Q,decision:Q});return}let G=K;await U(G.scope,async(_)=>{G.judged=!0;let E=Q,C,q,y=G.attempt;if(G.accountId===void 0||!y)E={retry:!1},C="no-account";else if(G.outputStarted)E={retry:!1},C="output-started";else{if(!G.limit){let n=Z.limitFromError?.(Y.error,y);if(n)P2(G,n,"error")}if(G.ended)await G.ended,_();if(G.limit)await G.limit.delivered,_(),G.rerouted=!0,q={accountId:G.accountId,limit:G.limit.signal},E={retry:!0,delay:0},C="reroute";else C="host-decides"}if(Y.decision=E,E.retry&&G.accountId!==void 0)O.set(G.key,{sessionID:G.scope.sessionID,accountId:G.accountId,...q===void 0?{}:{rerouteFrom:q}});await V("retry",{sessionID:Y.sessionID,...G.accountId===void 0?{}:{accountId:G.accountId},kind:G.scope.kind,attempt:Y.attempt,reason:C,hostDecision:Q,decision:E,...y===void 0?{}:{handle:y}})})},t));let l2=(Y)=>{l(Y),x.delete(Y);for(let K of w)if(JSON.parse(K)[0]===Y)w.delete(K);for(let K of[...H.values()]){if(K.scope.sessionID!==Y)continue;R(K,"its session was forgotten"),H.delete(K.id)}for(let[K,Q]of O)if(Q.sessionID===Y)O.delete(K)},T2=new AbortController,p2=$.event;if(p2)(async()=>{try{for await(let Y of p2.subscribe({signal:T2.signal}))if(Y.type==="session.deleted")l2(Y.data.sessionID)}catch(Y){if(!T2.signal.aborted)I("opencode2 auth stopped listening for session deletion",{error:J(Y)})}})();return{on(Y,K){let Q=c.get(Y);if(!Q)Q=new Set,c.set(Y,Q);let G=K;return Q.add(G),()=>{Q.delete(G)}},accountFor(Y,K){return D(e(Y,K))?.accountId},forgetSession:l2,get size(){return H.size},async dispose(){if(u)return;u=!0;for(let Y of m.keys())l(Y);T2.abort();for(let Y of H.values())R(Y,"the installation was disposed");H.clear(),O.clear(),w.clear(),x.clear(),c.clear(),await Promise.all(o.map(async(Y)=>{try{await Y.dispose()}catch(K){I("opencode2 auth hook did not dispose cleanly",{error:J(K)})}}))}}}var x2={version:o2,"user-agent":r2,originator:"codex_exec"},L$="x-openai-internal-codex-responses-lite",_$=1024,q$=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,G2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),x$=($)=>G2($)&&($.type==="message"||("role"in $))&&$.role==="user",S$=($)=>G2($)&&$.type==="configuration_update";class S2{#$=new Map;apply($,Z,X){if(Z.kind!=="primary")return!1;let z=typeof $.model==="string"?$.model:"";if(!t2.has(z))return!1;if(q$.test(z))return!1;let j=G2($.reasoning)?$.reasoning:void 0,B=typeof j?.effort==="string"?j.effort:void 0;if(!B)return!1;let F=this.#$.get(Z.sessionID);if(F===void 0)return this.#Y(Z.sessionID,B),!1;if(B===F)return!1;let P=Array.isArray($.input)?$.input:void 0;if(!P||P.length===0)return!1;let A=P.findLastIndex(x$);if(A<0){if(X==="http")return!1;return $.reasoning={...j,effort:F},!0}if($.reasoning={...j,effort:F},!S$(P[A-1]))P.splice(A,0,{type:"configuration_update",reasoning:{effort:B}});return!0}forget($){this.#$.delete($)}#Y($,Z){this.#$.set($,Z);while(this.#$.size>_$){let X=this.#$.keys().next().value;if(X===void 0)break;this.#$.delete(X)}}}function E$($){if(typeof $.model!=="string"||!a2.has($.model))return!1;return e2($),!0}function $1($){try{let Z=JSON.parse($);return G2(Z)?Z:void 0}catch{return}}async function Y1($,Z,X,z){if($.method.toUpperCase()!=="POST"||$.body===null)return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let j=$1(await $.clone().text());if(!j)return;let B="max_output_tokens"in j;delete j.max_output_tokens;let F=X.apply(j,Z,"http"),P=z&&E$(j);if(!B&&!F&&!P)return;let A=new Headers($.headers);if(A.delete("content-length"),P)A.set(L$,"true");return new Request($,{headers:A,body:JSON.stringify(j)})}function Z1($,Z,X){let z=$1($);if(z?.type!=="response.create")return;let j="max_output_tokens"in z;delete z.max_output_tokens;let B=X.apply(z,Z,"ws");return j||B?JSON.stringify(z):void 0}function R$($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function E2($,Z){let X=new URL($);if(X.origin!=="https://api.openai.com"&&X.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(X.pathname))return $;let z=new URL(`${R$(Z)}/responses`);if(z.search=X.search,X.protocol==="ws:"||X.protocol==="wss:")z.protocol=z.protocol==="https:"?"wss:":"ws:";return z.href}var i="openai",D$=60000,K1=1,A$="request refused: no account with a usable credential",O$=1024,Y2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function D2($){try{return JSON.parse($)}catch{return}}function z1($){let Z=W2($);return Z?H2(Z):void 0}var b$=new Set(["usage_limit_reached","rate_limit_exceeded"]);function A2($,Z,X){return{reason:$.window,...X!==void 0?{status:X}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function k$($,Z){let X=V2($);if(X){let B=typeof $.status==="number"?$.status:void 0;return A2(X,Z,B)}if($.type!=="response.failed"||!Y2($.response))return;let z=$.response.failed;if(Y2(z)&&typeof z.rate_limit_reached_type==="string")return{reason:z.rate_limit_reached_type};let j=$.response.error;if(Y2(j)){let B=typeof j.code==="string"?j.code:typeof j.type==="string"?j.type:void 0;if(B&&b$.has(B))return{reason:B}}return}function y$($,Z){let X=D2($);if(!Y2(X))return;let z=typeof X.type==="string"?X.type:void 0;if(z==="codex.rate_limits")return{quota:{snapshot:Q1(X),complete:!0}};let j=k$(X,Z);if(j)return{limit:j};if(z===void 0||z==="error")return;return _1(z)?void 0:{outputStarted:!0}}function w$($){let Z=!1;for(let X of $.keys())if(X.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:J1($),complete:j1($)}}function I$($){let Z=$.get("retry-after");if(Z===null)return;let X=Number(Z);return Number.isFinite(X)&&X>=0?X*1000:void 0}function q1($){let{source:Z,pins:X}=$,z=$.now??Date.now,j=$.log,B=$.vault,F=new S2,P=new Map,A=(J)=>`${J.sessionID}\x00${J.kind}\x00${J.accountId}`,H=new Map,W=new Map,O=(J,V)=>{W.delete(J),W.set(J,V);while(W.size>O$){let M=W.keys().next().value;if(M===void 0)break;W.delete(M)}},w=(J,V,M)=>{let T=M?[]:L1(Z.peek().rows,J,V,B?.identities()??new Set),R=(B?.routes()??[]).filter((L)=>L.kind==="oauth"&&B1(B2(L.quota),J,V));return[...T.map((L)=>({id:L.id,...L.identity!==void 0?{identity:L.identity}:{},quota:L.quota,row:L})),...R.map((L)=>({id:L.id,...L.identity!==void 0?{identity:L.identity}:{},quota:L.quota}))]},x=(J,V,M)=>{let T=new Map;if(V1(V))for(let S of J)T.set(S.id,H1(B2(S.quota),V,S.id===R2?void 0:S.id,M));let R=J.map((S)=>({id:S.id,kind:"oauth",...X1(S.quota)?{quota:S.quota}:{}})),L=J.flatMap((S)=>S.row?[S.row]:[]),D=new Set(J.filter((S)=>!S.row).map((S)=>S.id)),k=Z.rateLimitMarks(L);for(let S of D){let g=H.get(S);if(g===void 0)continue;if(g<=M)H.delete(S);else k.set(S,g)}return{rows:R,now:M,rateLimitMarks:k,refreshBackoff:Z.refreshBackoffFor(L),killswitch:T,requestPull:(S)=>D.has(S)?B?.requestReading(S):Z.requestReading(S)}},b=(J,V,M,T)=>{let R=F1({...J,placement:C1(V)});if(R.kind==="block"){j?.debug("pool admission refused the request",{reason:R.block.reason});return}let L=R.order.filter((D)=>!M.has(D));if(T!==void 0&&L.includes(T))return T;return L[0]},r=(J,V,M,T,R,L)=>{let D={requestBytes:K1,reservePercent:(N)=>W1(M,N===R2?void 0:N),resetCredits:()=>{return}},k=P1(J),S=(N,h)=>X.place({sessionId:T,requestBytes:K1,validPinnedAccountIds:J.rows.map((f)=>f.id).filter((f)=>!k.excluded.has(f)),excludeAccountIds:N,quotaCheckedAtByAccount:Object.fromEntries(J.rows.map((f)=>[f.id,k.projections.get(f.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(V.map((f)=>[f.id,f.identity])),select:(f)=>T1(J,D,new Set(N),f),persist:h}),g=[...R],p=S(g,L);if(!p)return;let l=p.accountId,U=M1(J,D,l);if(U.kind==="none")return;if(U.kind==="move"){let N=S([...g,l],L);if(N)return N.accountId;return U.reason==="killswitch"?void 0:l}if(U.kind==="detour")return S([...g,l],!1)?.accountId;return l},u={providerID:i,chooseAccount:async(J)=>{let V=await B?.authority(),M=await $.storage(),T=V!==void 0&&V!=="local",R=()=>{throw new d({kind:"no-account",providerID:i,sessionID:J.sessionID,requestKind:J.kind,message:U2})};if(T)await $.awaitVaultRoster?.();else{if(!(await Z.current()).active){if(await $.slotPlaceholderWithoutMain?.())R();j?.warn("the account pool does not serve requests yet; refusing the request",{kind:J.kind});return}await Z.prepareTokens(Z.peek().rows,M)}let L=z(),D=w(M,L,T),k=new Map(D.map((h)=>[h.id,h])),S=x(D,M,L),g=new Set(J.rerouteFrom?[J.rerouteFrom.accountId]:[]),p=M?.routing?.mode??"main-first",l=J.kind==="primary",U=new Set,N;for(;;){let h=new Set([...g,...U]);if(N=void 0,p==="sticky-balanced")N=r(S,D,M,J.sessionID,h,l&&U.size===0);if(N??=b(S,p,h,l?void 0:W.get(J.sessionID)),N===void 0||U.has(N)){N=void 0;break}let f=k.get(N)?.row;if(f){if(Z.usableToken(f)!==void 0)break;j?.debug("pool row holds no usable token; choosing again",{accountId:N})}else{if(!B)break;let Z2=await B.authorize(N);if(Z2){P.set(A({...J,accountId:N}),Z2);break}j?.debug("the vault refused to serve an account; choosing again",{accountId:N})}U.add(N)}if(N===void 0&&!T&&D.length===0&&await $.slotPlaceholderWithoutMain?.())R();if(N===void 0&&T&&B&&(D.length===0||U.size>0)){let h=U.size>0?"vault-refused":N1(B);throw j?.warn("vault mode: no vault account can serve; refusing the request",{cause:h}),new d({kind:"no-account",providerID:i,sessionID:J.sessionID,requestKind:J.kind,message:U1[h]})}if(N!==void 0&&l)O(J.sessionID,N);return j?.debug("pool account chosen",{kind:J.kind,accountId:N,mode:p,...J.rerouteFrom?{rerouteFrom:J.rerouteFrom.accountId}:{}}),N},accountHeaders:async(J)=>{let{accountId:V}=J,M=()=>new d({kind:"no-account",providerID:i,sessionID:J.sessionID,requestKind:J.kind,message:A$}),T=B&&await B.authority()!=="local"?void 0:Z.peek().rows.find((D)=>D.id===V);if(!T&&B){let D=A(J),k=P.get(D)??await B.authorize(V);if(P.delete(D),!k)throw j?.warn("the vault refused to serve an account; refusing the request",{accountId:V}),M();return{headers:{...x2,"session-id":J.sessionID,authorization:`Bearer ${k.accessToken}`,"chatgpt-account-id":k.accountIdentity??z1(k.accessToken)??null},attempt:{kind:"vault",routeId:V,receipt:k}}}let R=T?Z.usableToken(T):void 0;if(!T||!R)throw j?.warn("pool row holds no usable token; refusing the request",{accountId:V}),M();let L=T.identity??z1(R);return{headers:{...x2,"session-id":J.sessionID,authorization:`Bearer ${R}`,"chatgpt-account-id":L??null},attempt:{kind:"pool",token:R,credentialEpoch:T.credentialEpoch}}},async rewriteRequest({request:J,sessionID:V,kind:M}){let T=$.codexEndpoint?E2(J.url,$.codexEndpoint()):J.url,R=T===J.url?J:new Request(T,J);return await Y1(R,{sessionID:V,kind:M},F,$.responsesLite?.()??!1)??R},rewriteHandshakeURL:({url:J})=>$.codexEndpoint?E2(J,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:J,sessionID:V,kind:M})=>Z1(J,{sessionID:V,kind:M},F),quotaFromHeaders:(J)=>w$(J),async limitFromResponse({status:J,headers:V,body:M}){if(J<400)return;let T=D2(await M().catch(()=>"")),R=V2({...Y2(T)?T:{},status:J});if(!R)return;let L=z(),D=A2(R,L,J);if(D.retryAfterMs!==void 0)return D;let k=I$(V);return k===void 0?D:{...D,retryAfterMs:k}},inspectEvent:({data:J})=>y$(J,z()),limitFromError(J){let V=D2(J.message),M=V2({...Y2(V)?V:{},...J.status!==void 0?{status:J.status}:{}})??(J.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return M?A2(M,z(),J.status):void 0},async onAttemptEnd(J,V){let M=J.data;if(M?.kind!=="vault"||V.status!==401)return;j?.warn("a vault account answered 401; reporting it to the vault",{accountId:J.accountId}),await B?.reportFailure(M.receipt,401)}},m=(J,V,M)=>{let T=M.data;if(T?.kind==="vault"){B?.recordSnapshot(J,V.snapshot,V.complete,T.receipt);return}if(T?.kind!=="pool")return;if(Z.peek().rows.find((L)=>L.id===J)?.credentialEpoch!==T.credentialEpoch){j?.debug("quota reading dropped: the row holds another credential",{accountId:J});return}Z.recordSnapshot(J,V.snapshot,T.token,V.complete)},I=(J,V,M)=>{let T=z(),R=M.data?.kind==="vault",L=R?B?.routes().find((S)=>S.id===J)?.quota:Z.peek().rows.find((S)=>S.id===J)?.quota,D=G1(B2(L),V.reason,T,D$,V.retryAfterMs!==void 0?T+V.retryAfterMs:void 0);if(!R){Z.markRateLimited(J,D);return}let k=H.get(J);if(k===void 0||k<D)H.set(J,D)};return{adapter:u,attach(J){J.on("quota",(V)=>m(V.accountId,V.quota,V.handle)),J.on("limit",(V)=>{I(V.accountId,V.limit,V.handle),j?.debug("pool row refused the request",{accountId:V.accountId,via:V.via,reason:V.limit.reason,outputStarted:V.outputStarted})})},forgetSession(J){X.forget(J),W.delete(J),F.forget(J)}}}import{randomUUID as v$}from"node:crypto";import{chmod as h$,mkdir as f$,readFile as m$,rename as g$,rm as u$,stat as l$,writeFile as p$}from"node:fs/promises";import{dirname as c$,resolve as d$}from"node:path";var i$="(no OpenCode 1 logins on this machine)";function n$($=process.env){return x1($)}async function O2($){let Z;try{Z=await m$($,"utf8")}catch(z){if(z.code==="ENOENT")return;throw z}let X=JSON.parse(Z);if(!X||typeof X!=="object"||Array.isArray(X))throw Error(`${$} does not hold a JSON object`);return X}function b2($){return $===void 0?void 0:JSON.stringify($)}async function s$($){try{return(await l$($)).mode&511}catch(Z){if(Z.code==="ENOENT")return;throw Z}}function S1($=n$()){let Z=new Map;return{path:d$($),async get(X){let z=(await O2($))?.[X.path.id];return Z.set(X.path.id,b2(z)),z},async set(X){let z=X.path.id,j=await s$($),B=await O2($)??{};if(!Z.has(z)||Z.get(z)!==b2(B[z]))throw new k2;B[z]=X.body,await f$(c$($),{recursive:!0});let F=`${$}.${v$()}.tmp`;try{await p$(F,`${JSON.stringify(B,null,2)}
4
- `,{mode:j??384}),await h$(F,j??384),await g$(F,$)}catch(P){throw await u$(F,{force:!0}).catch(()=>{}),P}return Z.set(z,b2(X.body)),!0},async all(){let X=await O2($);if(!X||Object.keys(X).length===0)return{[i$]:!0};return X}}}var a$="openai-auth-pool-browser",o$="openai-auth-pool-headless",r$="openai-auth-vault",t$="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Connect to the vault or disconnect this host before trying again.";async function X2($){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 b1($){return{method:{id:r$,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await E1($.paths,$.name)!=="vault")throw Error(t$)}}}function k1($){let Z=(X,z,j)=>({method:{id:X,type:"oauth",label:z},async authorize(){if($.vault)await X2($.vault);let B=await $.beginLogin({version:$.version,headless:j});return{url:B.url,instructions:B.instructions,mode:"auto",callback:B.completion}}});return[Z(a$,"ChatGPT (openai-auth pool, browser)",!1),Z(o$,"ChatGPT (openai-auth pool, headless)",!0)]}function y2($){let Z=(X)=>typeof X==="string"?X:"";return z2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===A1||R1($)}function e$($){if($.accountId)return $.accountId;let Z=$.access?W2($.access):void 0;return Z?H2(Z):void 0}async function y1($,Z,X,z={}){if(z.vault)await X2(z.vault);if(y2(X))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let j=D1($,{rowLocks:(x)=>O1(Z,x)}),B=await j.read();if(B.status!=="ready")throw Error(`the account pool cannot be read (${B.status}); the login was not stored`);let F={type:"oauth",refresh:X.refresh,...X.access!==void 0?{access:X.access}:{},...X.expires!==void 0?{expires:X.expires}:{}},P=e$(X);if(z.vault)await X2(z.vault);let A=P!==void 0?{identity:P}:{};if(z.origin==="import"){let x=B.rows.find((b)=>P!==void 0&&b.identity===P||b.credential?.type==="oauth"&&b.credential.refresh===X.refresh);if(x)return{id:x.id,operation:"kept"}}let H=B.rows.filter((x)=>x.type==="oauth"&&!x.invalid),W=P?H.find((x)=>x.identity===P):void 0,O=B.rows.find((x)=>x.id===N2);if(W)return{id:(await j.replace(W.id,F,A)).id,operation:"replaced"};if(!O){let x=await j.add({id:N2,credential:F,...A,...X.label!==void 0?{label:X.label}:{}});return{id:x.id,operation:x.outcome==="added-disabled"?"added-disabled":"added"}}if(!O.invalid&&!O.credential)return{id:(await j.replace(N2,F,A)).id,operation:"replaced"};let w=await j.add({id:X.id,credential:F,...A,...X.label!==void 0?{label:X.label}:{}});return{id:w.id,operation:w.outcome==="added-disabled"?"added-disabled":w.outcome==="rotated"?"replaced":"added"}}function $Y($){if(!w1($.modelID??$.id)){$.enabled=!1;return}let Z=I1($.id);if(Z)$.limit={...Z}}function v1($){return $.model.transform((Z)=>{for(let X of Z.list(i))Z.update(i,String(X.id),(z)=>$Y(z))})}var YY=1024;class w2{pins=new Map;limit;constructor($=YY){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.pins.delete($)}get size(){return this.pins.size}set($,Z){this.pins.delete($),this.pins.set($,Z);while(this.pins.size>this.limit){let X=this.pins.keys().next().value;if(X===void 0)break;this.pins.delete(X)}}place($){let Z=this.pins.get($.sessionId),X=new Set($.validPinnedAccountIds);if(Z&&!$.excludeAccountIds.includes(Z.accountId)&&h1(Z,X,$.wireAccountIdByAccount[Z.accountId])){if($.persist){let F=$.quotaCheckedAtByAccount[Z.accountId];this.set($.sessionId,{accountId:Z.accountId,inputBytes:$.requestBytes,...Z.wireIdentity!==void 0?{wireIdentity:Z.wireIdentity}:{},...F!==void 0?{quotaCheckedAt:F}:{}})}return{accountId:Z.accountId}}let z=new Map(Object.entries($.quotaCheckedAtByAccount)),j=f1(this.pins,z,$.sessionId),B=$.select(j);if(!B)return;if($.persist){let F=$.wireAccountIdByAccount[B.accountId];this.set($.sessionId,{accountId:B.accountId,inputBytes:$.requestBytes,...F!==void 0?{wireIdentity:F}:{},...B.quotaCheckedAt!==void 0?{quotaCheckedAt:B.quotaCheckedAt}:{}})}return{accountId:B.accountId}}}var C2="cortexkit-openai-auth",ZY=5000;async function m1($,Z,X){let z=new Map,j=new Map,B=(H)=>{j.delete(H);for(let W of z.keys())if(W.startsWith(`${H}:`))z.delete(W)},P=await q2({session:{hook:(H,W,O)=>$.session.hook(H,async(w)=>{let x=H==="http.request"?w:void 0,b=H==="experimental.ws.handshake"?w:void 0,c=(x?x.request.headers:b?new Headers(b.headers):void 0)?.get("authorization")===`Bearer ${s(Z.providerID)}`;try{await W(w)}catch(v){if(c&&!(v instanceof d))throw o1(v);throw v}if(x||b){let v=x??b;if(!v)return;let m=(x?x.request.headers:new Headers(v.headers)).get("authorization")?.replace(/^Bearer /,"");if(c&&m)j.set(v.sessionID,m);else j.delete(v.sessionID);if(b){let I=`${b.sessionID}:${b.kind}`;if(c&&m)z.set(I,m);else z.delete(I)}if(j.size>512){let I=j.keys().next().value;if(I)j.delete(I)}if(z.size>512){let I=z.keys().next().value;if(I)z.delete(I)}}else if(H==="experimental.ws.receive"){let v=w,u=z.get(`${v.sessionID}:${v.kind}`);if(u)v.frame=r1(v.frame,u)}else if(H==="retry"){let v=w,u=j.get(v.sessionID);if(u)Object.assign(v.error,{message:a1(v.error.message,u)})}},O)},event:{subscribe:(H)=>async function*(){for await(let W of $.event.subscribe(H)){if(W.type==="session.deleted")B(W.data.sessionID);yield W}}()}},{...Z,rewriteResponse:async(H)=>{let W=await Z.rewriteResponse?.(H)??H.response;return t1(W,H.request.headers.get("authorization")?.replace(/^Bearer /,""))}},{gateOnPlaceholder:{credential:(H)=>{let W=H.get("authorization");return W?.startsWith("Bearer ")?W.slice(7):void 0}},logger:{warn:(H,W)=>X.warn(H,{data:W})}}),A=P.dispose;return{...P,dispose:async()=>{j.clear(),z.clear(),await A()}}}function h2($={}){return{id:C2,setup:(Z)=>KY(Z,$)}}async function KY($,Z={}){let S=[];try{let X=J2("opencode2");let z=J2("quota");let j=Z.paths??(()=>$$(e1()));let B=Z.fetch??fetch;let F=Z.version??X$;let P=Z.poolMigration??W$;if(!P&&!j2(j().configPath)){X.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 U=(h)=>{throw new d({kind:"no-account",providerID:i,sessionID:h.sessionID,requestKind:h.kind,message:U2})},N=await m1($,{providerID:i,chooseAccount:U,accountHeaders:U},X);return()=>N.dispose()}let A=Z.vault?.firstRosterWaitMs??j$;let H=V$({host:"opencode",stateDir:Z.vault?.stateDir??s1(j().statePath),reservedRouteIds:()=>b.peek().rows.map((U)=>U.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:()=>B},j());let W=H.vault;let O=!1;const w=g1(S,{[Symbol.dispose](){if(!O)H.release()}},0);await W.authority();let x=H.firstRoster;let b=new Q$({paths:j,refreshProvider:async(U)=>{let N=await c1({refreshToken:U.refresh,fetchImpl:B,now:Date.now}),h=l1({id_token:"",access_token:N.access,refresh_token:N.refresh});return{...N,...h?{identity:h}:{}}},pullQuota:async(U)=>{let N=U.credential;if(N.type!=="oauth"||!N.access)throw Error("the row holds no access token to poll with");let h=await d1({accessToken:N.access,fetchImpl:B,now:Date.now,...U.identity?{accountId:U.identity}:{},accountKey:U.id,logger:z});return n1(h,Date.now(),!0)},vaultIdentities:()=>W.identities(),vaultMode:()=>W.enrolled(),vaultAuthority:()=>W.authority(),vaultFirstRoster:x,vaultFirstRosterBackgroundWaitMs:A,log:J2("pool")});await b.load();let r=Z.heartbeat===!1?void 0:await B$({version:F,logger:J2("heartbeat")});let c=Z.fence??(()=>z$({currentVersion:F}));let v=Z.slot??S1();let u=async()=>Y$(j(),await v.get({path:{id:"openai"}}));let m=!1;let I=P?G$({paths:j,slot:v,version:F,fence:c,runDeps:{vaultServes:()=>W.serves()},paused:async()=>await W.authority()!=="local",migrate:async(U)=>{let N=await Z$(U);return m=N.status==="refused",b.load(),N},adopt:async(U)=>{if(!await v2(x,A))return{status:"retry",reason:"vault-roster-pending"};let N=await K$(U);return b.load(),N}}):void 0;I?.start();H.start();let J=new w2;let V=q1({source:b,slotPlaceholderWithoutMain:u,storage:()=>i1(j()),pins:J,vault:W,awaitVaultRoster:async()=>{await v2(x,J$)},responsesLite:()=>I2().responsesLite,codexEndpoint:()=>I2().codexApiEndpoint,log:X});let M=await m1($,V.adapter,X);V.attach(M);let T=async(U)=>{if(await X2(W),j2(j().configPath))return;if(await I?.idle(),j2(j().configPath))return;if(m&&!y2(U)&&(await c()).open){await b.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(U)=>{await T(U);let N=await y1(b.poolStore(),j(),U,{vault:W});if(!j2(j().configPath))await I?.requestAdoption();await b.load(),X.info("ChatGPT login stored in the account pool",N)};let L=await M2($,{integrationID:i,methods:k1({beginLogin:Z.beginLogin??p1,version:F,vault:W}),onLogin:(U)=>R(U),label:"ChatGPT (openai-auth account pool)",vault:b1(W)});let D=await v1($);let k=new AbortController;(async()=>{try{for await(let U of $.event.subscribe({signal:k.signal}))if(U.type==="session.deleted")V.forgetSession(U.data.sessionID)}catch(U){if(!k.signal.aborted)X.warn("stopped listening for session deletion",{error:U instanceof Error?U.message:String(U)})}})();O=!0;return async()=>{k.abort(),I?.dispose(),await Promise.allSettled([M.dispose(),L.dispose(),D.dispose()]),await Promise.race([b.settled(),new Promise((U)=>setTimeout(U,ZY).unref?.())]),H.release(),b.dispose(),await r?.release()}}catch(g){var p=g,l=1}finally{u1(S,p,l)}}var zY=h2(),_Z={id:C2,setup:zY.setup,server:H$.server};export{_Z as default,h2 as createOpenAIAuthPlugin,C2 as OPENAI_AUTH_PLUGIN_ID};
4
+ `,{mode:j??384}),await h$(F,j??384),await g$(F,$)}catch(P){throw await u$(F,{force:!0}).catch(()=>{}),P}return Z.set(z,b2(X.body)),!0},async all(){let X=await O2($);if(!X||Object.keys(X).length===0)return{[i$]:!0};return X}}}var a$="openai-auth-pool-browser",o$="openai-auth-pool-headless",r$="openai-auth-vault",t$="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Connect to the vault or disconnect this host before trying again.";async function X2($){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 b1($){return{method:{id:r$,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await E1($.paths,$.name)!=="vault")throw Error(t$)}}}function k1($){let Z=(X,z,j)=>({method:{id:X,type:"oauth",label:z},async authorize(){if($.vault)await X2($.vault);let B=await $.beginLogin({version:$.version,headless:j});return{url:B.url,instructions:B.instructions,mode:"auto",callback:B.completion}}});return[Z(a$,"ChatGPT (openai-auth pool, browser)",!1),Z(o$,"ChatGPT (openai-auth pool, headless)",!0)]}function y2($){let Z=(X)=>typeof X==="string"?X:"";return z2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===A1||R1($)}function e$($){if($.accountId)return $.accountId;let Z=$.access?W2($.access):void 0;return Z?H2(Z):void 0}async function y1($,Z,X,z={}){if(z.vault)await X2(z.vault);if(y2(X))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let j=D1($,{rowLocks:(x)=>O1(Z,x)}),B=await j.read();if(B.status!=="ready")throw Error(`the account pool cannot be read (${B.status}); the login was not stored`);let F={type:"oauth",refresh:X.refresh,...X.access!==void 0?{access:X.access}:{},...X.expires!==void 0?{expires:X.expires}:{}},P=e$(X);if(z.vault)await X2(z.vault);let A=P!==void 0?{identity:P}:{};if(z.origin==="import"){let x=B.rows.find((b)=>P!==void 0&&b.identity===P||b.credential?.type==="oauth"&&b.credential.refresh===X.refresh);if(x)return{id:x.id,operation:"kept"}}let H=B.rows.filter((x)=>x.type==="oauth"&&!x.invalid),W=P?H.find((x)=>x.identity===P):void 0,O=B.rows.find((x)=>x.id===N2);if(W)return{id:(await j.replace(W.id,F,A)).id,operation:"replaced"};if(!O){let x=await j.add({id:N2,credential:F,...A,...X.label!==void 0?{label:X.label}:{}});return{id:x.id,operation:x.outcome==="added-disabled"?"added-disabled":"added"}}if(!O.invalid&&!O.credential)return{id:(await j.replace(N2,F,A)).id,operation:"replaced"};let w=await j.add({id:X.id,credential:F,...A,...X.label!==void 0?{label:X.label}:{}});return{id:w.id,operation:w.outcome==="added-disabled"?"added-disabled":w.outcome==="rotated"?"replaced":"added"}}function $Y($){if(!w1($.modelID??$.id)){$.enabled=!1;return}let Z=I1($.id);if(Z)$.limit={...Z}}function v1($){return $.model.transform((Z)=>{for(let X of Z.list(i))Z.update(i,String(X.id),(z)=>$Y(z))})}var YY=1024;class w2{pins=new Map;limit;constructor($=YY){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.pins.delete($)}get size(){return this.pins.size}set($,Z){this.pins.delete($),this.pins.set($,Z);while(this.pins.size>this.limit){let X=this.pins.keys().next().value;if(X===void 0)break;this.pins.delete(X)}}place($){let Z=this.pins.get($.sessionId),X=new Set($.validPinnedAccountIds);if(Z&&!$.excludeAccountIds.includes(Z.accountId)&&h1(Z,X,$.wireAccountIdByAccount[Z.accountId])){if($.persist){let F=$.quotaCheckedAtByAccount[Z.accountId];this.set($.sessionId,{accountId:Z.accountId,inputBytes:$.requestBytes,...Z.wireIdentity!==void 0?{wireIdentity:Z.wireIdentity}:{},...F!==void 0?{quotaCheckedAt:F}:{}})}return{accountId:Z.accountId}}let z=new Map(Object.entries($.quotaCheckedAtByAccount)),j=f1(this.pins,z,$.sessionId),B=$.select(j);if(!B)return;if($.persist){let F=$.wireAccountIdByAccount[B.accountId];this.set($.sessionId,{accountId:B.accountId,inputBytes:$.requestBytes,...F!==void 0?{wireIdentity:F}:{},...B.quotaCheckedAt!==void 0?{quotaCheckedAt:B.quotaCheckedAt}:{}})}return{accountId:B.accountId}}}var C2="cortexkit-openai-auth",ZY=5000;async function m1($,Z,X){let z=new Map,j=new Map,B=(H)=>{j.delete(H);for(let W of z.keys())if(W.startsWith(`${H}:`))z.delete(W)},P=await q2({session:{hook:(H,W,O)=>$.session.hook(H,async(w)=>{let x=H==="http.request"?w:void 0,b=H==="experimental.ws.handshake"?w:void 0,c=(x?x.request.headers:b?new Headers(b.headers):void 0)?.get("authorization")===`Bearer ${s(Z.providerID)}`;try{await W(w)}catch(v){if(c&&!(v instanceof d))throw o1(v);throw v}if(x||b){let v=x??b;if(!v)return;let m=(x?x.request.headers:new Headers(v.headers)).get("authorization")?.replace(/^Bearer /,"");if(c&&m)j.set(v.sessionID,m);else j.delete(v.sessionID);if(b){let I=`${b.sessionID}:${b.kind}`;if(c&&m)z.set(I,m);else z.delete(I)}if(j.size>512){let I=j.keys().next().value;if(I)j.delete(I)}if(z.size>512){let I=z.keys().next().value;if(I)z.delete(I)}}else if(H==="experimental.ws.receive"){let v=w,u=z.get(`${v.sessionID}:${v.kind}`);if(u)v.frame=r1(v.frame,u)}else if(H==="retry"){let v=w,u=j.get(v.sessionID);if(u)Object.assign(v.error,{message:a1(v.error.message,u)})}},O)},event:{subscribe:(H)=>async function*(){for await(let W of $.event.subscribe(H)){if(W.type==="session.deleted")B(W.data.sessionID);yield W}}()}},{...Z,rewriteResponse:async(H)=>{let W=await Z.rewriteResponse?.(H)??H.response;return t1(W,H.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(H)=>{let W=H.get("authorization");return W?.startsWith("Bearer ")?W.slice(7):void 0}},logger:{warn:(H,W)=>X.warn(H,{data:W})}}),A=P.dispose;return{...P,dispose:async()=>{j.clear(),z.clear(),await A()}}}function h2($={}){return{id:C2,setup:(Z)=>KY(Z,$)}}async function KY($,Z={}){let S=[];try{let X=J2("opencode2");let z=J2("quota");let j=Z.paths??(()=>$$(e1()));let B=Z.fetch??fetch;let F=Z.version??X$;let P=Z.poolMigration??W$;if(!P&&!j2(j().configPath)){X.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 U=(h)=>{throw new d({kind:"no-account",providerID:i,sessionID:h.sessionID,requestKind:h.kind,message:U2})},N=await m1($,{providerID:i,chooseAccount:U,accountHeaders:U},X);return()=>N.dispose()}let A=Z.vault?.firstRosterWaitMs??j$;let H=V$({host:"opencode",stateDir:Z.vault?.stateDir??s1(j().statePath),reservedRouteIds:()=>b.peek().rows.map((U)=>U.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:()=>B},j());let W=H.vault;let O=!1;const w=g1(S,{[Symbol.dispose](){if(!O)H.release()}},0);await W.authority();let x=H.firstRoster;let b=new Q$({paths:j,refreshProvider:async(U)=>{let N=await c1({refreshToken:U.refresh,fetchImpl:B,now:Date.now}),h=l1({id_token:"",access_token:N.access,refresh_token:N.refresh});return{...N,...h?{identity:h}:{}}},pullQuota:async(U)=>{let N=U.credential;if(N.type!=="oauth"||!N.access)throw Error("the row holds no access token to poll with");let h=await d1({accessToken:N.access,fetchImpl:B,now:Date.now,...U.identity?{accountId:U.identity}:{},accountKey:U.id,logger:z});return n1(h,Date.now(),!0)},vaultIdentities:()=>W.identities(),vaultMode:()=>W.enrolled(),vaultAuthority:()=>W.authority(),vaultFirstRoster:x,vaultFirstRosterBackgroundWaitMs:A,log:J2("pool")});await b.load();let r=Z.heartbeat===!1?void 0:await B$({version:F,logger:J2("heartbeat")});let c=Z.fence??(()=>z$({currentVersion:F}));let v=Z.slot??S1();let u=async()=>Y$(j(),await v.get({path:{id:"openai"}}));let m=!1;let I=P?G$({paths:j,slot:v,version:F,fence:c,runDeps:{vaultServes:()=>W.serves()},paused:async()=>await W.authority()!=="local",migrate:async(U)=>{let N=await Z$(U);return m=N.status==="refused",b.load(),N},adopt:async(U)=>{if(!await v2(x,A))return{status:"retry",reason:"vault-roster-pending"};let N=await K$(U);return b.load(),N}}):void 0;I?.start();H.start();let J=new w2;let V=q1({source:b,slotPlaceholderWithoutMain:u,storage:()=>i1(j()),pins:J,vault:W,awaitVaultRoster:async()=>{await v2(x,J$)},responsesLite:()=>I2().responsesLite,codexEndpoint:()=>I2().codexApiEndpoint,log:X});let M=await m1($,V.adapter,X);V.attach(M);let T=async(U)=>{if(await X2(W),j2(j().configPath))return;if(await I?.idle(),j2(j().configPath))return;if(m&&!y2(U)&&(await c()).open){await b.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(U)=>{await T(U);let N=await y1(b.poolStore(),j(),U,{vault:W});if(!j2(j().configPath))await I?.requestAdoption();await b.load(),X.info("ChatGPT login stored in the account pool",N)};let L=await M2($,{integrationID:i,methods:k1({beginLogin:Z.beginLogin??p1,version:F,vault:W}),onLogin:(U)=>R(U),label:"ChatGPT (openai-auth account pool)",vault:b1(W)});let D=await v1($);let k=new AbortController;(async()=>{try{for await(let U of $.event.subscribe({signal:k.signal}))if(U.type==="session.deleted")V.forgetSession(U.data.sessionID)}catch(U){if(!k.signal.aborted)X.warn("stopped listening for session deletion",{error:U instanceof Error?U.message:String(U)})}})();O=!0;return async()=>{k.abort(),I?.dispose(),await Promise.allSettled([M.dispose(),L.dispose(),D.dispose()]),await Promise.race([b.settled(),new Promise((U)=>setTimeout(U,ZY).unref?.())]),H.release(),b.dispose(),await r?.release()}}catch(g){var p=g,l=1}finally{u1(S,p,l)}}var zY=h2(),_Z={id:C2,setup:zY.setup,server:H$.server};export{_Z as default,h2 as createOpenAIAuthPlugin,C2 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.0.1",
3
+ "version": "1.0.2",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {