@cortexkit/opencode-openai-auth 1.6.2 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/bin.js +9 -9
  2. package/dist/{codex-request-D_In8uaR.d.ts → codex-request-DohnbsFR.d.ts} +66 -848
  3. package/dist/index-3v868rnp.js +63 -0
  4. package/dist/{index-b0ty9qam.js → index-5d4y47h8.js} +2 -2
  5. package/dist/{index-7nmdsmpp.js → index-5dxpsa3t.js} +2 -2
  6. package/dist/{index-8xq099qf.js → index-8pk9savd.js} +6 -6
  7. package/dist/{index-jkpg9d1p.js → index-cbcka7sa.js} +1 -1
  8. package/dist/{index-79y7w9bz.js → index-cxstwq02.js} +1 -1
  9. package/dist/{index-x9nffaye.js → index-dtwgf694.js} +1 -1
  10. package/dist/index-dzaqj248.js +2 -0
  11. package/dist/index-g3d50jz0.js +74 -0
  12. package/dist/{index-1qxz4s8a.js → index-n7fxqgfb.js} +2 -2
  13. package/dist/{index-rf0ht3gc.js → index-th47aqez.js} +2 -2
  14. package/dist/index-tvban5vp.js +91 -0
  15. package/dist/{index-ya9c5e4m.js → index-x7jzcvqy.js} +1 -1
  16. package/dist/index.d.ts +6 -79
  17. package/dist/index.js +1 -1
  18. package/dist/{port-file-8ElfwDcq.d.ts → port-file-DQ7-ItDK.d.ts} +1 -1
  19. package/dist/{model-D22uj0OB.d.ts → protocol-CVQK-d3j.d.ts} +25 -67
  20. package/dist/rpc/port-file.d.ts +4 -2
  21. package/dist/rpc/port-file.js +1 -1
  22. package/dist/rpc/protocol.d.ts +1 -1
  23. package/dist/rpc/protocol.js +1 -1
  24. package/dist/rpc/rpc-client.d.ts +2 -12
  25. package/dist/rpc/rpc-client.js +1 -1
  26. package/dist/rpc/rpc-dir.js +1 -1
  27. package/dist/rpc-client-BQfIKrXI.d.ts +13 -0
  28. package/dist/{sidebar-state-Bb9L9oPq.d.ts → sidebar-state-B1cq68UB.d.ts} +5 -7
  29. package/dist/sidebar-state.d.ts +2 -2
  30. package/dist/sidebar-state.js +1 -1
  31. package/dist/{token-xtq3457d.js → token-gy442bba.js} +1 -1
  32. package/dist/token-util-rxy0p234.js +1 -0
  33. package/dist/tui-preferences.js +1 -1
  34. package/dist/tui.d.ts +11 -2
  35. package/dist/v2/server.d.ts +15 -7
  36. package/dist/v2/server.js +2 -2
  37. package/package.json +2 -2
  38. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +95 -11
  39. package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +320 -35
  40. package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +187 -12
  41. package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +988 -0
  42. package/src/tui-compiled/raw/shared/458b934e92490331-mutate.js +4 -0
  43. package/src/tui-compiled/raw/shared/81dddd203f1b92a3-quota-writer.js +34 -12
  44. package/src/tui-compiled/raw/shared/836fc615de6afbd9-settings.js +16 -6
  45. package/src/tui-compiled/raw/shared/88b7fc40900fb003-commit-interval.js +18 -0
  46. package/src/tui-compiled/raw/shared/92e38944b51b2405-file-read-cache.js +57 -0
  47. package/src/tui-compiled/raw/shared/a670cb7f5987bc1b-shutdown.js +42 -0
  48. package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +37 -12
  49. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +1 -1
  50. package/src/tui-compiled/raw/shared/c911dbb64c9d85c7-quota-writer.js +27 -13
  51. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +20 -11
  52. package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +37 -4
  53. package/src/tui-compiled/raw/tui/v2.tsx +88 -6
  54. package/src/tui-compiled/raw/tui.tsx +45 -3
  55. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +95 -11
  56. package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +320 -35
  57. package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +187 -12
  58. package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +988 -0
  59. package/src/tui-compiled/runtime/shared/458b934e92490331-mutate.js +4 -0
  60. package/src/tui-compiled/runtime/shared/81dddd203f1b92a3-quota-writer.js +34 -12
  61. package/src/tui-compiled/runtime/shared/836fc615de6afbd9-settings.js +16 -6
  62. package/src/tui-compiled/runtime/shared/88b7fc40900fb003-commit-interval.js +18 -0
  63. package/src/tui-compiled/runtime/shared/92e38944b51b2405-file-read-cache.js +57 -0
  64. package/src/tui-compiled/runtime/shared/a670cb7f5987bc1b-shutdown.js +42 -0
  65. package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +37 -12
  66. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +1 -1
  67. package/src/tui-compiled/runtime/shared/c911dbb64c9d85c7-quota-writer.js +27 -13
  68. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +20 -11
  69. package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +37 -4
  70. package/src/tui-compiled/runtime/tui/v2.js +66 -5
  71. package/src/tui-compiled/runtime/tui.js +32 -3
  72. package/dist/index-ge60xry3.js +0 -90
  73. package/dist/index-k5anexvs.js +0 -69
  74. package/dist/index-xpc2hm9h.js +0 -65
  75. package/dist/index-z8bptbrk.js +0 -2
  76. package/dist/protocol-CK9guiFy.d.ts +0 -29
  77. package/dist/token-util-nyvn9866.js +0 -1
