@cortexkit/opencode-openai-auth 1.9.4 → 1.9.6

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.
Files changed (78) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/{codex-request-By530v1D.d.ts → codex-request-CZ16goZ6.d.ts} +20 -4
  3. package/dist/index-1kbr03m0.js +2 -0
  4. package/dist/{index-rrtsaz80.js → index-3mmdgz6r.js} +1 -1
  5. package/dist/index-5xs8nfcx.js +63 -0
  6. package/dist/index-7bv7pgy8.js +12 -0
  7. package/dist/{index-v1ztg103.js → index-cf0mrvqj.js} +1 -1
  8. package/dist/index-jqqeynjm.js +91 -0
  9. package/dist/index-qn927h9w.js +76 -0
  10. package/dist/{index-2bf808fw.js → index-s52j2h64.js} +1 -1
  11. package/dist/{index-7bjgmbx4.js → index-se7mn1wg.js} +1 -1
  12. package/dist/index-t52k32ab.js +8 -0
  13. package/dist/{index-jej9cfk7.js → index-tcaef7wq.js} +1 -1
  14. package/dist/{index-cmybrjbd.js → index-x8qjasc7.js} +1 -1
  15. package/dist/{index-g3gbp1m4.js → index-y4j7y8b8.js} +1 -1
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/{port-file-DXCxv8tU.d.ts → port-file-CEjki7bM.d.ts} +6 -1
  19. package/dist/rpc/port-file.d.ts +1 -1
  20. package/dist/rpc/port-file.js +1 -1
  21. package/dist/rpc/protocol.js +1 -1
  22. package/dist/rpc/rpc-client.d.ts +1 -1
  23. package/dist/rpc/rpc-client.js +1 -1
  24. package/dist/rpc/rpc-dir.js +1 -1
  25. package/dist/{rpc-client-CmaZW1by.d.ts → rpc-client-rWuV04C-.d.ts} +1 -1
  26. package/dist/sidebar-state.js +1 -1
  27. package/dist/{token-dcr3tgsk.js → token-djwdynff.js} +1 -1
  28. package/dist/token-util-0xt1ws82.js +1 -0
  29. package/dist/tui-preferences.js +1 -1
  30. package/dist/tui.d.ts +1 -1
  31. package/dist/v2/server.d.ts +1 -1
  32. package/dist/v2/server.js +3 -3
  33. package/package.json +5 -5
  34. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +74 -9
  35. package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +36 -0
  36. package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +2 -0
  37. package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +8 -0
  38. package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +7 -0
  39. package/src/tui-compiled/raw/shared/45bf5343bbbf9add-admission.js +17 -7
  40. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +2 -5
  41. package/src/tui-compiled/raw/shared/4ede5af6a878a14e-usage.js +145 -0
  42. package/src/tui-compiled/raw/shared/5f8cc863449a6c85-limits-namespace.js +34 -0
  43. package/src/tui-compiled/raw/shared/754d6017f8e419cf-builtins.js +38 -0
  44. package/src/tui-compiled/raw/shared/836fc615de6afbd9-settings.js +11 -4
  45. package/src/tui-compiled/raw/shared/97484d9bb98c705b-provider-state.js +5 -5
  46. package/src/tui-compiled/raw/shared/9d3fc9e37456504e-refresh.js +1 -1
  47. package/src/tui-compiled/raw/shared/9deae3c4da4fd63b-hooks.js +20 -5
  48. package/src/tui-compiled/raw/shared/a62a27a204266acd-attribution.js +3 -2
  49. package/src/tui-compiled/raw/shared/c14988621dc60a75-port-file.js +46 -4
  50. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +2 -0
  51. package/src/tui-compiled/raw/shared/cd94316a888b0a8e-schema.js +9 -4
  52. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +142 -47
  53. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +74 -9
  54. package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +36 -0
  55. package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +2 -0
  56. package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +8 -0
  57. package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +7 -0
  58. package/src/tui-compiled/runtime/shared/45bf5343bbbf9add-admission.js +17 -7
  59. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +2 -5
  60. package/src/tui-compiled/runtime/shared/4ede5af6a878a14e-usage.js +145 -0
  61. package/src/tui-compiled/runtime/shared/5f8cc863449a6c85-limits-namespace.js +34 -0
  62. package/src/tui-compiled/runtime/shared/754d6017f8e419cf-builtins.js +38 -0
  63. package/src/tui-compiled/runtime/shared/836fc615de6afbd9-settings.js +11 -4
  64. package/src/tui-compiled/runtime/shared/97484d9bb98c705b-provider-state.js +5 -5
  65. package/src/tui-compiled/runtime/shared/9d3fc9e37456504e-refresh.js +1 -1
  66. package/src/tui-compiled/runtime/shared/9deae3c4da4fd63b-hooks.js +20 -5
  67. package/src/tui-compiled/runtime/shared/a62a27a204266acd-attribution.js +3 -2
  68. package/src/tui-compiled/runtime/shared/c14988621dc60a75-port-file.js +46 -4
  69. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +2 -0
  70. package/src/tui-compiled/runtime/shared/cd94316a888b0a8e-schema.js +9 -4
  71. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +142 -47
  72. package/dist/index-2esezxst.js +0 -12
  73. package/dist/index-4p45bmbz.js +0 -63
  74. package/dist/index-6xz3n4qh.js +0 -91
  75. package/dist/index-81yvwra9.js +0 -8
  76. package/dist/index-hz6f9gpq.js +0 -2
  77. package/dist/index-xx3k2qbv.js +0 -76
  78. package/dist/token-util-gbd7jw6d.js +0 -1