package/dist/v2/server.js CHANGED
@@ -1,3 +1,3 @@
1
- import{c as tZ}from"../index-79y7w9bz.js";import{A as u2,B as M$,C as C$,D as dZ,E as iZ,F as E1,G as aZ,H as nZ,I as U$,J as CZ,K as EZ,L as oZ,M as rZ,N as u$,O as p$,P as v2,Q as W$,T as JZ,U as zZ,aa as jZ,ba as VZ,d as x$,e as hZ,f as XZ,fa as sZ,g as n2,h as C2,i as l2,j as pZ,k as cZ,l as d2,la as I1,m as P2,ma as v1,o as y1,p as f1,pa as eZ,q as k1,r as y2,s as q$,t as b$,u as D$,v as m$,w as g$,x as l$,y as e$,z as $Z}from"../index-xpc2hm9h.js";import{Aa as Z$,Ra as a$,Ya as g2,gb as i2,hb as fZ,ib as IZ,jb as vZ,lb as mZ,mb as n$,vb as gZ,wa as yZ,wb as lZ,xb as uZ,yb as o$,za as $$}from"../index-k5anexvs.js";import{Ob as LZ,bc as PZ,cc as TZ,ec as _Z,ic as MZ}from"../index-1qxz4s8a.js";import{Hd as U2,Md as t1,Od as _$,Pd as e1,Vd as c2,Wc as h2,Xc as m2,Yc as kZ,ae as QZ,be as S2,ce as J$,dd as C1,de as z$,ed as n1,ee as G$,fd as o1,gd as r1,ge as X$,he as Y$,je as Q$,ke as j$,le as V1,me as V$,ne as B$,od as d$,ud as i$,wd as wZ,xd as YZ,yc as a1,yd as s1}from"../index-ge60xry3.js";import{te as S$}from"../index-8xq099qf.js";import{Ce as v$}from"../index-z8bptbrk.js";import"../index-rf0ht3gc.js";import{Me as DZ,Oe as Y2}from"../index-b0ty9qam.js";import"../index-7nmdsmpp.js";import{if as h$}from"../index-x9nffaye.js";import{mf as a2,nf as bZ}from"../index-ya9c5e4m.js";import{AsyncLocalStorage as J4}from"node:async_hooks";import{randomUUID as z4}from"node:crypto";class J2 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 j2($){return`common-auth-placeholder.${$}`}function x1($){let Z=j2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function O2($,Z){if($?.type!=="oauth")return!1;let J=Z===void 0?void 0:j2(Z),z=(X)=>J===void 0?X.startsWith("common-auth-placeholder."):X===J;return z($.access)&&z($.refresh)}var q1="No browser sign-in: this connects the plugin to the accounts in its vault.";async function t2($,Z){let J=Z.now??Date.now,{integrationID:z}=Z,X=(N)=>x1({integrationID:z,methodID:N,now:J()}),Y=async(N,U)=>{return await Z.onLogin(N,{integrationID:z,methodID:U}),X(U)},F=(N)=>async(U)=>{let j=N.method.id,B=await N.authorize(U),L={url:B.url,instructions:B.instructions,...B.expiresAt===void 0?{}:{expiresAt:B.expiresAt}};if(B.mode==="auto")return{...L,mode:"auto",callback:B.callback.then((T)=>Y(T,j))};let S=B.callback;return{...L,mode:"code",callback:async(T)=>Y(await S(T),j)}};return $.integration.transform((N)=>{let U=Z.label===void 0?{}:{label:()=>Z.label};for(let L of Z.methods)N.method.update({integrationID:z,method:L.method,authorize:F(L),refresh:async(S)=>{if(!O2(S,z))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return X(S.methodID)},...U});let j=Z.vault;if(j===void 0)return;let B=j.method.id;N.method.update({integrationID:z,method:j.method,authorize:async()=>({url:"",instructions:j.instructions??q1,mode:"auto",callback:Promise.resolve().then(()=>j.activate({integrationID:z,methodID:B})).then(()=>X(B))}),refresh:async(L)=>{if(!O2(L,z)||L.methodID!==B)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return X(B)},...U})})}function J0($){let Z=[],J;for(let z of $.split(/\r?\n/))if(z.startsWith("data:"))Z.push(z.slice(5).replace(/^ /,""));else if(z.startsWith("event:"))J=z.slice(6).trim();if(Z.length===0)return;return J===void 0?{data:Z.join(`
1
+ import{c as V0}from"../index-cxstwq02.js";import{A as G0,B as M$,C as DZ,D as wZ,E as j0,F as s$,G as t$,H as g2,I as C$,L as WZ,M as UZ,N as HZ,V as PZ,W as TZ,_ as B0,d as nZ,e as FZ,ea as a1,f as s2,fa as i1,g as E2,h as c2,i as n2,ia as W0,k as c1,l as d1,m as u1,n as v2,o as o$,p as M1,q as r$,r as jZ,s as BZ,t as d2,u as k$,v as D$,w as Z0,x as J0,y as q1,z as z0}from"../index-3v868rnp.js";import{$a as o2,Bb as _2,Cb as h$,Db as m$,Eb as P1,Fb as g$,Gb as l$,Ib as Y0,Jb as Q0,Ka as JZ,Kb as X0,Ra as p2,ab as dZ,bb as aZ,cb as iZ,db as rZ,eb as v$,gb as sZ,hb as zZ,pa as cZ,qb as tZ,rb as eZ,sa as V$,sb as $0,ta as W$,tb as GZ}from"../index-g3d50jz0.js";import{Ub as xZ,hc as SZ,ic as qZ,kc as bZ,oc as kZ}from"../index-n7fxqgfb.js";import{Dd as ZZ,Ec as z$,Fd as pZ,Gd as KZ,Hd as X$,Qd as H2,Vd as j$,Xd as b$,Yd as B$,ce as i2,dd as l2,ed as u2,fd as uZ,je as LZ,ke as q2,le as U$,md as S1,me as H$,nd as G$,ne as N$,od as Y$,pd as Q$,pe as F$,qe as K$,se as L$,te as P$,ue as H1,ve as T$,we as _$,xd as $Z}from"../index-tvban5vp.js";import"../index-8pk9savd.js";import{Me as i$,Ne as oZ}from"../index-dzaqj248.js";import"../index-th47aqez.js";import{Ye as lZ,_e as V2}from"../index-5d4y47h8.js";import"../index-5dxpsa3t.js";import{vf as n$}from"../index-dtwgf694.js";import{Af as gZ,zf as r2}from"../index-x7jzcvqy.js";import{AsyncLocalStorage as V4}from"node:async_hooks";import{randomUUID as W4}from"node:crypto";class Z2 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 B2($){return`common-auth-placeholder.${$}`}function v1($){let Z=B2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function R2($,Z){if($?.type!=="oauth")return!1;let J=Z===void 0?void 0:B2(Z),z=(Q)=>J===void 0?Q.startsWith("common-auth-placeholder."):Q===J;return z($.access)&&z($.refresh)}var h1="No browser sign-in: this connects the plugin to the accounts in its vault.";async function z1($,Z){let J=Z.now??Date.now,{integrationID:z}=Z,Q=(H)=>v1({integrationID:z,methodID:H,now:J()}),Y=async(H,U)=>{return await Z.onLogin(H,{integrationID:z,methodID:U}),Q(U)},N=(H)=>async(U)=>{let j=H.method.id,B=await H.authorize(U),L={url:B.url,instructions:B.instructions,...B.expiresAt===void 0?{}:{expiresAt:B.expiresAt}};if(B.mode==="auto")return{...L,mode:"auto",callback:B.callback.then((_)=>Y(_,j))};let b=B.callback;return{...L,mode:"code",callback:async(_)=>Y(await b(_),j)}};return $.integration.transform((H)=>{let U=Z.label===void 0?{}:{label:()=>Z.label};for(let L of Z.methods)H.method.update({integrationID:z,method:L.method,authorize:N(L),refresh:async(b)=>{if(!R2(b,z))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return Q(b.methodID)},...U});let j=Z.vault;if(j===void 0)return;let B=j.method.id;H.method.update({integrationID:z,method:j.method,authorize:async()=>({url:"",instructions:j.instructions??h1,mode:"auto",callback:Promise.resolve().then(()=>j.activate({integrationID:z,methodID:B})).then(()=>Q(B))}),refresh:async(L)=>{if(!R2(L,z)||L.methodID!==B)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return Q(B)},...U})})}function F0($){let Z=[],J;for(let z of $.split(/\r?\n/))if(z.startsWith("data:"))Z.push(z.slice(5).replace(/^ /,""));else if(z.startsWith("event:"))J=z.slice(6).trim();if(Z.length===0)return;return J===void 0?{data:Z.join(`
2
2
  `)}:{event:J,data:Z.join(`
3
- `)}}function e2($,Z){let J=new TextDecoder,z="",X=(F)=>{let N=J0(F);if(!N)return;try{$(N)}catch(U){Z(U)}},Y=()=>{for(;;){let F=/\r?\n\r?\n/.exec(z);if(!F)return;let N=z.slice(0,F.index);z=z.slice(F.index+F[0].length),X(N)}};return new TransformStream({transform(F,N){N.enqueue(F),z+=J.decode(F,{stream:!0}),Y()},flush(){if(z+=J.decode(),Y(),z.trim()!=="")X(z);z=""}})}var b1=512,M2="x-common-auth-attempt",L2=($,Z)=>JSON.stringify([$,Z]),V2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function z0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function G0($,Z){let J=$.getReader();return new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(Y){Z({reason:"failed",message:Y instanceof Error?Y.message:String(Y)}),z.error(Y);return}if(X.done)Z(),z.close();else z.enqueue(X.value)},async cancel(z){Z({reason:"cancelled",...z===void 0?{}:{message:String(z)}}),await J.cancel(z)}})}function $1($,Z){for(let[J,z]of Object.entries(Z)){let X=J.toLowerCase();for(let Y of Object.keys($))if(Y.toLowerCase()===X)delete $[Y];if(z!==null)$[J]=z}}function X0($,Z){for(let[J,z]of Object.entries(Z))if(z===null)$.delete(J);else $.set(J,z)}async function Z1($,Z,J={}){let{providerID:z}=Z,X=J.gateOnPlaceholder,Y=(G)=>X===void 0||X.credential(G)===j2(z),F=J.logger,N=Math.max(1,J.maxRecords??b1),U=[...J.hostCredentials??[j2(z)],...X?[j2(z)]:[]].filter((G)=>G!==""),j=new Map,B=new WeakMap,L=new Map,S=new Set,T=new Map,u=!1,a=!1,R=new Map,k=0,z2=!1,w=new Map,h=(G,Q)=>{try{F?.warn(G,Q)}catch{}},v=(G)=>G instanceof Error?G.message:String(G),V=new Map,P=(G,Q)=>{let W=(V.get(G)??Promise.resolve()).then(Q),H=W.then(()=>{},()=>{});return V.set(G,H),H.then(()=>{if(V.get(G)===H)V.delete(G)}),W},E=(G,Q)=>{let W=V.get(G);return W?W.then(()=>E(G,Q)):Q()},K=async(G)=>{try{await Z.dropChoice?.({...G.input,accountId:G.accountId})}catch(Q){h("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:G.input.sessionID,error:v(Q)})}},A=(G)=>{let Q=L.get(G);if(L.delete(G),Q?.next){let W=Q.next;P(Q.sessionID,()=>K(W))}},_=async(G,Q)=>{let W=R.get(G);if(!W||W.size===0)return;await Promise.all([...W].map(async(H)=>{try{await H(Q)}catch(x){h("opencode2 auth listener threw; the request is unaffected",{event:G,error:v(x)})}}))},C=async(G,Q)=>{try{await Z.onAttemptEnd?.(G,Q)}catch(W){h("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:G.attemptId,error:v(W)})}},y=(G,Q)=>{if(G.ended||!G.attempt)return;let W={...G.status===void 0?{}:{status:G.status},outputStarted:G.outputStarted,...G.limit?{limit:G.limit.signal}:{},...Q?{error:Q}:{}};if(Q)G.endError=Q;G.ended=C(G.attempt,W)},b=(G,Q)=>y(G,{reason:"abandoned",message:Q}),m=(G)=>[...j.values()].filter((Q)=>Q.key===G),g=(G)=>m(G).at(-1),r=(G)=>{if(j.delete(G.id),L.get(G.key)?.attemptId===G.id||!m(G.key).length)A(G.key)},e=(G)=>{j.set(G.id,G);while(j.size>N){let Q=j.values().next().value;if(Q===void 0)break;b(Q,"dropped to keep the record bound"),r(Q)}},c=(G)=>G.accountId===void 0?void 0:{...G.scope,accountId:G.accountId},s=(G,Q)=>new J2({kind:"no-account",providerID:z,sessionID:G.sessionID,requestKind:G.kind,...Q===void 0?{}:{message:Q}}),l=(G)=>{w.get(G)?.clear(),w.delete(G)},f=async(G,Q)=>{let W=()=>s(G,`${z} ${G.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(z2)throw W();let H=w.get(G.sessionID);if(!H)H=new Set,w.set(G.sessionID,H);let x={};H.add(x);let q=()=>{if(!H.has(x))throw W()};try{return await Q(q)}finally{if(H.delete(x),H.size===0&&w.get(G.sessionID)===H)w.delete(G.sessionID)}},I=(G,Q)=>{for(let[W,H]of Q)if(U.some((x)=>H.includes(x)))throw new J2({kind:"host-credential-on-wire",providerID:z,sessionID:G.sessionID,requestKind:G.kind,message:`${z} ${G.kind} request still carries the host's placeholder credential in ${W}; the adapter's account headers must replace it`})},$2=(G)=>{for(let Q of m(G))if(Q.ended||!Q.attempt)r(Q);else if(Q.transport==="ws"||Q.judged)b(Q,"a newer attempt of its session and kind began"),r(Q)},p=async(G,Q,W,H)=>{let x=L2(G.sessionID,G.kind),{input:q,accountId:O}=await E(G.sessionID,async()=>{W();let o=L.get(x);L.delete(x);let _2=o?.accountId??g(x)?.accountId;$2(x);let t=o?.next,E2=t!==void 0&&t.input.modelID===G.modelID&&t.input.agent===G.agent,N2={...G,phase:"request",..._2===void 0?{}:{previousAccountId:_2},...o?.rerouteFrom?{rerouteFrom:o.rerouteFrom}:{}};if(t&&!E2)await P(G.sessionID,()=>K(t)),W();let k2=E2?t.accountId:await Z.chooseAccount(N2);return{input:N2,accountId:k2}});W();let D={},i;if(O!==void 0){let o=await Z.accountHeaders({...G,accountId:O});if(W(),z0(o))D=o.headers,i=o.attempt;else D=o}let G2=`attempt-${++k}`,Z2={id:G2,key:x,scope:G,accountId:O,headers:D,attempt:O===void 0?void 0:{...G,accountId:O,attemptId:G2,transport:H,data:i},...H===void 0?{}:{transport:H},outputStarted:!1};if(e(Z2),Z2.attempt)_("select",{...G,accountId:Z2.attempt.accountId,hook:Q,...q.previousAccountId===void 0?{}:{previousAccountId:q.previousAccountId},...q.rerouteFrom===void 0?{}:{rerouteFrom:q.rerouteFrom},handle:Z2.attempt});return Z2},n=async(G,Q,W,H,x)=>{let q=L2(G.sessionID,G.kind),O=H===void 0?void 0:j.get(H);if(O?.key!==q)O=void 0;if(!O){if(O=g(q),m(q).filter((i)=>i.transport===void 0&&!i.ended).length>1&&!a)a=!0,h("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:G.sessionID,kind:G.kind})}if(!O||O.transport!==void 0||O.ended)O=await p(G,Q,x,W);else if(O.transport=W,O.attempt)O.attempt.transport=W;if(W==="ws"){for(let D of m(q))if(D!==O&&D.transport==="ws")b(D,"a newer attempt of its session and kind went out over WebSocket")}return O},W2=async(G,Q)=>{try{return await Q()}catch(W){throw y(G,{reason:"failed",message:v(W)}),W}},T2=(G,Q)=>{let W=m(L2(G,Q)).filter((H)=>H.transport==="ws").at(-1);return W?.attempt!==void 0&&!W.ended?W:void 0},F2=(G,Q,W)=>{let H=c(G);if(!H||!G.attempt||G.limit)return;G.limit={signal:Q,delivered:_("limit",{...H,via:W,limit:Q,outputStarted:G.outputStarted,handle:G.attempt})}},M=(G,Q,W,H)=>{let x=c(G);if(!x||!G.attempt)return;_("quota",{...x,transport:Q,...H===void 0?{}:{status:H},quota:W,handle:G.attempt})},d=(G,Q,W,H)=>{let x=G.attempt;if(!x)return;let q=Z.inspectEvent?.(H===void 0?{transport:Q,data:W,attempt:x}:{transport:Q,data:W,event:H,attempt:x});if(!q)return;if(q.quota!==void 0)M(G,Q,q.quota);if(q.outputStarted)G.outputStarted=!0;if(q.limit)F2(G,q.limit,Q);if(q.error!==void 0)y(G,{reason:"failed",message:q.error});else if(q.done)y(G)},Q2=(G,Q)=>{let W=G.attempt;if(!W||Q.accountId===G.accountId)return;if(W.reboundFrom??=W.accountId,W.accountId=Q.accountId,"data"in Q)W.data=Q.data;G.accountId=Q.accountId},$0=(G)=>!G.attempt||G.endError!==void 0||G.status!==void 0&&G.status>=400,Z0=(G)=>{let Q=[...j.values()].filter((D)=>D.scope.sessionID===G),W=Q.filter((D)=>D.limit&&!D.rerouted).at(-1);if(W)return W;let H=Q.filter((D)=>D.scope.kind==="primary"),x=H.length>0?H:Q;if(x.length<=1)return x[0];let q=x.filter((D)=>!D.judged&&$0(D)).at(-1);if(q)return q;let O=x.filter((D)=>D.attempt&&!D.ended);if(O.length>1)return"ambiguous";return O[0]??x.at(-1)},K2={providerID:z},H2=[];H2.push(await $.session.hook("model.request",(G)=>{if(X)return;return f(V2(G),async(Q)=>{let W=await p(V2(G),"model.request",Q);if(Q(),W.accountId===void 0)throw s(W.scope);$1(G.headers,{...W.headers,[M2]:W.id})})},K2)),H2.push(await $.session.hook("http.request",(G)=>{if(X){let Q=Y(G.request.headers);if(T.set(G.sessionID,Q),!Q)return}return f(V2(G),async(Q)=>{let W=G.request.headers.get(M2)??void 0,H=X?await p(V2(G),"http.request",Q,"http"):await n(V2(G),"http.request","http",W,Q);Q();let x=c(H),q=H.attempt;if(!x||!q)throw s(H.scope);await W2(H,async()=>{let O=G.request;if(Z.rewriteRequest){if(W!==void 0){let G2=new Headers(O.headers);G2.delete(M2),O=new Request(O,{headers:G2})}O=await Z.rewriteRequest({...x,request:O,attempt:q})??O,Q()}let D=new Headers(O.headers);D.delete(M2),X0(D,H.headers),I(H.scope,D.entries());let i=new Request(O,{headers:D});B.set(i,H),G.request=i})})},K2)),H2.push(await $.session.hook("http.response",async(G)=>{let Q=B.get(G.request);if(!Q){if(X)return;if(!u)u=!0,h("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:G.sessionID,kind:G.kind});return}let W=G.response;if(Z.answeredBy&&Q.attempt){let D=Q.attempt,i=await W2(Q,async()=>Z.answeredBy?.({request:G.request,response:W,attempt:D}));if(i)Q2(Q,i)}let H=c(Q),x=Q.attempt;if(!H||!x)return;Q.status=W.status;let q=Z.quotaFromHeaders?.(W.headers,W.status,x);if(q!==void 0)M(Q,"http",q,W.status);if(!W.ok&&Z.limitFromResponse){let D=await Z.limitFromResponse({status:W.status,headers:W.headers,body:()=>W.clone().text(),attempt:x});if(D)F2(Q,D,"http")}if(!W.ok||!W.body)y(Q);let O=W;if(W.body&&(Z.inspectEvent||Z.onAttemptEnd)){let D=W.body;if(Z.inspectEvent)D=D.pipeThrough(e2((i)=>d(Q,"http",i.data,i.event),(i)=>h("opencode2 auth event inspection threw",{error:v(i)})));O=new Response(G0(D,(i)=>y(Q,i)),{status:W.status,statusText:W.statusText,headers:W.headers})}if(Z.rewriteResponse)O=await Z.rewriteResponse({...H,request:G.request,response:O,attempt:x})??O;if(O!==W)G.response=O},K2)),H2.push(await $.session.hook("experimental.ws.handshake",(G)=>{if(X){let Q=Y(new Headers(G.headers)),W=L2(G.sessionID,G.kind);if(T.set(G.sessionID,Q),S.delete(W),!Q)return}return f(V2(G),async(Q)=>{let W;for(let O of Object.keys(G.headers)){if(O.toLowerCase()!==M2)continue;W??=G.headers[O],delete G.headers[O]}let H=X?await p(V2(G),"experimental.ws.handshake",Q,"ws"):await n(V2(G),"experimental.ws.handshake","ws",W,Q);Q();let x=c(H),q=H.attempt;if(!x||!q)throw s(H.scope);await W2(H,async()=>{$1(G.headers,H.headers);let O=Z.rewriteHandshakeURL?.({...x,url:G.url,attempt:q});if(O!==void 0)G.url=O;if(I(H.scope,Object.entries(G.headers)),X)S.add(H.key)})})},K2));let A1=Z.rewriteWebSocketFrame?.bind(Z);if(A1)H2.push(await $.session.hook("experimental.ws.send",async(G)=>{let Q=V2(G);if(X&&!S.has(L2(Q.sessionID,Q.kind)))return;let W=T2(Q.sessionID,Q.kind),H=await A1({...Q,attempt:W?.attempt,frame:G.frame});if(H!==void 0)G.frame=H},K2));H2.push(await $.session.hook("experimental.ws.receive",(G)=>{if(X&&!S.has(L2(G.sessionID,G.kind)))return;let Q=T2(G.sessionID,G.kind);if(!Q)return;try{d(Q,"ws",G.frame)}catch(W){h("opencode2 auth frame inspection threw",{error:v(W)})}},K2)),H2.push(await $.session.hook("retry",async(G)=>{if(X&&T.get(G.sessionID)!==!0)return;let Q=Z0(G.sessionID);if(!Q)return;let W=G.decision;if(Q==="ambiguous"){await _("retry",{sessionID:G.sessionID,attempt:G.attempt,reason:"host-decides",hostDecision:W,decision:W});return}let H=Q;await f(H.scope,async(x)=>{let q=x;H.judged=!0;let O=H.attempt;if(O&&!H.outputStarted){if(!H.limit){let G2=Z.limitFromError?.(G.error,O);if(G2)F2(H,G2,"error")}if(H.ended)await H.ended;if(H.limit)await H.limit.delivered}q();let{decision:D,reason:i}=await P(H.scope.sessionID,async()=>{q();let G2=L.get(H.key);if(L.delete(H.key),G2?.next)await K(G2.next);q();let Z2=W,o,_2,t;if(H.accountId===void 0||!O)Z2={retry:!1},o="no-account";else if(H.outputStarted)Z2={retry:!1},o="output-started";else if(H.limit){let E2={accountId:H.accountId,limit:H.limit.signal},N2,k2={...H.scope,phase:"retry",previousAccountId:H.accountId,rerouteFrom:E2};try{N2=await Z.chooseAccount(k2)}catch(s2){h("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:H.scope.sessionID,error:v(s2)})}if(N2!==void 0)t={accountId:N2,input:k2};try{q()}catch(s2){if(t)await K(t);throw s2}if(N2!==void 0&&N2!==H.accountId)H.rerouted=!0,_2=E2,Z2={retry:!0,delay:0},o="reroute";else o="host-decides-last-account"}else o="host-decides";if(G.decision=Z2,Z2.retry&&H.accountId!==void 0&&j.has(H.id))L.set(H.key,{attemptId:H.id,sessionID:H.scope.sessionID,accountId:H.accountId,..._2===void 0?{}:{rerouteFrom:_2},...t===void 0?{}:{next:t}});else if(t)await K(t);return{decision:Z2,reason:o}});q(),await _("retry",{sessionID:G.sessionID,...H.accountId===void 0?{}:{accountId:H.accountId},kind:H.scope.kind,attempt:G.attempt,reason:i,hostDecision:W,decision:D,...O===void 0?{}:{handle:O}})})},K2));let R1=(G)=>{l(G),T.delete(G);for(let Q of S)if(JSON.parse(Q)[0]===G)S.delete(Q);for(let Q of[...j.values()]){if(Q.scope.sessionID!==G)continue;b(Q,"its session was forgotten"),j.delete(Q.id)}for(let[Q,W]of L)if(W.sessionID===G)A(Q)},r2=new AbortController,S1=$.event;if(S1)(async()=>{try{for await(let G of S1.subscribe({signal:r2.signal}))if(G.type==="session.deleted")R1(G.data.sessionID)}catch(G){if(!r2.signal.aborted)h("opencode2 auth stopped listening for session deletion",{error:v(G)})}})();return{on(G,Q){let W=R.get(G);if(!W)W=new Set,R.set(G,W);let H=Q;return W.add(H),()=>{W.delete(H)}},accountFor(G,Q){return g(L2(G,Q))?.accountId},forgetSession:R1,get size(){return j.size},async dispose(){if(z2)return;z2=!0;for(let G of w.keys())l(G);r2.abort();for(let G of j.values())b(G,"the installation was disposed");j.clear();for(let G of L.keys())A(G);S.clear(),T.clear(),R.clear(),await Promise.all(V.values()),await Promise.all(H2.map(async(G)=>{try{await G.dispose()}catch(Q){h("opencode2 auth hook did not dispose cleanly",{error:v(Q)})}}))}}}import{createHash as Y0}from"node:crypto";var Q0=1024,j0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),D1=($)=>k1($,"user"),V0=($)=>j0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function B0($){return Y0("sha256").update(JSON.stringify($)).digest("hex")}class A2{runtime;maxSessions;#$=new Map;constructor($,Z=Q0){this.runtime=$;this.maxSessions=Z}advance($,Z,J=this.runtime){let z=this.#$.get($),X=Array.isArray(Z.input)?Z.input:[],Y=X.filter(D1),F=X.findLastIndex(D1),N=F<0?void 0:B0(X[F]),U=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,j,B,L;if(U)j=Y.length>0,B=N??z?.fingerprint,L=z?.userCount===void 0?void 0:z.userCount+Y.length;else{B=N,L=Y.length;let T=F>=0&&F>X.findLastIndex(V0),u=z!==void 0&&!z.completed&&z.fingerprint===B&&z.userCount===L;j=T&&!u}let S=j||!z?{turnID:(J?.uuid??P2)(),turnStartedAt:(J?.now??Date.now)()}:{turnID:z.turnID,turnStartedAt:z.turnStartedAt};return this.#Z($,{...S,completed:!1,fingerprint:B,userCount:L}),S}completed($){let Z=this.#$.get($);if(Z)this.#Z($,{...Z,completed:!0})}get($){return this.#$.get($)}forget($){this.#$.delete($)}#Z($,Z){this.#$.delete($),this.#$.set($,Z);while(this.#$.size>this.maxSessions){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function J1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var w1=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function U0(){let $=globalThis;return $[w1]??=crypto.randomUUID(),$[w1]}class R2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,J){this.runtime=$;this.store=J;this.installationID=Z??U0(),this.sessions=J?.sessions??new Map,this.frameTurns=J?.frameTurns??new A2}get($){let Z=this.runtime?.uuid??P2;if(this.store)return this.store.get($,Z);let J=this.sessions.get($);if(!J){let z=Z();J={threadID:z,turnID:Z(),windowID:`${z}: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(w2(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($),this.frameTurns.forget($)}}var z1={version:y1,"user-agent":f1,originator:"codex_exec"};var W0=1024,H0=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,f2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),h1=($)=>f2($)&&($.type==="message"||("role"in $))&&$.role==="user",m1=($)=>f2($)&&$.type==="configuration_update";class G1{http;#$=new Map;constructor($=new R2){this.http=$}apply($,Z,J){if(Z.kind!=="primary")return!1;let z=typeof $.model==="string"?$.model:"";if(!I1.has(z))return!1;if(H0.test(z))return!1;let X=f2($.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 N=Array.isArray($.input)?$.input:void 0;if(!N||N.length===0)return!1;let U=N.findLastIndex(h1);if(U<0){if(J==="http")return!1;return $.reasoning={...X,effort:F},!0}if($.reasoning={...X,effort:F},!m1(N[U-1]))N.splice(U,0,{type:"configuration_update",reasoning:{effort:Y}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>W0){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function w2($){try{let Z=JSON.parse($);return f2(Z)?Z:void 0}catch{return}}async function g1($,Z,J,z,X=J.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Y=await $.clone().text(),F=w2(Y);if(F)delete F.max_output_tokens;let N=new Headers($.headers),U=y2({rewriteLite:v1,init:{body:F?JSON.stringify(F):$.body===null?void 0:Y},headers:N,metadata:X.get(Z.sessionID),installationID:X.installationID,runtime:X.runtime,websocket:!1,responsesLite:z,applyEffort:(j)=>{J.apply(j,Z,"http")}});return new Request($,{headers:N,body:U.init?.body})}function l1($,Z,J,z){let X=z.sessions.get($.sessionID),Y=z.frameTurns.get($.sessionID);if(!X||!Y)return;let F=J1(X,Y),N=new Headers({"content-type":"application/json"});for(let j of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let B=J.get(j);if(B!==null)N.set(j,B)}y2({init:{body:$.bodyText},headers:N,metadata:F,installationID:z.installationID,runtime:z.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let U=new URL(Z);if(U.protocol==="wss:")U.protocol="https:";if(U.protocol==="ws:")U.protocol="http:";return new Request(U,{method:"POST",headers:N,body:$.bodyText})}function N0($,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((z,X)=>JSON.stringify(z)!==JSON.stringify($[X]));return J>=0&&m1(Z[J])&&h1(Z[J+1])&&JSON.stringify(Z.slice(J+1))===JSON.stringify($.slice(J))}function u1($,Z,J){let z=w2($);if(z?.type!=="response.create")return;let X=J.http.advanceFrame(Z.sessionID,z),Y=J.http.get(Z.sessionID);delete z.max_output_tokens;let F=y2({rewriteLite:()=>{},init:{body:JSON.stringify(z)},headers:new Headers,metadata:J1(Y,X),installationID:J.http.installationID,runtime:J.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(U)=>{J.apply(U,Z,"ws")}}),N=w2(String(F.init?.body));if(!N)return;if(!N0(z.input,N.input)){if("input"in z)N.input=z.input;else delete N.input;return JSON.stringify(N)}return String(F.init?.body)}function F0($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function X1($,Z){let J=new URL($);if(J.origin!=="https://api.openai.com"&&J.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(J.pathname))return $;let z=new URL(`${F0(Z)}/responses`);if(z.search=J.search,J.protocol==="ws:"||J.protocol==="wss:")z.protocol=z.protocol==="https:"?"wss:":"ws:";return z.href}import{resolve as p1}from"node:path";var K0=1024;class I2{accounts=new Map;limit;constructor($=K0){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 c1=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),d1=globalThis,Y1=d1[c1]??new Map;d1[c1]=Y1;function Q1($){let Z=JSON.stringify([p1($.configPath),p1($.statePath)]),J=Y1.get(Z);if(!J)J=new I2,Y1.set(Z,J);return J}var X2="openai",L0=60000,j1=1,P0="request refused: no account with a usable credential",B2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function T0($){let Z=B2($)?$.counters:void 0,J=B2(Z)?Z.resetCredits:void 0,z=B2(J)?J.value:void 0;return typeof z==="number"&&Number.isFinite(z)?z:void 0}function B1($){try{return JSON.parse($)}catch{return}}function i1($){let Z=h2($);return Z?m2(Z):void 0}var _0=new Set(["usage_limit_reached","rate_limit_exceeded"]);function U1($,Z,J){return{reason:$.window,...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function M0($,Z){let J=v2($);if(J){let Y=typeof $.status==="number"?$.status:void 0;return U1(J,Z,Y)}if($.type!=="response.failed"||!B2($.response))return;let z=$.response.failed;if(B2(z)&&typeof z.rate_limit_reached_type==="string")return{reason:z.rate_limit_reached_type};let X=$.response.error;if(B2(X)){let Y=typeof X.code==="string"?X.code:typeof X.type==="string"?X.type:void 0;if(Y&&_0.has(Y))return{reason:Y}}return}function C0($,Z){let J=B1($);if(!B2(J))return;let z=typeof J.type==="string"?J.type:void 0;if(z==="codex.rate_limits")return{quota:{snapshot:r1(J),complete:!0}};let X=M0(J,Z);if(X)return{limit:X};if(z===void 0||z==="error")return;return W$(z)?void 0:{outputStarted:!0}}function E0($){let Z=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:n1($),complete:o1($)}}function O0($){let Z=$.get("retry-after");if(Z===null)return;let J=Number(Z);return Number.isFinite(J)&&J>=0?J*1000:void 0}function H$($){let{source:Z,pins:J}=$,z=$.now??Date.now,X=$.log,Y=$.vault,F=new G1($.codex),N=new Map,U=new Map,j=(V)=>`${V.sessionID}\x00${V.kind}\x00${V.accountId}`,B=new Map,L=$.sessionAccounts??new I2,S=new Q$,T=(V,P,E)=>{let K=E?[]:U$(Z.peek().rows,V,P,Y?.identities()??new Set),A=(Y?.routes()??[]).filter((_)=>_.kind==="oauth"&&t1(S2(_.quota),V,P));return[...K.map((_)=>({id:_.id,..._.identity!==void 0?{identity:_.identity}:{},quota:_.quota,row:_})),...A.map((_)=>({id:_.id,..._.identity!==void 0?{identity:_.identity}:{},quota:_.quota}))]},u=(V,P,E)=>{let K=G$(V,P,E),A=V.map((b)=>({id:b.id,kind:"oauth",...a1(b.quota)?{quota:b.quota}:{}})),_=V.flatMap((b)=>b.row?[b.row]:[]),C=new Set(V.filter((b)=>!b.row).map((b)=>b.id)),y=Z.rateLimitMarks(_);for(let b of C){let m=B.get(b);if(m===void 0)continue;if(m<=E)B.delete(b);else y.set(b,m)}return{rows:A,now:E,rateLimitMarks:y,refreshBackoff:Z.refreshBackoffFor(_),killswitch:K,requestPull:(b)=>C.has(b)?Y?.requestReading(b):Z.requestReading(b)}},a=(V,P,E,K,A)=>{let _=j$({...V,placement:X$(P),mainId:A});if(_.kind==="block"){X?.debug("pool admission refused the request",{reason:_.block.reason});return}let C=_.order.filter((y)=>!E.has(y));if(K!==void 0&&C.includes(K))return K;return C[0]},R=(V,P,E,K,A,_,C)=>{let y=new Map(P.map((l)=>[l.id,l.quota])),b={requestBytes:j1,reservePercent:(l)=>e1(E,l===J$?void 0:l),resetCredits:(l)=>T0(y.get(l))},m=V1(V),g=(l,f)=>g2(C,{sessionId:K,requestBytes:j1,validPinnedAccountIds:V.rows.map((I)=>I.id).filter((I)=>!m.excluded.has(I)),excludeAccountIds:l,quotaCheckedAtByAccount:Object.fromEntries(V.rows.map((I)=>[I.id,m.projections.get(I.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(P.map((I)=>[I.id,I.identity])),select:(I)=>V$(V,b,new Set(l),I),persist:f},(I,$2)=>C.set(I,$2)),r=[...A],e=g(r,_);if(!e)return;let c=e.accountId,s=B$(V,b,c);if(s.kind==="none")return;if(s.kind==="move"){let l=g([...r,c],_);if(l)return l.accountId;return s.reason==="killswitch"?void 0:c}if(s.kind==="detour")return g([...r,c],!1)?.accountId;return c},w={providerID:X2,dropChoice(V){let P=j(V);U.get(P)?.drop(),U.delete(P),N.delete(P)},chooseAccount:async(V)=>{let P=await Y?.authority(),E=await $.storage(),K=P!==void 0&&P!=="local",A=()=>{throw new J2({kind:"no-account",providerID:X2,sessionID:V.sessionID,requestKind:V.kind,message:l2})};if(K)await $.awaitVaultRoster?.();else{if(!(await Z.current()).active){if(await $.slotPlaceholderWithoutMain?.())A();X?.warn("the account pool does not serve requests yet; refusing the request",{kind:V.kind});return}await Z.prepareTokens(Z.peek().rows,E)}let _=z(),C=T(E,_,K),y=Y$(u(C.filter((I)=>I.id!==V.rerouteFrom?.accountId),E,_));if(y)await y,_=z(),C=T(E,_,K);let b=new Map(C.map((I)=>[I.id,I])),m=u(C,E,_),g=new Set(V.rerouteFrom?[V.rerouteFrom.accountId]:[]),r=E?.routing?.mode??"main-first",e=V.kind==="primary",c=new Set,s,l,f;try{for(;;){let I=new Set([...g,...c]);if(f=void 0,s=void 0,r==="sticky-balanced"){let p=new Map(J.placementSnapshot(V.sessionID)),n=p.get(V.sessionID);if(f=R(m,C,E,V.sessionID,I,e&&c.size===0,p),f!==void 0&&p.get(V.sessionID)!==n)s=p.get(V.sessionID)}if(f??=a(m,r,I,e?void 0:L.activeAccount(V.sessionID),K?r==="sticky-balanced"?null:z$(Y?.routes()??[]):void 0),f===void 0||c.has(f)){if(g.size>0){let p=new Map(m.rateLimitMarks);for(let n of g)p.delete(n);m={...m,rateLimitMarks:p},g.clear();continue}f=void 0;break}if(e&&r==="sticky-balanced"){let p=V1(m).projections.get(f)?.checkedAt,n=b.get(f)?.identity;l=J.reserve(V.sessionID,{accountId:f,inputBytes:j1,...p!==void 0?{quotaCheckedAt:p}:{},...n!==void 0?{wireIdentity:n}:{}})}let $2=b.get(f)?.row;if($2){if(Z.usableToken($2)!==void 0)break;X?.debug("pool row holds no usable token; choosing again",{accountId:f})}else{if(!Y)break;let p=await Y.authorize(f);if(p){N.set(j({...V,accountId:f}),p);break}X?.debug("the vault refused to serve an account; choosing again",{accountId:f})}if(l)J.rollback(l);l=void 0,c.add(f)}if(f===void 0&&!K&&C.length===0&&await $.slotPlaceholderWithoutMain?.())A();if(f===void 0&&K&&Y&&(C.length===0||c.size>0)){let I=c.size>0?"vault-refused":Z$(Y);throw X?.warn("vault mode: no vault account can serve; refusing the request",{cause:I}),new J2({kind:"no-account",providerID:X2,sessionID:V.sessionID,requestKind:V.kind,message:$$(I,Y.name)})}if(f!==void 0){let I=f,$2=l,p=s,n=()=>{if($2)J.finish($2,p);if(e)L.record(V.sessionID,I),$.onRoute?.(V.sessionID,I,r)};if(V.phase==="retry")U.set(j({...V,accountId:f}),{commit:n,drop:()=>{if($2)J.rollback($2)}}),l=void 0;else n();let W2=X?.info;S.served(m,f,X&&W2?{info:(T2,F2)=>W2.call(X,T2,F2)}:void 0)}return X?.debug("pool account chosen",{kind:V.kind,accountId:f,mode:r,...V.rerouteFrom?{rerouteFrom:V.rerouteFrom.accountId}:{}}),f}finally{if(l)J.rollback(l)}},accountHeaders:async(V)=>{let{accountId:P}=V,E=j(V),K=U.get(E);U.delete(E);let A=()=>{K?.commit()};try{let _=()=>new J2({kind:"no-account",providerID:X2,sessionID:V.sessionID,requestKind:V.kind,message:P0}),C=Y&&await Y.authority()!=="local"?void 0:Z.peek().rows.find((m)=>m.id===P);if(!C&&Y){let m=j(V),g=N.get(m)??await Y.authorize(P);if(N.delete(m),!g)throw X?.warn("the vault refused to serve an account; refusing the request",{accountId:P}),_();return A(),{headers:{...z1,"session-id":V.sessionID,authorization:`Bearer ${g.accessToken}`,"chatgpt-account-id":g.accountIdentity??i1(g.accessToken)??null},attempt:{kind:"vault",routeId:P,receipt:g}}}let y=C?Z.usableToken(C):void 0;if(!C||!y)throw X?.warn("pool row holds no usable token; refusing the request",{accountId:P}),_();let b=C.identity??i1(y);return A(),{headers:{...z1,"session-id":V.sessionID,authorization:`Bearer ${y}`,"chatgpt-account-id":b??null},attempt:{kind:"pool",token:y,credentialEpoch:C.credentialEpoch}}}finally{K?.drop()}},async rewriteRequest({request:V,sessionID:P,kind:E}){let K=$.codexEndpoint?X1(V.url,$.codexEndpoint()):V.url,A=K===V.url?V:new Request(K,V);return await g1(A,{sessionID:P,kind:E},F,$.responsesLite?.()??!1)??A},rewriteHandshakeURL:({url:V})=>$.codexEndpoint?X1(V,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:V,sessionID:P,kind:E})=>u1(V,{sessionID:P,kind:E},F),quotaFromHeaders:(V)=>E0(V),async limitFromResponse({status:V,headers:P,body:E}){if(V<400)return;let K=B1(await E().catch(()=>"")),A=v2({...B2(K)?K:{},status:V});if(!A)return;let _=z(),C=U1(A,_,V);if(C.retryAfterMs!==void 0)return C;let y=O0(P);return y===void 0?C:{...C,retryAfterMs:y}},inspectEvent:({data:V})=>C0(V,z()),limitFromError(V){let P=B1(V.message),E=v2({...B2(P)?P:{},...V.status!==void 0?{status:V.status}:{}})??(V.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return E?U1(E,z(),V.status):void 0},async onAttemptEnd(V,P){let E=V.data;if(E?.kind!=="vault"||P.status!==401)return;X?.warn("a vault account answered 401; reporting it to the vault",{accountId:V.accountId}),await Y?.reportFailure(E.receipt,401)}},h=(V,P,E)=>{let K=E.data;if(K?.kind==="vault"){Y?.recordSnapshot(V,P.snapshot,P.complete,K.receipt);return}if(K?.kind!=="pool")return;if(Z.peek().rows.find((_)=>_.id===V)?.credentialEpoch!==K.credentialEpoch){X?.debug("quota reading dropped: the row holds another credential",{accountId:V});return}Z.recordSnapshot(V,P.snapshot,K.token,P.complete)},v=(V,P,E)=>{let K=z(),A=E.data?.kind==="vault",_=A?Y?.routes().find((b)=>b.id===V)?.quota:Z.peek().rows.find((b)=>b.id===V)?.quota,C=s1(S2(_),P.reason,K,L0,P.retryAfterMs!==void 0?K+P.retryAfterMs:void 0);if(!A){Z.markRateLimited(V,C);return}let y=B.get(V);if(y===void 0||y<C)B.set(V,C)};return{adapter:w,attach(V){V.on("quota",(P)=>h(P.accountId,P.quota,P.handle)),V.on("limit",(P)=>{v(P.accountId,P.limit,P.handle),X?.debug("pool row refused the request",{accountId:P.accountId,via:P.via,reason:P.limit.reason,outputStarted:P.outputStarted})})},forgetSession(V){J.forget(V),L.forget(V),F.forget(V)},activeAccount:(V)=>L.activeAccount(V)}}import{resolve as T$}from"node:path";import{Buffer as A0}from"node:buffer";import{resolve as N$}from"node:path";function x2($){return A0.byteLength(JSON.stringify($))}function R0($){return $.reduce((Z,J)=>Z+x2(J),0)}function W1($,Z){return 2+$+Math.max(0,Z-1)}function S0($){let{head:Z,pending:J}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+W1(Z.inputBytes,Z.input.length)+1:0)+(J?20+W1(J.inputBytes,J.input.length)+10+W1(J.outputBytes,J.output.length)+(J.responseID===void 0?0:14+J.responseIDBytes)+1:0)}function F$($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class K${enabled;caps=u2;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=F$(Z);if(J?.type!=="response.create")return;if(!Array.isArray(J.input)){this.forget($);return}let z=J.previous_response_id,X=this.entries.get($),Y=X?.head;if(z&&z!==Y?.responseID){this.forget($);return}let{type:F,previous_response_id:N,input:U,...j}=J;this.keep($,{fields:z&&X?X.fields:j,fieldsBytes:z&&X?X.fieldsBytes:x2(j),...z&&Y?{head:Y}:{},pending:{input:U,inputBytes:R0(U),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 z=this.entries.get($);if(!z?.pending)return;let X=F$(Z);if(!X)return;let Y=z.pending,F=X.response;if(X.type==="response.created"&&typeof F?.id==="string")Y.responseID=F.id,Y.responseIDBytes=x2(F.id),this.keep($,z);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+=x2(X.item),this.keep($,z)}else if(X.type==="response.completed"&&typeof F?.id==="string"){if(F.id===z.head?.responseID||Y.responseID!==void 0&&F.id!==Y.responseID)return;let N={responseID:F.id,responseIDBytes:Y.responseID===F.id?Y.responseIDBytes:x2(F.id),input:[...z.head?.input??[],...Y.input,...Y.output],inputBytes:(z.head?.inputBytes??0)+Y.inputBytes+Y.outputBytes},U={...z,head:N,pending:void 0};if(!this.keep($,U))return;J?.({sessionID:$,responseID:N.responseID,bodyText:this.body(z.fields,N)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let J=S0(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 z=this.entries.keys().next().value;if(z===void 0)break;this.forget(z)}return this.entries.has($)}}var L$=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),P$=globalThis,H1=P$[L$]??new Map;P$[L$]=H1;function p2($){let Z=JSON.stringify([N$($.configPath),N$($.statePath)]),J=H1.get(Z);if(!J)J=new K$,H1.set(Z,J);return J}var x0=5000,q0=["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"],b0=["x-opencode-parent-session-id","x-parent-session-id"];function E$($){let Z=_$($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:M$($?{...$,cachekeep:Z}:$)}}var O$=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),A$=globalThis,q2=A$[O$]??new Map;A$[O$]=q2;function D0($,Z){let J=[],z=()=>J.at(-1)?.location,X=()=>{let U=z();if(!U)throw Error("no location holds keep-warm");return U},Y=(U,j)=>{N.remove(U),z()?.log?.debug(`cachekeep dropped target (${j})`,{sessionKey:U})},F=async(U)=>{if(U.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let j=U.accountId??"main",B=X(),L=await B.source.accessFor(j,await B.storage());if(!L)throw Error(`pool row ${j} has no usable token`);return{token:L.token,identity:L.row.identity}},N=C$({...u2,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(U,j)=>X().fetch(U,j),logger:{debug:(U,j)=>z()?.log?.debug(U,j),warn:(U,j)=>z()?.log?.warn(U,j)},getWindow:()=>z()?.settings().window,getSustain:()=>z()?.settings().sustain===!0,resolveLocal:F,vault:{owns:(U)=>z()?.vault.owns(U)===!0,authority:()=>X().vault.authority(),send:async(U,j,B)=>{let L=X();if(await L.vault.authority()!=="vault")return;return L.vault.send(U,j,B)}},activeAccount:(U)=>{if(U===void 0)throw Error("target has no session");let j=z(),B=j?.settings();if(!j||!B?.enabled){Y(U,"keep-warm is off");return}if(!B.subagents&&N.status().targets.some((S)=>S.sessionKey===U&&S.isSubagent)){Y(U,"subagent warming is off");return}let L=j.accounts.activeAccount(U);if(L===void 0){Y(U,"no account recorded for the session");return}return L},verifyCredential:({target:U,mode:j,identity:B})=>{if(U.meta.credentialMode!==j)throw Error(`a target captured in ${U.meta.credentialMode??"an unknown"} mode is not warmed with a ${j} credential`);if(B!==U.meta.chatgptAccountId)throw Y(U.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:N,settings:Z,holders:J,joinTimeoutMs:$.joinTimeoutMs??x0}}function k0($){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((X)=>typeof X?.text==="string"?X.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function w0($){let Z={};for(let J of q0){let z=$.get(J);if(z)Z[J]=z}return Z}function R$($,Z,J){let z=JSON.stringify([T$($.configPath),T$($.statePath)]),X=q2.get(z);if(!X)X=D0(J,Z.settings()),q2.set(z,X);let Y=X,F=p2($);F.setEnabled(Y.settings.enabled);let N={location:{...Z,settings:()=>Y.settings}};Y.holders.push(N);let U=!1,j=async(B)=>{try{let L=N.location.settings();if(U||!L.enabled)return;if(B.kind!=="primary"){if(B.kind==="generate"&&k0(await B.request.clone().text())){if(U)return;Y.manager.remove(B.sessionID)}return}let S=B.attempt.data,T=S?.kind==="pool"?"local":S?.kind==="vault"?"vault":void 0;if(!T)return;let u=B.request.headers,a=b0.some((z2)=>u.has(z2))||Z.parentOf!==void 0&&await Z.parentOf(B.sessionID)!==void 0;if(a&&!L.subagents)return;let R=await B.request.clone().text();if(U)return;let k=u.get("chatgpt-account-id")??void 0;Y.manager.track({sessionKey:B.sessionID,bodyText:R,accountId:B.attempt.accountId,isSubagent:a,meta:{replayHeaders:w0(u),...k?{chatgptAccountId:k}:{},routingSessionId:B.sessionID,url:B.request.url,credentialMode:T}})}catch(L){Z.log?.warn("cachekeep capture failed",{error:L instanceof Error?L.message:String(L)})}};return{manager:Y.manager,configure:(B)=>{Object.assign(Y.settings,B),F.setEnabled(Y.settings.enabled)},capture:j,forget:(B)=>Y.manager.remove(B),async release(){if(U)return;U=!0;let B=Y.holders.indexOf(N);if(B>=0)Y.holders.splice(B,1);if(Y.holders.length>0)return;if(q2.get(z)===Y)q2.delete(z);Y.manager.stop();let L;try{await Promise.race([Y.manager.tick().catch(()=>{}),new Promise((S)=>{L=setTimeout(S,Y.joinTimeoutMs),L.unref?.()})])}finally{clearTimeout(L)}}}}import{mkdirSync as y0}from"node:fs";import{dirname as f0,join as I0,resolve as v0}from"node:path";var h0="openai-auth-sessions-opencode2.json";function m0(){return I0(x$(),h0)}var g0="sessions",l0=1e4,u0=5000,p0=25;class k${path;options;sessions;frameTurns=new A2;#$=new Set;#Z=new Set;#J=Promise.resolve();#z=!1;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=b$($,Z.uuid??P2)}get($,Z=P2){let J=this.sessions.get($);if(!J){let z=Z();J={threadID:z,turnID:Z(),windowID:`${z}:0`},this.sessions.set($,J),this.#Z.delete($),this.#$.add($),this.save()}return J}delete($){this.sessions.delete($),this.frameTurns.forget($),this.#$.delete($),this.#Z.add($),this.save()}save(){if(!this.#z)this.#z=!0,this.#J=this.#J.then(()=>{return this.#z=!1,this.#G()});return this.#J}settled(){return this.#J}async#G(){if(this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((z)=>{let X=this.sessions.get(z);return X?[[z,X]]:[]}),Z=[...this.#Z],J=null;try{if(y0(f0(this.path),{recursive:!0}),J=await this.#X(),!J)return;let z;try{z=q$(this.path)}catch{z=new Map}await this.options.afterRead?.();for(let X of Z)z.delete(X);for(let[X,Y]of $)z.set(X,Y.threadID);D$(this.path,z)}catch{return}finally{await J?.release().catch(()=>{})}for(let[z,X]of $)if(this.sessions.get(z)===X)this.#$.delete(z);for(let z of Z)if(!this.sessions.has(z))this.#Z.delete(z)}async#X(){let $=performance.now()+(this.options.lockWaitMs??u0);for(;;){let Z=await S$({name:g0,path:this.path,ttlMs:l0});if(Z||performance.now()>=$)return Z;await new Promise((J)=>setTimeout(J,p0))}}}var w$=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),y$=globalThis,N1=y$[w$]??new Map;y$[w$]=N1;function f$($=m0()){let Z=v0($),J=N1.get(Z);if(!J)J=new k$(Z),N1.set(Z,J);return J}var I$=Symbol.for("cortexkit.openai-auth.v2.commands"),c0=Y2("v2-command");function F1($){c0.warn(`/openai needs the terminal UI (session state: ${$}).`)}function d0(){let $=globalThis;return $[I$]??={locations:new Map},$[I$]}async function c$($,Z){let J=d0(),z=$.location.directory,X={menu:Z,session:$.session,closed:new AbortController},Y=await h$(z),F=await v$(u$,Y.dir,()=>p$({...Y,drain:l$,apply:(B)=>{let L=J.locations.get(z);if(!L)throw Error("The OpenAI menu location was closed");return L.menu.apply(B)}})),N=J.locations.get(z);J.locations.set(z,X),N?.closed.abort(),await N?.registration?.dispose(),J.command??={name:"openai",description:"OpenAI account menu",async execute(B){let L=J.locations.values().next().value?.session;if(!L)return F1("no live location");let S=await L.get({sessionID:B.sessionID}),T=J.locations.get(S.location.directory);if(!T)return F1("location closed");if(!await m$(B.sessionID,T.closed.signal)||J.locations.get(S.location.directory)!==T)return F1(T.closed.signal.aborted?"location closed":"no TUI poll within 2 s");let a=await T.menu.open(B.sessionID);g$(a,B.sessionID)}};let U=J.command;try{X.registration=await $.command.transform((B)=>{B.add(U)})}catch(B){if(X.closed.abort(),J.locations.get(z)===X)J.locations.delete(z);throw await F.release(),B}let j=!1;return async()=>{if(j)return;if(j=!0,X.closed.abort(),J.locations.get(z)===X)J.locations.delete(z);await F.release(),await X.registration?.dispose()}}var i0="openai-auth-pool-browser",a0="openai-auth-pool-headless",n0="openai-auth-vault",o0="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 b2($){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 r$($){return{method:{id:n0,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await d$($.paths,$.name)!=="vault")throw Error(o0)}}}function s$($){let Z=(J,z,X)=>({method:{id:J,type:"oauth",label:z},async authorize(){if($.vault)await b2($.vault);let Y=await $.beginLogin({version:$.version,headless:X});return{url:Y.url,instructions:Y.instructions,mode:"auto",callback:Y.completion}}});return[Z(i0,"ChatGPT (openai-auth pool, browser)",!1),Z(a0,"ChatGPT (openai-auth pool, headless)",!0)]}function K1($){let Z=(J)=>typeof J==="string"?J:"";return O2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===n$||i$($)}function r0($){if($.accountId)return $.accountId;let Z=$.access?h2($.access):void 0;return Z?m2(Z):void 0}async function t$($,Z,J,z={}){if(z.vault)await b2(z.vault);if(K1(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let X=a$($,{rowLocks:(T)=>o$(Z,T)}),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:J.refresh,...J.access!==void 0?{access:J.access}:{},...J.expires!==void 0?{expires:J.expires}:{}},N=r0(J);if(z.vault)await b2(z.vault);let U=N!==void 0?{identity:N}:{};if(z.origin==="import"){let T=Y.rows.find((u)=>N!==void 0&&u.identity===N||u.credential?.type==="oauth"&&u.credential.refresh===J.refresh);if(T)return{id:T.id,operation:"kept"}}let j=Y.rows.filter((T)=>T.type==="oauth"&&!T.invalid),B=N?j.find((T)=>T.identity===N):void 0,L=Y.rows.find((T)=>T.id===c2);if(B)return{id:(await X.replace(B.id,F,U)).id,operation:"replaced"};if(!L){let T=await X.add({id:c2,credential:F,...U,...J.label!==void 0?{label:J.label}:{}});return{id:T.id,operation:T.outcome==="added-disabled"?"added-disabled":"added"}}if(!L.invalid&&!L.credential)return{id:(await X.replace(c2,F,U)).id,operation:"replaced"};let S=await X.add({id:J.id,credential:F,...U,...J.label!==void 0?{label:J.label}:{}});return{id:S.id,operation:S.outcome==="added-disabled"?"added-disabled":S.outcome==="rotated"?"replaced":"added"}}function s0($){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 ZZ($){let Z={...$,allowAction:s0,unavailableSections:[]};return{open:(J)=>e$(Z,J),apply:(J)=>{let z=J!==null&&typeof J==="object"?J:{},X=z.values&&typeof z.values==="object"&&!Array.isArray(z.values)?Object.fromEntries(Object.entries(z.values).filter(([,Y])=>Y===null||["string","number","boolean"].includes(typeof Y))):void 0;return $Z(Z,{command:"openai",sectionId:typeof z.sectionId==="string"?z.sectionId:"",actionId:typeof z.actionId==="string"?z.actionId:"",...X?{values:X}:{},...z.confirmed===!0?{confirmed:!0}:{},...typeof z.itemId==="string"?{itemId:z.itemId}:{},...typeof z.sessionId==="string"?{sessionId:z.sessionId}:{}})}}}function t0($){if(!JZ($.modelID??$.id)){$.enabled=!1;return}let Z=zZ($.id);if(Z)$.limit={...Z}}function GZ($){return $.model.transform((Z)=>{for(let J of Z.list(X2))Z.update(X2,String(J.id),(z)=>t0(z))})}class L1{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(!XZ())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 z=this.pending.keys().next().value;if(z)this.take(z)}})}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(()=>d2({...J,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let J=this.requests.get($.attemptId),z=J&&this.take(J);if(!z)return;let{reason:X,message:Y}=Z.error,F=Y?`${X}: ${Y}`:X;await this.safely(()=>d2({...z,error:i2(F,J?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>d2({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 P1{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 BZ($){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 z=await YZ({accessToken:J.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,z),QZ(z,$.now(),!0)}}function UZ($){let{source:Z,counts:J,now:z}=$,X=async(j)=>{let B=await Z.rowAccess(j,await $.storage());if(!B?.row)throw new jZ("unknown_account",`${j==="main"?"Main":"Fallback"} account ${j} was not found.`);return VZ(j,B)},Y=async(j)=>{if($.authority&&await $.authority()!=="local")return{account:j,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[B]=await Z.pollRows(await $.storage(),{ids:[j]});if(!B)return{account:j,ok:!1,error:"targeted quota refresh returned no result"};return{account:B.id,ok:B.ok,...B.error!==void 0?{error:B.error}:{}}},F=(j)=>Z.peek().rows.find((B)=>B.id===j),N=(j)=>{let B=F(j);if(!B)return null;let L=S2(B.quota)??{},S=J.applicable(B),T=Math.max(0,...[L.primary?.checkedAt,L.secondary?.checkedAt].filter((u)=>typeof u==="number"));return{quota:{...L,...S!==void 0?{resetCreditsApplicable:S}:{}},checkedAt:T,refreshAfter:T,...B.identity!==void 0?{accountId:B.identity}:{}}};return{resolveResetTarget:X,refreshResetTargetQuota:Y,quotaManager:{isRateLimited:(j)=>{let B=F(j);if(!B)return!1;let L=Z.rateLimitMarks([B]).get(B.id);return L!==void 0&&L>z()},getMain:()=>N("main"),getFallback:(j)=>N(j)}}}import{resolve as WZ}from"node:path";var e0=1024;class T1{pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=e0){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 g2(this.placementSnapshot($.sessionId),$,(Z,J)=>this.set(Z,J))}}var HZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),NZ=globalThis,_1=NZ[HZ]??new Map;NZ[HZ]=_1;function FZ($){let Z=JSON.stringify([WZ($.configPath),WZ($.statePath)]),J=_1.get(Z);if(!J)J=new T1,_1.set(Z,J);return J}import{statSync as $4}from"node:fs";import{resolve as Z4}from"node:path";function OZ($){return $.map((Z)=>{try{let J=$4(Z);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}function M1($){return OZ([$.vault.paths.tokenPath,$.vault.paths.statePath])}function KZ($){return OZ([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+M1($)}class AZ{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:KZ($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),J=this.subscriptions.get($.pins);if(!J){let z=new Set;J={producers:z,stop:$.pins.subscribe((X,Y)=>{let F=z.values().next().value;if(F)this.publish(F,{sessionId:X,pin:Y,accountId:Y?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,J)}return J.producers.add($),this.timer??=setInterval(()=>{for(let z of this.producers){let X={stamp:KZ(z),roster:z.vault.snapshot()},Y=this.observations.get(z);if(X.stamp!==Y?.stamp||X.roster!==Y?.roster)this.observations.set(z,X),this.publish(z)}},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;let z=await $.vault.authority()!=="local",X=M1($),Y=()=>this.producers.has($)&&$.vault.enrolled()===z&&M1($)===X,F=await U2($.paths),N=z?CZ($.vault.snapshot()?.rows??[],new Set($.vault.routes().map((j)=>j.id)),F,Date.now()):EZ((await $.source.sidebarView()).rows,F,Date.now());if(await PZ(N,this.file,{canWrite:Y}),!Y()||!Z)return;let U=N.vaultAccounts??N.fallbacks;if(Z.accountId===void 0){await _Z(Z.sessionId,U,this.file,{canWrite:Y});return}if(Z.pin){let j=Date.now();await MZ({sessionId:Z.sessionId,assignment:{accountId:Z.pin.accountId,wireAccountId:Z.pin.wireIdentity,inputBytes:Z.pin.inputBytes??0,quotaCheckedAt:Z.pin.quotaCheckedAt,assignedAt:j,lastSeenAt:j},validPinnedAccountIds:[...z?[]:["main"],...U.filter((B)=>B.enabled).map((B)=>B.id)]},this.file)}await TZ({sessionId:Z.sessionId,activeId:Z.accountId,route:Z.route??N.route,updatedAt:Date.now()},U,this.file,{canWrite:Y})}).catch(()=>{Y2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var RZ=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),SZ=globalThis,D2=SZ[RZ]??new Map;SZ[RZ]=D2;function xZ($,Z=LZ(),J=2000){let z=Z4(Z),X=D2.get(z);if(!X)X=new AZ(z,J),D2.set(z,X);let Y=X,F=Y.add($),N=!1;for(let[U,j]of $.pins.snapshot())Y.publish($,{sessionId:U,pin:j,accountId:j.accountId,route:"sticky-balanced"});return{publish:()=>Y.publish($),route:(U,j,B)=>{Y.publish($,{sessionId:U,accountId:j,route:B})},async release(){if(N)return;if(N=!0,F(),await Y.settled(),Y.empty&&D2.get(z)===Y)D2.delete(z)}}}var o2="cortexkit-openai-auth",G4=5000;async function qZ($,Z,J,z=new R2,X,Y,F){let N=new L1(J),U=new J4,j=new Map,B=new Map,L=(R)=>{B.delete(R);for(let k of j.keys())if(k.startsWith(`${R}:`))j.delete(k)},S=(R)=>{F?.(R.sessionID),Y?.send(R.sessionID,R.frame)},u=await Z1({session:{hook:(R,k,z2)=>$.session.hook(R,async(w)=>{let h=R==="http.request"?w:void 0,v=R==="experimental.ws.handshake"?w:void 0,P=(h?h.request.headers:v?new Headers(v.headers):void 0)?.get("authorization")===`Bearer ${j2(Z.providerID)}`,E={};if(v)j.delete(`${v.sessionID}:${v.kind}`);try{await U.run(E,()=>k(w))}catch(K){if(P&&!(K instanceof J2))throw fZ(K);throw K}if(h&&P&&E.attempt){let K=h.request.headers.get("thread-id");if(K)h.request.headers.set("session-id",K)}if(h&&P&&E.attempt)await N.captureHttp(h.request,E.attempt);if(h&&P&&E.attempt)await X?.({sessionID:h.sessionID,kind:h.kind,request:h.request,attempt:E.attempt});if(v&&P&&E.attempt)v.headers["session-id"]=z.get(v.sessionID).threadID;if(R==="experimental.ws.send"){let K=w,A=j.get(`${K.sessionID}:${K.kind}`);if(A)await N.frame(K.frame,A.attempt);if(A&&K.kind==="primary")S(K)}if(h||v){let K=h??v;if(!K)return;let _=(h?h.request.headers:new Headers(K.headers)).get("authorization")?.replace(/^Bearer /,"");if(P&&_)B.set(K.sessionID,_);else B.delete(K.sessionID);if(v){let C=`${v.sessionID}:${v.kind}`;if(P&&_&&E.attempt)j.set(C,{bearer:_,attempt:E.attempt,url:v.url,headers:new Headers(Object.entries(v.headers).filter(([y])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(y.toLowerCase())))});else j.delete(C)}if(B.size>512){let C=B.keys().next().value;if(C)B.delete(C)}if(j.size>512){let C=j.keys().next().value;if(C)j.delete(C)}}else if(R==="experimental.ws.receive"){let K=w,A=j.get(`${K.sessionID}:${K.kind}`);if(A){if(z.frameReceived(K.sessionID,K.frame),K.kind==="primary"){let _;if(Y?.receive(K.sessionID,K.frame,(C)=>{_=C}),_)try{let C=l1(_,A.url,A.headers,z);if(C)await X?.({sessionID:K.sessionID,kind:"primary",request:C,attempt:A.attempt})}catch(C){J.warn("cachekeep WebSocket capture failed",{error:C instanceof Error?C.message:String(C)})}}K.frame=IZ(K.frame,A.bearer)}}else if(R==="retry"){let K=w,A=B.get(K.sessionID);if(A)Object.assign(K.error,{message:i2(K.error.message,A)})}},z2)},event:{subscribe:(R)=>async function*(){for await(let k of $.event.subscribe(R)){if(k.type==="session.deleted")L(k.data.sessionID);yield k}}()}},{...Z,rewriteRequest:async(R)=>{let k=U.getStore();if(k)k.attempt=R.attempt;return Z.rewriteRequest?.(R)},rewriteHandshakeURL:(R)=>{let k=U.getStore();if(k)k.attempt=R.attempt;return Z.rewriteHandshakeURL?.(R)},onAttemptEnd:async(R,k)=>{await N.end(R,k),await Z.onAttemptEnd?.(R,k)},rewriteResponse:async(R)=>{await N.response(R.request,R.response.status);let k=await Z.rewriteResponse?.(R)??R.response;return vZ(k,R.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(R)=>{let k=R.get("authorization");return k?.startsWith("Bearer ")?k.slice(7):void 0}},logger:{warn:(R,k)=>J.warn(R,{data:k})}}),a=u.dispose;return{...u,dispose:async()=>{B.clear(),j.clear(),await a(),await N.settle(),N.clear()}}}function O1($={}){return{id:o2,setup:(Z)=>X4(Z,$)}}async function X4($,Z={}){let n=[];try{let J=Y2("opencode2");let z=Y2("quota");let X=Z.paths??(()=>mZ(hZ()));let Y=await U2(X());let F=Y?.logging?.level;if(F&&typeof F==="string")DZ(F);let N=Z.fetch??fetch;let U=Z.now??Date.now;let j=Z.version??cZ;let B=Z.poolMigration??sZ;if(!B&&!C2(X().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 M=(Q2)=>{throw new J2({kind:"no-account",providerID:X2,sessionID:Q2.sessionID,requestKind:Q2.kind,message:l2})},d=await qZ($,{providerID:X2,chooseAccount:M,accountHeaders:M},J);return()=>d.dispose()}let L=Z.vault?.firstRosterWaitMs??iZ;let S=rZ({host:"opencode",stateDir:Z.vault?.stateDir??yZ(X().statePath),reservedRouteIds:()=>w.peek().rows.map((M)=>M.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},X());let T=S.vault;let u=!1;let a=!1;const R=a2(n,{[Symbol.dispose](){if(!u)S.release()}},0);await T.authority();let k=S.firstRoster;let z2=new P1;let w=new aZ({paths:X,refreshProvider:async(M)=>{let d=await wZ({refreshToken:M.refresh,fetchImpl:N,now:U}),Q2=kZ({id_token:"",access_token:d.access,refresh_token:d.refresh});return{...d,...Q2?{identity:Q2}:{}}},pullQuota:BZ({fetchImpl:N,now:U,counts:z2,logger:z}),now:U,vaultIdentities:()=>T.identities(),vaultMode:()=>T.enrolled(),vaultAuthority:()=>T.authority(),vaultFirstRoster:k,vaultFirstRosterBackgroundWaitMs:L,log:Y2("pool")});await w.load();let h=Z.heartbeat===!1?void 0:await oZ({version:j,logger:Y2("heartbeat")});let v=Z.fence??(()=>pZ({currentVersion:j}));let V=Z.slot??tZ();let P=async()=>gZ(X(),await V.get({path:{id:"openai"}}));let E=!1;let K=B?nZ({paths:X,slot:V,version:j,fence:v,runDeps:{vaultServes:()=>T.serves()},paused:async()=>await T.authority()!=="local",migrate:async(M)=>{let d=await lZ(M);if(E=d.status==="refused",!a)await w.load();return d},adopt:async(M)=>{if(a)return{status:"retry",reason:"unsettled"};if(!await E1(k,L))return{status:"retry",reason:"vault-roster-pending"};if(a)return{status:"retry",reason:"unsettled"};let d=await uZ(M);if(!a)await w.load();return d}}):void 0;K?.start();S.start();let A=FZ(X());let _=xZ({paths:X(),source:w,pins:A,vault:T},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const C=a2(n,{[Symbol.dispose](){if(!u)_.release()}},0);_.publish();let y=Z.codex??new R2(void 0,void 0,f$());let b=E$(Y);let m=p2(X());let g=R$(X(),{source:w,storage:()=>U2(X()),vault:T,accounts:Q1(X()),settings:()=>b,parentOf:async(M)=>(await $.session.get({sessionID:M}))?.parentID??void 0,fetch:N,log:Y2("cachekeep")},{now:U,codexResponsesUrl:n2().codexApiEndpoint,...Z.cacheKeep});const r=a2(n,{[Symbol.dispose](){if(!u)g.release()}},0);let e=H$({codex:y,onRoute:_.route,source:w,slotPlaceholderWithoutMain:P,storage:()=>U2(X()),pins:A,sessionAccounts:Q1(X()),vault:T,awaitVaultRoster:async()=>{await E1(T.awaitRequestRoster(),dZ)},responsesLite:()=>n2().responsesLite,codexEndpoint:()=>n2().codexApiEndpoint,now:U,log:J});let c=await qZ($,e.adapter,J,y,(M)=>g.capture(M),m,(M)=>g.forget(M));e.attach(c);let s=async(M)=>{if(await b2(T),C2(X().configPath))return;if(await K?.idle(),C2(X().configPath))return;if(E&&!K1(M)&&(await v()).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 l=async(M)=>{await s(M);let d=await t$(w.poolStore(),X(),M,{vault:T});if(!C2(X().configPath))await K?.requestAdoption();await w.load(),J.info("ChatGPT login stored in the account pool",d)};let f=await t2($,{integrationID:X2,methods:s$({beginLogin:Z.beginLogin??C1,version:j,vault:T}),onLogin:(M)=>l(M),label:"ChatGPT (openai-auth account pool)",vault:r$(T)});let I=await GZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let $2=$.command&&$.location?await c$({session:$.session,command:$.command,location:$.location},Z.controlPlane??ZZ({...UZ({source:w,storage:()=>U2(X()),counts:z2,now:U,authority:()=>T.authority()}),fetchImpl:N,now:U,randomUUID:z4,accountStoragePath:X().configPath,accountStatePath:X().statePath,packageVersion:j,loadAccounts:U2,store:()=>w.poolStore(),migration:async()=>{if(C2(X().configPath))return{migrated:!0};let M=await v();return{migrated:!1,blockers:M.open?[]:M.blockers}},beginAccountLogin:Z.beginLogin??C1,refreshAllQuota:async()=>(await w.pollRows(await U2(X()))).map((M)=>({...M,account:M.id})),getStickyRouting:async(M)=>A.get(M),cacheKeepManager:g.manager,setCacheKeepEnabled:(M)=>g.configure({enabled:M}),setCacheKeepSubagents:(M)=>g.configure({subagents:M}),setCacheKeepSustain:(M)=>g.configure({sustain:M}),setCacheKeepWindow:(M)=>g.configure({window:M}),afterWrite:()=>w.load(),refreshSidebar:()=>_.publish(),clearStickyRouting:async(M)=>{let d=A.get(M)!==void 0;return A.forget(M),d},vault:T})):void 0;let p=new AbortController;(async()=>{try{for await(let M of $.event.subscribe({signal:p.signal}))if(M.type==="session.deleted")e.forgetSession(M.data.sessionID),g.forget(M.data.sessionID),m.forget(M.data.sessionID)}catch(M){if(!p.signal.aborted)J.warn("stopped listening for session deletion",{error:M instanceof Error?M.message:String(M)})}})();u=!0;return async()=>{a=!0,p.abort();let M=g.release();await $2?.(),K?.dispose(),await w.dispose(),await _.release(),await Promise.allSettled([c.dispose(),f.dispose(),I.dispose()]);let d;try{await Promise.race([Promise.all([K?.idle(),w.settled(),y.store?.settled(),M]),new Promise((Q2)=>{d=setTimeout(Q2,G4),d.unref?.()})])}finally{clearTimeout(d),S.release(),await h?.release()}}}catch(W2){var T2=W2,F2=1}finally{bZ(n,T2,F2)}}var Y4=O1(),q6={id:o2,setup:Y4.setup,server:eZ.server};export{q6 as default,O1 as createOpenAIAuthPlugin,o2 as OPENAI_AUTH_PLUGIN_ID};
3
+ `)}}function G1($,Z){let J=new TextDecoder,z="",Q=(N)=>{let H=F0(N);if(!H)return;try{$(H)}catch(U){Z(U)}},Y=()=>{for(;;){let N=/\r?\n\r?\n/.exec(z);if(!N)return;let H=z.slice(0,N.index);z=z.slice(N.index+N[0].length),Q(H)}};return new TransformStream({transform(N,H){H.enqueue(N),z+=J.decode(N,{stream:!0}),Y()},flush(){if(z+=J.decode(),Y(),z.trim()!=="")Q(z);z=""}})}var m1=512,g1=1200000,C2="x-common-auth-attempt",T2=($,Z)=>JSON.stringify([$,Z]),G2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function K0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function L0($,Z){let J=$.getReader();return new ReadableStream({async pull(z){let Q;try{Q=await J.read()}catch(Y){Z({reason:"failed",message:Y instanceof Error?Y.message:String(Y)}),z.error(Y);return}if(Q.done)Z(),z.close();else z.enqueue(Q.value)},async cancel(z){Z({reason:"cancelled",...z===void 0?{}:{message:String(z)}}),await J.cancel(z)}})}function f2($,Z){for(let[J,z]of Object.entries(Z)){let Q=J.toLowerCase();for(let Y of Object.keys($))if(Y.toLowerCase()===Q)delete $[Y];if(z!==null)$[J]=z}}function P0($,Z){for(let[J,z]of Object.entries(Z))if(z===null)$.delete(J);else $.set(J,z)}async function Y1($,Z,J={}){let{providerID:z}=Z,Q=J.gateOnPlaceholder,Y=(G)=>Q===void 0||Q.credential(G)===B2(z),N=J.logger,H=Math.max(1,J.maxRecords??m1),U=[...J.hostCredentials??[B2(z)],...Q?[B2(z)]:[]].filter((G)=>G!==""),j=new Map,B=new WeakMap,L=new Map,b=0,_=new Set,I=new Map,c=new Map,x=(G)=>{let X=c.get(G);return X?.ownedSeen===!0&&X.foreignSeen},D=(G,X)=>{I.set(G,X);let V=c.get(G)??{ownedSeen:!1,foreignSeen:!1};if(X)V.ownedSeen=!0;else V.foreignSeen=!0;c.set(G,V)},Q2=(G,X)=>{let V=Q?.refuseMisplaced,P=V?[...X].filter(([,k])=>k.includes(B2(z))):[],K=Y(X)&&(!V||P.length>0);if(V){if(P.length>0&&(P.length!==1||!K))throw D(G.sessionID,!1),new Z2({kind:"placement-refused",providerID:z,sessionID:G.sessionID,requestKind:G.kind,message:V(P[0]?.[0]??"")})}return D(G.sessionID,K),K},m=!1,p=!1,g=new Map,W=0,T=!1,E=new Map,F=(G,X)=>{try{N?.warn(G,X)}catch{}},A=(G)=>G instanceof Error?G.message:String(G),M=new Map,O=(G,X)=>{let V=(M.get(G)??Promise.resolve()).then(X),P=V.then(()=>{},()=>{});return M.set(G,P),P.then(()=>{if(M.get(G)===P)M.delete(G)}),V},v=(G,X)=>{let V=M.get(G);return V?V.then(()=>v(G,X)):X()},S=async(G)=>{try{await Z.dropChoice?.({...G.input,accountId:G.accountId})}catch(X){F("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:G.input.sessionID,error:A(X)})}},l=(G)=>{let X=L.get(G);if(L.delete(G),X?.next){let V=X.next;O(X.sessionID,()=>S(V))}},w=async(G,X)=>{let V=g.get(G);if(!V||V.size===0)return;await Promise.all([...V].map(async(P)=>{try{await P(X)}catch(K){F("opencode2 auth listener threw; the request is unaffected",{event:G,error:A(K)})}}))},$2=async(G,X)=>{try{await Z.onAttemptEnd?.(G,X)}catch(V){F("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:G.attemptId,error:A(V)})}},n=(G,X)=>{if(G.ended||!G.attempt)return;let V={...G.status===void 0?{}:{status:G.status},outputStarted:G.outputStarted,...G.limit?{limit:G.limit.signal}:{},...X?{error:X}:{}};if(X)G.endError=X;G.ended=$2(G.attempt,V)},d=(G,X)=>n(G,{reason:"abandoned",message:X}),o=(G)=>[...j.values()].filter((X)=>X.key===G),h=(G)=>o(G).at(-1),y=(G)=>{if(j.delete(G.id),L.get(G.key)?.attemptId===G.id||!o(G.key).length)l(G.key)},f=(G)=>{j.set(G.id,G);while(j.size>H){let X=j.values().next().value;if(X===void 0)break;d(X,"dropped to keep the record bound"),y(X)}},r=(G)=>G.accountId===void 0?void 0:{...G.scope,accountId:G.accountId},u=(G,X)=>new Z2({kind:"no-account",providerID:z,sessionID:G.sessionID,requestKind:G.kind,...X===void 0?{}:{message:X}}),s=(G)=>{E.get(G)?.clear(),E.delete(G)},W2=async(G,X)=>{let V=()=>u(G,`${z} ${G.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(T)throw V();let P=E.get(G.sessionID);if(!P)P=new Set,E.set(G.sessionID,P);let K={};P.add(K);let k=()=>{if(!P.has(K))throw V()};try{return await X(k)}finally{if(P.delete(K),P.size===0&&E.get(G.sessionID)===P)E.delete(G.sessionID)}},M2=(G,X)=>{for(let[V,P]of X)if(U.some((K)=>P.includes(K)))throw new Z2({kind:"host-credential-on-wire",providerID:z,sessionID:G.sessionID,requestKind:G.kind,message:`${z} ${G.kind} request still carries the host's placeholder credential in ${V}; the adapter's account headers must replace it`})},O2=(G)=>{for(let X of o(G))if(X.ended||!X.attempt)y(X);else if(X.transport==="ws"||X.judged)d(X,"a newer attempt of its session and kind began"),y(X)},C=async(G,X,V,P)=>{let K=T2(G.sessionID,G.kind),{input:k,accountId:R}=await v(G.sessionID,async()=>{V();let t=L.get(K);L.delete(K);let X2=t?.accountId??h(K)?.accountId;O2(K);let j2=t?.next,e=j2!==void 0&&j2.input.modelID===G.modelID&&j2.input.agent===G.agent,A2={...G,phase:"request",...X2===void 0?{}:{previousAccountId:X2},...t?.rerouteFrom?{rerouteFrom:t.rerouteFrom}:{}};if(j2&&!e)await O(G.sessionID,()=>S(j2)),V();let F2=e?j2.accountId:await Z.chooseAccount(A2);return{input:A2,accountId:typeof F2==="string"?F2:void 0}});V();let q={},i;if(R!==void 0){let t=await Z.accountHeaders({...G,accountId:R});if(V(),K0(t))q=t.headers,i=t.attempt;else q=t}let L2=`attempt-${++W}`,z2={id:L2,key:K,scope:G,accountId:R,headers:q,attempt:R===void 0?void 0:{...G,accountId:R,attemptId:L2,transport:P,data:i},...P===void 0?{}:{transport:P},outputStarted:!1};if(f(z2),z2.attempt)w("select",{...G,accountId:z2.attempt.accountId,hook:X,...k.previousAccountId===void 0?{}:{previousAccountId:k.previousAccountId},...k.rerouteFrom===void 0?{}:{rerouteFrom:k.rerouteFrom},handle:z2.attempt});return z2},a=async(G,X,V,P,K)=>{let k=T2(G.sessionID,G.kind),R=P===void 0?void 0:j.get(P);if(R?.key!==k)R=void 0;if(!R){if(R=h(k),o(k).filter((i)=>i.transport===void 0&&!i.ended).length>1&&!p)p=!0,F("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:G.sessionID,kind:G.kind})}if(!R||R.transport!==void 0||R.ended)R=await C(G,X,K,V);else if(R.transport=V,R.attempt)R.attempt.transport=V;if(V==="ws"){for(let q of o(k))if(q!==R&&q.transport==="ws")d(q,"a newer attempt of its session and kind went out over WebSocket")}return R},J2=async(G,X)=>{try{return await X()}catch(V){throw n(G,{reason:"failed",message:A(V)}),V}},k1=(G,X)=>{let V=o(T2(G,X)).filter((P)=>P.transport==="ws").at(-1);return V?.attempt!==void 0&&!V.ended?V:void 0},e2=(G,X,V)=>{let P=r(G);if(!P||!G.attempt||G.limit)return;G.limit={signal:X,delivered:w("limit",{...P,via:V,limit:X,outputStarted:G.outputStarted,handle:G.attempt})}},D1=(G,X,V,P)=>{let K=r(G);if(!K||!G.attempt)return;w("quota",{...K,transport:X,...P===void 0?{}:{status:P},quota:V,handle:G.attempt})},w1=(G,X,V,P)=>{let K=G.attempt;if(!K)return;let k=Z.inspectEvent?.(P===void 0?{transport:X,data:V,attempt:K}:{transport:X,data:V,event:P,attempt:K});if(!k)return;if(k.quota!==void 0)D1(G,X,k.quota);if(k.outputStarted)G.outputStarted=!0;if(k.limit)e2(G,k.limit,X);if(k.error!==void 0)n(G,{reason:"failed",message:k.error});else if(k.done)n(G)},U0=(G,X)=>{let V=G.attempt;if(!V||X.accountId===G.accountId)return;if(V.reboundFrom??=V.accountId,V.accountId=X.accountId,"data"in X)V.data=X.data;G.accountId=X.accountId},H0=(G)=>!G.attempt||G.endError!==void 0||G.status!==void 0&&G.status>=400,N0=(G)=>{let X=[...j.values()].filter((q)=>q.scope.sessionID===G),V=X.filter((q)=>q.limit&&!q.rerouted).at(-1);if(V)return V;let P=X.filter((q)=>q.scope.kind==="primary"),K=P.length>0?P:X;if(K.length<=1)return K[0];let k=K.filter((q)=>!q.judged&&H0(q)).at(-1);if(k)return k;let R=K.filter((q)=>q.attempt&&!q.ended);if(R.length>1)return"ambiguous";return R[0]??K.at(-1)},K2={providerID:z},N2=[];N2.push(await $.session.hook("model.request",(G)=>{if(Q)return;return W2(G2(G),async(X)=>{let V=await C(G2(G),"model.request",X);if(X(),V.accountId===void 0)throw u(V.scope);f2(G.headers,{...V.headers,[C2]:V.id})})},K2)),N2.push(await $.session.hook("http.request",(G)=>{if(Q){if(!Q2(G2(G),G.request.headers))return}return W2(G2(G),async(X)=>{let V=G.request.headers.get(C2)??void 0,P=Q?await C(G2(G),"http.request",X,"http"):await a(G2(G),"http.request","http",V,X);X();let K=r(P),k=P.attempt;if(!K||!k)throw u(P.scope);await J2(P,async()=>{let R=G.request;if(Z.rewriteRequest){if(V!==void 0){let L2=new Headers(R.headers);L2.delete(C2),R=new Request(R,{headers:L2})}R=await Z.rewriteRequest({...K,request:R,attempt:k})??R,X()}let q=new Headers(R.headers);q.delete(C2),P0(q,P.headers),M2(P.scope,q.entries());let i=new Request(R,{headers:q});B.set(i,P),G.request=i})})},K2)),N2.push(await $.session.hook("http.response",async(G)=>{let X=B.get(G.request);if(!X){if(Q)return;if(!m)m=!0,F("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:G.sessionID,kind:G.kind});return}let V=G.response;if(Z.answeredBy&&X.attempt){let q=X.attempt,i=await J2(X,async()=>Z.answeredBy?.({request:G.request,response:V,attempt:q}));if(i)U0(X,i)}let P=r(X),K=X.attempt;if(!P||!K)return;X.status=V.status;let k=Z.quotaFromHeaders?.(V.headers,V.status,K);if(k!==void 0)D1(X,"http",k,V.status);if(!V.ok&&Z.limitFromResponse){let q=await Z.limitFromResponse({status:V.status,headers:V.headers,body:()=>V.clone().text(),attempt:K});if(q)e2(X,q,"http")}if(!V.ok||!V.body)n(X);let R=V;if(V.body&&(Z.inspectEvent||Z.onAttemptEnd)){let q=V.body;if(Z.inspectEvent)q=q.pipeThrough(G1((i)=>w1(X,"http",i.data,i.event),(i)=>F("opencode2 auth event inspection threw",{error:A(i)})));R=new Response(L0(q,(i)=>n(X,i)),{status:V.status,statusText:V.statusText,headers:V.headers})}if(Z.rewriteResponse)R=await Z.rewriteResponse({...P,request:G.request,response:R,attempt:K})??R;if(R!==V)G.response=R},K2)),N2.push(await $.session.hook("experimental.ws.handshake",(G)=>{if(Q){let X=T2(G.sessionID,G.kind);if(_.delete(X),!Q2(G2(G),new Headers(G.headers)))return}return W2(G2(G),async(X)=>{let V;for(let R of Object.keys(G.headers)){if(R.toLowerCase()!==C2)continue;V??=G.headers[R],delete G.headers[R]}let P=Q?await C(G2(G),"experimental.ws.handshake",X,"ws"):await a(G2(G),"experimental.ws.handshake","ws",V,X);X();let K=r(P),k=P.attempt;if(!K||!k)throw u(P.scope);await J2(P,async()=>{if(!Q?.refuseMisplaced)f2(G.headers,P.headers);let R=Z.rewriteHandshakeURL?.({...K,url:G.url,attempt:k});if(R!==void 0)G.url=R;if(Q?.refuseMisplaced)f2(G.headers,P.headers);if(M2(P.scope,Object.entries(G.headers)),Q)_.add(P.key)})})},K2));let y1=Z.rewriteWebSocketFrame?.bind(Z);if(y1)N2.push(await $.session.hook("experimental.ws.send",async(G)=>{let X=G2(G);if(Q&&!_.has(T2(X.sessionID,X.kind)))return;let V=k1(X.sessionID,X.kind),P=await y1({...X,attempt:V?.attempt,frame:G.frame});if(P!==void 0)G.frame=P},K2));N2.push(await $.session.hook("experimental.ws.receive",(G)=>{if(Q&&!_.has(T2(G.sessionID,G.kind)))return;let X=k1(G.sessionID,G.kind);if(!X)return;try{w1(X,"ws",G.frame)}catch(V){F("opencode2 auth frame inspection threw",{error:A(V)})}},K2)),N2.push(await $.session.hook("retry",async(G)=>{if(Q&&I.get(G.sessionID)!==!0)return;let X=G.decision,V=()=>w("retry",{sessionID:G.sessionID,attempt:G.attempt,reason:"host-decides",hostDecision:X,decision:X});if(x(G.sessionID)){await V();return}let P=N0(G.sessionID);if(!P)return;if(P==="ambiguous"){await w("retry",{sessionID:G.sessionID,attempt:G.attempt,reason:"host-decides",hostDecision:X,decision:X});return}let K=P;await W2(K.scope,async(k)=>{let R=k;if(x(G.sessionID)){await V();return}K.judged=!0;let q=K.attempt;if(q&&!K.outputStarted){if(!K.limit){let z2=Z.limitFromError?.(G.error,q);if(z2)e2(K,z2,"error")}if(K.ended)await K.ended;if(K.limit)await K.limit.delivered}R();let{decision:i,reason:L2}=await O(K.scope.sessionID,async()=>{if(R(),x(G.sessionID))return{decision:X,reason:"host-decides"};let z2=L.get(K.key);if(L.delete(K.key),z2?.next)await S(z2.next);if(R(),x(G.sessionID))return{decision:X,reason:"host-decides"};let t=X,X2,j2,e;if(K.accountId===void 0||!q)t={retry:!1},X2="no-account";else if(K.outputStarted)t={retry:!1},X2="output-started";else if(K.limit){let A2={accountId:K.accountId,limit:K.limit.signal},F2,Z1={...K.scope,phase:"retry",previousAccountId:K.accountId,rerouteFrom:A2};try{F2=await Z.chooseAccount(Z1)}catch(J1){F("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:K.scope.sessionID,error:A(J1)})}let P2=typeof F2==="object"?F2.hold:void 0,y2=typeof F2==="string"?F2:P2?K.accountId:void 0;if(y2!==void 0)e={accountId:y2,input:Z1};try{R()}catch(J1){if(e)await S(e);throw J1}if(x(G.sessionID)){if(e)await S(e);return{decision:X,reason:"host-decides"}}if(P2&&Number.isFinite(P2.delayMs)&&P2.delayMs>=0)t={retry:!0,delay:Math.min(P2.delayMs,g1)},X2="hold";else if(!P2&&y2!==void 0&&y2!==K.accountId)K.rerouted=!0,j2=A2,t={retry:!0,delay:0},X2="reroute";else{if(P2&&e)await S(e),e=void 0;X2="host-decides-last-account"}}else X2="host-decides";if(G.decision=t,t.retry&&K.accountId!==void 0&&j.has(K.id))L.set(K.key,{attemptId:K.id,sessionID:K.scope.sessionID,order:++b,accountId:K.accountId,...j2===void 0?{}:{rerouteFrom:j2},...e===void 0?{}:{next:e}});else if(e)await S(e);return{decision:t,reason:X2}});R(),await w("retry",{sessionID:G.sessionID,...K.accountId===void 0?{}:{accountId:K.accountId},kind:K.scope.kind,attempt:G.attempt,reason:L2,hostDecision:X,decision:i,...q===void 0?{}:{handle:q}})})},K2));let f1=(G)=>{if(s(G),I.delete(G),!c.get(G)?.foreignSeen)c.delete(G);for(let X of _)if(JSON.parse(X)[0]===G)_.delete(X);for(let X of[...j.values()]){if(X.scope.sessionID!==G)continue;d(X,"its session was forgotten"),j.delete(X.id)}for(let[X,V]of L)if(V.sessionID===G)l(X)},$1=new AbortController,I1=$.event;if(I1)(async()=>{try{for await(let G of I1.subscribe({signal:$1.signal}))if(G.type==="session.deleted")f1(G.data.sessionID);else if(G.type==="session.status"&&G.data.status.type==="idle"){let X=G.data.sessionID,V=++b;O(X,async()=>{for(let[P,K]of L)if(K.sessionID===X&&K.order<V){if(L.delete(P),K.next)await S(K.next)}})}}catch(G){if(!$1.signal.aborted)F("opencode2 auth stopped listening for session deletion",{error:A(G)})}})();return{on(G,X){let V=g.get(G);if(!V)V=new Set,g.set(G,V);let P=X;return V.add(P),()=>{V.delete(P)}},accountFor(G,X){return h(T2(G,X))?.accountId},forgetSession:f1,get size(){return j.size},async dispose(){if(T)return;T=!0;for(let G of E.keys())s(G);$1.abort();for(let G of j.values())d(G,"the installation was disposed");j.clear();for(let G of L.keys())l(G);_.clear(),I.clear(),c.clear(),g.clear(),await Promise.all(M.values()),await Promise.all(N2.map(async(G)=>{try{await G.dispose()}catch(X){F("opencode2 auth hook did not dispose cleanly",{error:A(X)})}}))}}}import{createHash as T0}from"node:crypto";var _0=1024,M0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),l1=($)=>u1($,"user"),C0=($)=>M0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function E0($){return T0("sha256").update(JSON.stringify($)).digest("hex")}class x2{runtime;maxSessions;#$=new Map;constructor($,Z=_0){this.runtime=$;this.maxSessions=Z}advance($,Z,J=this.runtime){let z=this.#$.get($),Q=Array.isArray(Z.input)?Z.input:[],Y=Q.filter(l1),N=Q.findLastIndex(l1),H=N<0?void 0:E0(Q[N]),U=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,j,B,L;if(U)j=Y.length>0,B=H??z?.fingerprint,L=z?.userCount===void 0?void 0:z.userCount+Y.length;else{B=H,L=Y.length;let _=N>=0&&N>Q.findLastIndex(C0),I=z!==void 0&&!z.completed&&z.fingerprint===B&&z.userCount===L;j=_&&!I}let b=j||!z?{turnID:(J?.uuid??_2)(),turnStartedAt:(J?.now??Date.now)()}:{turnID:z.turnID,turnStartedAt:z.turnStartedAt};return this.#Z($,{...b,completed:!1,fingerprint:B,userCount:L}),b}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 Q1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var p1=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function O0(){let $=globalThis;return $[p1]??=crypto.randomUUID(),$[p1]}class S2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,J){this.runtime=$;this.store=J;this.installationID=Z??O0(),this.sessions=J?.sessions??new Map,this.frameTurns=J?.frameTurns??new x2}get($){let Z=this.runtime?.uuid??_2;if(this.store)return this.store.get($,Z);let J=this.sessions.get($);if(!J){let z=Z();J={threadID:z,turnID:Z(),windowID:`${z}: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(I2(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($),this.frameTurns.forget($)}}var X1={version:c1,"user-agent":d1,originator:"codex_exec"};var A0=1024,R0=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,h2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),n1=($)=>h2($)&&($.type==="message"||("role"in $))&&$.role==="user",o1=($)=>h2($)&&$.type==="configuration_update";class j1{http;#$=new Map;constructor($=new S2){this.http=$}apply($,Z,J){if(Z.kind!=="primary")return!1;let z=typeof $.model==="string"?$.model:"";if(!a1.has(z))return!1;if(R0.test(z))return!1;let Q=h2($.reasoning)?$.reasoning:void 0,Y=typeof Q?.effort==="string"?Q.effort:void 0;if(!Y)return!1;let N=this.#$.get(Z.sessionID);if(N===void 0)return this.#Z(Z.sessionID,Y),!1;if(Y===N)return!1;let H=Array.isArray($.input)?$.input:void 0;if(!H||H.length===0)return!1;let U=H.findLastIndex(n1);if(U<0){if(J==="http")return!1;return $.reasoning={...Q,effort:N},!0}if($.reasoning={...Q,effort:N},!o1(H[U-1]))H.splice(U,0,{type:"configuration_update",reasoning:{effort:Y}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>A0){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function I2($){try{let Z=JSON.parse($);return h2(Z)?Z:void 0}catch{return}}async function r1($,Z,J,z,Q=J.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Y=await $.clone().text(),N=I2(Y);if(N)delete N.max_output_tokens;let H=new Headers($.headers),U=v2({rewriteLite:i1,init:{body:N?JSON.stringify(N):$.body===null?void 0:Y},headers:H,metadata:Q.get(Z.sessionID),installationID:Q.installationID,runtime:Q.runtime,websocket:!1,responsesLite:z,applyEffort:(j)=>{J.apply(j,Z,"http")}});return new Request($,{headers:H,body:U.init?.body})}function s1($,Z,J,z){let Q=z.sessions.get($.sessionID),Y=z.frameTurns.get($.sessionID);if(!Q||!Y)return;let N=Q1(Q,Y),H=new Headers({"content-type":"application/json"});for(let j of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let B=J.get(j);if(B!==null)H.set(j,B)}v2({init:{body:$.bodyText},headers:H,metadata:N,installationID:z.installationID,runtime:z.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let U=new URL(Z);if(U.protocol==="wss:")U.protocol="https:";if(U.protocol==="ws:")U.protocol="http:";return new Request(U,{method:"POST",headers:H,body:$.bodyText})}function x0($,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((z,Q)=>JSON.stringify(z)!==JSON.stringify($[Q]));return J>=0&&o1(Z[J])&&n1(Z[J+1])&&JSON.stringify(Z.slice(J+1))===JSON.stringify($.slice(J))}function t1($,Z,J){let z=I2($);if(z?.type!=="response.create")return;let Q=J.http.advanceFrame(Z.sessionID,z),Y=J.http.get(Z.sessionID);delete z.max_output_tokens;let N=v2({rewriteLite:()=>{},init:{body:JSON.stringify(z)},headers:new Headers,metadata:Q1(Y,Q),installationID:J.http.installationID,runtime:J.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(U)=>{J.apply(U,Z,"ws")}}),H=I2(String(N.init?.body));if(!H)return;if(!x0(z.input,H.input)){if("input"in z)H.input=z.input;else delete H.input;return JSON.stringify(H)}return String(N.init?.body)}function S0($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function B1($,Z){let J=new URL($);if(J.origin!=="https://api.openai.com"&&J.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(J.pathname))return $;let z=new URL(`${S0(Z)}/responses`);if(z.search=J.search,J.protocol==="ws:"||J.protocol==="wss:")z.protocol=z.protocol==="https:"?"wss:":"ws:";return z.href}import{resolve as e1}from"node:path";var q0=1024;class m2{accounts=new Map;limit;constructor($=q0){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 $$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),Z$=globalThis,V1=Z$[$$]??new Map;Z$[$$]=V1;function W1($){let Z=JSON.stringify([e1($.configPath),e1($.statePath)]),J=V1.get(Z);if(!J)J=new m2,V1.set(Z,J);return J}var Y2="openai",b0=60000,U1=1,k0="request refused: no account with a usable credential",U2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function D0($){let Z=U2($)?$.counters:void 0,J=U2(Z)?Z.resetCredits:void 0,z=U2(J)?J.value:void 0;return typeof z==="number"&&Number.isFinite(z)?z:void 0}function N1($){try{return JSON.parse($)}catch{return}}function J$($){let Z=l2($);return Z?u2(Z):void 0}var w0=new Set(["usage_limit_reached","rate_limit_exceeded"]);function F1($,Z,J){return{reason:$.window,...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function y0($,Z){let J=g2($);if(J){let Y=typeof $.status==="number"?$.status:void 0;return F1(J,Z,Y)}if($.type!=="response.failed"||!U2($.response))return;let z=$.response.failed;if(U2(z)&&typeof z.rate_limit_reached_type==="string")return{reason:z.rate_limit_reached_type};let Q=$.response.error;if(U2(Q)){let Y=typeof Q.code==="string"?Q.code:typeof Q.type==="string"?Q.type:void 0;if(Y&&w0.has(Y))return{reason:Y}}return}function f0($,Z){let J=N1($);if(!U2(J))return;let z=typeof J.type==="string"?J.type:void 0;if(z==="codex.rate_limits")return{quota:{snapshot:Q$(J),complete:!0}};let Q=y0(J,Z);if(Q)return{limit:Q};if(z===void 0||z==="error")return;return C$(z)?void 0:{outputStarted:!0}}function I0($){let Z=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:G$($),complete:Y$($)}}function v0($){let Z=$.get("retry-after");if(Z===null)return;let J=Number(Z);return Number.isFinite(J)&&J>=0?J*1000:void 0}function E$($){let{source:Z,pins:J}=$,z=$.now??Date.now,Q=$.log,Y=$.vault,N=new j1($.codex),H=new Map,U=new Map,j=(W)=>`${W.sessionID}\x00${W.kind}\x00${W.accountId}`,B=new Map,L=$.sessionAccounts??new m2,b=new L$,_=(W,T,E)=>{let F=E?[]:M$(Z.peek().rows,W,T,Y?.identities()??new Set),A=(Y?.routes()??[]).filter((M)=>M.kind==="oauth"&&j$(q2(M.quota),W,T));return[...F.map((M)=>({id:M.id,...M.identity!==void 0?{identity:M.identity}:{},quota:M.quota,row:M})),...A.map((M)=>({id:M.id,...M.identity!==void 0?{identity:M.identity}:{},quota:M.quota}))]},I=(W,T,E)=>{let F=N$(W,T,E),A=W.map((S)=>({id:S.id,kind:"oauth",...z$(S.quota)?{quota:S.quota}:{}})),M=W.flatMap((S)=>S.row?[S.row]:[]),O=new Set(W.filter((S)=>!S.row).map((S)=>S.id)),v=Z.rateLimitMarks(M);for(let S of O){let l=B.get(S);if(l===void 0)continue;if(l<=E)B.delete(S);else v.set(S,l)}return{rows:A,now:E,rateLimitMarks:v,refreshBackoff:Z.refreshBackoffFor(M),killswitch:F,requestPull:(S)=>O.has(S)?Y?.requestReading(S):Z.requestReading(S)}},c=(W,T,E,F,A)=>{let M=P$({...W,placement:F$(T),mainId:A});if(M.kind==="block"){Q?.debug("pool admission refused the request",{reason:M.block.reason});return}let O=M.order.filter((v)=>!E.has(v));if(F!==void 0&&O.includes(F))return F;return O[0]},x=(W,T,E,F,A,M,O)=>{let v=new Map(T.map((h)=>[h.id,h.quota])),S={requestBytes:U1,reservePercent:(h)=>B$(E,h===U$?void 0:h),resetCredits:(h)=>D0(v.get(h))},l=H1(W),w=(h,y)=>p2(O,{sessionId:F,requestBytes:U1,validPinnedAccountIds:W.rows.map((f)=>f.id).filter((f)=>!l.excluded.has(f)),excludeAccountIds:h,quotaCheckedAtByAccount:Object.fromEntries(W.rows.map((f)=>[f.id,l.projections.get(f.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(T.map((f)=>[f.id,f.identity])),select:(f)=>T$(W,S,new Set(h),f),persist:y},(f,r)=>O.set(f,r)),$2=[...A],n=w($2,M);if(!n)return;let d=n.accountId,o=_$(W,S,d);if(o.kind==="none")return;if(o.kind==="move"){let h=w([...$2,d],M);if(h)return h.accountId;return o.reason==="killswitch"?void 0:d}if(o.kind==="detour")return w([...$2,d],!1)?.accountId;return d},m={providerID:Y2,dropChoice(W){let T=j(W);U.get(T)?.drop(),U.delete(T),H.delete(T)},chooseAccount:async(W)=>{let T=await Y?.authority(),E=await $.storage(),F=T!==void 0&&T!=="local",A=()=>{throw new Z2({kind:"no-account",providerID:Y2,sessionID:W.sessionID,requestKind:W.kind,message:c2})};if(F)await $.awaitVaultRoster?.();else{if(!(await Z.current()).active){if(await $.slotPlaceholderWithoutMain?.())A();Q?.warn("the account pool does not serve requests yet; refusing the request",{kind:W.kind});return}await Z.prepareTokens(Z.peek().rows,E)}let M=z(),O=_(E,M,F),v=K$(I(O.filter((f)=>f.id!==W.rerouteFrom?.accountId),E,M));if(v)await v,M=z(),O=_(E,M,F);let S=new Map(O.map((f)=>[f.id,f])),l=I(O,E,M),w=new Set(W.rerouteFrom?[W.rerouteFrom.accountId]:[]),$2=E?.routing?.mode??"main-first",n=W.kind==="primary",d=new Set,o,h,y;try{for(;;){let f=new Set([...w,...d]);if(y=void 0,o=void 0,$2==="sticky-balanced"){let u=new Map(J.placementSnapshot(W.sessionID)),s=u.get(W.sessionID);if(y=x(l,O,E,W.sessionID,f,n&&d.size===0,u),y!==void 0&&u.get(W.sessionID)!==s)o=u.get(W.sessionID)}if(y??=c(l,$2,f,n?void 0:L.activeAccount(W.sessionID),F?$2==="sticky-balanced"?null:H$(Y?.routes()??[]):void 0),y===void 0||d.has(y)){if(w.size>0){let u=new Map(l.rateLimitMarks);for(let s of w)u.delete(s);l={...l,rateLimitMarks:u},w.clear();continue}y=void 0;break}if(n&&$2==="sticky-balanced"){let u=H1(l).projections.get(y)?.checkedAt,s=S.get(y)?.identity;h=J.reserve(W.sessionID,{accountId:y,inputBytes:U1,...u!==void 0?{quotaCheckedAt:u}:{},...s!==void 0?{wireIdentity:s}:{}})}let r=S.get(y)?.row;if(r){if(Z.usableToken(r)!==void 0)break;Q?.debug("pool row holds no usable token; choosing again",{accountId:y})}else{if(!Y)break;let u=await Y.authorize(y);if(u){H.set(j({...W,accountId:y}),u);break}Q?.debug("the vault refused to serve an account; choosing again",{accountId:y})}if(h)J.rollback(h);h=void 0,d.add(y)}if(y===void 0&&!F&&O.length===0&&await $.slotPlaceholderWithoutMain?.())A();if(y===void 0&&F&&Y&&(O.length===0||d.size>0)){let f=d.size>0?"vault-refused":W$(Y);throw Q?.warn("vault mode: no vault account can serve; refusing the request",{cause:f}),new Z2({kind:"no-account",providerID:Y2,sessionID:W.sessionID,requestKind:W.kind,message:V$(f,Y.name)})}if(y!==void 0){let f=y,r=h,u=o,s=()=>{if(r)J.finish(r,u);if(n)L.record(W.sessionID,f),$.onRoute?.(W.sessionID,f,$2)};if(W.phase==="retry")U.set(j({...W,accountId:y}),{commit:s,drop:()=>{if(r)J.rollback(r)}}),h=void 0;else s();let W2=Q?.info;b.served(l,y,Q&&W2?{info:(M2,O2)=>W2.call(Q,M2,O2)}:void 0)}return Q?.debug("pool account chosen",{kind:W.kind,accountId:y,mode:$2,...W.rerouteFrom?{rerouteFrom:W.rerouteFrom.accountId}:{}}),y}finally{if(h)J.rollback(h)}},accountHeaders:async(W)=>{let{accountId:T}=W,E=j(W),F=U.get(E);U.delete(E);let A=()=>{F?.commit()};try{let M=()=>new Z2({kind:"no-account",providerID:Y2,sessionID:W.sessionID,requestKind:W.kind,message:k0}),O=Y&&await Y.authority()!=="local"?void 0:Z.peek().rows.find((l)=>l.id===T);if(!O&&Y){let l=j(W),w=H.get(l)??await Y.authorize(T);if(H.delete(l),!w)throw Q?.warn("the vault refused to serve an account; refusing the request",{accountId:T}),M();return A(),{headers:{...X1,"session-id":W.sessionID,authorization:`Bearer ${w.accessToken}`,"chatgpt-account-id":w.accountIdentity??J$(w.accessToken)??null},attempt:{kind:"vault",routeId:T,receipt:w}}}let v=O?Z.usableToken(O):void 0;if(!O||!v)throw Q?.warn("pool row holds no usable token; refusing the request",{accountId:T}),M();let S=O.identity??J$(v);return A(),{headers:{...X1,"session-id":W.sessionID,authorization:`Bearer ${v}`,"chatgpt-account-id":S??null},attempt:{kind:"pool",token:v,credentialEpoch:O.credentialEpoch}}}finally{F?.drop()}},async rewriteRequest({request:W,sessionID:T,kind:E}){let F=$.codexEndpoint?B1(W.url,$.codexEndpoint()):W.url,A=F===W.url?W:new Request(F,W);return await r1(A,{sessionID:T,kind:E},N,$.responsesLite?.()??!1)??A},rewriteHandshakeURL:({url:W})=>$.codexEndpoint?B1(W,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:W,sessionID:T,kind:E})=>t1(W,{sessionID:T,kind:E},N),quotaFromHeaders:(W)=>I0(W),async limitFromResponse({status:W,headers:T,body:E}){if(W<400)return;let F=N1(await E().catch(()=>"")),A=g2({...U2(F)?F:{},status:W});if(!A)return;let M=z(),O=F1(A,M,W);if(O.retryAfterMs!==void 0)return O;let v=v0(T);return v===void 0?O:{...O,retryAfterMs:v}},inspectEvent:({data:W})=>f0(W,z()),limitFromError(W){let T=N1(W.message),E=g2({...U2(T)?T:{},...W.status!==void 0?{status:W.status}:{}})??(W.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return E?F1(E,z(),W.status):void 0},async onAttemptEnd(W,T){let E=W.data;if(E?.kind!=="vault"||T.status!==401)return;Q?.warn("a vault account answered 401; reporting it to the vault",{accountId:W.accountId}),await Y?.reportFailure(E.receipt,401)}},p=(W,T,E)=>{let F=E.data;if(F?.kind==="vault"){Y?.recordSnapshot(W,T.snapshot,T.complete,F.receipt);return}if(F?.kind!=="pool")return;if(Z.peek().rows.find((M)=>M.id===W)?.credentialEpoch!==F.credentialEpoch){Q?.debug("quota reading dropped: the row holds another credential",{accountId:W});return}Z.recordSnapshot(W,T.snapshot,F.token,T.complete)},g=(W,T,E)=>{let F=z(),A=E.data?.kind==="vault",M=A?Y?.routes().find((S)=>S.id===W)?.quota:Z.peek().rows.find((S)=>S.id===W)?.quota,O=X$(q2(M),T.reason,F,b0,T.retryAfterMs!==void 0?F+T.retryAfterMs:void 0);if(!A){Z.markRateLimited(W,O);return}let v=B.get(W);if(v===void 0||v<O)B.set(W,O)};return{adapter:m,attach(W){W.on("quota",(T)=>p(T.accountId,T.quota,T.handle)),W.on("limit",(T)=>{g(T.accountId,T.limit,T.handle),Q?.debug("pool row refused the request",{accountId:T.accountId,via:T.via,reason:T.limit.reason,outputStarted:T.outputStarted})})},forgetSession(W){J.forget(W),L.forget(W),N.forget(W)},activeAccount:(W)=>L.activeAccount(W)}}import{resolve as q$}from"node:path";import{Buffer as h0}from"node:buffer";import{resolve as O$}from"node:path";function b2($){return h0.byteLength(JSON.stringify($))}function m0($){return $.reduce((Z,J)=>Z+b2(J),0)}function K1($,Z){return 2+$+Math.max(0,Z-1)}function g0($){let{head:Z,pending:J}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+K1(Z.inputBytes,Z.input.length)+1:0)+(J?20+K1(J.inputBytes,J.input.length)+10+K1(J.outputBytes,J.output.length)+(J.responseID===void 0?0:14+J.responseIDBytes)+1:0)}function A$($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class R${enabled;caps=d2;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=A$(Z);if(J?.type!=="response.create")return;if(!Array.isArray(J.input)){this.forget($);return}let z=J.previous_response_id,Q=this.entries.get($),Y=Q?.head;if(z&&z!==Y?.responseID){this.forget($);return}let{type:N,previous_response_id:H,input:U,...j}=J;this.keep($,{fields:z&&Q?Q.fields:j,fieldsBytes:z&&Q?Q.fieldsBytes:b2(j),...z&&Y?{head:Y}:{},pending:{input:U,inputBytes:m0(U),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 z=this.entries.get($);if(!z?.pending)return;let Q=A$(Z);if(!Q)return;let Y=z.pending,N=Q.response;if(Q.type==="response.created"&&typeof N?.id==="string")Y.responseID=N.id,Y.responseIDBytes=b2(N.id),this.keep($,z);else if(Q.type==="response.output_item.done"&&Q.item){if(typeof Q.response_id==="string"&&Y.responseID!==void 0&&Q.response_id!==Y.responseID)return;Y.output.push(Q.item),Y.outputBytes+=b2(Q.item),this.keep($,z)}else if(Q.type==="response.completed"&&typeof N?.id==="string"){if(N.id===z.head?.responseID||Y.responseID!==void 0&&N.id!==Y.responseID)return;let H={responseID:N.id,responseIDBytes:Y.responseID===N.id?Y.responseIDBytes:b2(N.id),input:[...z.head?.input??[],...Y.input,...Y.output],inputBytes:(z.head?.inputBytes??0)+Y.inputBytes+Y.outputBytes},U={...z,head:H,pending:void 0};if(!this.keep($,U))return;J?.({sessionID:$,responseID:H.responseID,bodyText:this.body(z.fields,H)})}}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=g0(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 z=this.entries.keys().next().value;if(z===void 0)break;this.forget(z)}return this.entries.has($)}}var x$=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),S$=globalThis,L1=S$[x$]??new Map;S$[x$]=L1;function a2($){let Z=JSON.stringify([O$($.configPath),O$($.statePath)]),J=L1.get(Z);if(!J)J=new R$,L1.set(Z,J);return J}var l0=5000,u0=["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"],p0=["x-opencode-parent-session-id","x-parent-session-id"];function w$($){let Z=b$($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:k$($?{...$,cachekeep:Z}:$)}}var y$=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),f$=globalThis,k2=f$[y$]??new Map;f$[y$]=k2;function c0($,Z){let J=[],z=()=>J.at(-1)?.location,Q=()=>{let U=z();if(!U)throw Error("no location holds keep-warm");return U},Y=(U,j)=>{H.remove(U),z()?.log?.debug(`cachekeep dropped target (${j})`,{sessionKey:U})},N=async(U)=>{if(U.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let j=U.accountId??"main",B=Q(),L=await B.source.accessFor(j,await B.storage());if(!L)throw Error(`pool row ${j} has no usable token`);return{token:L.token,identity:L.row.identity}},H=D$({...d2,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(U,j)=>Q().fetch(U,j),logger:{debug:(U,j)=>z()?.log?.debug(U,j),warn:(U,j)=>z()?.log?.warn(U,j)},getWindow:()=>z()?.settings().window,getSustain:()=>z()?.settings().sustain===!0,resolveLocal:N,vault:{owns:(U)=>z()?.vault.owns(U)===!0,authority:()=>Q().vault.authority(),send:async(U,j,B)=>{let L=Q();if(await L.vault.authority()!=="vault")return;return L.vault.send(U,j,B)}},activeAccount:(U)=>{if(U===void 0)throw Error("target has no session");let j=z(),B=j?.settings();if(!j||!B?.enabled){Y(U,"keep-warm is off");return}if(!B.subagents&&H.status().targets.some((b)=>b.sessionKey===U&&b.isSubagent)){Y(U,"subagent warming is off");return}let L=j.accounts.activeAccount(U);if(L===void 0){Y(U,"no account recorded for the session");return}return L},verifyCredential:({target:U,mode:j,identity:B})=>{if(U.meta.credentialMode!==j)throw Error(`a target captured in ${U.meta.credentialMode??"an unknown"} mode is not warmed with a ${j} credential`);if(B!==U.meta.chatgptAccountId)throw Y(U.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:H,settings:Z,holders:J,joinTimeoutMs:$.joinTimeoutMs??l0}}function d0($){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((Q)=>typeof Q?.text==="string"?Q.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function a0($){let Z={};for(let J of u0){let z=$.get(J);if(z)Z[J]=z}return Z}function I$($,Z,J){let z=JSON.stringify([q$($.configPath),q$($.statePath)]),Q=k2.get(z);if(!Q)Q=c0(J,Z.settings()),k2.set(z,Q);let Y=Q,N=a2($);N.setEnabled(Y.settings.enabled);let H={location:{...Z,settings:()=>Y.settings}};Y.holders.push(H);let U=!1,j=async(B)=>{try{let L=H.location.settings();if(U||!L.enabled)return;if(B.kind!=="primary"){if(B.kind==="generate"&&d0(await B.request.clone().text())){if(U)return;Y.manager.remove(B.sessionID)}return}let b=B.attempt.data,_=b?.kind==="pool"?"local":b?.kind==="vault"?"vault":void 0;if(!_)return;let I=B.request.headers,c=p0.some((Q2)=>I.has(Q2))||Z.parentOf!==void 0&&await Z.parentOf(B.sessionID)!==void 0;if(c&&!L.subagents)return;let x=await B.request.clone().text();if(U)return;let D=I.get("chatgpt-account-id")??void 0;Y.manager.track({sessionKey:B.sessionID,bodyText:x,accountId:B.attempt.accountId,isSubagent:c,meta:{replayHeaders:a0(I),...D?{chatgptAccountId:D}:{},routingSessionId:B.sessionID,url:B.request.url,credentialMode:_}})}catch(L){Z.log?.warn("cachekeep capture failed",{error:L instanceof Error?L.message:String(L)})}};return{manager:Y.manager,configure:(B)=>{Object.assign(Y.settings,B),N.setEnabled(Y.settings.enabled)},capture:j,forget:(B)=>Y.manager.remove(B),async release(){if(U)return;U=!0;let B=Y.holders.indexOf(H);if(B>=0)Y.holders.splice(B,1);if(Y.holders.length>0)return;if(k2.get(z)===Y)k2.delete(z);Y.manager.stop();let L;try{await Promise.race([Y.manager.tick().catch(()=>{}),new Promise((b)=>{L=setTimeout(b,Y.joinTimeoutMs),L.unref?.()})])}finally{clearTimeout(L)}}}}import{mkdirSync as i0}from"node:fs";import{dirname as n0,resolve as o0}from"node:path";function r0(){return v$("opencode2")}var s0=2000;class u${path;options;sessions;frameTurns=new x2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Y=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=g$($,Z.uuid??_2)}get($,Z=_2){let J=this.sessions.get($);if(!J){let z=Z();J={threadID:z,turnID:Z(),windowID:`${z}:0`},this.sessions.set($,J),this.#Z.delete($),this.#z.delete($),this.#$.add($),this.#Q()}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.#Q()}#Q(){if(this.#J)return;this.#J=setTimeout(()=>{this.#J=void 0,this.save()},this.options.saveDelayMs??s0),this.#J.unref?.()}save(){if(clearTimeout(this.#J),this.#J=void 0,!this.#Y)this.#Y=!0,this.#G=this.#G.then(()=>{return this.#Y=!1,this.#j()});return this.#G}settled(){return this.#J?this.save():this.#G}#X(){if(this.#z.size===0)return;let $;try{$=P1(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((z)=>{let Q=this.sessions.get(z);return Q?[[z,Q]]:[]}),Z=[...this.#Z],J=null;try{if(i0(n0(this.path),{recursive:!0}),J=await this.#B(),!J)return;let z;try{z=P1(this.path)}catch{z=new Map}await this.options.afterRead?.();let Q=!1;for(let Y of Z)if(z.delete(Y))Q=!0;for(let[Y,N]of $){if(z.get(Y)===N.threadID)continue;z.set(Y,N.threadID),Q=!0}if(Q)l$(this.path,z)}catch{return}finally{await J?.release().catch(()=>{})}for(let[z,Q]of $)if(this.sessions.get(z)===Q)this.#$.delete(z);for(let z of Z)if(!this.sessions.has(z))this.#Z.delete(z)}#B(){return m$(this.path,this.options.lockWaitMs??h$)}}var p$=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),c$=globalThis,T1=c$[p$]??new Map;c$[p$]=T1;function d$($=r0()){let Z=o0($),J=T1.get(Z);if(!J)J=new u$(Z),T1.set(Z,J);return J}var a$=Symbol.for("cortexkit.openai-auth.v2.commands"),t0=V2("v2-command");function _1($){t0.warn(`/openai needs the terminal UI (session state: ${$}).`)}function e0(){let $=globalThis;return $[a$]??={locations:new Map},$[a$]}async function e$($,Z){let J=e0(),z=$.location.directory,Q={menu:Z,session:$.session,closed:new AbortController},Y=await n$(z),N=await i$(s$,Y.dir,()=>t$({...Y,drain:r$,apply:(B)=>{let L=J.locations.get(z);if(!L)throw Error("The OpenAI menu location was closed");return L.menu.apply(B)}})),H=J.locations.get(z);J.locations.set(z,Q),H?.closed.abort(),await H?.registration?.dispose(),J.command??={name:"openai",description:"OpenAI account menu",async execute(B){let L=J.locations.values().next().value?.session;if(!L)return _1("no live location");let b=await L.get({sessionID:B.sessionID}),_=J.locations.get(b.location.directory);if(!_)return _1("location closed");let I=await o$(B.sessionID,_.closed.signal);if(!I||J.locations.get(b.location.directory)!==_){if(!I&&!_.closed.signal.aborted)M1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},B.sessionID);return _1(_.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let c=await _.menu.open(B.sessionID);M1(c,B.sessionID)}};let U=J.command;try{Q.registration=await $.command.transform((B)=>{B.add(U)})}catch(B){if(Q.closed.abort(),J.locations.get(z)===Q)J.locations.delete(z);throw await N.release(),B}let j=!1;return async()=>{if(j)return;if(j=!0,Q.closed.abort(),J.locations.get(z)===Q)J.locations.delete(z);await N.release(),await Q.registration?.dispose()}}var $4="openai-auth-pool-browser",Z4="openai-auth-pool-headless",J4="openai-auth-vault",z4="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 D2($){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:J4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await $Z($.paths,$.name)!=="vault")throw Error(z4)}}}function QZ($){let Z=(J,z,Q)=>({method:{id:J,type:"oauth",label:z},async authorize(){if($.vault)await D2($.vault);let Y=await $.beginLogin({version:$.version,headless:Q});return{url:Y.url,instructions:Y.instructions,mode:"auto",callback:Y.completion}}});return[Z($4,"ChatGPT (openai-auth pool, browser)",!1),Z(Z4,"ChatGPT (openai-auth pool, headless)",!0)]}function C1($){let Z=(J)=>typeof J==="string"?J:"";return R2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===zZ||ZZ($)}function G4($){if($.accountId)return $.accountId;let Z=$.access?l2($.access):void 0;return Z?u2(Z):void 0}async function XZ($,Z,J,z={}){if(z.vault)await D2(z.vault);if(C1(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Q=JZ($,{rowLocks:(_)=>GZ(Z,_)}),Y=await Q.read();if(Y.status!=="ready")throw Error(`the account pool cannot be read (${Y.status}); the login was not stored`);let N={type:"oauth",refresh:J.refresh,...J.access!==void 0?{access:J.access}:{},...J.expires!==void 0?{expires:J.expires}:{}},H=G4(J);if(z.vault)await D2(z.vault);let U=H!==void 0?{identity:H}:{};if(z.origin==="import"){let _=Y.rows.find((I)=>H!==void 0&&I.identity===H||I.credential?.type==="oauth"&&I.credential.refresh===J.refresh);if(_)return{id:_.id,operation:"kept"}}let j=Y.rows.filter((_)=>_.type==="oauth"&&!_.invalid),B=H?j.find((_)=>_.identity===H):void 0,L=Y.rows.find((_)=>_.id===i2);if(B)return{id:(await Q.replace(B.id,N,U)).id,operation:"replaced"};if(!L){let _=await Q.add({id:i2,credential:N,...U,...J.label!==void 0?{label:J.label}:{}});return{id:_.id,operation:_.outcome==="added-disabled"?"added-disabled":"added"}}if(!L.invalid&&!L.credential)return{id:(await Q.replace(i2,N,U)).id,operation:"replaced"};let b=await Q.add({id:J.id,credential:N,...U,...J.label!==void 0?{label:J.label}:{}});return{id:b.id,operation:b.outcome==="added-disabled"?"added-disabled":b.outcome==="rotated"?"replaced":"added"}}function Y4($){let Z=$.itemId!==void 0;switch($.sectionId){case"accounts":return Z?["enable","disable","remove","move"].includes($.actionId):$.actionId==="add";case"routing":return!Z&&["order","mode"].includes($.actionId);case"quota":return $.actionId==="check";case"limits":return Z?$.actionId==="floors":$.actionId==="killswitch";case"session":return!Z&&$.actionId==="clear-pin";case"vault":return Z?["enable","disable"].includes($.actionId):["connect","disconnect"].includes($.actionId);case"diagnostics":return!Z&&["logging","dump"].includes($.actionId);case"cache":return!Z&&["enabled","subagents","sustain","window"].includes($.actionId);case"reset":return Z&&["preview","spend","retry"].includes($.actionId);default:return!1}}function VZ($){let Z={...$,allowAction:Y4,unavailableSections:[]};return{open:(J)=>jZ(Z,J),apply:(J)=>{let z=J!==null&&typeof J==="object"?J:{},Q=z.values&&typeof z.values==="object"&&!Array.isArray(z.values)?Object.fromEntries(Object.entries(z.values).filter(([,Y])=>Y===null||["string","number","boolean"].includes(typeof Y))):void 0;return BZ(Z,{command:"openai",sectionId:typeof z.sectionId==="string"?z.sectionId:"",actionId:typeof z.actionId==="string"?z.actionId:"",...Q?{values:Q}:{},...z.confirmed===!0?{confirmed:!0}:{},...typeof z.itemId==="string"?{itemId:z.itemId}:{},...typeof z.sessionId==="string"?{sessionId:z.sessionId}:{}})}}}function Q4($,Z){if(!WZ($.modelID??$.id)){$.enabled=!1;return}let J=UZ($.id);if(J)$.limit={...J};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((z)=>[z.id,z])).values()]}function NZ($){return $.model.transform((Z)=>{let J=Z.list(Y2);for(let z of J){let Q=HZ(String(z.id)),Y=Q?J.find((N)=>String(N.id)===Q):void 0;Z.update(Y2,String(z.id),(N)=>Q4(N,Y?.variants?.map((H)=>({...H,id:String(H.id)}))))}})}class E1{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(!FZ())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 z=this.pending.keys().next().value;if(z)this.take(z)}})}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(()=>n2({...J,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let J=this.requests.get($.attemptId),z=J&&this.take(J);if(!z)return;let{reason:Q,message:Y}=Z.error,N=Y?`${Q}: ${Y}`:Q;await this.safely(()=>n2({...z,error:o2(N,J?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>n2({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 O1{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 _Z($){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 z=await KZ({accessToken:J.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,z),LZ(z,$.now(),!0)}}function MZ($){let{source:Z,counts:J,now:z}=$,Q=async(j)=>{let B=await Z.rowAccess(j,await $.storage());if(!B?.row)throw new PZ("unknown_account",`${j==="main"?"Main":"Fallback"} account ${j} was not found.`);return TZ(j,B)},Y=async(j)=>{if($.authority&&await $.authority()!=="local")return{account:j,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[B]=await Z.pollRows(await $.storage(),{ids:[j]});if(!B)return{account:j,ok:!1,error:"targeted quota refresh returned no result"};return{account:B.id,ok:B.ok,...B.error!==void 0?{error:B.error}:{}}},N=(j)=>Z.peek().rows.find((B)=>B.id===j),H=(j)=>{let B=N(j);if(!B)return null;let L=q2(B.quota)??{},b=J.applicable(B),_=Math.max(0,...[L.primary?.checkedAt,L.secondary?.checkedAt].filter((I)=>typeof I==="number"));return{quota:{...L,...b!==void 0?{resetCreditsApplicable:b}:{}},checkedAt:_,refreshAfter:_,...B.identity!==void 0?{accountId:B.identity}:{}}};return{resolveResetTarget:Q,refreshResetTargetQuota:Y,quotaManager:{isRateLimited:(j)=>{let B=N(j);if(!B)return!1;let L=Z.rateLimitMarks([B]).get(B.id);return L!==void 0&&L>z()},getMain:()=>H("main"),getFallback:(j)=>H(j)}}}import{resolve as CZ}from"node:path";var X4=1024;class A1{pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=X4){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 p2(this.placementSnapshot($.sessionId),$,(Z,J)=>this.set(Z,J))}}var EZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),OZ=globalThis,R1=OZ[EZ]??new Map;OZ[EZ]=R1;function AZ($){let Z=JSON.stringify([CZ($.configPath),CZ($.statePath)]),J=R1.get(Z);if(!J)J=new A1,R1.set(Z,J);return J}import{statSync as j4}from"node:fs";import{resolve as B4}from"node:path";function yZ($){return $.map((Z)=>{try{let J=j4(Z);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}function x1($){return yZ([$.vault.paths.tokenPath,$.vault.paths.statePath])}function RZ($){return yZ([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+x1($)}class fZ{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:RZ($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),J=this.subscriptions.get($.pins);if(!J){let z=new Set;J={producers:z,stop:$.pins.subscribe((Q,Y)=>{let N=z.values().next().value;if(N)this.publish(N,{sessionId:Q,pin:Y,accountId:Y?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,J)}return J.producers.add($),this.timer??=setInterval(()=>{for(let z of this.producers){let Q={stamp:RZ(z),roster:z.vault.snapshot()},Y=this.observations.get(z);if(Q.stamp!==Y?.stamp||Q.roster!==Y?.roster)this.observations.set(z,Q),this.publish(z)}},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;let z=await $.vault.authority()!=="local",Q=x1($),Y=()=>this.producers.has($)&&$.vault.enrolled()===z&&x1($)===Q,N=await H2($.paths),H=z?DZ($.vault.snapshot()?.rows??[],new Set($.vault.routes().map((j)=>j.id)),N,Date.now()):wZ((await $.source.sidebarView()).rows,N,Date.now());if(await SZ(H,this.file,{canWrite:Y}),!Y()||!Z)return;let U=H.vaultAccounts??H.fallbacks;if(Z.accountId===void 0){await bZ(Z.sessionId,U,this.file,{canWrite:Y});return}if(Z.pin){let j=Date.now();await kZ({sessionId:Z.sessionId,assignment:{accountId:Z.pin.accountId,wireAccountId:Z.pin.wireIdentity,inputBytes:Z.pin.inputBytes??0,quotaCheckedAt:Z.pin.quotaCheckedAt,assignedAt:j,lastSeenAt:j},validPinnedAccountIds:[...z?[]:["main"],...U.filter((B)=>B.enabled).map((B)=>B.id)]},this.file)}await qZ({sessionId:Z.sessionId,activeId:Z.accountId,route:Z.route??H.route,updatedAt:Date.now()},U,this.file,{canWrite:Y})}).catch(()=>{V2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var IZ=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),vZ=globalThis,w2=vZ[IZ]??new Map;vZ[IZ]=w2;function hZ($,Z=xZ(),J=2000){let z=B4(Z),Q=w2.get(z);if(!Q)Q=new fZ(z,J),w2.set(z,Q);let Y=Q,N=Y.add($),H=!1;for(let[U,j]of $.pins.snapshot())Y.publish($,{sessionId:U,pin:j,accountId:j.accountId,route:"sticky-balanced"});return{publish:()=>Y.publish($),route:(U,j,B)=>{Y.publish($,{sessionId:U,accountId:j,route:B})},async release(){if(H)return;if(H=!0,N(),await Y.settled(),Y.empty&&w2.get(z)===Y)w2.delete(z)}}}var t2="cortexkit-openai-auth",U4=5000;async function mZ($,Z,J,z=new S2,Q,Y,N){let H=new E1(J),U=new V4,j=new Map,B=new Map,L=(x)=>{B.delete(x);for(let D of j.keys())if(D.startsWith(`${x}:`))j.delete(D)},b=(x)=>{N?.(x.sessionID),Y?.send(x.sessionID,x.frame)},I=await Y1({session:{hook:(x,D,Q2)=>$.session.hook(x,async(m)=>{let p=x==="http.request"?m:void 0,g=x==="experimental.ws.handshake"?m:void 0,T=(p?p.request.headers:g?new Headers(g.headers):void 0)?.get("authorization")===`Bearer ${B2(Z.providerID)}`,E={};if(g)j.delete(`${g.sessionID}:${g.kind}`);try{await U.run(E,()=>D(m))}catch(F){if(T&&!(F instanceof Z2))throw dZ(F);throw F}if(p&&T&&E.attempt){let F=p.request.headers.get("thread-id");if(F)p.request.headers.set("session-id",F)}if(p&&T&&E.attempt)await H.captureHttp(p.request,E.attempt);if(p&&T&&E.attempt)await Q?.({sessionID:p.sessionID,kind:p.kind,request:p.request,attempt:E.attempt});if(g&&T&&E.attempt)g.headers["session-id"]=z.get(g.sessionID).threadID;if(x==="experimental.ws.send"){let F=m,A=j.get(`${F.sessionID}:${F.kind}`);if(A)await H.frame(F.frame,A.attempt);if(A&&F.kind==="primary")b(F)}if(p||g){let F=p??g;if(!F)return;let M=(p?p.request.headers:new Headers(F.headers)).get("authorization")?.replace(/^Bearer /,"");if(T&&M)B.set(F.sessionID,M);else B.delete(F.sessionID);if(g){let O=`${g.sessionID}:${g.kind}`;if(T&&M&&E.attempt)j.set(O,{bearer:M,attempt:E.attempt,url:g.url,headers:new Headers(Object.entries(g.headers).filter(([v])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(v.toLowerCase())))});else j.delete(O)}if(B.size>512){let O=B.keys().next().value;if(O)B.delete(O)}if(j.size>512){let O=j.keys().next().value;if(O)j.delete(O)}}else if(x==="experimental.ws.receive"){let F=m,A=j.get(`${F.sessionID}:${F.kind}`);if(A){if(z.frameReceived(F.sessionID,F.frame),F.kind==="primary"){let M;if(Y?.receive(F.sessionID,F.frame,(O)=>{M=O}),M)try{let O=s1(M,A.url,A.headers,z);if(O)await Q?.({sessionID:F.sessionID,kind:"primary",request:O,attempt:A.attempt})}catch(O){J.warn("cachekeep WebSocket capture failed",{error:O instanceof Error?O.message:String(O)})}}F.frame=aZ(F.frame,A.bearer)}}else if(x==="retry"){let F=m,A=B.get(F.sessionID);if(A)Object.assign(F.error,{message:o2(F.error.message,A)})}},Q2)},event:{subscribe:(x)=>async function*(){for await(let D of $.event.subscribe(x)){if(D.type==="session.deleted")L(D.data.sessionID);yield D}}()}},{...Z,rewriteRequest:async(x)=>{let D=U.getStore();if(D)D.attempt=x.attempt;return Z.rewriteRequest?.(x)},rewriteHandshakeURL:(x)=>{let D=U.getStore();if(D)D.attempt=x.attempt;return Z.rewriteHandshakeURL?.(x)},onAttemptEnd:async(x,D)=>{await H.end(x,D),await Z.onAttemptEnd?.(x,D)},rewriteResponse:async(x)=>{await H.response(x.request,x.response.status);let D=await Z.rewriteResponse?.(x)??x.response;return iZ(D,x.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(x)=>{let D=x.get("authorization");return D?.startsWith("Bearer ")?D.slice(7):void 0}},logger:{warn:(x,D)=>J.warn(x,{data:D})}}),c=I.dispose;return{...I,dispose:async()=>{B.clear(),j.clear(),await c(),await H.settle(),H.clear()}}}function b1($={}){return{id:t2,setup:(Z)=>H4(Z,$)}}async function H4($,Z={}){let s=[];try{let J=V2("opencode2");let z=V2("quota");let Q=Z.version??oZ;await X0({version:Q,...Z.runtimeLayout});let Y=Z.paths??(()=>sZ(nZ()));let N=await H2(Y());let H=N?.logging?.level;if(H&&typeof H==="string")lZ(H);let U=Z.fetch??fetch;let j=Z.now??Date.now;let B=Z.poolMigration??B0;if(!B&&!E2(Y().configPath)){J.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let C=(J2)=>{throw new Z2({kind:"no-account",providerID:Y2,sessionID:J2.sessionID,requestKind:J2.kind,message:c2})},a=await mZ($,{providerID:Y2,chooseAccount:C,accountHeaders:C},J);return()=>a.dispose()}let L=Z.vault?.firstRosterWaitMs??J0;let b=j0({host:"opencode",stateDir:Z.vault?.stateDir??cZ(Y().statePath),reservedRouteIds:()=>m.peek().rows.map((C)=>C.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>U},Y());let _=b.vault;let I=!1;let c=!1;const x=r2(s,{[Symbol.dispose](){if(!I)b.release()}},0);await _.authority();let D=b.firstRoster;let Q2=new O1;let m=new z0({paths:Y,refreshProvider:async(C)=>{let a=await pZ({refreshToken:C.refresh,fetchImpl:U,now:j}),J2=uZ({id_token:"",access_token:a.access,refresh_token:a.refresh});return{...a,...J2?{identity:J2}:{}}},pullQuota:_Z({fetchImpl:U,now:j,counts:Q2,logger:z}),now:j,vaultIdentities:()=>_.identities(),vaultMode:()=>_.enrolled(),vaultAuthority:()=>_.authority(),vaultFirstRoster:D,vaultFirstRosterBackgroundWaitMs:L,log:V2("pool")});await m.load();let p=Z.heartbeat===!1?void 0:await Y0({version:Q,logger:V2("heartbeat")});let g=Z.fence??(()=>rZ({currentVersion:Q}));let W=Z.slot??V0();let T=async()=>tZ(Y(),await W.get({path:{id:"openai"}}));let E=!1;let F=B?G0({paths:Y,slot:W,version:Q,fence:g,runDeps:{vaultServes:()=>_.serves()},paused:async()=>await _.authority()!=="local",migrate:async(C)=>{let a=await eZ(C);if(E=a.status==="refused",!c)await m.load();return a},adopt:async(C)=>{if(c)return{status:"retry",reason:"unsettled"};if(!await q1(D,L))return{status:"retry",reason:"vault-roster-pending"};if(c)return{status:"retry",reason:"unsettled"};let a=await $0(C);if(!c)await m.load();return a}}):void 0;F?.start();b.start();let A=AZ(Y());let M=hZ({paths:Y(),source:m,pins:A,vault:_},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const O=r2(s,{[Symbol.dispose](){if(!I)M.release()}},0);M.publish();let v=Z.codex??new S2(void 0,void 0,d$());let S=w$(N);let l=a2(Y());let w=I$(Y(),{source:m,storage:()=>H2(Y()),vault:_,accounts:W1(Y()),settings:()=>S,parentOf:async(C)=>(await $.session.get({sessionID:C}))?.parentID??void 0,fetch:U,log:V2("cachekeep")},{now:j,codexResponsesUrl:s2().codexApiEndpoint,...Z.cacheKeep});const $2=r2(s,{[Symbol.dispose](){if(!I)w.release()}},0);let n=E$({codex:v,onRoute:M.route,source:m,slotPlaceholderWithoutMain:T,storage:()=>H2(Y()),pins:A,sessionAccounts:W1(Y()),vault:_,awaitVaultRoster:async()=>{await q1(_.awaitRequestRoster(),Z0)},responsesLite:()=>s2().responsesLite,codexEndpoint:()=>s2().codexApiEndpoint,now:j,log:J});let d=await mZ($,n.adapter,J,v,(C)=>w.capture(C),l,(C)=>w.forget(C));n.attach(d);let o=async(C)=>{if(await D2(_),E2(Y().configPath))return;if(await F?.idle(),E2(Y().configPath))return;if(E&&!C1(C)&&(await g()).open){await m.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 h=async(C)=>{await o(C);let a=await XZ(m.poolStore(),Y(),C,{vault:_});if(!E2(Y().configPath))await F?.requestAdoption();await m.load(),J.info("ChatGPT login stored in the account pool",a)};let y=await z1($,{integrationID:Y2,methods:QZ({beginLogin:Z.beginLogin??S1,version:Q,vault:_}),onLogin:(C)=>h(C),label:"ChatGPT (openai-auth account pool)",vault:YZ(_)});let f=await NZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let r=$.command&&$.location?await e$({session:$.session,command:$.command,location:$.location},Z.controlPlane??VZ({...MZ({source:m,storage:()=>H2(Y()),counts:Q2,now:j,authority:()=>_.authority()}),fetchImpl:U,now:j,randomUUID:W4,accountStoragePath:Y().configPath,accountStatePath:Y().statePath,packageVersion:Q,layoutNotice:Q0,loadAccounts:H2,store:()=>m.poolStore(),migration:async()=>{if(E2(Y().configPath))return{migrated:!0};let C=await g();return{migrated:!1,blockers:C.open?[]:C.blockers}},beginAccountLogin:Z.beginLogin??S1,refreshAllQuota:async()=>(await m.pollRows(await H2(Y()))).map((C)=>({...C,account:C.id})),getStickyRouting:async(C)=>A.get(C),cacheKeepManager:w.manager,setCacheKeepEnabled:(C)=>w.configure({enabled:C}),setCacheKeepSubagents:(C)=>w.configure({subagents:C}),setCacheKeepSustain:(C)=>w.configure({sustain:C}),setCacheKeepWindow:(C)=>w.configure({window:C}),afterWrite:()=>m.load(),refreshSidebar:()=>M.publish(),clearStickyRouting:async(C)=>{let a=A.get(C)!==void 0;return A.forget(C),a},vault:_})):void 0;let u=new AbortController;(async()=>{try{for await(let C of $.event.subscribe({signal:u.signal}))if(C.type==="session.deleted")n.forgetSession(C.data.sessionID),w.forget(C.data.sessionID),l.forget(C.data.sessionID)}catch(C){if(!u.signal.aborted)J.warn("stopped listening for session deletion",{error:C instanceof Error?C.message:String(C)})}})();I=!0;return async()=>{c=!0,u.abort();let C=w.release();await r?.(),F?.dispose(),await m.dispose(),await M.release(),await Promise.allSettled([d.dispose(),y.dispose(),f.dispose()]);let a;try{await Promise.race([Promise.all([F?.idle(),m.settled(),v.store?.settled(),C]),new Promise((J2)=>{a=setTimeout(J2,U4),a.unref?.()})])}finally{clearTimeout(a),b.release(),await p?.release()}}}catch(W2){var M2=W2,O2=1}finally{gZ(s,M2,O2)}}var N4=b1(),h6={id:t2,setup:N4.setup,server:W0.server};export{h6 as default,b1 as createOpenAIAuthPlugin,t2 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.6.2",
3
+ "version": "1.8.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -66,7 +66,7 @@
66
66
  },
67
67
  "devDependencies": {
68
68
  "@ai-sdk/openai": "3.0.88",
69
- "@cortexkit/common-auth": "^0.26.0",
69
+ "@cortexkit/common-auth": "^0.27.1",
70
70
  "@cortexkit/openai-auth-core": "workspace:*",
71
71
  "@opencode/plugin": "2.0.32"
72
72
  },
@@ -4,6 +4,7 @@ import { ClaustrumUnreachableError, classifyVaultFailure, } from "./94f53cfd572b
4
4
  import { readClaustrumEnrollmentToken } from "./b9588ad4725c1d10-enrollment.js";
5
5
  import { ClaustrumConsumerError } from "./ca0fccaba1d87af4-errors.js";
6
6
  import { CUSTODY_PLACEHOLDER_PREFIX } from "./d9d2892a4c371301-host-slot.js";
7
+ import { drainShutdown, shutdownWarning } from "./a670cb7f5987bc1b-shutdown.js";
7
8
  import { ScopedRosterWatch, } from "./dc9290c2a7552ba6-watch.js";
8
9
  /** Only a new version of the same account may replace an in-flight 401. */
9
10
  export function isScopedCredentialRotation(served, current) {
@@ -79,15 +80,56 @@ function accessTokenFromMaterial(material) {
79
80
  return access;
80
81
  }
81
82
  function credentialTypeOf(row, family) {
83
+ const notMine = { kind: 'not-mine' };
82
84
  if (!row.operations.includes('read'))
83
- return undefined;
85
+ return notMine;
84
86
  if (!row.categories.includes(family.category))
85
- return undefined;
87
+ return notMine;
88
+ if (row.credentialType !== 'oauth' && row.credentialType !== 'api_key')
89
+ return notMine;
90
+ if ('classify' in family) {
91
+ // Older clients omit these facts entirely; do not call a policy that needs them.
92
+ const facts = {
93
+ credentialId: row.id,
94
+ credentialType: row.credentialType,
95
+ categories: row.categories,
96
+ refreshAdapter: row.refreshAdapter,
97
+ ...rowFactsOf(row),
98
+ };
99
+ if (facts.providerIds === undefined)
100
+ return { kind: 'refused', code: 'unmapped' };
101
+ try {
102
+ const result = family.classify(facts);
103
+ if (result.kind === 'not-mine')
104
+ return notMine;
105
+ if (result.kind === 'mine' && typeof result.member === 'string')
106
+ return { kind: 'mine', type: row.credentialType, member: result.member };
107
+ if (result.kind === 'refused' &&
108
+ typeof result.code === 'string' &&
109
+ /^[a-z][a-z0-9-]{0,31}$/.test(result.code) &&
110
+ !result.code.includes('\n') &&
111
+ family.refusalCodes.includes(result.code))
112
+ return { kind: 'refused', code: result.code };
113
+ }
114
+ catch {
115
+ // A classifier error may contain vault data; expose only a fixed code.
116
+ }
117
+ return { kind: 'refused', code: 'unclassified' };
118
+ }
86
119
  if (row.credentialType === 'oauth')
87
- return row.refreshAdapter === family.refreshAdapter ? 'oauth' : undefined;
120
+ return row.refreshAdapter === family.refreshAdapter
121
+ ? { kind: 'mine', type: 'oauth' }
122
+ : notMine;
88
123
  if (row.credentialType === 'api_key' && family.apiKeys)
89
- return row.refreshAdapter === undefined ? 'api_key' : undefined;
90
- return undefined;
124
+ return row.refreshAdapter === undefined
125
+ ? { kind: 'mine', type: 'api_key' }
126
+ : notMine;
127
+ return notMine;
128
+ }
129
+ /** Structural access keeps the public facts independent of client declarations. */
130
+ function rowFactsOf(row) {
131
+ const metadata = row;
132
+ return { providerIds: metadata.providerIds, authMethod: metadata.authMethod };
91
133
  }
92
134
  /**
93
135
  * The grants named in the vault's list reply, or undefined when it names none.
@@ -136,6 +178,9 @@ export class ClaustrumScopedCustody {
136
178
  /** The view of the last successful `discover()`, for `watchRoster`. */
137
179
  #discoveredView;
138
180
  #watches = new Set();
181
+ #tokenReads = new Set();
182
+ #warnShutdown;
183
+ #disposing;
139
184
  constructor(options) {
140
185
  const tokenPath = options.tokenPath;
141
186
  if (options.readToken) {
@@ -153,6 +198,7 @@ export class ClaustrumScopedCustody {
153
198
  this.#requireAssertion = options.requireAssertion ?? false;
154
199
  this.#now = options.now ?? Date.now;
155
200
  this.#logger = options.logger ?? defaultLogger;
201
+ this.#warnShutdown = shutdownWarning(this.#logger);
156
202
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
157
203
  this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
158
204
  }
@@ -220,7 +266,15 @@ export class ClaustrumScopedCustody {
220
266
  }
221
267
  async #token(signal) {
222
268
  this.#check(signal);
223
- const value = await this.#readToken();
269
+ const pending = this.#readToken();
270
+ this.#tokenReads.add(pending);
271
+ let value;
272
+ try {
273
+ value = await pending;
274
+ }
275
+ finally {
276
+ this.#tokenReads.delete(pending);
277
+ }
224
278
  this.#check(signal);
225
279
  if (!/^[0-9a-f]{64}$/.test(value.token) ||
226
280
  !Number.isSafeInteger(value.token_generation) ||
@@ -299,17 +353,32 @@ export class ClaustrumScopedCustody {
299
353
  throw error;
300
354
  }
301
355
  const skipped = [];
356
+ const refused = [];
357
+ let notMine = 0;
302
358
  const candidates = [];
303
359
  const counts = new Map();
304
360
  for (const row of inventory.rows) {
305
- const type = credentialTypeOf(row, this.#family);
306
- if (!type)
361
+ const classified = credentialTypeOf(row, this.#family);
362
+ if (classified.kind === 'not-mine') {
363
+ notMine++;
364
+ continue;
365
+ }
366
+ if (classified.kind === 'refused') {
367
+ refused.push({
368
+ ...(row.id.trim() && { credentialId: row.id }),
369
+ code: classified.code,
370
+ });
307
371
  continue;
308
- candidates.push({ row, type });
372
+ }
373
+ candidates.push({
374
+ row,
375
+ type: classified.type,
376
+ ...(classified.member !== undefined && { member: classified.member }),
377
+ });
309
378
  counts.set(row.id, (counts.get(row.id) ?? 0) + 1);
310
379
  }
311
380
  const credentials = [];
312
- for (const { row, type } of candidates) {
381
+ for (const { row, type, member } of candidates) {
313
382
  let reason;
314
383
  if (!row.id.trim())
315
384
  reason = 'empty credential id';
@@ -320,12 +389,17 @@ export class ClaustrumScopedCustody {
320
389
  else if (!row.state.trim())
321
390
  reason = 'empty state';
322
391
  if (reason) {
323
- skipped.push({ ...(row.id.trim() && { credentialId: row.id }), reason });
392
+ skipped.push({
393
+ ...(row.id.trim() && { credentialId: row.id }),
394
+ ...(member !== undefined && { member }),
395
+ reason,
396
+ });
324
397
  continue;
325
398
  }
326
399
  credentials.push(Object.freeze({
327
400
  credentialId: row.id,
328
401
  credentialType: type,
402
+ ...(member !== undefined && { member }),
329
403
  ...(row.accountId !== undefined && {
330
404
  accountIdentity: row.accountId,
331
405
  }),
@@ -341,6 +415,10 @@ export class ClaustrumScopedCustody {
341
415
  view: inventory.view,
342
416
  credentials: Object.freeze(credentials),
343
417
  skipped: Object.freeze(skipped),
418
+ ...('classify' in this.#family && {
419
+ refused: Object.freeze(refused),
420
+ notMine,
421
+ }),
344
422
  ...(grantReach && { grantReach }),
345
423
  };
346
424
  }
@@ -646,4 +724,10 @@ export class ClaustrumScopedCustody {
646
724
  this.#kept.clear();
647
725
  this.#client.close();
648
726
  }
727
+ /** Stop immediately; allow token reads 2 s and share an owner's timeout warning. */
728
+ async dispose(onTimeout = this.#warnShutdown) {
729
+ this.close();
730
+ this.#disposing ??= drainShutdown(this.#tokenReads, onTimeout);
731
+ await this.#disposing;
732
+ }
649
733
  }