package/dist/v2/server.js CHANGED
@@ -1,3 +1,3 @@
1
- import{c as k0}from"../index-jej9cfk7.js";import{A as A0,B as o2,C as l$,D as u$,E as rZ,F as tZ,G as S0,H as KZ,I as TZ,L as bZ,M as kZ,N as DZ,V as vZ,W as hZ,_ as b0,d as F0,e as yZ,ea as G$,f as B1,fa as Q$,g as S2,h as e2,i as Q1,ia as D0,k as J$,l as z$,m as $$,n as c2,o as NZ,p as w1,q as FZ,r as xZ,s as qZ,t as $1,u as r$,v as t$,w as C0,x as E0,y as g1,z as O0}from"../index-4p45bmbz.js";import{Ab as P0,Bb as M0,Cb as EZ,Kb as A2,Lb as GZ,Ma as MZ,Mb as QZ,Nb as b1,Ob as YZ,Pb as XZ,Rb as R0,Sb as x0,Ta as t2,Tb as q0,bb as Y1,cb as U0,db as H0,eb as N0,fb as w2,hb as h$,ib as a2,jb as m$,kb as g$,mb as T0,nb as zZ,pa as W0,pb as _0,qb as CZ,ta as x$,ua as q$,zb as L0}from"../index-xx3k2qbv.js";import{bc as iZ,qc as aZ,rc as nZ,tc as oZ,xc as sZ}from"../index-7bjgmbx4.js";import{Ae as w$,Ce as y$,De as I$,Ee as R1,Fe as f$,Gd as LZ,Ge as v$,Md as PZ,Nc as P$,Od as V0,Pd as IZ,Qd as O$,Zd as q2,_d as m2,de as A$,fe as s$,ge as R$,md as s2,me as G1,nd as r2,od as B0,te as fZ,ue as y2,vd as m1,ve as S$,wd as M$,we as b$,xd as C$,xe as k$,yd as E$,ze as D$}from"../index-6xz3n4qh.js";import"../index-81yvwra9.js";import{We as UZ,Xe as K0}from"../index-rrtsaz80.js";import"../index-2esezxst.js";import{gf as j0,if as _2}from"../index-cmybrjbd.js";import"../index-hz6f9gpq.js";import{Ff as HZ}from"../index-g3gbp1m4.js";import{Jf as j1,Kf as X0}from"../index-v1ztg103.js";import{AsyncLocalStorage as D4}from"node:async_hooks";import{randomUUID as w4}from"node:crypto";class Y2 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 K2($){return`common-auth-placeholder.${$}`}function o1($){let Z=K2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function k2($,Z){if($?.type!=="oauth")return!1;let J=Z===void 0?void 0:K2(Z),G=(Y)=>J===void 0?Y.startsWith("common-auth-placeholder."):Y===J;return G($.access)&&G($.refresh)}var s1="No browser sign-in: this connects the plugin to the accounts in its vault.";async function N1($,Z){let J=Z.now??Date.now,{integrationID:G}=Z,Y=(W)=>o1({integrationID:G,methodID:W,now:J()}),Q=async(W,N)=>{return await Z.onLogin(W,{integrationID:G,methodID:N}),Y(N)},F=(W)=>async(N)=>{let B=W.method.id,H=await W.authorize(N),T={url:H.url,instructions:H.instructions,...H.expiresAt===void 0?{}:{expiresAt:H.expiresAt}};if(H.mode==="auto")return{...T,mode:"auto",callback:H.callback.then((C)=>Q(C,B))};let R=H.callback;return{...T,mode:"code",callback:async(C)=>Q(await R(C),B)}};return $.integration.transform((W)=>{let N=Z.label===void 0?{}:{label:()=>Z.label};for(let T of Z.methods)W.method.update({integrationID:G,method:T.method,authorize:F(T),refresh:async(R)=>{if(!k2(R,G))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return Y(R.methodID)},...N});let B=Z.vault;if(B===void 0)return;let H=B.method.id;W.method.update({integrationID:G,method:B.method,authorize:async()=>({url:"",instructions:B.instructions??s1,mode:"auto",callback:Promise.resolve().then(()=>B.activate({integrationID:G,methodID:H})).then(()=>Y(H))}),refresh:async(T)=>{if(!k2(T,G)||T.methodID!==H)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return Y(H)},...N})})}function I0($){let Z=[],J;for(let G of $.split(/\r?\n/))if(G.startsWith("data:"))Z.push(G.slice(5).replace(/^ /,""));else if(G.startsWith("event:"))J=G.slice(6).trim();if(Z.length===0)return;return J===void 0?{data:Z.join(`
2
- `)}:{event:J,data:Z.join(`
3
- `)}}function 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 l0}from"../index-tcaef7wq.js";import{A as I0,B as X1,C as r$,D as t$,E as X0,F as j0,G as g0,H as RZ,I as xZ,L as mZ,M as lZ,N as uZ,V as aZ,W as nZ,_ as m0,d as A0,e as cZ,ea as L$,f as M1,fa as P$,g as v2,h as W1,i as T1,ia as u0,k as T$,l as _$,m as F$,n as z1,o as OZ,p as s1,q as AZ,r as vZ,s as hZ,t as U1,u as XZ,v as jZ,w as k0,x as w0,y as z$,z as y0}from"../index-5xs8nfcx.js";import{Ab as b0,Bb as D0,Cb as wZ,Kb as k2,Lb as NZ,Ma as DZ,Mb as FZ,Nb as a1,Ob as KZ,Pb as TZ,Rb as f0,Sb as v0,Ta as V1,Tb as h0,bb as _1,cb as E0,db as C0,eb as O0,fb as p2,hb as n$,ib as Y1,jb as o$,kb as s$,mb as x0,nb as HZ,pa as M0,pb as S0,qb as kZ,ta as l$,ua as u$,zb as q0}from"../index-qn927h9w.js";import{bc as J0,qc as z0,rc as G0,tc as Q0,xc as Y0}from"../index-se7mn1wg.js";import{Ae as d$,Ce as i$,De as l1,Ee as u1,Fe as a$,Gd as qZ,Ge as p1,Md as bZ,Nc as y$,Od as P0,Pd as dZ,Qd as h$,Zd as f2,_d as s2,de as g$,fe as YZ,ge as m$,md as j1,me as K1,nd as B1,od as L0,te as iZ,ue as d2,vd as J$,ve as p$,wd as I$,we as g1,xd as f$,xe as c$,yd as v$,ze as m1}from"../index-jqqeynjm.js";import"../index-t52k32ab.js";import{We as EZ,Xe as R0}from"../index-3mmdgz6r.js";import"../index-7bv7pgy8.js";import{gf as _0,if as R2}from"../index-x8qjasc7.js";import"../index-1kbr03m0.js";import{Gf as CZ}from"../index-y4j7y8b8.js";import{Kf as P1,Lf as T0}from"../index-cf0mrvqj.js";import{AsyncLocalStorage as p4}from"node:async_hooks";import{randomUUID as c4}from"node:crypto";class F2 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 A2($){return`common-auth-placeholder.${$}`}function U$($){let Z=A2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function m2($,Z){if($?.type!=="oauth")return!1;let z=Z===void 0?void 0:A2(Z),G=(X)=>z===void 0?X.startsWith("common-auth-placeholder."):X===z;return G($.access)&&G($.refresh)}var H$="No browser sign-in: this connects the plugin to the accounts in its vault.";async function R1($,Z){let z=Z.now??Date.now,{integrationID:G}=Z,X=(W)=>U$({integrationID:G,methodID:W,now:z()}),Y=async(W,H)=>{return await Z.onLogin(W,{integrationID:G,methodID:H}),X(H)},F=(W)=>async(H)=>{let N=W.method.id,V=await W.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)=>Y(E,N))};let C=V.callback;return{...P,mode:"code",callback:async(E)=>Y(await C(E),N)}};return $.integration.transform((W)=>{let H=Z.label===void 0?{}:{label:()=>Z.label};for(let P of Z.methods)W.method.update({integrationID:G,method:P.method,authorize:F(P),refresh:async(C)=>{if(!m2(C,G))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return X(C.methodID)},...H});let N=Z.vault;if(N===void 0)return;let V=N.method.id;W.method.update({integrationID:G,method:N.method,authorize:async()=>({url:"",instructions:N.instructions??H$,mode:"auto",callback:Promise.resolve().then(()=>N.activate({integrationID:G,methodID:V})).then(()=>X(V))}),refresh:async(P)=>{if(!m2(P,G)||P.methodID!==V)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return X(V)},...H})})}function i0($){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 x1($,Z){let z=new TextDecoder,G="",X=(F)=>{let W=i0(F);if(!W)return;try{$(W)}catch(H){Z(H)}},Y=()=>{for(;;){let F=/\r?\n\r?\n/.exec(G);if(!F)return;let W=G.slice(0,F.index);G=G.slice(F.index+F[0].length),X(W)}};return new TransformStream({transform(F,W){W.enqueue(F),G+=z.decode(F,{stream:!0}),Y()},flush(){if(G+=z.decode(),Y(),G.trim()!=="")X(G);G=""}})}var Z1=512,S1=3621000,y2="x-common-auth-attempt",D2=($,Z)=>JSON.stringify([$,Z]),M2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function a0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function n0($,Z){let z=$.getReader();return new ReadableStream({async pull(G){let X;try{X=await z.read()}catch(Y){Z({reason:"failed",message:Y instanceof Error?Y.message:String(Y)}),G.error(Y);return}if(X.done)Z(),G.close();else G.enqueue(X.value)},async cancel(G){Z({reason:"cancelled",...G===void 0?{}:{message:String(G)}}),await z.cancel(G)}})}function $1($,Z){for(let[z,G]of Object.entries(Z)){let X=z.toLowerCase();for(let Y of Object.keys($))if(Y.toLowerCase()===X)delete $[Y];if(G!==null)$[z]=G}}function o0($,Z){for(let[z,G]of Object.entries(Z))if(G===null)$.delete(z);else $.set(z,G)}async function q1($,Z,z={}){let{providerID:G}=Z,X=z.gateOnPlaceholder,Y=(J)=>X===void 0||X.credential(J)===A2(G),F=z.logger,W=Math.max(1,z.maxRecords??Z1),H=z.hostRetryLimit??10,N=[...z.hostCredentials??[A2(G)],...X?[A2(G)]:[]].filter((J)=>J!==""),V=new Map,P=new WeakMap,C=new Map,E=0,h=new Set,a=new Map,A=new Map,k=(J)=>{let j=A.get(J);return j?.ownedSeen===!0&&j.foreignSeen},W2=(J,j)=>{a.set(J,j);let U=A.get(J)??{ownedSeen:!1,foreignSeen:!1};if(j)U.ownedSeen=!0;else U.foreignSeen=!0;A.set(J,U)},X2=(J,j)=>{let U=X?.refuseMisplaced,L=U?[...j].filter(([,I])=>I.includes(A2(G))):[],B=Y(j)&&(!U||L.length>0);if(U){if(L.length>0&&(L.length!==1||!B))throw W2(J.sessionID,!1),new F2({kind:"placement-refused",providerID:G,sessionID:J.sessionID,requestKind:J.kind,message:U(L[0]?.[0]??"")})}return W2(J.sessionID,B),B},v=!1,n=!1,K2=new Map,U2=0,j2=!1,b=new Map,g=(J,j)=>{try{F?.warn(J,j)}catch{}},p=(J)=>J instanceof Error?J.message:String(J),Q=(J)=>J.excluded.clear(),K=(J)=>J.excluded.size===0?{}:{excluded:[...J.excluded]},_=(J,j,U)=>{if(!z.enforceRequestExclusion||J===void 0||!U.excluded.has(J))return!1;return g("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:j.sessionID,kind:j.kind,phase:j.phase,accountId:J}),!0},M=new Map,D=(J,j)=>{let U=(M.get(J)??Promise.resolve()).then(j),L=U.then(()=>{},()=>{});return M.set(J,L),L.then(()=>{if(M.get(J)===L)M.delete(J)}),U},O=(J,j)=>{let U=M.get(J);return U?U.then(()=>O(J,j)):j()},R=async(J)=>{try{await Z.dropChoice?.({...J.input,accountId:J.accountId})}catch(j){g("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:J.input.sessionID,error:p(j)})}},f=async(J)=>{try{await Z.dropSameAccountRetry?.({...J.input,accountId:J.accountId})}catch(j){g("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:J.input.sessionID,error:p(j)})}},q=async(J)=>{if(J.next)await R(J.next);if(J.sameAccount)await f(J.sameAccount)},w=(J)=>{let j=C.get(J);if(C.delete(J),j)D(j.sessionID,()=>q(j))},y=async(J,j)=>{let U=K2.get(J);if(!U||U.size===0)return;await Promise.all([...U].map(async(L)=>{try{await L(j)}catch(B){g("opencode2 auth listener threw; the request is unaffected",{event:J,error:p(B)})}}))},J2=async(J,j)=>{try{await Z.onAttemptEnd?.(J,j)}catch(U){g("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:J.attemptId,error:p(U)})}},G2=(J,j)=>{if(J.ended||!J.attempt)return;let U={...J.status===void 0?{}:{status:J.status},outputStarted:J.outputStarted,...J.limit?{limit:J.limit.signal}:{},...j?{error:j}:{}};if(j)J.endError=j;if(j?.reason==="cancelled"||!j&&!J.limit&&(J.status===void 0||J.status<400))Q(J.request);J.ended=J2(J.attempt,U)},e=(J,j)=>G2(J,{reason:"abandoned",message:j}),s=(J)=>[...V.values()].filter((j)=>j.key===J),c=(J)=>s(J).at(-1),m=(J)=>{if(V.delete(J.id),C.get(J.key)?.attemptId===J.id||!s(J.key).length)w(J.key)},$2=(J)=>{V.set(J.id,J);while(V.size>W){let j=V.values().next().value;if(j===void 0)break;e(j,"dropped to keep the record bound"),m(j)}},T2=(J)=>J.accountId===void 0?void 0:{...J.scope,accountId:J.accountId},T=(J,j)=>new F2({kind:"no-account",providerID:G,sessionID:J.sessionID,requestKind:J.kind,...j===void 0?{}:{message:j}}),l=(J)=>{b.get(J)?.clear(),b.delete(J)},Z2=async(J,j)=>{let U=()=>T(J,`${G} ${J.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(j2)throw U();let L=b.get(J.sessionID);if(!L)L=new Set,b.set(J.sessionID,L);let B={};L.add(B);let I=()=>{if(!L.has(B))throw U()};try{return await j(I)}finally{if(L.delete(B),L.size===0&&b.get(J.sessionID)===L)b.delete(J.sessionID)}},t=(J,j)=>{for(let[U,L]of j)if(N.some((B)=>L.includes(B)))throw new F2({kind:"host-credential-on-wire",providerID:G,sessionID:J.sessionID,requestKind:J.kind,message:`${G} ${J.kind} request still carries the host's placeholder credential in ${U}; the adapter's account headers must replace it`})},B2=(J)=>{for(let j of s(J))if(j.ended||!j.attempt)m(j);else if(j.transport==="ws"||j.judged)e(j,"a newer attempt of its session and kind began"),m(j)},w2=async(J,j,U,L)=>{let B=D2(J.sessionID,J.kind),{input:I,accountId:x,sameAccountRetry:S,request:r}=await O(J.sessionID,async()=>{U();let Q2=C.get(B);C.delete(B);let g2=s(B);if(Q2&&g2.some((o)=>o.id!==Q2.attemptId&&o.attempt&&!o.ended))g("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:J.sessionID,kind:J.kind});if(!Q2){let o=new Set(g2.filter((N2)=>N2.attempt&&!N2.ended).map((N2)=>N2.request));for(let N2 of g2)if(!o.has(N2.request))Q(N2.request)}let V2=Q2?.request??{excluded:new Set},z2=Q2?.accountId??c(B)?.accountId;B2(B);let i=Q2?.next,Y2=Q2?.sameAccount,u=Y2!==void 0&&Y2.input.modelID===J.modelID&&Y2.input.agent===J.agent,H2=i!==void 0&&i.input.modelID===J.modelID&&i.input.agent===J.agent,O2=Q2?.wake,d={...J,phase:"request",...K(V2),...z2===void 0?{}:{previousAccountId:z2},...Q2?.rerouteFrom?{rerouteFrom:Q2.rerouteFrom}:{},...O2===void 0?{}:{wake:O2,hostAttempt:i?.input.hostAttempt}};if(i&&(!H2||O2!==void 0))await D(J.sessionID,()=>R(i)),U();if(Y2&&!u)await D(J.sessionID,()=>f(Y2)),U();if(Y2?.continuation&&(!u||k(J.sessionID))){if(u)await D(J.sessionID,()=>f(Y2));throw T(J)}let b2=u?Y2.accountId:H2&&O2===void 0?i.accountId:await Z.chooseAccount(d),S2=typeof b2==="string"?b2:void 0;if(_(S2,d,V2)){let o=S2;if(u&&Y2)await D(J.sessionID,()=>f(Y2));else if(o!==void 0)await D(J.sessionID,()=>R(H2&&i?i:{accountId:o,input:d}));S2=void 0,U()}return{input:d,accountId:S2,sameAccountRetry:u,request:V2}});U();let _2={},L2;if(x!==void 0){let Q2=await Z.accountHeaders({...J,accountId:x});if(U(),a0(Q2))_2=Q2.headers,L2=Q2.attempt;else _2=Q2}let h2=`attempt-${++U2}`,P2={id:h2,key:B,scope:J,request:r,accountId:x,headers:_2,attempt:x===void 0?void 0:{...J,accountId:x,attemptId:h2,transport:L,data:L2},...L===void 0?{}:{transport:L},outputStarted:!1,sameAccountRetry:S};if($2(P2),P2.attempt)y("select",{...J,accountId:P2.attempt.accountId,hook:j,...I.previousAccountId===void 0?{}:{previousAccountId:I.previousAccountId},...I.rerouteFrom===void 0?{}:{rerouteFrom:I.rerouteFrom},handle:P2.attempt});return P2},r2=async(J,j,U,L,B)=>{let I=D2(J.sessionID,J.kind),x=L===void 0?void 0:V.get(L);if(x?.key!==I)x=void 0;if(!x){if(x=c(I),s(I).filter((r)=>r.transport===void 0&&!r.ended).length>1&&!n)n=!0,g("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:J.sessionID,kind:J.kind})}if(!x||x.transport!==void 0||x.ended)x=await w2(J,j,B,U);else if(x.transport=U,x.attempt)x.attempt.transport=U;if(U==="ws"){for(let S of s(I))if(S!==x&&S.transport==="ws")e(S,"a newer attempt of its session and kind went out over WebSocket")}return x},C1=async(J,j)=>{try{return await j()}catch(U){throw G2(J,{reason:"failed",message:p(U)}),U}},Q$=(J,j)=>{let U=s(D2(J,j)).filter((L)=>L.transport==="ws").at(-1);return U?.attempt!==void 0&&!U.ended?U:void 0},t2=(J,j,U)=>{let L=T2(J);if(!L||!J.attempt||J.limit)return;J.limit={signal:j,delivered:y("limit",{...L,via:U,limit:j,outputStarted:J.outputStarted,handle:J.attempt})}},Y$=(J,j,U,L)=>{let B=T2(J);if(!B||!J.attempt)return;y("quota",{...B,transport:j,...L===void 0?{}:{status:L},quota:U,handle:J.attempt})},X$=(J,j,U,L)=>{let B=J.attempt;if(!B)return;let I=Z.inspectEvent?.(L===void 0?{transport:j,data:U,attempt:B}:{transport:j,data:U,event:L,attempt:B});if(!I)return;if(I.quota!==void 0)Y$(J,j,I.quota);if(I.outputStarted)J.outputStarted=!0;if(I.hostRetry==="veto")J.hostRetry="veto";if(I.limit)t2(J,I.limit,j);if(I.error!==void 0)G2(J,{reason:"failed",message:I.error});else if(I.done)G2(J)},p0=(J,j)=>{let U=J.attempt;if(!U||j.accountId===J.accountId)return;if(U.reboundFrom??=U.accountId,U.accountId=j.accountId,"data"in j)U.data=j.data;J.accountId=j.accountId},c0=(J)=>!J.attempt||J.endError!==void 0||J.status!==void 0&&J.status>=400,j$=(J)=>{let j=[...V.values()].filter((S)=>S.scope.sessionID===J),U=j.filter((S)=>S.limit&&!S.rerouted).at(-1);if(U)return U;let L=j.filter((S)=>S.scope.kind==="primary"),B=L.length>0?L:j;if(B.length<=1)return B[0];let I=B.filter((S)=>!S.judged&&c0(S)).at(-1);if(I)return I;let x=B.filter((S)=>S.attempt&&!S.ended);if(x.length>1)return"ambiguous";return x[0]??B.at(-1)},q2={providerID:G},x2=[];x2.push(await $.session.hook("model.request",(J)=>{if(X)return;return Z2(M2(J),async(j)=>{let U=await w2(M2(J),"model.request",j);if(j(),U.accountId===void 0)throw T(U.scope);$1(J.headers,{...U.headers,[y2]:U.id})})},q2)),x2.push(await $.session.hook("http.request",(J)=>{if(X){if(!X2(M2(J),J.request.headers))return}return Z2(M2(J),async(j)=>{let U=J.request.headers.get(y2)??void 0,L=X?await w2(M2(J),"http.request",j,"http"):await r2(M2(J),"http.request","http",U,j);j();let B=T2(L),I=L.attempt;if(!B||!I)throw T(L.scope);await C1(L,async()=>{let x=J.request;if(Z.rewriteRequest){if(U!==void 0){let _2=new Headers(x.headers);_2.delete(y2),x=new Request(x,{headers:_2})}x=await Z.rewriteRequest({...B,request:x,attempt:I})??x,j()}let S=new Headers(x.headers);S.delete(y2),o0(S,L.headers),t(L.scope,S.entries());let r=new Request(x,{headers:S});P.set(r,L),J.request=r})})},q2)),x2.push(await $.session.hook("http.response",async(J)=>{let j=P.get(J.request);if(!j){if(X)return;if(!v)v=!0,g("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:J.sessionID,kind:J.kind});return}let U=J.response;if(Z.answeredBy&&j.attempt){let S=j.attempt,r=await C1(j,async()=>Z.answeredBy?.({request:J.request,response:U,attempt:S}));if(r)p0(j,r)}let L=T2(j),B=j.attempt;if(!L||!B)return;j.status=U.status;let I=Z.quotaFromHeaders?.(U.headers,U.status,B);if(I!==void 0)Y$(j,"http",I,U.status);if(!U.ok&&Z.limitFromResponse){let S=await Z.limitFromResponse({status:U.status,headers:U.headers,body:()=>U.clone().text(),attempt:B});if(S)t2(j,S,"http")}if(!U.ok||!U.body)G2(j);let x=U;if(U.body&&(Z.inspectEvent||Z.onAttemptEnd)){let S=U.body;if(Z.inspectEvent)S=S.pipeThrough(x1((r)=>X$(j,"http",r.data,r.event),(r)=>g("opencode2 auth event inspection threw",{error:p(r)})));x=new Response(n0(S,(r)=>{if(r?.reason==="failed")j.httpReadFailed=!0;G2(j,r)}),{status:U.status,statusText:U.statusText,headers:U.headers})}if(Z.rewriteResponse)x=await Z.rewriteResponse({...L,request:J.request,response:x,attempt:B})??x;if(Z.responseRetry){if(await Z.responseRetry({...L,request:J.request,response:x,attempt:B})==="veto")j.hostRetry="veto"}if(x!==U)J.response=x},q2)),x2.push(await $.session.hook("experimental.ws.handshake",(J)=>{if(X){let j=D2(J.sessionID,J.kind);if(h.delete(j),!X2(M2(J),new Headers(J.headers)))return}return Z2(M2(J),async(j)=>{let U;for(let x of Object.keys(J.headers)){if(x.toLowerCase()!==y2)continue;U??=J.headers[x],delete J.headers[x]}let L=X?await w2(M2(J),"experimental.ws.handshake",j,"ws"):await r2(M2(J),"experimental.ws.handshake","ws",U,j);j();let B=T2(L),I=L.attempt;if(!B||!I)throw T(L.scope);await C1(L,async()=>{if(!X?.refuseMisplaced)$1(J.headers,L.headers);let x=Z.rewriteHandshakeURL?.({...B,url:J.url,attempt:I});if(x!==void 0)J.url=x;if(X?.refuseMisplaced)$1(J.headers,L.headers);if(t(L.scope,Object.entries(J.headers)),X)h.add(L.key)})})},q2));let B$=Z.rewriteWebSocketFrame?.bind(Z);if(B$)x2.push(await $.session.hook("experimental.ws.send",async(J)=>{let j=M2(J);if(X&&!h.has(D2(j.sessionID,j.kind)))return;let U=Q$(j.sessionID,j.kind),L=await B$({...j,attempt:U?.attempt,frame:J.frame});if(L!==void 0)J.frame=L},q2));x2.push(await $.session.hook("experimental.ws.receive",(J)=>{if(X&&!h.has(D2(J.sessionID,J.kind)))return;let j=Q$(J.sessionID,J.kind);if(!j)return;try{X$(j,"ws",J.frame)}catch(U){g("opencode2 auth frame inspection threw",{error:p(U)})}},q2)),x2.push(await $.session.hook("retry",async(J)=>{if(X&&a.get(J.sessionID)!==!0)return;let j=J.decision,U=()=>y("retry",{sessionID:J.sessionID,attempt:J.attempt,reason:"host-decides",hostDecision:j,decision:j});if(k(J.sessionID)&&!Z.retrySameAccount){await U();return}let L=j$(J.sessionID);if(!L)return;if(L==="ambiguous"){await y("retry",{sessionID:J.sessionID,attempt:J.attempt,reason:"host-decides",hostDecision:j,decision:j});return}let B=L,I=()=>B.hostRetry==="veto";await Z2(B.scope,async(x)=>{let S=x,r=Z.retrySameAccount?.bind(Z),_2=B.attempt,L2=B.outputStarted;if(L2&&B.httpReadFailed&&r&&_2&&!k(J.sessionID)){if(!B.limit){let V2=Z.limitFromError?.(J.error,_2);if(V2)t2(B,V2,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;S()}let h2=()=>B.httpReadFailed===!0&&J.error.type==="provider.transport"&&j.retry&&H-J.attempt>=1&&!B.limit&&!(B.status!==void 0&&B.status>=400)&&!(J.error.status!==void 0&&J.error.status>=400)&&!_2?.reboundFrom&&!I()&&!k(J.sessionID);if(r&&_2&&(!L2||h2())&&(!I()||k(J.sessionID))&&!B.sameAccountRetry){if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;let V2=await D(B.scope.sessionID,async()=>{S();let z2=_2.accountId,i=()=>V.has(B.id)&&B.accountId===z2&&j$(J.sessionID)===B&&B.outputStarted===L2&&(!L2||h2())&&(!I()||k(J.sessionID))&&(!X||a.get(J.sessionID)===!0);if(!i()||B.sameAccountRetry)return!1;B.sameAccountRetry=!0;let Y2={...B.scope,accountId:z2,error:J.error,attempt:J.attempt,...B.limit?{limit:B.limit.signal}:{},...L2?{continuation:"interrupted-read"}:{}},u;try{u=await r(Y2)}catch(d){g("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:J.sessionID,error:p(d)})}if(!u)return S(),!1;let H2={accountId:u.accountId,input:Y2,...L2?{continuation:!0}:{}};try{S()}catch(d){throw await f(H2),d}if(!i()||u.accountId!==z2)return await f(H2),!1;let O2=C.get(B.key);if(C.delete(B.key),O2)await q(O2);try{S()}catch(d){throw await f(H2),d}if(!i())return await f(H2),!1;return C.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++E,accountId:z2,sameAccount:H2}),B.judged=!0,J.decision=L2?j:{retry:!0,delay:0},!0});if(S(),V2){await y("retry",{sessionID:J.sessionID,accountId:B.accountId,kind:B.scope.kind,attempt:J.attempt,reason:L2?"continue-same-account":"same-account",hostDecision:j,decision:J.decision,handle:B.attempt});return}}if(k(J.sessionID)){await U();return}B.judged=!0;let P2=B.attempt;if(P2&&!B.outputStarted){if(!B.limit){let V2=Z.limitFromError?.(J.error,P2);if(V2)t2(B,V2,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered}S();let{decision:Q2,reason:g2}=await D(B.scope.sessionID,async()=>{if(S(),k(J.sessionID))return{decision:j,reason:"host-decides"};let V2=C.get(B.key);if(C.delete(B.key),V2)await q(V2);if(S(),k(J.sessionID))return{decision:j,reason:"host-decides"};let z2=j,i,Y2,u,H2;if(B.accountId===void 0||!P2)z2={retry:!1},i="no-account";else if(B.outputStarted)z2={retry:!1},i="output-started";else if(I())z2={retry:!1},i="adapter-veto";else if(B.limit){let O2={accountId:B.accountId,limit:B.limit.signal},d,b2={...B.scope,phase:"retry",...K(B.request),hostAttempt:J.attempt,previousAccountId:B.accountId,rerouteFrom:O2};try{d=await Z.chooseAccount(b2)}catch(A1){g("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:B.scope.sessionID,error:p(A1)})}let S2=typeof d==="string"?d:typeof d==="object"&&("hold"in d)?B.accountId:void 0;if(_(S2,b2,B.request)){if(S2!==void 0)await R({accountId:S2,input:b2});d=void 0}let o=typeof d==="object"&&"hold"in d?d.hold:void 0,N2=typeof d==="object"&&"waitThenReselect"in d?d.waitThenReselect:void 0,d0=typeof d==="object"&&"hostRetry"in d?d.hostRetry:void 0,e2=typeof d==="string"?d:o?B.accountId:void 0;if(e2!==void 0)u={accountId:e2,input:b2};try{S()}catch(A1){if(u)await R(u);throw A1}if(k(J.sessionID)){if(u)await R(u);return{decision:j,reason:"host-decides"}}if(I()||d0==="veto"){if(u)await R(u);if(u=void 0,S(),k(J.sessionID))return{decision:j,reason:"host-decides"};B.hostRetry="veto",z2={retry:!1},i="adapter-veto"}else if(!(H-J.attempt>=1)){if(u)await R(u);u=void 0,i="host-decides-last-account"}else if(N2&&Number.isFinite(N2.delayMs)&&N2.delayMs>=0&&N2.delayMs<=S1)z2={retry:!0,delay:Math.ceil(N2.delayMs)},i="wait-then-reselect";else if(o&&Number.isFinite(o.delayMs)&&o.delayMs>=0&&o.delayMs<=S1){if(z2={retry:!0,delay:Math.ceil(o.delayMs)},o.target!==void 0)H2={target:o.target,...o.checkpoint===void 0?{}:{checkpoint:o.checkpoint},...o.kind===void 0?{}:{kind:o.kind}};i="hold"}else if(!o&&e2!==void 0&&e2!==B.accountId)B.rerouted=!0,B.request.excluded.add(B.accountId),Y2=O2,z2={retry:!0,delay:0},i="reroute";else{if(o&&u)await R(u),u=void 0;i="host-decides-last-account"}}else i="host-decides";if(J.decision=z2,z2.retry&&B.accountId!==void 0&&V.has(B.id))C.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++E,accountId:B.accountId,...Y2===void 0?{}:{rerouteFrom:Y2},...u===void 0?{}:{next:u},...H2===void 0?{}:{wake:H2}});else if(u)await R(u);if(!z2.retry)Q(B.request);return{decision:z2,reason:i}});S(),await y("retry",{sessionID:J.sessionID,...B.accountId===void 0?{}:{accountId:B.accountId},kind:B.scope.kind,attempt:J.attempt,reason:g2,hostDecision:j,decision:Q2,...P2===void 0?{}:{handle:P2}})})},q2));let V$=(J)=>{if(l(J),a.delete(J),!A.get(J)?.foreignSeen)A.delete(J);for(let j of h)if(JSON.parse(j)[0]===J)h.delete(j);for(let j of[...V.values()]){if(j.scope.sessionID!==J)continue;e(j,"its session was forgotten"),Q(j.request),V.delete(j.id)}for(let[j,U]of C)if(U.sessionID===J)w(j)},O1=new AbortController,W$=$.event;if(W$)(async()=>{try{for await(let J of W$.subscribe({signal:O1.signal}))if(J.type==="session.deleted")V$(J.data.sessionID);else if(J.type==="session.status"&&J.data.status.type==="idle"){let j=J.data.sessionID,U=++E;D(j,async()=>{for(let[L,B]of C)if(B.sessionID===j&&B.order<U)C.delete(L),Q(B.request),await q(B)})}}catch(J){if(!O1.signal.aborted)g("opencode2 auth stopped listening for session deletion",{error:p(J)})}})();return{on(J,j){let U=K2.get(J);if(!U)U=new Set,K2.set(J,U);let L=j;return U.add(L),()=>{U.delete(L)}},accountFor(J,j){return c(D2(J,j))?.accountId},forgetSession:V$,get size(){return V.size},async dispose(){if(j2)return;j2=!0;for(let J of b.keys())l(J);O1.abort();for(let J of V.values())e(J,"the installation was disposed");V.clear();for(let J of C.keys())w(J);h.clear(),a.clear(),A.clear(),K2.clear(),await Promise.all(M.values()),await Promise.all(x2.map(async(J)=>{try{await J.dispose()}catch(j){g("opencode2 auth hook did not dispose cleanly",{error:p(j)})}}))}}}import{createHash as s0}from"node:crypto";var r0=1024,t0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),N$=($)=>F$($,"user"),e0=($)=>t0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function $4($){return s0("sha256").update(JSON.stringify($)).digest("hex")}class I2{runtime;maxSessions;#$=new Map;constructor($,Z=r0){this.runtime=$;this.maxSessions=Z}advance($,Z,z=this.runtime){let G=this.#$.get($),X=Array.isArray(Z.input)?Z.input:[],Y=X.filter(N$),F=X.findLastIndex(N$),W=F<0?void 0:$4(X[F]),H=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,N,V,P;if(H)N=Y.length>0,V=W??G?.fingerprint,P=G?.userCount===void 0?void 0:G.userCount+Y.length;else{V=W,P=Y.length;let E=F>=0&&F>X.findLastIndex(e0),h=G!==void 0&&!G.completed&&G.fingerprint===V&&G.userCount===P;N=E&&!h}let C=N||!G?{turnID:(z?.uuid??k2)(),turnStartedAt:(z?.now??Date.now)()}:{turnID:G.turnID,turnStartedAt:G.turnStartedAt};return this.#Z($,{...C,completed:!1,fingerprint:V,userCount:P}),C}completed($){let Z=this.#$.get($);if(Z)this.#Z($,{...Z,completed:!0})}get($){return this.#$.get($)}forget($){this.#$.delete($)}#Z($,Z){this.#$.delete($),this.#$.set($,Z);while(this.#$.size>this.maxSessions){let z=this.#$.keys().next().value;if(z===void 0)break;this.#$.delete(z)}}}function b1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var K$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function Z4(){let $=globalThis;return $[K$]??=crypto.randomUUID(),$[K$]}class l2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,z){this.runtime=$;this.store=z;this.installationID=Z??Z4(),this.sessions=z?.sessions??new Map,this.frameTurns=z?.frameTurns??new I2}get($){let Z=this.runtime?.uuid??k2;if(this.store)return this.store.get($,Z);let z=this.sessions.get($);if(!z){let G=Z();z={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,z)}return z}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(J1(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var D1={version:T$,"user-agent":_$,originator:"codex_exec"};var J4=1024,z4=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,G1=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),M$=($)=>G1($)&&($.type==="message"||("role"in $))&&$.role==="user",E$=($)=>G1($)&&$.type==="configuration_update";class k1{http;#$=new Map;constructor($=new l2){this.http=$}apply($,Z,z){if(Z.kind!=="primary")return!1;let G=typeof $.model==="string"?$.model:"";if(!L$.has(G))return!1;if(z4.test(G))return!1;let X=G1($.reasoning)?$.reasoning:void 0,Y=typeof X?.effort==="string"?X.effort:void 0;if(!Y)return!1;let F=this.#$.get(Z.sessionID);if(F===void 0)return this.#Z(Z.sessionID,Y),!1;if(Y===F)return!1;let W=Array.isArray($.input)?$.input:void 0;if(!W||W.length===0)return!1;let H=W.findLastIndex(M$);if(H<0){if(z==="http")return!1;return $.reasoning={...X,effort:F},!0}if($.reasoning={...X,effort:F},!E$(W[H-1]))W.splice(H,0,{type:"configuration_update",reasoning:{effort:Y}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>J4){let z=this.#$.keys().next().value;if(z===void 0)break;this.#$.delete(z)}}}function J1($){try{let Z=JSON.parse($);return G1(Z)?Z:void 0}catch{return}}async function C$($,Z,z,G,X=z.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Y=await $.clone().text(),F=J1(Y);if(F)delete F.max_output_tokens;let W=new Headers($.headers),H=z1({rewriteLite:P$,init:{body:F?JSON.stringify(F):$.body===null?void 0:Y},headers:W,metadata:X.get(Z.sessionID),installationID:X.installationID,runtime:X.runtime,websocket:!1,responsesLite:G,applyEffort:(N)=>{z.apply(N,Z,"http")}});return new Request($,{headers:W,body:H.init?.body})}function O$($,Z,z,G){let X=G.sessions.get($.sessionID),Y=G.frameTurns.get($.sessionID);if(!X||!Y)return;let F=b1(X,Y),W=new Headers({"content-type":"application/json"});for(let N of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let V=z.get(N);if(V!==null)W.set(N,V)}z1({init:{body:$.bodyText},headers:W,metadata:F,installationID:G.installationID,runtime:G.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let H=new URL(Z);if(H.protocol==="wss:")H.protocol="https:";if(H.protocol==="ws:")H.protocol="http:";return new Request(H,{method:"POST",headers:W,body:$.bodyText})}function G4($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let z=Z.findIndex((G,X)=>JSON.stringify(G)!==JSON.stringify($[X]));return z>=0&&E$(Z[z])&&M$(Z[z+1])&&JSON.stringify(Z.slice(z+1))===JSON.stringify($.slice(z))}function A$($,Z,z){let G=J1($);if(G?.type!=="response.create")return;let X=z.http.advanceFrame(Z.sessionID,G),Y=z.http.get(Z.sessionID);delete G.max_output_tokens;let F=z1({rewriteLite:()=>{},init:{body:JSON.stringify(G)},headers:new Headers,metadata:b1(Y,X),installationID:z.http.installationID,runtime:z.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(H)=>{z.apply(H,Z,"ws")}}),W=J1(String(F.init?.body));if(!W)return;if(!G4(G.input,W.input)){if("input"in G)W.input=G.input;else delete W.input;return JSON.stringify(W)}return String(F.init?.body)}function Q4($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function w1($,Z){let z=new URL($);if(z.origin!=="https://api.openai.com"&&z.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(z.pathname))return $;let G=new URL(`${Q4(Z)}/responses`);if(G.search=z.search,z.protocol==="ws:"||z.protocol==="wss:")G.protocol=G.protocol==="https:"?"wss:":"ws:";return G.href}import{resolve as y1}from"node:path";var R$=Symbol.for("@cortexkit/openai-auth/opencode2-rate-limits/v1"),x$=globalThis,I1=x$[R$]??new Map;x$[R$]=I1;function S$($){let Z=I1.get($);if(!Z)Z=new Map,I1.set($,Z);return Z}function q$($){return S$(JSON.stringify(["pool",y1($.configPath),y1($.statePath)]))}function b$($){return S$(JSON.stringify(["vault",y1($)]))}import{resolve as D$}from"node:path";var Y4=1024;class Q1{accounts=new Map;limit;constructor($=Y4){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let z=this.accounts.keys().next().value;if(z===void 0)break;this.accounts.delete(z)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var k$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),w$=globalThis,f1=w$[k$]??new Map;w$[k$]=f1;function v1($){let Z=JSON.stringify([D$($.configPath),D$($.statePath)]),z=f1.get(Z);if(!z)z=new Q1,f1.set(Z,z);return z}var E2="openai",X4=60000,h1=1,j4="request refused: no account with a usable credential",C2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function B4($){let Z=C2($)?$.counters:void 0,z=C2(Z)?Z.resetCredits:void 0,G=C2(z)?z.value:void 0;return typeof G==="number"&&Number.isFinite(G)?G:void 0}function c2($){try{return JSON.parse($)}catch{return}}function u2($){let Z=j1($);return Z?B1(Z):void 0}var V4=new Set(["usage_limit_reached","rate_limit_exceeded"]);function c1($,Z,z){return{reason:$.window,...z!==void 0?{status:z}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function W4($,Z){let z=X1($);if(z){let Y=typeof $.status==="number"?$.status:void 0;return c1(z,Z,Y)}if($.type!=="response.failed"||!C2($.response))return;let G=$.response.failed;if(C2(G)&&typeof G.rate_limit_reached_type==="string")return{reason:G.rate_limit_reached_type};let X=$.response.error;if(C2(X)){let Y=typeof X.code==="string"?X.code:typeof X.type==="string"?X.type:void 0;if(Y&&V4.has(Y))return{reason:Y}}return}function U4($,Z){let z=c2($);if(!C2(z))return;let G=typeof z.type==="string"?z.type:void 0;if(G==="codex.rate_limits")return{quota:{snapshot:v$(z),complete:!0}};let X=W4(z,Z);if(X)return{limit:X};if(G===void 0||G==="error")return;return r$(G)?void 0:{outputStarted:!0}}function H4($){let Z=!1;for(let z of $.keys())if(z.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:I$($),complete:f$($)}}function N4($){let Z=$.get("retry-after");if(Z===null)return;let z=Number(Z);return Number.isFinite(z)&&z>=0?z*1000:void 0}function e$($){let Z=new WeakMap,z=new WeakSet,{source:G,pins:X}=$,Y=$.now??Date.now,F=$.log,W=$.vault,H=new k1($.codex),N=new Map,V=new Map,P=(Q)=>`${Q.sessionID}\x00${Q.kind}`,C=new Map,E=(Q)=>`${Q.sessionID}\x00${Q.kind}\x00${Q.accountId}`,h=W?.paths?.rosterPath,a=h?b$(h):new Map,A=$.sessionAccounts??new Q1,k=new i$,W2=(Q,K,_)=>{let M=_?[]:t$(G.peek().rows,Q,K,W?.identities()??new Set),D=(W?.routes()??[]).filter((O)=>O.kind==="oauth"&&g$(d2(O.quota),Q,K));return[...M.map((O)=>({id:O.id,...O.identity!==void 0?{identity:O.identity}:{},quota:O.quota,row:O})),...D.map((O)=>({id:O.id,...O.identity!==void 0?{identity:O.identity}:{},quota:O.quota}))]},X2=(Q,K,_)=>{let M=c$(Q,K,_),D=Q.map((q)=>({id:q.id,kind:"oauth",...y$(q.quota)?{quota:q.quota}:{}})),O=Q.flatMap((q)=>q.row?[q.row]:[]),R=new Set(Q.filter((q)=>!q.row).map((q)=>q.id)),f=G.rateLimitMarks(O);for(let q of R){let w=a.get(q);if(w===void 0)continue;if(w<=_)a.delete(q);else f.set(q,w)}return{rows:D,now:_,rateLimitMarks:f,refreshBackoff:G.refreshBackoffFor(O),killswitch:M,requestPull:(q)=>R.has(q)?W?.requestReading(q):G.requestReading(q)}},v=(Q,K,_,M,D)=>{let O=l1({...Q,placement:m1(K),mainId:D});if(O.kind==="block"){F?.debug("pool admission refused the request",{reason:O.block.reason});return}let R=O.order.filter((f)=>!_.has(f));if(M!==void 0&&R.includes(M))return M;return R[0]},n=(Q,K)=>{let _=new Map(Q.map((M)=>[M.id,M.quota]));return{requestBytes:h1,reservePercent:(M)=>m$(K,M===p$?void 0:M),resetCredits:(M)=>B4(_.get(M))}},K2=(Q,K,_,M,D,O,R,f)=>{let q=n(K,_),w=u1(Q),y=(c,m)=>V1(R,{sessionId:M,requestBytes:h1,validPinnedAccountIds:Q.rows.map(($2)=>$2.id).filter(($2)=>!w.excluded.has($2)),excludeAccountIds:c,quotaCheckedAtByAccount:Object.fromEntries(Q.rows.map(($2)=>[$2.id,w.projections.get($2.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(K.map(($2)=>[$2.id,$2.identity])),select:($2)=>f?{accountId:f,source:"mode-fallback",quotaCheckedAt:w.projections.get(f)?.checkedAt}:a$(Q,q,new Set(c),$2),persist:m},($2,T2)=>R.set($2,T2)),J2=[...D],G2=y(J2,O);if(!G2)return;let e=G2.accountId,s=p1(Q,q,e);if(s.kind==="none")return;if(s.kind==="move"){let c=y([...J2,e],O);if(c)return c.accountId;return s.reason==="killswitch"?void 0:e}if(s.kind==="detour")return y([...J2,e],!1)?.accountId;return e},b={providerID:E2,async retrySameAccount(Q){if(Q.continuation!=="interrupted-read")return;let K=V.get(P(Q));if(V.delete(P(Q)),!K||K.accountId!==Q.accountId||K.modelID!==Q.modelID||K.agent!==Q.agent||Q.limit)return;let _=W!==void 0&&await W.authority()!=="local",M=await $.storage();if(!_&&!(await G.current()).active)return;let D=Y(),O=W2(M,D,_),R=O.find((y)=>y.id===Q.accountId);if(!R)return;let f=X2(O,M,D),q=M?.routing?.mode??"main-first";if(q==="sticky-balanced"){let y=p1(f,n(O,M),Q.accountId);if(y.kind!=="serve"&&y.kind!=="last-path")return}else{let y=l1({...f,placement:m1(q),..._?{mainId:g1(W?.routes()??[])}:{}});if(y.kind==="block"||!y.order.includes(Q.accountId))return}let w=K.data;if(R.row){if(w?.kind!=="pool")return;let y=G.usableToken(R.row),J2=R.row.identity??(y&&u2(y));if(!y||!w.identity||J2!==w.identity)return}else{if(w?.kind!=="vault"||!W)return;let y=await W.authorize(Q.accountId);if(!y||y.credentialId!==w.credentialId||y.accountIdentity!==w.accountIdentity||(y.accountIdentity??u2(y.accessToken))!==w.wireIdentity||R.identity!==void 0&&R.identity!==w.wireIdentity)return}return{accountId:Q.accountId}},dropSameAccountRetry(){},dropChoice(Q){let K=E(Q);C.get(K)?.drop(),C.delete(K),N.delete(K)},chooseAccount:async(Q)=>{let K=await W?.authority(),_=await $.storage(),M=K!==void 0&&K!=="local",D=()=>{throw new F2({kind:"no-account",providerID:E2,sessionID:Q.sessionID,requestKind:Q.kind,message:W1})};if(M)await $.awaitVaultRoster?.();else{if(!(await G.current()).active){if(await $.slotPlaceholderWithoutMain?.())D();F?.warn("the account pool does not serve requests yet; refusing the request",{kind:Q.kind});return}await G.prepareTokens(G.peek().rows,_)}let O=Y(),R=W2(_,O,M),f=d$(X2(R.filter((T)=>T.id!==Q.rerouteFrom?.accountId),_,O));if(f)await f,O=Y(),R=W2(_,O,M);let q=new Map(R.map((T)=>[T.id,T])),w=X2(R,_,O),y=new Set(Q.rerouteFrom?[Q.rerouteFrom.accountId]:[]),J2=_?.routing?.mode??"main-first",G2=Q.kind==="primary",e=new Set,s,c,m,$2=!1,T2=(T)=>{let l=u1(w).projections.get(T)?.checkedAt,Z2=q.get(T)?.identity;return X.reserve(Q.sessionID,{accountId:T,inputBytes:h1,...l!==void 0?{quotaCheckedAt:l}:{},...Z2!==void 0?{wireIdentity:Z2}:{}})};try{for(;;){let T=new Set([...y,...e]);m=void 0,s=void 0;let l=J2!=="sticky-balanced";if(J2==="sticky-balanced"){let t=new Map(X.placementSnapshot(Q.sessionID)),B2=t.get(Q.sessionID);if(l=B2===void 0,m=K2(w,R,_,Q.sessionID,T,G2&&e.size===0,t),m!==void 0&&t.get(Q.sessionID)!==B2)s=t.get(Q.sessionID)}if(m??=v(w,J2,T,G2?void 0:A.activeAccount(Q.sessionID),M?J2==="sticky-balanced"?null:g1(W?.routes()??[]):void 0),m===void 0||e.has(m)){if(y.size>0){let t=new Map(w.rateLimitMarks);for(let B2 of y)t.delete(B2);w={...w,rateLimitMarks:t},y.clear();continue}if(w.rateLimitMarks.size>0){w={...w,rateLimitMarks:new Map};continue}m=void 0;break}if(G2&&J2==="sticky-balanced")c=T2(m);if(!$2){$2=!0;let t=await n$({vaultMode:M,fresh:l,sessionId:Q.sessionID,request:{modelId:Q.modelID,kind:Q.kind,retry:Q.phase==="retry"||Q.rerouteFrom!==void 0},routes:W?.routes()??[],routing:w,eligibleIds:R.filter((B2)=>!T.has(B2.id)).map((B2)=>B2.id)});if(t&&t!==m){if(c)X.rollback(c);if(c=void 0,J2==="sticky-balanced"){let B2=new Map(X.placementSnapshot(Q.sessionID));m=K2(w,R,_,Q.sessionID,T,G2,B2,t)??m,s=B2.get(Q.sessionID)??s}else m=t;if(G2&&J2==="sticky-balanced")c=T2(m)}}let Z2=q.get(m)?.row;if(Z2){if(G.usableToken(Z2)!==void 0)break;F?.debug("pool row holds no usable token; choosing again",{accountId:m})}else{if(!W)break;let t=await W.authorize(m);if(t){N.set(E({...Q,accountId:m}),t);break}F?.debug("the vault refused to serve an account; choosing again",{accountId:m})}if(c)X.rollback(c);c=void 0,e.add(m)}if(m===void 0&&!M&&R.length===0&&await $.slotPlaceholderWithoutMain?.())D();if(m===void 0&&M&&W&&(R.length===0||e.size>0)){let T=e.size>0?"vault-refused":u$(W);throw F?.warn("vault mode: no vault account can serve; refusing the request",{cause:T}),new F2({kind:"no-account",providerID:E2,sessionID:Q.sessionID,requestKind:Q.kind,message:l$(T,W.name)})}if(m!==void 0){let T=m,l=c,Z2=s,t=()=>{if(l)X.finish(l,Z2);if(G2)A.record(Q.sessionID,T),$.onRoute?.(Q.sessionID,T,J2)};if(Q.phase==="retry")C.set(E({...Q,accountId:m}),{commit:t,drop:()=>{if(l)X.rollback(l)}}),c=void 0;else t();let B2=F?.info;k.served(w,m,F&&B2?{info:(w2,r2)=>B2.call(F,w2,r2)}:void 0)}return F?.debug("pool account chosen",{kind:Q.kind,accountId:m,mode:J2,...Q.rerouteFrom?{rerouteFrom:Q.rerouteFrom.accountId}:{}}),m}finally{if(c)X.rollback(c)}},accountHeaders:async(Q)=>{let{accountId:K}=Q;V.delete(P(Q));let _=E(Q),M=C.get(_);C.delete(_);let D=()=>{M?.commit()};try{let O=()=>new F2({kind:"no-account",providerID:E2,sessionID:Q.sessionID,requestKind:Q.kind,message:j4}),R=W&&await W.authority()!=="local"?void 0:G.peek().rows.find((w)=>w.id===K);if(!R&&W){let w=E(Q),y=N.get(w)??await W.authorize(K);if(N.delete(w),!y)throw F?.warn("the vault refused to serve an account; refusing the request",{accountId:K}),O();return D(),{headers:{...D1,"session-id":Q.sessionID,authorization:`Bearer ${y.accessToken}`,"chatgpt-account-id":y.accountIdentity??u2(y.accessToken)??null},attempt:{kind:"vault",routeId:K,receipt:y}}}let f=R?G.usableToken(R):void 0;if(!R||!f)throw F?.warn("pool row holds no usable token; refusing the request",{accountId:K}),O();let q=R.identity??u2(f);return D(),{headers:{...D1,"session-id":Q.sessionID,authorization:`Bearer ${f}`,"chatgpt-account-id":q??null},attempt:{kind:"pool",token:f,credentialEpoch:R.credentialEpoch,...q!==void 0?{identity:q}:{}}}}finally{M?.drop()}},async rewriteRequest({request:Q,sessionID:K,kind:_}){let M=$.codexEndpoint?w1(Q.url,$.codexEndpoint()):Q.url,D=M===Q.url?Q:new Request(M,Q);return await C$(D,{sessionID:K,kind:_},H,$.responsesLite?.()??!1)??D},rewriteHandshakeURL:({url:Q})=>$.codexEndpoint?w1(Q,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:Q,sessionID:K,kind:_})=>A$(Q,{sessionID:K,kind:_},H),quotaFromHeaders:(Q,K,_)=>{if(_.data?.kind==="vault")W?.reportUsage(_.data.routeId,{headers:Q},_.data.receipt);if(_.data?.kind==="vault"&&p2()&&K>=200&&K<300)Z.set(_,{status:K,headers:Q});return H4(Q)},async limitFromResponse({status:Q,headers:K,body:_,attempt:M}){if(Q<400)return;let D=c2(await _().catch(()=>"")),O=X1({...C2(D)?D:{},status:Q});if(M.data?.kind==="vault"&&p2())Y1(M.sessionID,M.data.receipt,{status:Q,headers:K,body:D,limit:O,quota:W?.routes().find((w)=>w.id===M.accountId)?.quota,now:Y()});if(!O)return;let R=Y(),f=c1(O,R,Q);if(f.retryAfterMs!==void 0)return f;let q=N4(K);return q===void 0?f:{...f,retryAfterMs:q}},inspectEvent:({data:Q,transport:K,attempt:_})=>{if(_.data?.kind==="vault"&&Q.includes("codex.rate_limits")){let M=c2(Q);if(C2(M)&&M.type==="codex.rate_limits")W?.reportUsage(_.data.routeId,{frame:M},_.data.receipt)}if(_.data?.kind==="vault"&&p2()&&(s$(Q)||K==="ws"&&Q.includes('"response.completed"'))){let M=c2(Q);if(o$(M))z.add(_);if(K==="ws"&&C2(M)&&M.type==="response.completed")Y1(_.sessionID,_.data.receipt,{status:200,headers:new Headers,failed:z.has(_)})}return U4(Q,Y())},limitFromError(Q){let K=c2(Q.message),_=X1({...C2(K)?K:{},...Q.status!==void 0?{status:Q.status}:{}})??(Q.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return _?c1(_,Y(),Q.status):void 0},async onAttemptEnd(Q,K){let _=Q.data;if(_&&K.outputStarted&&K.error?.reason==="failed"){if(V.set(P(Q),{accountId:Q.accountId,modelID:Q.modelID,agent:Q.agent,sessionID:Q.sessionID,data:_.kind==="pool"?{kind:"pool",identity:_.identity}:{kind:"vault",credentialId:_.receipt.credentialId,accountIdentity:_.receipt.accountIdentity,wireIdentity:_.receipt.accountIdentity??u2(_.receipt.accessToken)}}),V.size>Z1){let D=V.keys().next().value;if(D!==void 0)V.delete(D)}}let M=_?.kind==="vault"&&p2()?Z.get(Q):void 0;if(Z.delete(Q),_?.kind==="vault"&&M&&!K.error&&!K.limit)Y1(Q.sessionID,_.receipt,{...M,failed:z.has(Q)});if(_?.kind!=="vault"||K.status!==401)return;F?.warn("a vault account answered 401; reporting it to the vault",{accountId:Q.accountId}),await W?.reportFailure(_.receipt,401)}},g=(Q,K,_)=>{let M=_.data;if(M?.kind==="vault"){W?.recordSnapshot(Q,K.snapshot,K.complete,M.receipt);return}if(M?.kind!=="pool")return;if(G.peek().rows.find((O)=>O.id===Q)?.credentialEpoch!==M.credentialEpoch){F?.debug("quota reading dropped: the row holds another credential",{accountId:Q});return}G.recordSnapshot(Q,K.snapshot,M.token,K.complete)},p=(Q,K,_)=>{let M=Y(),D=_.data?.kind==="vault",O=D?W?.routes().find((q)=>q.id===Q)?.quota:G.peek().rows.find((q)=>q.id===Q)?.quota,R=h$(d2(O),K.reason,M,X4,K.retryAfterMs!==void 0?M+K.retryAfterMs:void 0);if(!D){G.markRateLimited(Q,R);return}let f=a.get(Q);if(f===void 0||f<R)a.set(Q,R)};return{adapter:b,attach(Q){Q.on("quota",(K)=>g(K.accountId,K.quota,K.handle)),Q.on("limit",(K)=>{p(K.accountId,K.limit,K.handle),F?.debug("pool row refused the request",{accountId:K.accountId,via:K.via,reason:K.limit.reason,outputStarted:K.outputStarted})})},forgetSession(Q){for(let[K,_]of V)if(_.sessionID===Q)V.delete(K);X.forget(Q),A.forget(Q),H.forget(Q)},activeAccount:(Q)=>A.activeAccount(Q)}}import{resolve as QZ}from"node:path";import{Buffer as F4}from"node:buffer";import{resolve as $Z}from"node:path";function i2($){return F4.byteLength(JSON.stringify($))}function K4($){return $.reduce((Z,z)=>Z+i2(z),0)}function d1($,Z){return 2+$+Math.max(0,Z-1)}function T4($){let{head:Z,pending:z}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+d1(Z.inputBytes,Z.input.length)+1:0)+(z?20+d1(z.inputBytes,z.input.length)+10+d1(z.outputBytes,z.output.length)+(z.responseID===void 0?0:14+z.responseIDBytes)+1:0)}function ZZ($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class JZ{enabled;caps=U1;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$)this.entries.clear(),this.bytes=0}send($,Z){if(!this.enabled)return;let z=ZZ(Z);if(z?.type!=="response.create")return;if(!Array.isArray(z.input)){this.forget($);return}let G=z.previous_response_id,X=this.entries.get($),Y=X?.head;if(G&&G!==Y?.responseID){this.forget($);return}let{type:F,previous_response_id:W,input:H,...N}=z;this.keep($,{fields:G&&X?X.fields:N,fieldsBytes:G&&X?X.fieldsBytes:i2(N),...G&&Y?{head:Y}:{},pending:{input:H,inputBytes:K4(H),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,z){if(!this.enabled||!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed"))return;let G=this.entries.get($);if(!G?.pending)return;let X=ZZ(Z);if(!X)return;let Y=G.pending,F=X.response;if(X.type==="response.created"&&typeof F?.id==="string")Y.responseID=F.id,Y.responseIDBytes=i2(F.id),this.keep($,G);else if(X.type==="response.output_item.done"&&X.item){if(typeof X.response_id==="string"&&Y.responseID!==void 0&&X.response_id!==Y.responseID)return;Y.output.push(X.item),Y.outputBytes+=i2(X.item),this.keep($,G)}else if(X.type==="response.completed"&&typeof F?.id==="string"){if(F.id===G.head?.responseID||Y.responseID!==void 0&&F.id!==Y.responseID)return;let W={responseID:F.id,responseIDBytes:Y.responseID===F.id?Y.responseIDBytes:i2(F.id),input:[...G.head?.input??[],...Y.input,...Y.output],inputBytes:(G.head?.inputBytes??0)+Y.inputBytes+Y.outputBytes},H={...G,head:W,pending:void 0};if(!this.keep($,H))return;z?.({sessionID:$,responseID:W.responseID,bodyText:this.body(G.fields,W)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let z=T4(Z);if(this.forget($),z>this.caps.maxBytes)return!1;Z.bytes=z,this.entries.set($,Z),this.bytes+=z;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let G=this.entries.keys().next().value;if(G===void 0)break;this.forget(G)}return this.entries.has($)}}var zZ=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),GZ=globalThis,i1=GZ[zZ]??new Map;GZ[zZ]=i1;function H1($){let Z=JSON.stringify([$Z($.configPath),$Z($.statePath)]),z=i1.get(Z);if(!z)z=new JZ,i1.set(Z,z);return z}var _4=5000,L4=["accept","originator","session-id","thread-id","user-agent","version","x-client-request-id","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-openai-internal-codex-responses-lite","x-opencode-parent-session-id","x-parent-session-id"],P4=["x-opencode-parent-session-id","x-parent-session-id"];function BZ($){let Z=YZ($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:XZ($?{...$,cachekeep:Z}:$)}}var VZ=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),WZ=globalThis,a2=WZ[VZ]??new Map;WZ[VZ]=a2;function M4($,Z){let z=[],G=()=>z.at(-1)?.location,X=()=>{let H=G();if(!H)throw Error("no location holds keep-warm");return H},Y=(H,N)=>{W.remove(H),G()?.log?.debug(`cachekeep dropped target (${N})`,{sessionKey:H})},F=async(H)=>{if(H.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let N=H.accountId??"main",V=X(),P=await V.source.accessFor(N,await V.storage());if(!P)throw Error(`pool row ${N} has no usable token`);return{token:P.token,identity:P.row.identity}},W=jZ({...U1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(H,N)=>X().fetch(H,N),logger:{debug:(H,N)=>G()?.log?.debug(H,N),warn:(H,N)=>G()?.log?.warn(H,N)},getWindow:()=>G()?.settings().window,getSustain:()=>G()?.settings().sustain===!0,resolveLocal:F,vault:{owns:(H)=>G()?.vault.owns(H)===!0,authority:()=>X().vault.authority(),reportUsage:(...H)=>G()?.vault.reportUsage(...H),send:async(H,N,V)=>{let P=X();if(await P.vault.authority()!=="vault")return;return P.vault.send(H,N,V)}},activeAccount:(H)=>{if(H===void 0)throw Error("target has no session");let N=G(),V=N?.settings();if(!N||!V?.enabled){Y(H,"keep-warm is off");return}if(!V.subagents&&W.status().targets.some((C)=>C.sessionKey===H&&C.isSubagent)){Y(H,"subagent warming is off");return}let P=N.accounts.activeAccount(H);if(P===void 0){Y(H,"no account recorded for the session");return}return P},verifyCredential:({target:H,mode:N,identity:V})=>{if(H.meta.credentialMode!==N)throw Error(`a target captured in ${H.meta.credentialMode??"an unknown"} mode is not warmed with a ${N} credential`);if(V!==H.meta.chatgptAccountId)throw Y(H.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:W,settings:Z,holders:z,joinTimeoutMs:$.joinTimeoutMs??_4}}function E4($){try{let Z=JSON.parse($),z=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(z?.role!=="user")return!1;return(typeof z.content==="string"?z.content:Array.isArray(z.content)?z.content.map((X)=>typeof X?.text==="string"?X.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function C4($){let Z={};for(let z of L4){let G=$.get(z);if(G)Z[z]=G}return Z}function UZ($,Z,z){let G=JSON.stringify([QZ($.configPath),QZ($.statePath)]),X=a2.get(G);if(!X)X=M4(z,Z.settings()),a2.set(G,X);let Y=X,F=H1($);F.setEnabled(Y.settings.enabled);let W={location:{...Z,settings:()=>Y.settings}};Y.holders.push(W);let H=!1,N=async(V)=>{try{let P=W.location.settings();if(H||!P.enabled)return;if(V.kind!=="primary"){if(V.kind==="generate"&&E4(await V.request.clone().text())){if(H)return;Y.manager.remove(V.sessionID)}return}let C=V.attempt.data,E=C?.kind==="pool"?"local":C?.kind==="vault"?"vault":void 0;if(!E)return;let h=V.request.headers,a=P4.some((W2)=>h.has(W2))||Z.parentOf!==void 0&&await Z.parentOf(V.sessionID)!==void 0;if(a&&!P.subagents)return;let A=await V.request.clone().text();if(H)return;let k=h.get("chatgpt-account-id")??void 0;Y.manager.track({sessionKey:V.sessionID,bodyText:A,accountId:V.attempt.accountId,isSubagent:a,meta:{replayHeaders:C4(h),...k?{chatgptAccountId:k}:{},routingSessionId:V.sessionID,url:V.request.url,credentialMode:E}})}catch(P){Z.log?.warn("cachekeep capture failed",{error:P instanceof Error?P.message:String(P)})}};return{manager:Y.manager,configure:(V)=>{Object.assign(Y.settings,V),F.setEnabled(Y.settings.enabled)},capture:N,forget:(V)=>Y.manager.remove(V),async release(){if(H)return;H=!0;let V=Y.holders.indexOf(W);if(V>=0)Y.holders.splice(V,1);if(Y.holders.length>0)return;if(a2.get(G)===Y)a2.delete(G);Y.manager.stop();let P;try{await Promise.race([Y.manager.tick().catch(()=>{}),new Promise((C)=>{P=setTimeout(C,Y.joinTimeoutMs),P.unref?.()})])}finally{clearTimeout(P)}}}}import{mkdirSync as O4}from"node:fs";import{dirname as A4,resolve as R4}from"node:path";function x4(){return HZ("opencode2")}var S4=2000;class _Z{path;options;sessions;frameTurns=new I2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Q=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=KZ($,Z.uuid??k2)}get($,Z=k2){let z=this.sessions.get($);if(!z){let G=Z();z={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,z),this.#Z.delete($),this.#z.delete($),this.#$.add($),this.#Y()}return z}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#z.add($);this.#Y()}#Y(){if(this.#J)return;this.#J=setTimeout(()=>{this.#J=void 0,this.save()},this.options.saveDelayMs??S4),this.#J.unref?.()}save(){if(clearTimeout(this.#J),this.#J=void 0,!this.#Q)this.#Q=!0,this.#G=this.#G.then(()=>{return this.#Q=!1,this.#j()});return this.#G}settled(){return this.#J?this.save():this.#G}#X(){if(this.#z.size===0)return;let $;try{$=a1(this.path)}catch{$=new Map}for(let Z of this.#z)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#z.clear()}async#j(){if(this.#X(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((G)=>{let X=this.sessions.get(G);return X?[[G,X]]:[]}),Z=[...this.#Z],z=null;try{if(O4(A4(this.path),{recursive:!0}),z=await this.#B(),!z)return;let G;try{G=a1(this.path)}catch{G=new Map}await this.options.afterRead?.();let X=!1;for(let Y of Z)if(G.delete(Y))X=!0;for(let[Y,F]of $){if(G.get(Y)===F.threadID)continue;G.set(Y,F.threadID),X=!0}if(X)TZ(this.path,G)}catch{return}finally{await z?.release().catch(()=>{})}for(let[G,X]of $)if(this.sessions.get(G)===X)this.#$.delete(G);for(let G of Z)if(!this.sessions.has(G))this.#Z.delete(G)}#B(){return FZ(this.path,this.options.lockWaitMs??NZ)}}var LZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),PZ=globalThis,N1=PZ[LZ]??new Map;PZ[LZ]=N1;function q4($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.sessions instanceof Map&&typeof Z.get==="function"&&typeof Z.delete==="function"&&typeof Z.save==="function"&&typeof Z.settled==="function"&&(Z.frameTurns===void 0||Z.frameTurns!==null&&typeof Z.frameTurns.advance==="function"&&typeof Z.frameTurns.get==="function"&&typeof Z.frameTurns.completed==="function"&&typeof Z.frameTurns.forget==="function")}function MZ($=x4()){let Z=R4($),z=N1,G=N1.get(Z),X=N1;if(G!==void 0&&!q4(G))z.compatible??=new Map,X=z.compatible;let Y=X.get(Z);if(!Y)Y=new _Z(Z),X.set(Z,Y);let F=Y;return F.frameTurns??=new I2,Y}var n1=Symbol.for("cortexkit.openai-auth.v2.commands"),b4=R2("v2-command");function F1($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.closed instanceof AbortController&&typeof Z.menu?.open==="function"&&typeof Z.menu?.apply==="function"&&typeof Z.session?.get==="function"&&(Z.registration===void 0||Z.registration!==null&&typeof Z.registration.dispose==="function")}function o1($){b4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function D4(){let $=globalThis;return $[n1]??={locations:new Map},$[n1].locations??=new Map,$[n1]}async function SZ($,Z){let z=D4(),G=$.location.directory,X={menu:Z,session:$.session,closed:new AbortController},Y=await CZ(G),F=await EZ(RZ,Y.dir,()=>xZ({...Y,drain:AZ,apply:(P)=>{let C=z.locations.get(G);if(!F1(C))throw Error("The OpenAI menu location was closed");return C.menu.apply(P)}})),W=z.locations.get(G);if(z.locations.set(G,X),F1(W))W.closed.abort(),await W.registration?.dispose();let H={name:"openai",description:"OpenAI account menu",async execute(P){let C=[...z.locations.values()].find(F1)?.session;if(!C)return o1("no live location");let E=await C.get({sessionID:P.sessionID}),h=z.locations.get(E.location.directory);if(!F1(h))return o1("location closed");let a=await OZ(P.sessionID,h.closed.signal);if(!a||z.locations.get(E.location.directory)!==h){if(!a&&!h.closed.signal.aborted)s1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},P.sessionID);return o1(h.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let A=await h.menu.open(P.sessionID);s1(A,P.sessionID)}};z.command??=H,z.command.execute=H.execute;let N=z.command;try{X.registration=await $.command.transform((P)=>{P.add(N)})}catch(P){if(X.closed.abort(),z.locations.get(G)===X)z.locations.delete(G);throw await F.release(),P}let V=!1;return async()=>{if(V)return;if(V=!0,X.closed.abort(),z.locations.get(G)===X)z.locations.delete(G);await F.release(),await X.registration?.dispose()}}var k4="openai-auth-pool-browser",w4="openai-auth-pool-headless",y4="openai-auth-vault",I4="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Run /openai → Vault → Connect and approve the request before trying again.";async function n2($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function yZ($){return{method:{id:y4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await qZ($.paths,$.name)!=="vault")throw Error(I4)}}}function IZ($){let Z=(z,G,X)=>({method:{id:z,type:"oauth",label:G},async authorize(){if($.vault)await n2($.vault);let Y=await $.beginLogin({version:$.version,headless:X});return{url:Y.url,instructions:Y.instructions,mode:"auto",callback:Y.completion}}});return[Z(k4,"ChatGPT (openai-auth pool, browser)",!1),Z(w4,"ChatGPT (openai-auth pool, headless)",!0)]}function r1($){let Z=(z)=>typeof z==="string"?z:"";return m2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===kZ||bZ($)}function f4($){if($.accountId)return $.accountId;let Z=$.access?j1($.access):void 0;return Z?B1(Z):void 0}async function fZ($,Z,z,G={}){if(G.vault)await n2(G.vault);if(r1(z))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let X=DZ($,{rowLocks:(E)=>wZ(Z,E)}),Y=await X.read();if(Y.status!=="ready")throw Error(`the account pool cannot be read (${Y.status}); the login was not stored`);let F={type:"oauth",refresh:z.refresh,...z.access!==void 0?{access:z.access}:{},...z.expires!==void 0?{expires:z.expires}:{}},W=f4(z);if(G.vault)await n2(G.vault);let H=W!==void 0?{identity:W}:{};if(G.origin==="import"){let E=Y.rows.find((h)=>W!==void 0&&h.identity===W||h.credential?.type==="oauth"&&h.credential.refresh===z.refresh);if(E)return{id:E.id,operation:"kept"}}let N=Y.rows.filter((E)=>E.type==="oauth"&&!E.invalid),V=W?N.find((E)=>E.identity===W):void 0,P=Y.rows.find((E)=>E.id===K1);if(V)return{id:(await X.replace(V.id,F,H)).id,operation:"replaced"};if(!P){let E=await X.add({id:K1,credential:F,...H,...z.label!==void 0?{label:z.label}:{}});return{id:E.id,operation:E.outcome==="added-disabled"?"added-disabled":"added"}}if(!P.invalid&&!P.credential)return{id:(await X.replace(K1,F,H)).id,operation:"replaced"};let C=await X.add({id:z.id,credential:F,...H,...z.label!==void 0?{label:z.label}:{}});return{id:C.id,operation:C.outcome==="added-disabled"?"added-disabled":C.outcome==="rotated"?"replaced":"added"}}function v4($){let Z=$.itemId!==void 0;switch($.sectionId){case"accounts":return Z?["enable","disable","remove","move"].includes($.actionId):$.actionId==="add";case"routing":return!Z&&["order","mode"].includes($.actionId);case"quota":return $.actionId==="check";case"limits":return Z?$.actionId==="floors":$.actionId==="killswitch";case"session":return!Z&&$.actionId==="clear-pin";case"vault":return Z?["enable","disable"].includes($.actionId):["connect","disconnect"].includes($.actionId);case"diagnostics":return!Z&&["logging","dump"].includes($.actionId);case"cache":return!Z&&["enabled","subagents","sustain","window"].includes($.actionId);case"reset":return Z&&["preview","spend","retry"].includes($.actionId);default:return!1}}function gZ($){let Z={...$,allowAction:v4,unavailableSections:[]};return{open:(z)=>vZ(Z,z),apply:(z)=>{let G=z!==null&&typeof z==="object"?z:{},X=G.values&&typeof G.values==="object"&&!Array.isArray(G.values)?Object.fromEntries(Object.entries(G.values).filter(([,Y])=>Y===null||["string","number","boolean"].includes(typeof Y))):void 0;return hZ(Z,{command:"openai",sectionId:typeof G.sectionId==="string"?G.sectionId:"",actionId:typeof G.actionId==="string"?G.actionId:"",...X?{values:X}:{},...G.confirmed===!0?{confirmed:!0}:{},...typeof G.itemId==="string"?{itemId:G.itemId}:{},...typeof G.sessionId==="string"?{sessionId:G.sessionId}:{}})}}}function h4($,Z){if(!mZ($.modelID??$.id)){$.enabled=!1;return}let z=lZ($.id);if(z)$.limit={...z};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((G)=>[G.id,G])).values()]}function pZ($){return $.model.transform((Z)=>{let z=Z.list(E2);for(let G of z){let X=uZ(String(G.id)),Y=X?z.find((F)=>String(F.id)===X):void 0;Z.update(E2,String(G.id),(F)=>h4(F,Y?.variants?.map((W)=>({...W,id:String(W.id)}))))}})}class t1{log;pending=new Map;requests=new Map;writing=new Set;constructor($){this.log=$}async safely($){let Z=(async()=>{try{await $()}catch{this.log.warn("request dump failed")}})();this.writing.add(Z);try{await Z}finally{this.writing.delete(Z)}}async captureHttp($,Z){if(!cZ())return;await this.safely(async()=>{let z={sessionID:Z.sessionID,accountId:Z.accountId,transport:"http",phase:"http",url:$.url,method:$.method,headers:new Headers($.headers),bodyText:await $.clone().text()};if(this.pending.set($,{attemptId:Z.attemptId,input:z}),this.requests.set(Z.attemptId,$),this.pending.size>512){let G=this.pending.keys().next().value;if(G)this.take(G)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let z=this.take($);if(z)await this.safely(()=>T1({...z,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let z=this.requests.get($.attemptId),G=z&&this.take(z);if(!G)return;let{reason:X,message:Y}=Z.error,F=Y?`${X}: ${Y}`:X;await this.safely(()=>T1({...G,error:_1(F,z?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>T1({sessionID:Z.sessionID,accountId:Z.accountId,transport:"websocket",phase:"observed",bodyText:$}))}clear(){this.pending.clear(),this.requests.clear()}async settle(){await Promise.all(this.writing)}}class e1{counts=new Map;record($,Z){let z=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof z==="number"&&Number.isFinite(z)?z:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function oZ($){return async(Z)=>{let z=Z.credential;if(z.type!=="oauth"||!z.access)throw Error("the row holds no access token to poll with");let G=await dZ({accessToken:z.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,G),iZ(G,$.now(),!0)}}function sZ($){let{source:Z,counts:z,now:G}=$,X=async(N)=>{let V=await Z.rowAccess(N,await $.storage());if(!V?.row)throw new aZ("unknown_account",`${N==="main"?"Main":"Fallback"} account ${N} was not found.`);return nZ(N,V)},Y=async(N)=>{if($.authority&&await $.authority()!=="local")return{account:N,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[V]=await Z.pollRows(await $.storage(),{ids:[N]});if(!V)return{account:N,ok:!1,error:"targeted quota refresh returned no result"};return{account:V.id,ok:V.ok,...V.error!==void 0?{error:V.error}:{}}},F=(N)=>Z.peek().rows.find((V)=>V.id===N),W=(N)=>{let V=F(N);if(!V)return null;let P=d2(V.quota)??{},C=z.applicable(V),E=Math.max(0,...[P.primary?.checkedAt,P.secondary?.checkedAt].filter((h)=>typeof h==="number"));return{quota:{...P,...C!==void 0?{resetCreditsApplicable:C}:{}},checkedAt:E,refreshAfter:E,...V.identity!==void 0?{accountId:V.identity}:{}}};return{resolveResetTarget:X,refreshResetTargetQuota:Y,quotaManager:{isRateLimited:(N)=>{let V=F(N);if(!V)return!1;let P=Z.rateLimitMarks([V]).get(V.id);return P!==void 0&&P>G()},getMain:()=>W("main"),getFallback:(N)=>W(N)}}}import{resolve as rZ}from"node:path";var g4=1024;class $${pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=g4){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.reservations.delete($),this.pins.delete($);for(let Z of this.listeners)Z($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}snapshot(){return new Map(this.pins)}placementSnapshot($){let Z=new Map(this.pins);for(let z of this.reservations.values())if(z.sessionId!==$)Z.set(z.sessionId,z.pin);return Z}reserve($,Z){let z={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,z),z}rollback($){if(this.reservations.get($.sessionId)===$)this.reservations.delete($.sessionId)}finish($,Z){if(this.reservations.get($.sessionId)!==$)return;if(this.rollback($),Z&&this.pins.get($.sessionId)===$.previous)this.set($.sessionId,Z)}get size(){return this.pins.size}set($,Z){this.reservations.delete($),this.pins.delete($),this.pins.set($,Z);for(let z of this.listeners)z($,Z);while(this.pins.size>this.limit){let z=this.pins.keys().next().value;if(z===void 0)break;this.forget(z)}}place($){return V1(this.placementSnapshot($.sessionId),$,(Z,z)=>this.set(Z,z))}}var tZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),eZ=globalThis,L1=eZ[tZ]??new Map;eZ[tZ]=L1;function m4($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.get==="function"&&typeof Z.forget==="function"&&typeof Z.subscribe==="function"&&typeof Z.snapshot==="function"&&typeof Z.place==="function"&&typeof Z.placementSnapshot==="function"&&typeof Z.reserve==="function"&&typeof Z.rollback==="function"&&typeof Z.finish==="function"}function $0($){let Z=JSON.stringify([rZ($.configPath),rZ($.statePath)]),z=L1,G=L1.get(Z);if(G!==void 0&&!m4(G)){let Y=L1;Y.compatibleV1??=new Map,z=Y.compatibleV1}let X=z.get(Z);if(!X)X=new $$,z.set(Z,X);return X}import{statSync as l4}from"node:fs";import{resolve as u4}from"node:path";function B0($){return $.map((Z)=>{try{let z=l4(Z);return`${z.ino}:${z.size}:${z.mtimeMs}:${z.ctimeMs}`}catch{return"?"}}).join("|")}function Z$($){return B0([$.vault.paths.tokenPath,$.vault.paths.statePath])}function Z0($){return B0([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+Z$($)}class V0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;protocol=U0;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:Z0($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),z=this.subscriptions.get($.pins);if(!z){let G=new Set;z={producers:G,stop:$.pins.subscribe((X,Y)=>{let F=G.values().next().value;if(F)this.publish(F,{sessionId:X,pin:Y,accountId:Y?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,z)}return z.producers.add($),this.timer??=setInterval(()=>{for(let G of this.producers){let X={stamp:Z0(G),roster:G.vault.snapshot()},Y=this.observations.get(G);if(X.stamp!==Y?.stamp||X.roster!==Y?.roster)this.observations.set(G,X),this.publish(G)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),z.producers.delete($),!z.producers.size)z.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;await($.write??W0)(this.file,$,Z,()=>this.producers.has($))}).catch(()=>{R2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var W0=async($,Z,z,G)=>{let Y=await Z.vault.authority()!=="local",F=Z$(Z),W=()=>G()&&Z.vault.enrolled()===Y&&Z$(Z)===F,H=await(Y?s2(Z.paths):f2(Z.paths)),N=Y?X0(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((C)=>C.id)),H,Date.now()):j0((await Z.source.sidebarView()).rows,H,Date.now()),V={canWrite:W,vaultMode:Y};if(await z0(N,$,V),!W()||!z)return;let P=N.vaultAccounts??N.fallbacks;if(z.accountId===void 0){await Q0(z.sessionId,P,$,V);return}if(z.pin){let C=Date.now();await Y0({sessionId:z.sessionId,assignment:{accountId:z.pin.accountId,wireAccountId:z.pin.wireIdentity,inputBytes:z.pin.inputBytes??0,quotaCheckedAt:z.pin.quotaCheckedAt,assignedAt:C,lastSeenAt:C},validPinnedAccountIds:[...Y?[]:["main"],...P.filter((E)=>E.enabled).map((E)=>E.id)]},$,V)}await G0({sessionId:z.sessionId,activeId:z.accountId,route:z.route??N.route,updatedAt:Date.now()},P,$,V)},U0=2,H0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),N0=globalThis,o2=N0[H0]??new Map;N0[H0]=o2;function F0($,Z=J0(),z=2000){let G=u4(Z),X=o2.get(G);if(X?.protocol!==U0)X=new V0(G,z),o2.set(G,X);let Y=X;$={...$,write:$.write??W0};let F=Y.add($),W=!1;for(let[H,N]of $.pins.snapshot())Y.publish($,{sessionId:H,pin:N,accountId:N.accountId,route:"sticky-balanced"});return{publish:()=>Y.publish($),route:(H,N,V)=>{Y.publish($,{sessionId:H,accountId:N,route:V})},async release(){if(W)return;if(W=!0,F(),await Y.settled(),Y.empty&&o2.get(G)===Y)o2.delete(G)}}}var E1="cortexkit-openai-auth",d4=5000;async function K0($,Z,z,G=new l2,X,Y,F){let W=new t1(z),H=new p4,N=new Map,V=new Map,P=(A)=>{V.delete(A);for(let k of N.keys())if(k.startsWith(`${A}:`))N.delete(k)},C=(A)=>{F?.(A.sessionID),Y?.send(A.sessionID,A.frame)},h=await q1({session:{hook:(A,k,W2)=>$.session.hook(A,async(X2)=>{let v=A==="http.request"?X2:void 0,n=A==="experimental.ws.handshake"?X2:void 0,U2=(v?v.request.headers:n?new Headers(n.headers):void 0)?.get("authorization")===`Bearer ${A2(Z.providerID)}`,j2={};if(n)N.delete(`${n.sessionID}:${n.kind}`);try{await H.run(j2,()=>k(X2))}catch(b){if(U2&&!(b instanceof F2))throw E0(b);throw b}if(v&&U2&&j2.attempt){let b=v.request.headers.get("thread-id");if(b)v.request.headers.set("session-id",b)}if(v&&U2&&j2.attempt)await W.captureHttp(v.request,j2.attempt);if(v&&U2&&j2.attempt)await X?.({sessionID:v.sessionID,kind:v.kind,request:v.request,attempt:j2.attempt});if(n&&U2&&j2.attempt)n.headers["session-id"]=G.get(n.sessionID).threadID;if(A==="experimental.ws.send"){let b=X2,g=N.get(`${b.sessionID}:${b.kind}`);if(g)await W.frame(b.frame,g.attempt);if(g&&b.kind==="primary")C(b)}if(v||n){let b=v??n;if(!b)return;let p=(v?v.request.headers:new Headers(b.headers)).get("authorization")?.replace(/^Bearer /,"");if(U2&&p)V.set(b.sessionID,p);else V.delete(b.sessionID);if(n){let Q=`${n.sessionID}:${n.kind}`;if(U2&&p&&j2.attempt)N.set(Q,{bearer:p,attempt:j2.attempt,url:n.url,headers:new Headers(Object.entries(n.headers).filter(([K])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(K.toLowerCase())))});else N.delete(Q)}if(V.size>512){let Q=V.keys().next().value;if(Q)V.delete(Q)}if(N.size>512){let Q=N.keys().next().value;if(Q)N.delete(Q)}}else if(A==="experimental.ws.receive"){let b=X2,g=N.get(`${b.sessionID}:${b.kind}`);if(g){if(G.frameReceived(b.sessionID,b.frame),b.kind==="primary"){let p;if(Y?.receive(b.sessionID,b.frame,(Q)=>{p=Q}),p)try{let Q=O$(p,g.url,g.headers,G);if(Q)await X?.({sessionID:b.sessionID,kind:"primary",request:Q,attempt:g.attempt})}catch(Q){z.warn("cachekeep WebSocket capture failed",{error:Q instanceof Error?Q.message:String(Q)})}}b.frame=C0(b.frame,g.bearer)}}else if(A==="retry"){let b=X2,g=V.get(b.sessionID);if(g)Object.assign(b.error,{message:_1(b.error.message,g)})}},W2)},event:{subscribe:(A)=>async function*(){for await(let k of $.event.subscribe(A)){if(k.type==="session.deleted")P(k.data.sessionID);yield k}}()}},{...Z,rewriteRequest:async(A)=>{let k=H.getStore();if(k)k.attempt=A.attempt;return Z.rewriteRequest?.(A)},rewriteHandshakeURL:(A)=>{let k=H.getStore();if(k)k.attempt=A.attempt;return Z.rewriteHandshakeURL?.(A)},onAttemptEnd:async(A,k)=>{await W.end(A,k),await Z.onAttemptEnd?.(A,k)},rewriteResponse:async(A)=>{await W.response(A.request,A.response.status);let k=await Z.rewriteResponse?.(A)??A.response;return O0(k,A.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(A)=>{let k=A.get("authorization");return k?.startsWith("Bearer ")?k.slice(7):void 0}},logger:{warn:(A,k)=>z.warn(A,{data:k})}}),a=h.dispose;return{...h,dispose:async()=>{V.clear(),N.clear(),await a(),await W.settle(),W.clear()}}}function G$($={}){return{id:E1,setup:(Z)=>i4(Z,$)}}async function i4($,Z={}){let c=[];try{let z=R2("opencode2");let G=R2("quota");let X=Z.version??R0;await h0({version:X,...Z.runtimeLayout});let Y=Z.paths??(()=>S0(A0()));let F=await s2(Y());let W=F?.logging?.level;if(W&&typeof W==="string")_0(W);let H=Z.fetch??fetch;let N=Z.now??Date.now;let V=Z.poolMigration??m0;if(!V&&!v2(Y().configPath)){z.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let T=(Z2)=>{throw new F2({kind:"no-account",providerID:E2,sessionID:Z2.sessionID,requestKind:Z2.kind,message:W1})},l=await K0($,{providerID:E2,chooseAccount:T,accountHeaders:T},z);return()=>l.dispose()}let P=Z.vault?.firstRosterWaitMs??w0;let C=g0({host:"opencode",stateDir:Z.vault?.stateDir??M0(Y().statePath),reservedRouteIds:()=>v.peek().rows.map((T)=>T.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>H},Y());let E=C.vault;let h=async()=>await E.authority()==="local"?f2(Y()):s2(Y());let a=!1;let A=!1;const k=P1(c,{[Symbol.dispose](){if(!a)C.release()}},0);await E.authority();let W2=C.firstRoster;let X2=new e1;let v=new y0({paths:Y,rateLimitMarks:q$(Y()),refreshProvider:async(T)=>{let l=await P0({refreshToken:T.refresh,fetchImpl:H,now:N}),Z2=L0({id_token:"",access_token:l.access,refresh_token:l.refresh});return{...l,...Z2?{identity:Z2}:{}}},pullQuota:oZ({fetchImpl:H,now:N,counts:X2,logger:G}),now:N,vaultIdentities:()=>E.identities(),vaultMode:()=>E.enrolled(),vaultAuthority:()=>E.authority(),vaultFirstRoster:W2,vaultFirstRosterBackgroundWaitMs:P,log:R2("pool")});if(await E.authority()==="local")await v.load();let n=Z.heartbeat===!1?void 0:await f0({version:X,logger:R2("heartbeat")});let K2=Z.fence??(()=>x0({currentVersion:X}));let U2=Z.slot??l0();let j2=async()=>q0(Y(),await U2.get({path:{id:"openai"}}));let b=!1;let g=V?I0({paths:Y,slot:U2,version:X,fence:K2,runDeps:{vaultServes:()=>E.serves()},paused:async()=>await E.authority()!=="local",migrate:async(T)=>{let l=await b0(T);if(b=l.status==="refused",!A)await v.load();return l},adopt:async(T)=>{if(A)return{status:"retry",reason:"unsettled"};if(!await z$(W2,P))return{status:"retry",reason:"vault-roster-pending"};if(A)return{status:"retry",reason:"unsettled"};let l=await D0(T);if(!A)await v.load();return l}}):void 0;g?.start();C.start();let p=$0(Y());let Q=F0({paths:Y(),source:v,pins:p,vault:E},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const K=P1(c,{[Symbol.dispose](){if(!a)Q.release()}},0);Q.publish();let _=Z.codex??new l2(void 0,void 0,MZ());let M=BZ(F);let D=H1(Y());let O=UZ(Y(),{source:v,storage:h,vault:E,accounts:v1(Y()),settings:()=>M,parentOf:async(T)=>(await $.session.get({sessionID:T}))?.parentID??void 0,fetch:H,log:R2("cachekeep")},{now:N,codexResponsesUrl:M1().codexApiEndpoint,...Z.cacheKeep});const R=P1(c,{[Symbol.dispose](){if(!a)O.release()}},0);let f=e$({codex:_,onRoute:Q.route,source:v,slotPlaceholderWithoutMain:j2,storage:h,pins:p,sessionAccounts:v1(Y()),vault:E,awaitVaultRoster:async()=>{await z$(E.awaitRequestRoster(),k0)},responsesLite:()=>M1().responsesLite,codexEndpoint:()=>M1().codexApiEndpoint,now:N,log:z});let q=await K0($,f.adapter,z,_,(T)=>O.capture(T),D,(T)=>O.forget(T));f.attach(q);let w=async(T)=>{if(await n2(E),v2(Y().configPath))return;if(await g?.idle(),v2(Y().configPath))return;if(b&&!r1(T)&&(await K2()).open){await v.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let y=async(T)=>{await w(T);let l=await fZ(v.poolStore(),Y(),T,{vault:E});if(!v2(Y().configPath))await g?.requestAdoption();await v.load(),z.info("ChatGPT login stored in the account pool",l)};let J2=await R1($,{integrationID:E2,methods:IZ({beginLogin:Z.beginLogin??J$,version:X,vault:E}),onLogin:(T)=>y(T),label:"ChatGPT (openai-auth account pool)",vault:yZ(E)});let G2=await pZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let e=$.command&&$.location?await SZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??gZ({...sZ({source:v,storage:h,counts:X2,now:N,authority:()=>E.authority()}),fetchImpl:H,now:N,randomUUID:c4,accountStoragePath:Y().configPath,accountStatePath:Y().statePath,packageVersion:X,layoutNotice:v0,loadAccounts:f2,store:()=>v.poolStore(),migration:async()=>{if(v2(Y().configPath))return{migrated:!0};let T=await K2();return{migrated:!1,blockers:T.open?[]:T.blockers}},beginAccountLogin:Z.beginLogin??J$,refreshAllQuota:async()=>(await v.pollRows(await f2(Y()))).map((T)=>({...T,account:T.id})),getStickyRouting:async(T)=>p.get(T),cacheKeepManager:O.manager,setCacheKeepEnabled:(T)=>O.configure({enabled:T}),setCacheKeepSubagents:(T)=>O.configure({subagents:T}),setCacheKeepSustain:(T)=>O.configure({sustain:T}),setCacheKeepWindow:(T)=>O.configure({window:T}),afterWrite:()=>v.load(),refreshSidebar:()=>Q.publish(),clearStickyRouting:async(T)=>{let l=p.get(T)!==void 0;return p.forget(T),l},vault:E})):void 0;let s=new AbortController;(async()=>{try{for await(let T of $.event.subscribe({signal:s.signal}))if(T.type==="session.deleted")f.forgetSession(T.data.sessionID),O.forget(T.data.sessionID),D.forget(T.data.sessionID)}catch(T){if(!s.signal.aborted)z.warn("stopped listening for session deletion",{error:T instanceof Error?T.message:String(T)})}})();a=!0;return async()=>{A=!0,s.abort();let T=O.release();await e?.(),g?.dispose(),await v.dispose(),await Q.release(),await Promise.allSettled([q.dispose(),J2.dispose(),G2.dispose()]);let l;try{await Promise.race([Promise.all([g?.idle(),v.settled(),_.store?.settled(),T]),new Promise((Z2)=>{l=setTimeout(Z2,d4),l.unref?.()})])}finally{clearTimeout(l),C.release(),await n?.release()}}}catch(m){var $2=m,T2=1}finally{T0(c,$2,T2)}}var a4=G$(),M7={id:E1,setup:a4.setup,server:u0.server};export{M7 as default,G$ as createOpenAIAuthPlugin,E1 as OPENAI_AUTH_PLUGIN_ID};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-openai-auth",
3
- "version": "1.9.4",
3
+ "version": "1.9.6",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -66,17 +66,17 @@
66
66
  },
67
67
  "devDependencies": {
68
68
  "@ai-sdk/openai": "3.0.88",
69
- "@cortexkit/common-auth": "^0.33.0",
69
+ "@cortexkit/common-auth": "^0.36.0",
70
70
  "@cortexkit/openai-auth-core": "workspace:*",
71
- "@opencode/plugin": "2.2.0"
71
+ "@opencode/plugin": "2.2.5"
72
72
  },
73
73
  "dependencies": {
74
- "@cortexkit/claustrum-client": "^0.13.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",
78
78
  "@opentui/solid": ">=0.7.0",
79
- "ai": "^7.0.155",
79
+ "ai": "^7.0.159",
80
80
  "jsonc-parser": "^3.3.1",
81
81
  "solid-js": "1.9.12"
82
82
  }
@@ -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
- if (!/^[0-9a-f]{64}$/.test(value.token) ||
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.#client.close();
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 immediately; allow token reads 2 s and share an owner's timeout warning. */
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
  }