@cortexkit/opencode-openai-auth 1.7.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist/bin.js +9 -9
  2. package/dist/{codex-request-CN4rD2kf.d.ts → codex-request-GJkvxv4S.d.ts} +51 -57
  3. package/dist/{index-b5459de4.js → index-21yxzeet.js} +2 -2
  4. package/dist/index-4rf3rkdm.js +2 -0
  5. package/dist/{index-dr93b3g6.js → index-73z9ftrg.js} +6 -6
  6. package/dist/index-97cz7kyq.js +74 -0
  7. package/dist/index-b7p76qqa.js +91 -0
  8. package/dist/{index-r4avvxf0.js → index-c50p5mem.js} +1 -1
  9. package/dist/{index-p9vnmnzr.js → index-fhcnxrtz.js} +1 -1
  10. package/dist/{index-7zy4vdd3.js → index-h1r8cbet.js} +2 -2
  11. package/dist/{index-jaqm1xda.js → index-hpnj460b.js} +1 -1
  12. package/dist/{index-yayz83vv.js → index-mg4w434p.js} +2 -2
  13. package/dist/{index-g08eptzm.js → index-p8m4yh73.js} +1 -1
  14. package/dist/index-vh1sr50d.js +63 -0
  15. package/dist/index-ww8w9edq.js +2 -0
  16. package/dist/index.d.ts +4 -12
  17. package/dist/index.js +1 -1
  18. package/dist/{port-file-8ElfwDcq.d.ts → port-file-DXCxv8tU.d.ts} +0 -2
  19. package/dist/{protocol-BeeDdtpa.d.ts → protocol-BZZtDn5h.d.ts} +0 -4
  20. package/dist/rpc/port-file.d.ts +4 -4
  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 +1 -1
  25. package/dist/rpc/rpc-client.js +1 -1
  26. package/dist/rpc/rpc-dir.d.ts +0 -2
  27. package/dist/rpc/rpc-dir.js +1 -1
  28. package/dist/{rpc-client-DlR9a0_7.d.ts → rpc-client-CmaZW1by.d.ts} +2 -6
  29. package/dist/{sidebar-state-DHsZ9axt.d.ts → sidebar-state-DkNebAiC.d.ts} +3 -11
  30. package/dist/sidebar-state.d.ts +1 -1
  31. package/dist/sidebar-state.js +1 -1
  32. package/dist/{token-511npvw8.js → token-3vtr29vt.js} +1 -1
  33. package/dist/token-util-erhrf24m.js +1 -0
  34. package/dist/tui-preferences.d.ts +0 -2
  35. package/dist/tui-preferences.js +1 -1
  36. package/dist/tui.d.ts +3 -7
  37. package/dist/v2/server.d.ts +15 -23
  38. package/dist/v2/server.js +2 -2
  39. package/package.json +6 -6
  40. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +95 -11
  41. package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +320 -35
  42. package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +187 -12
  43. package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +988 -0
  44. package/src/tui-compiled/raw/shared/458b934e92490331-mutate.js +4 -0
  45. package/src/tui-compiled/raw/shared/81dddd203f1b92a3-quota-writer.js +34 -12
  46. package/src/tui-compiled/raw/shared/836fc615de6afbd9-settings.js +16 -6
  47. package/src/tui-compiled/raw/shared/88b7fc40900fb003-commit-interval.js +18 -0
  48. package/src/tui-compiled/raw/shared/92e38944b51b2405-file-read-cache.js +57 -0
  49. package/src/tui-compiled/raw/shared/a670cb7f5987bc1b-shutdown.js +42 -0
  50. package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +37 -12
  51. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +1 -1
  52. package/src/tui-compiled/raw/shared/c911dbb64c9d85c7-quota-writer.js +27 -13
  53. package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +42 -0
  54. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +20 -11
  55. package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +37 -4
  56. package/src/tui-compiled/raw/sidebar-state.js +4 -2
  57. package/src/tui-compiled/raw/tui.tsx +7 -1
  58. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +95 -11
  59. package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +320 -35
  60. package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +187 -12
  61. package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +988 -0
  62. package/src/tui-compiled/runtime/shared/458b934e92490331-mutate.js +4 -0
  63. package/src/tui-compiled/runtime/shared/81dddd203f1b92a3-quota-writer.js +34 -12
  64. package/src/tui-compiled/runtime/shared/836fc615de6afbd9-settings.js +16 -6
  65. package/src/tui-compiled/runtime/shared/88b7fc40900fb003-commit-interval.js +18 -0
  66. package/src/tui-compiled/runtime/shared/92e38944b51b2405-file-read-cache.js +57 -0
  67. package/src/tui-compiled/runtime/shared/a670cb7f5987bc1b-shutdown.js +42 -0
  68. package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +37 -12
  69. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +1 -1
  70. package/src/tui-compiled/runtime/shared/c911dbb64c9d85c7-quota-writer.js +27 -13
  71. package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +42 -0
  72. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +20 -11
  73. package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +37 -4
  74. package/src/tui-compiled/runtime/sidebar-state.js +4 -2
  75. package/src/tui-compiled/runtime/tui.js +4 -1
  76. package/dist/index-0p3cbtwq.js +0 -2
  77. package/dist/index-2e2kqmsy.js +0 -2
  78. package/dist/index-apkavdvq.js +0 -90
  79. package/dist/index-qg2syg0r.js +0 -65
  80. package/dist/index-se9ykks8.js +0 -69
  81. package/dist/token-util-jsw1zdc6.js +0 -1
package/dist/v2/server.js CHANGED
@@ -1,3 +1,3 @@
1
- import{c as eZ}from"../index-p9vnmnzr.js";import{A as u2,B as C$,C as E$,D as iZ,E as aZ,F as O1,G as nZ,H as oZ,I as H$,J as EZ,K as OZ,L as rZ,M as sZ,N as u$,O as p$,P as v2,Q as U$,T as JZ,U as zZ,V as GZ,ba as BZ,ca as VZ,d as q$,e as mZ,f as YZ,g as n2,ga as tZ,h as C2,i as l2,j as cZ,k as dZ,l as d2,m as P2,ma as v1,na as h1,o as f1,p as I1,q as w1,qa as $0,r as y2,s as b$,t as D$,u as k$,v as g$,w as K1,x as l$,y as e$,z as $Z}from"../index-qg2syg0r.js";import{Aa as Z$,Ba as J$,Sa as a$,Za as g2,hb as i2,ib as IZ,jb as vZ,kb as hZ,mb as gZ,nb as n$,wb as lZ,xa as fZ,xb as uZ,yb as pZ,zb as o$}from"../index-se9ykks8.js";import{Pb as PZ,cc as TZ,dc as _Z,fc as MZ,jc as CZ}from"../index-2e2kqmsy.js";import{Id as W2,Nd as e1,Pd as M$,Qd as $$,Wd as c2,Xc as h2,Yc as m2,Zc as wZ,be as jZ,ce as S2,de as z$,ed as E1,ee as G$,fd as o1,fe as X$,gd as r1,hd as s1,he as Y$,ie as Q$,ke as j$,le as B$,me as B1,ne as V$,oe as W$,pd as d$,vd as i$,xd as yZ,yd as QZ,zc as n1,zd as t1}from"../index-apkavdvq.js";import{ue as x$}from"../index-dr93b3g6.js";import{De as h$}from"../index-0p3cbtwq.js";import"../index-b5459de4.js";import{Ne as kZ,Pe as Y2}from"../index-7zy4vdd3.js";import"../index-yayz83vv.js";import{jf as m$}from"../index-r4avvxf0.js";import{nf as a2,of as DZ}from"../index-jaqm1xda.js";import{AsyncLocalStorage as z4}from"node:async_hooks";import{randomUUID as G4}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 q1($){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 b1="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=(U)=>q1({integrationID:z,methodID:U,now:J()}),Y=async(U,W)=>{return await Z.onLogin(U,{integrationID:z,methodID:W}),X(W)},F=(U)=>async(W)=>{let j=U.method.id,B=await U.authorize(W),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((U)=>{let W=Z.label===void 0?{}:{label:()=>Z.label};for(let L of Z.methods)U.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)},...W});let j=Z.vault;if(j===void 0)return;let B=j.method.id;U.method.update({integrationID:z,method:j.method,authorize:async()=>({url:"",instructions:j.instructions??b1,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)},...W})})}function z0($){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 W0}from"../index-fhcnxrtz.js";import{A as Y0,B as C$,C as wZ,D as yZ,E as B0,F as t$,G as e$,H as u2,I as E$,L as UZ,M as HZ,N as NZ,V as TZ,W as _Z,_ as V0,d as oZ,e as KZ,ea as i1,f as e2,fa as n1,g as O2,h as a2,i as r2,ia as U0,k as d1,l as a1,m as p1,n as m2,o as r$,p as E1,q as s$,r as BZ,s as VZ,t as i2,u as D$,v as w$,w as J0,x as z0,y as k1,z as G0}from"../index-vh1sr50d.js";import{$a as s2,Bb as T2,Cb as m$,Db as g$,Eb as _1,Fb as l$,Gb as u$,Ib as Q0,Jb as X0,Ka as zZ,Kb as j0,Ra as d2,ab as aZ,bb as iZ,cb as nZ,db as sZ,eb as h$,gb as tZ,hb as GZ,pa as dZ,qb as eZ,rb as $0,sa as W$,sb as Z0,ta as U$,tb as YZ}from"../index-97cz7kyq.js";import{Ub as qZ,hc as SZ,ic as bZ,kc as kZ,oc as DZ}from"../index-4rf3rkdm.js";import{Dd as JZ,Ec as G$,Fd as cZ,Gd as LZ,Hd as j$,Qd as E2,Rd as f2,Wd as B$,Yd as k$,Zd as V$,dd as p2,de as o2,ed as c2,fd as pZ,ke as PZ,le as b2,md as b1,me as H$,nd as Y$,ne as N$,od as Q$,oe as F$,pd as X$,qe as K$,re as L$,te as P$,ue as T$,ve as F1,we as _$,xd as ZZ,xe as M$}from"../index-b7p76qqa.js";import"../index-73z9ftrg.js";import{Ne as n$,Oe as rZ}from"../index-ww8w9edq.js";import"../index-21yxzeet.js";import{$e as W2,Ze as uZ}from"../index-h1r8cbet.js";import"../index-mg4w434p.js";import{wf as o$}from"../index-c50p5mem.js";import{Af as t2,Bf as lZ}from"../index-hpnj460b.js";import{AsyncLocalStorage as W4}from"node:async_hooks";import{randomUUID as U4}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 V2($){return`common-auth-placeholder.${$}`}function h1($){let Z=V2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function x2($,Z){if($?.type!=="oauth")return!1;let J=Z===void 0?void 0:V2(Z),z=(Q)=>J===void 0?Q.startsWith("common-auth-placeholder."):Q===J;return z($.access)&&z($.refresh)}var m1="No browser sign-in: this connects the plugin to the accounts in its vault.";async function Y1($,Z){let J=Z.now??Date.now,{integrationID:z}=Z,Q=(H)=>h1({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(!x2(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??m1,mode:"auto",callback:Promise.resolve().then(()=>j.activate({integrationID:z,methodID:B})).then(()=>Q(B))}),refresh:async(L)=>{if(!x2(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 K0($){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 U=z0(F);if(!U)return;try{$(U)}catch(W){Z(W)}},Y=()=>{for(;;){let F=/\r?\n\r?\n/.exec(z);if(!F)return;let U=z.slice(0,F.index);z=z.slice(F.index+F[0].length),X(U)}};return new TransformStream({transform(F,U){U.enqueue(F),z+=J.decode(F,{stream:!0}),Y()},flush(){if(z+=J.decode(),Y(),z.trim()!=="")X(z);z=""}})}var D1=512,M2="x-common-auth-attempt",L2=($,Z)=>JSON.stringify([$,Z]),B2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function G0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function X0($,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 Y0($,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,U=Math.max(1,J.maxRecords??D1),W=[...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,l=!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 H=(V.get(G)??Promise.resolve()).then(Q),N=H.then(()=>{},()=>{});return V.set(G,N),N.then(()=>{if(V.get(G)===N)V.delete(G)}),H},E=(G,Q)=>{let H=V.get(G);return H?H.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 H=Q.next;P(Q.sessionID,()=>K(H))}},_=async(G,Q)=>{let H=R.get(G);if(!H||H.size===0)return;await Promise.all([...H].map(async(N)=>{try{await N(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(H){h("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:G.attemptId,error:v(H)})}},y=(G,Q)=>{if(G.ended||!G.attempt)return;let H={...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,H)},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>U){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}}),u=(G)=>{w.get(G)?.clear(),w.delete(G)},f=async(G,Q)=>{let H=()=>s(G,`${z} ${G.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(z2)throw H();let N=w.get(G.sessionID);if(!N)N=new Set,w.set(G.sessionID,N);let x={};N.add(x);let q=()=>{if(!N.has(x))throw H()};try{return await Q(q)}finally{if(N.delete(x),N.size===0&&w.get(G.sessionID)===N)w.delete(G.sessionID)}},I=(G,Q)=>{for(let[H,N]of Q)if(W.some((x)=>N.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 ${H}; 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,H,N)=>{let x=L2(G.sessionID,G.kind),{input:q,accountId:O}=await E(G.sessionID,async()=>{H();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)),H();let k2=E2?t.accountId:await Z.chooseAccount(N2);return{input:N2,accountId:k2}});H();let D={},i;if(O!==void 0){let o=await Z.accountHeaders({...G,accountId:O});if(H(),G0(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:N,data:i},...N===void 0?{}:{transport:N},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,H,N,x)=>{let q=L2(G.sessionID,G.kind),O=N===void 0?void 0:j.get(N);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,H);else if(O.transport=H,O.attempt)O.attempt.transport=H;if(H==="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},H2=async(G,Q)=>{try{return await Q()}catch(H){throw y(G,{reason:"failed",message:v(H)}),H}},T2=(G,Q)=>{let H=m(L2(G,Q)).filter((N)=>N.transport==="ws").at(-1);return H?.attempt!==void 0&&!H.ended?H:void 0},F2=(G,Q,H)=>{let N=c(G);if(!N||!G.attempt||G.limit)return;G.limit={signal:Q,delivered:_("limit",{...N,via:H,limit:Q,outputStarted:G.outputStarted,handle:G.attempt})}},M=(G,Q,H,N)=>{let x=c(G);if(!x||!G.attempt)return;_("quota",{...x,transport:Q,...N===void 0?{}:{status:N},quota:H,handle:G.attempt})},d=(G,Q,H,N)=>{let x=G.attempt;if(!x)return;let q=Z.inspectEvent?.(N===void 0?{transport:Q,data:H,attempt:x}:{transport:Q,data:H,event:N,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 H=G.attempt;if(!H||Q.accountId===G.accountId)return;if(H.reboundFrom??=H.accountId,H.accountId=Q.accountId,"data"in Q)H.data=Q.data;G.accountId=Q.accountId},Z0=(G)=>!G.attempt||G.endError!==void 0||G.status!==void 0&&G.status>=400,J0=(G)=>{let Q=[...j.values()].filter((D)=>D.scope.sessionID===G),H=Q.filter((D)=>D.limit&&!D.rerouted).at(-1);if(H)return H;let N=Q.filter((D)=>D.scope.kind==="primary"),x=N.length>0?N:Q;if(x.length<=1)return x[0];let q=x.filter((D)=>!D.judged&&Z0(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},U2=[];U2.push(await $.session.hook("model.request",(G)=>{if(X)return;return f(B2(G),async(Q)=>{let H=await p(B2(G),"model.request",Q);if(Q(),H.accountId===void 0)throw s(H.scope);$1(G.headers,{...H.headers,[M2]:H.id})})},K2)),U2.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(B2(G),async(Q)=>{let H=G.request.headers.get(M2)??void 0,N=X?await p(B2(G),"http.request",Q,"http"):await n(B2(G),"http.request","http",H,Q);Q();let x=c(N),q=N.attempt;if(!x||!q)throw s(N.scope);await H2(N,async()=>{let O=G.request;if(Z.rewriteRequest){if(H!==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),Y0(D,N.headers),I(N.scope,D.entries());let i=new Request(O,{headers:D});B.set(i,N),G.request=i})})},K2)),U2.push(await $.session.hook("http.response",async(G)=>{let Q=B.get(G.request);if(!Q){if(X)return;if(!l)l=!0,h("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:G.sessionID,kind:G.kind});return}let H=G.response;if(Z.answeredBy&&Q.attempt){let D=Q.attempt,i=await H2(Q,async()=>Z.answeredBy?.({request:G.request,response:H,attempt:D}));if(i)Q2(Q,i)}let N=c(Q),x=Q.attempt;if(!N||!x)return;Q.status=H.status;let q=Z.quotaFromHeaders?.(H.headers,H.status,x);if(q!==void 0)M(Q,"http",q,H.status);if(!H.ok&&Z.limitFromResponse){let D=await Z.limitFromResponse({status:H.status,headers:H.headers,body:()=>H.clone().text(),attempt:x});if(D)F2(Q,D,"http")}if(!H.ok||!H.body)y(Q);let O=H;if(H.body&&(Z.inspectEvent||Z.onAttemptEnd)){let D=H.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(X0(D,(i)=>y(Q,i)),{status:H.status,statusText:H.statusText,headers:H.headers})}if(Z.rewriteResponse)O=await Z.rewriteResponse({...N,request:G.request,response:O,attempt:x})??O;if(O!==H)G.response=O},K2)),U2.push(await $.session.hook("experimental.ws.handshake",(G)=>{if(X){let Q=Y(new Headers(G.headers)),H=L2(G.sessionID,G.kind);if(T.set(G.sessionID,Q),S.delete(H),!Q)return}return f(B2(G),async(Q)=>{let H;for(let O of Object.keys(G.headers)){if(O.toLowerCase()!==M2)continue;H??=G.headers[O],delete G.headers[O]}let N=X?await p(B2(G),"experimental.ws.handshake",Q,"ws"):await n(B2(G),"experimental.ws.handshake","ws",H,Q);Q();let x=c(N),q=N.attempt;if(!x||!q)throw s(N.scope);await H2(N,async()=>{$1(G.headers,N.headers);let O=Z.rewriteHandshakeURL?.({...x,url:G.url,attempt:q});if(O!==void 0)G.url=O;if(I(N.scope,Object.entries(G.headers)),X)S.add(N.key)})})},K2));let R1=Z.rewriteWebSocketFrame?.bind(Z);if(R1)U2.push(await $.session.hook("experimental.ws.send",async(G)=>{let Q=B2(G);if(X&&!S.has(L2(Q.sessionID,Q.kind)))return;let H=T2(Q.sessionID,Q.kind),N=await R1({...Q,attempt:H?.attempt,frame:G.frame});if(N!==void 0)G.frame=N},K2));U2.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(H){h("opencode2 auth frame inspection threw",{error:v(H)})}},K2)),U2.push(await $.session.hook("retry",async(G)=>{if(X&&T.get(G.sessionID)!==!0)return;let Q=J0(G.sessionID);if(!Q)return;let H=G.decision;if(Q==="ambiguous"){await _("retry",{sessionID:G.sessionID,attempt:G.attempt,reason:"host-decides",hostDecision:H,decision:H});return}let N=Q;await f(N.scope,async(x)=>{let q=x;N.judged=!0;let O=N.attempt;if(O&&!N.outputStarted){if(!N.limit){let G2=Z.limitFromError?.(G.error,O);if(G2)F2(N,G2,"error")}if(N.ended)await N.ended;if(N.limit)await N.limit.delivered}q();let{decision:D,reason:i}=await P(N.scope.sessionID,async()=>{q();let G2=L.get(N.key);if(L.delete(N.key),G2?.next)await K(G2.next);q();let Z2=H,o,_2,t;if(N.accountId===void 0||!O)Z2={retry:!1},o="no-account";else if(N.outputStarted)Z2={retry:!1},o="output-started";else if(N.limit){let E2={accountId:N.accountId,limit:N.limit.signal},N2,k2={...N.scope,phase:"retry",previousAccountId:N.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:N.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!==N.accountId)N.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&&N.accountId!==void 0&&j.has(N.id))L.set(N.key,{attemptId:N.id,sessionID:N.scope.sessionID,accountId:N.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,...N.accountId===void 0?{}:{accountId:N.accountId},kind:N.scope.kind,attempt:G.attempt,reason:i,hostDecision:H,decision:D,...O===void 0?{}:{handle:O}})})},K2));let S1=(G)=>{u(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,H]of L)if(H.sessionID===G)A(Q)},r2=new AbortController,x1=$.event;if(x1)(async()=>{try{for await(let G of x1.subscribe({signal:r2.signal}))if(G.type==="session.deleted")S1(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 H=R.get(G);if(!H)H=new Set,R.set(G,H);let N=Q;return H.add(N),()=>{H.delete(N)}},accountFor(G,Q){return g(L2(G,Q))?.accountId},forgetSession:S1,get size(){return j.size},async dispose(){if(z2)return;z2=!0;for(let G of w.keys())u(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(U2.map(async(G)=>{try{await G.dispose()}catch(Q){h("opencode2 auth hook did not dispose cleanly",{error:v(Q)})}}))}}}import{createHash as Q0}from"node:crypto";var j0=1024,B0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),k1=($)=>w1($,"user"),V0=($)=>B0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function W0($){return Q0("sha256").update(JSON.stringify($)).digest("hex")}class A2{runtime;maxSessions;#$=new Map;constructor($,Z=j0){this.runtime=$;this.maxSessions=Z}advance($,Z,J=this.runtime){let z=this.#$.get($),X=Array.isArray(Z.input)?Z.input:[],Y=X.filter(k1),F=X.findLastIndex(k1),U=F<0?void 0:W0(X[F]),W=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,j,B,L;if(W)j=Y.length>0,B=U??z?.fingerprint,L=z?.userCount===void 0?void 0:z.userCount+Y.length;else{B=U,L=Y.length;let T=F>=0&&F>X.findLastIndex(V0),l=z!==void 0&&!z.completed&&z.fingerprint===B&&z.userCount===L;j=T&&!l}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 y1=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function H0(){let $=globalThis;return $[y1]??=crypto.randomUUID(),$[y1]}class R2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,J){this.runtime=$;this.store=J;this.installationID=Z??H0(),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:f1,"user-agent":I1,originator:"codex_exec"};var U0=1024,N0=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,f2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),m1=($)=>f2($)&&($.type==="message"||("role"in $))&&$.role==="user",g1=($)=>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(!v1.has(z))return!1;if(N0.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 U=Array.isArray($.input)?$.input:void 0;if(!U||U.length===0)return!1;let W=U.findLastIndex(m1);if(W<0){if(J==="http")return!1;return $.reasoning={...X,effort:F},!0}if($.reasoning={...X,effort:F},!g1(U[W-1]))U.splice(W,0,{type:"configuration_update",reasoning:{effort:Y}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>U0){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 l1($,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 U=new Headers($.headers),W=y2({rewriteLite:h1,init:{body:F?JSON.stringify(F):$.body===null?void 0:Y},headers:U,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:U,body:W.init?.body})}function u1($,Z,J,z){let X=z.sessions.get($.sessionID),Y=z.frameTurns.get($.sessionID);if(!X||!Y)return;let F=J1(X,Y),U=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)U.set(j,B)}y2({init:{body:$.bodyText},headers:U,metadata:F,installationID:z.installationID,runtime:z.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let W=new URL(Z);if(W.protocol==="wss:")W.protocol="https:";if(W.protocol==="ws:")W.protocol="http:";return new Request(W,{method:"POST",headers:U,body:$.bodyText})}function F0($,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&&g1(Z[J])&&m1(Z[J+1])&&JSON.stringify(Z.slice(J+1))===JSON.stringify($.slice(J))}function p1($,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:(W)=>{J.apply(W,Z,"ws")}}),U=w2(String(F.init?.body));if(!U)return;if(!F0(z.input,U.input)){if("input"in z)U.input=z.input;else delete U.input;return JSON.stringify(U)}return String(F.init?.body)}function K0($){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(`${K0(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 c1}from"node:path";var L0=1024;class I2{accounts=new Map;limit;constructor($=L0){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 d1=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),i1=globalThis,Y1=i1[d1]??new Map;i1[d1]=Y1;function Q1($){let Z=JSON.stringify([c1($.configPath),c1($.statePath)]),J=Y1.get(Z);if(!J)J=new I2,Y1.set(Z,J);return J}var X2="openai",P0=60000,j1=1,T0="request refused: no account with a usable credential",V2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function _0($){let Z=V2($)?$.counters:void 0,J=V2(Z)?Z.resetCredits:void 0,z=V2(J)?J.value:void 0;return typeof z==="number"&&Number.isFinite(z)?z:void 0}function V1($){try{return JSON.parse($)}catch{return}}function a1($){let Z=h2($);return Z?m2(Z):void 0}var M0=new Set(["usage_limit_reached","rate_limit_exceeded"]);function W1($,Z,J){return{reason:$.window,...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function C0($,Z){let J=v2($);if(J){let Y=typeof $.status==="number"?$.status:void 0;return W1(J,Z,Y)}if($.type!=="response.failed"||!V2($.response))return;let z=$.response.failed;if(V2(z)&&typeof z.rate_limit_reached_type==="string")return{reason:z.rate_limit_reached_type};let X=$.response.error;if(V2(X)){let Y=typeof X.code==="string"?X.code:typeof X.type==="string"?X.type:void 0;if(Y&&M0.has(Y))return{reason:Y}}return}function E0($,Z){let J=V1($);if(!V2(J))return;let z=typeof J.type==="string"?J.type:void 0;if(z==="codex.rate_limits")return{quota:{snapshot:s1(J),complete:!0}};let X=C0(J,Z);if(X)return{limit:X};if(z===void 0||z==="error")return;return U$(z)?void 0:{outputStarted:!0}}function O0($){let Z=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:o1($),complete:r1($)}}function A0($){let Z=$.get("retry-after");if(Z===null)return;let J=Number(Z);return Number.isFinite(J)&&J>=0?J*1000:void 0}function N$($){let{source:Z,pins:J}=$,z=$.now??Date.now,X=$.log,Y=$.vault,F=new G1($.codex),U=new Map,W=new Map,j=(V)=>`${V.sessionID}\x00${V.kind}\x00${V.accountId}`,B=new Map,L=$.sessionAccounts??new I2,S=new j$,T=(V,P,E)=>{let K=E?[]:H$(Z.peek().rows,V,P,Y?.identities()??new Set),A=(Y?.routes()??[]).filter((_)=>_.kind==="oauth"&&e1(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}))]},l=(V,P,E)=>{let K=X$(V,P,E),A=V.map((b)=>({id:b.id,kind:"oauth",...n1(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 _=B$({...V,placement:Y$(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((u)=>[u.id,u.quota])),b={requestBytes:j1,reservePercent:(u)=>$$(E,u===z$?void 0:u),resetCredits:(u)=>_0(y.get(u))},m=B1(V),g=(u,f)=>g2(C,{sessionId:K,requestBytes:j1,validPinnedAccountIds:V.rows.map((I)=>I.id).filter((I)=>!m.excluded.has(I)),excludeAccountIds:u,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(u),I),persist:f},(I,$2)=>C.set(I,$2)),r=[...A],e=g(r,_);if(!e)return;let c=e.accountId,s=W$(V,b,c);if(s.kind==="none")return;if(s.kind==="move"){let u=g([...r,c],_);if(u)return u.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);W.get(P)?.drop(),W.delete(P),U.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=Q$(l(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=l(C,E,_),g=new Set(V.rerouteFrom?[V.rerouteFrom.accountId]:[]),r=E?.routing?.mode??"main-first",e=V.kind==="primary",c=new Set,s,u,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:G$(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=B1(m).projections.get(f)?.checkedAt,n=b.get(f)?.identity;u=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){U.set(j({...V,accountId:f}),p);break}X?.debug("the vault refused to serve an account; choosing again",{accountId:f})}if(u)J.rollback(u);u=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":J$(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:Z$(I,Y.name)})}if(f!==void 0){let I=f,$2=u,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")W.set(j({...V,accountId:f}),{commit:n,drop:()=>{if($2)J.rollback($2)}}),u=void 0;else n();let H2=X?.info;S.served(m,f,X&&H2?{info:(T2,F2)=>H2.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(u)J.rollback(u)}},accountHeaders:async(V)=>{let{accountId:P}=V,E=j(V),K=W.get(E);W.delete(E);let A=()=>{K?.commit()};try{let _=()=>new J2({kind:"no-account",providerID:X2,sessionID:V.sessionID,requestKind:V.kind,message:T0}),C=Y&&await Y.authority()!=="local"?void 0:Z.peek().rows.find((m)=>m.id===P);if(!C&&Y){let m=j(V),g=U.get(m)??await Y.authorize(P);if(U.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??a1(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??a1(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 l1(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})=>p1(V,{sessionID:P,kind:E},F),quotaFromHeaders:(V)=>O0(V),async limitFromResponse({status:V,headers:P,body:E}){if(V<400)return;let K=V1(await E().catch(()=>"")),A=v2({...V2(K)?K:{},status:V});if(!A)return;let _=z(),C=W1(A,_,V);if(C.retryAfterMs!==void 0)return C;let y=A0(P);return y===void 0?C:{...C,retryAfterMs:y}},inspectEvent:({data:V})=>E0(V,z()),limitFromError(V){let P=V1(V.message),E=v2({...V2(P)?P:{},...V.status!==void 0?{status:V.status}:{}})??(V.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return E?W1(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=t1(S2(_),P.reason,K,P0,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 _$}from"node:path";import{Buffer as R0}from"node:buffer";import{resolve as F$}from"node:path";function x2($){return R0.byteLength(JSON.stringify($))}function S0($){return $.reduce((Z,J)=>Z+x2(J),0)}function H1($,Z){return 2+$+Math.max(0,Z-1)}function x0($){let{head:Z,pending:J}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+H1(Z.inputBytes,Z.input.length)+1:0)+(J?20+H1(J.inputBytes,J.input.length)+10+H1(J.outputBytes,J.output.length)+(J.responseID===void 0?0:14+J.responseIDBytes)+1:0)}function K$($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class L${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=K$(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:U,input:W,...j}=J;this.keep($,{fields:z&&X?X.fields:j,fieldsBytes:z&&X?X.fieldsBytes:x2(j),...z&&Y?{head:Y}:{},pending:{input:W,inputBytes:S0(W),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=K$(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 U={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},W={...z,head:U,pending:void 0};if(!this.keep($,W))return;J?.({sessionID:$,responseID:U.responseID,bodyText:this.body(z.fields,U)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let J=x0(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 P$=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),T$=globalThis,U1=T$[P$]??new Map;T$[P$]=U1;function p2($){let Z=JSON.stringify([F$($.configPath),F$($.statePath)]),J=U1.get(Z);if(!J)J=new L$,U1.set(Z,J);return J}var q0=5000,b0=["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"],D0=["x-opencode-parent-session-id","x-parent-session-id"];function O$($){let Z=M$($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:C$($?{...$,cachekeep:Z}:$)}}var A$=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),R$=globalThis,q2=R$[A$]??new Map;R$[A$]=q2;function k0($,Z){let J=[],z=()=>J.at(-1)?.location,X=()=>{let W=z();if(!W)throw Error("no location holds keep-warm");return W},Y=(W,j)=>{U.remove(W),z()?.log?.debug(`cachekeep dropped target (${j})`,{sessionKey:W})},F=async(W)=>{if(W.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let j=W.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}},U=E$({...u2,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(W,j)=>X().fetch(W,j),logger:{debug:(W,j)=>z()?.log?.debug(W,j),warn:(W,j)=>z()?.log?.warn(W,j)},getWindow:()=>z()?.settings().window,getSustain:()=>z()?.settings().sustain===!0,resolveLocal:F,vault:{owns:(W)=>z()?.vault.owns(W)===!0,authority:()=>X().vault.authority(),send:async(W,j,B)=>{let L=X();if(await L.vault.authority()!=="vault")return;return L.vault.send(W,j,B)}},activeAccount:(W)=>{if(W===void 0)throw Error("target has no session");let j=z(),B=j?.settings();if(!j||!B?.enabled){Y(W,"keep-warm is off");return}if(!B.subagents&&U.status().targets.some((S)=>S.sessionKey===W&&S.isSubagent)){Y(W,"subagent warming is off");return}let L=j.accounts.activeAccount(W);if(L===void 0){Y(W,"no account recorded for the session");return}return L},verifyCredential:({target:W,mode:j,identity:B})=>{if(W.meta.credentialMode!==j)throw Error(`a target captured in ${W.meta.credentialMode??"an unknown"} mode is not warmed with a ${j} credential`);if(B!==W.meta.chatgptAccountId)throw Y(W.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:U,settings:Z,holders:J,joinTimeoutMs:$.joinTimeoutMs??q0}}function w0($){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 y0($){let Z={};for(let J of b0){let z=$.get(J);if(z)Z[J]=z}return Z}function S$($,Z,J){let z=JSON.stringify([_$($.configPath),_$($.statePath)]),X=q2.get(z);if(!X)X=k0(J,Z.settings()),q2.set(z,X);let Y=X,F=p2($);F.setEnabled(Y.settings.enabled);let U={location:{...Z,settings:()=>Y.settings}};Y.holders.push(U);let W=!1,j=async(B)=>{try{let L=U.location.settings();if(W||!L.enabled)return;if(B.kind!=="primary"){if(B.kind==="generate"&&w0(await B.request.clone().text())){if(W)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 l=B.request.headers,a=D0.some((z2)=>l.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(W)return;let k=l.get("chatgpt-account-id")??void 0;Y.manager.track({sessionKey:B.sessionID,bodyText:R,accountId:B.attempt.accountId,isSubagent:a,meta:{replayHeaders:y0(l),...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(W)return;W=!0;let B=Y.holders.indexOf(U);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 f0}from"node:fs";import{dirname as I0,join as v0,resolve as h0}from"node:path";var m0="openai-auth-sessions-opencode2.json";function g0(){return v0(q$(),m0)}var l0="sessions",u0=1e4,p0=5000,c0=25;class w${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=D$($,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(f0(I0(this.path),{recursive:!0}),J=await this.#X(),!J)return;let z;try{z=b$(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);k$(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??p0);for(;;){let Z=await x$({name:l0,path:this.path,ttlMs:u0});if(Z||performance.now()>=$)return Z;await new Promise((J)=>setTimeout(J,c0))}}}var y$=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),f$=globalThis,N1=f$[y$]??new Map;f$[y$]=N1;function I$($=g0()){let Z=h0($),J=N1.get(Z);if(!J)J=new w$(Z),N1.set(Z,J);return J}var v$=Symbol.for("cortexkit.openai-auth.v2.commands"),d0=Y2("v2-command");function F1($){d0.warn(`/openai needs the terminal UI (session state: ${$}).`)}function i0(){let $=globalThis;return $[v$]??={locations:new Map},$[v$]}async function c$($,Z){let J=i0(),z=$.location.directory,X={menu:Z,session:$.session,closed:new AbortController},Y=await m$(z),F=await h$(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)}})),U=J.locations.get(z);J.locations.set(z,X),U?.closed.abort(),await U?.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");let l=await g$(B.sessionID,T.closed.signal);if(!l||J.locations.get(S.location.directory)!==T){if(!l&&!T.closed.signal.aborted)K1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},B.sessionID);return F1(T.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let a=await T.menu.open(B.sessionID);K1(a,B.sessionID)}};let W=J.command;try{X.registration=await $.command.transform((B)=>{B.add(W)})}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 a0="openai-auth-pool-browser",n0="openai-auth-pool-headless",o0="openai-auth-vault",r0="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:o0,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await d$($.paths,$.name)!=="vault")throw Error(r0)}}}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(a0,"ChatGPT (openai-auth pool, browser)",!1),Z(n0,"ChatGPT (openai-auth pool, headless)",!0)]}function L1($){let Z=(J)=>typeof J==="string"?J:"";return O2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===n$||i$($)}function s0($){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(L1(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}:{}},U=s0(J);if(z.vault)await b2(z.vault);let W=U!==void 0?{identity:U}:{};if(z.origin==="import"){let T=Y.rows.find((l)=>U!==void 0&&l.identity===U||l.credential?.type==="oauth"&&l.credential.refresh===J.refresh);if(T)return{id:T.id,operation:"kept"}}let j=Y.rows.filter((T)=>T.type==="oauth"&&!T.invalid),B=U?j.find((T)=>T.identity===U):void 0,L=Y.rows.find((T)=>T.id===c2);if(B)return{id:(await X.replace(B.id,F,W)).id,operation:"replaced"};if(!L){let T=await X.add({id:c2,credential:F,...W,...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,W)).id,operation:"replaced"};let S=await X.add({id:J.id,credential:F,...W,...J.label!==void 0?{label:J.label}:{}});return{id:S.id,operation:S.outcome==="added-disabled"?"added-disabled":S.outcome==="rotated"?"replaced":"added"}}function t0($){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:t0,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 e0($,Z){if(!JZ($.modelID??$.id)){$.enabled=!1;return}let J=zZ($.id);if(J)$.limit={...J};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((z)=>[z.id,z])).values()]}function XZ($){return $.model.transform((Z)=>{let J=Z.list(X2);for(let z of J){let X=GZ(String(z.id)),Y=X?J.find((F)=>String(F.id)===X):void 0;Z.update(X2,String(z.id),(F)=>e0(F,Y?.variants?.map((U)=>({...U,id:String(U.id)}))))}})}class P1{log;pending=new Map;requests=new Map;writing=new Set;constructor($){this.log=$}async safely($){let Z=(async()=>{try{await $()}catch{this.log.warn("request dump failed")}})();this.writing.add(Z);try{await Z}finally{this.writing.delete(Z)}}async captureHttp($,Z){if(!YZ())return;await this.safely(async()=>{let J={sessionID:Z.sessionID,accountId:Z.accountId,transport:"http",phase:"http",url:$.url,method:$.method,headers:new Headers($.headers),bodyText:await $.clone().text()};if(this.pending.set($,{attemptId:Z.attemptId,input:J}),this.requests.set(Z.attemptId,$),this.pending.size>512){let 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 T1{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 WZ($){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 QZ({accessToken:J.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,z),jZ(z,$.now(),!0)}}function HZ($){let{source:Z,counts:J,now:z}=$,X=async(j)=>{let B=await Z.rowAccess(j,await $.storage());if(!B?.row)throw new BZ("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),U=(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((l)=>typeof l==="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:()=>U("main"),getFallback:(j)=>U(j)}}}import{resolve as UZ}from"node:path";var $4=1024;class _1{pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=$4){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 NZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),FZ=globalThis,M1=FZ[NZ]??new Map;FZ[NZ]=M1;function KZ($){let Z=JSON.stringify([UZ($.configPath),UZ($.statePath)]),J=M1.get(Z);if(!J)J=new _1,M1.set(Z,J);return J}import{statSync as Z4}from"node:fs";import{resolve as J4}from"node:path";function AZ($){return $.map((Z)=>{try{let J=Z4(Z);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}function C1($){return AZ([$.vault.paths.tokenPath,$.vault.paths.statePath])}function LZ($){return AZ([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+C1($)}class RZ{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:LZ($),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:LZ(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=C1($),Y=()=>this.producers.has($)&&$.vault.enrolled()===z&&C1($)===X,F=await W2($.paths),U=z?EZ($.vault.snapshot()?.rows??[],new Set($.vault.routes().map((j)=>j.id)),F,Date.now()):OZ((await $.source.sidebarView()).rows,F,Date.now());if(await TZ(U,this.file,{canWrite:Y}),!Y()||!Z)return;let W=U.vaultAccounts??U.fallbacks;if(Z.accountId===void 0){await MZ(Z.sessionId,W,this.file,{canWrite:Y});return}if(Z.pin){let j=Date.now();await CZ({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"],...W.filter((B)=>B.enabled).map((B)=>B.id)]},this.file)}await _Z({sessionId:Z.sessionId,activeId:Z.accountId,route:Z.route??U.route,updatedAt:Date.now()},W,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 SZ=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),xZ=globalThis,D2=xZ[SZ]??new Map;xZ[SZ]=D2;function qZ($,Z=PZ(),J=2000){let z=J4(Z),X=D2.get(z);if(!X)X=new RZ(z,J),D2.set(z,X);let Y=X,F=Y.add($),U=!1;for(let[W,j]of $.pins.snapshot())Y.publish($,{sessionId:W,pin:j,accountId:j.accountId,route:"sticky-balanced"});return{publish:()=>Y.publish($),route:(W,j,B)=>{Y.publish($,{sessionId:W,accountId:j,route:B})},async release(){if(U)return;if(U=!0,F(),await Y.settled(),Y.empty&&D2.get(z)===Y)D2.delete(z)}}}var o2="cortexkit-openai-auth",X4=5000;async function bZ($,Z,J,z=new R2,X,Y,F){let U=new P1(J),W=new z4,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)},l=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 W.run(E,()=>k(w))}catch(K){if(P&&!(K instanceof J2))throw IZ(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 U.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 U.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=u1(_,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=vZ(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=W.getStore();if(k)k.attempt=R.attempt;return Z.rewriteRequest?.(R)},rewriteHandshakeURL:(R)=>{let k=W.getStore();if(k)k.attempt=R.attempt;return Z.rewriteHandshakeURL?.(R)},onAttemptEnd:async(R,k)=>{await U.end(R,k),await Z.onAttemptEnd?.(R,k)},rewriteResponse:async(R)=>{await U.response(R.request,R.response.status);let k=await Z.rewriteResponse?.(R)??R.response;return hZ(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=l.dispose;return{...l,dispose:async()=>{B.clear(),j.clear(),await a(),await U.settle(),U.clear()}}}function A1($={}){return{id:o2,setup:(Z)=>Y4(Z,$)}}async function Y4($,Z={}){let n=[];try{let J=Y2("opencode2");let z=Y2("quota");let X=Z.paths??(()=>gZ(mZ()));let Y=await W2(X());let F=Y?.logging?.level;if(F&&typeof F==="string")kZ(F);let U=Z.fetch??fetch;let W=Z.now??Date.now;let j=Z.version??dZ;let B=Z.poolMigration??tZ;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 bZ($,{providerID:X2,chooseAccount:M,accountHeaders:M},J);return()=>d.dispose()}let L=Z.vault?.firstRosterWaitMs??aZ;let S=sZ({host:"opencode",stateDir:Z.vault?.stateDir??fZ(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:()=>U},X());let T=S.vault;let l=!1;let a=!1;const R=a2(n,{[Symbol.dispose](){if(!l)S.release()}},0);await T.authority();let k=S.firstRoster;let z2=new T1;let w=new nZ({paths:X,refreshProvider:async(M)=>{let d=await yZ({refreshToken:M.refresh,fetchImpl:U,now:W}),Q2=wZ({id_token:"",access_token:d.access,refresh_token:d.refresh});return{...d,...Q2?{identity:Q2}:{}}},pullQuota:WZ({fetchImpl:U,now:W,counts:z2,logger:z}),now:W,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 rZ({version:j,logger:Y2("heartbeat")});let v=Z.fence??(()=>cZ({currentVersion:j}));let V=Z.slot??eZ();let P=async()=>lZ(X(),await V.get({path:{id:"openai"}}));let E=!1;let K=B?oZ({paths:X,slot:V,version:j,fence:v,runDeps:{vaultServes:()=>T.serves()},paused:async()=>await T.authority()!=="local",migrate:async(M)=>{let d=await uZ(M);if(E=d.status==="refused",!a)await w.load();return d},adopt:async(M)=>{if(a)return{status:"retry",reason:"unsettled"};if(!await O1(k,L))return{status:"retry",reason:"vault-roster-pending"};if(a)return{status:"retry",reason:"unsettled"};let d=await pZ(M);if(!a)await w.load();return d}}):void 0;K?.start();S.start();let A=KZ(X());let _=qZ({paths:X(),source:w,pins:A,vault:T},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const C=a2(n,{[Symbol.dispose](){if(!l)_.release()}},0);_.publish();let y=Z.codex??new R2(void 0,void 0,I$());let b=O$(Y);let m=p2(X());let g=S$(X(),{source:w,storage:()=>W2(X()),vault:T,accounts:Q1(X()),settings:()=>b,parentOf:async(M)=>(await $.session.get({sessionID:M}))?.parentID??void 0,fetch:U,log:Y2("cachekeep")},{now:W,codexResponsesUrl:n2().codexApiEndpoint,...Z.cacheKeep});const r=a2(n,{[Symbol.dispose](){if(!l)g.release()}},0);let e=N$({codex:y,onRoute:_.route,source:w,slotPlaceholderWithoutMain:P,storage:()=>W2(X()),pins:A,sessionAccounts:Q1(X()),vault:T,awaitVaultRoster:async()=>{await O1(T.awaitRequestRoster(),iZ)},responsesLite:()=>n2().responsesLite,codexEndpoint:()=>n2().codexApiEndpoint,now:W,log:J});let c=await bZ($,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&&!L1(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 u=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??E1,version:j,vault:T}),onLogin:(M)=>u(M),label:"ChatGPT (openai-auth account pool)",vault:r$(T)});let I=await XZ($);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({...HZ({source:w,storage:()=>W2(X()),counts:z2,now:W,authority:()=>T.authority()}),fetchImpl:U,now:W,randomUUID:G4,accountStoragePath:X().configPath,accountStatePath:X().statePath,packageVersion:j,loadAccounts:W2,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??E1,refreshAllQuota:async()=>(await w.pollRows(await W2(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)})}})();l=!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,X4),d.unref?.()})])}finally{clearTimeout(d),S.release(),await h?.release()}}}catch(H2){var T2=H2,F2=1}finally{DZ(n,T2,F2)}}var Q4=A1(),b6={id:o2,setup:Q4.setup,server:$0.server};export{b6 as default,A1 as createOpenAIAuthPlugin,o2 as OPENAI_AUTH_PLUGIN_ID};
3
+ `)}}function Q1($,Z){let J=new TextDecoder,z="",Q=(N)=>{let H=K0(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 g1=512,l1=1200000,C2="x-common-auth-attempt",P2=($,Z)=>JSON.stringify([$,Z]),G2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function L0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function P0($,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 v2($,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 T0($,Z){for(let[J,z]of Object.entries(Z))if(z===null)$.delete(J);else $.set(J,z)}async function X1($,Z,J={}){let{providerID:z}=Z,Q=J.gateOnPlaceholder,Y=(G)=>Q===void 0||Q.credential(G)===V2(z),N=J.logger,H=Math.max(1,J.maxRecords??g1),U=[...J.hostCredentials??[V2(z)],...Q?[V2(z)]:[]].filter((G)=>G!==""),j=new Map,B=new WeakMap,L=new Map,b=0,_=new Set,I=new Map,a=new Map,x=(G)=>{let X=a.get(G);return X?.ownedSeen===!0&&X.foreignSeen},w=(G,X)=>{I.set(G,X);let V=a.get(G)??{ownedSeen:!1,foreignSeen:!1};if(X)V.ownedSeen=!0;else V.foreignSeen=!0;a.set(G,V)},Q2=(G,X)=>{let V=Q?.refuseMisplaced,P=V?[...X].filter(([,D])=>D.includes(V2(z))):[],F=Y(X)&&(!V||P.length>0);if(V){if(P.length>0&&(P.length!==1||!F))throw w(G.sessionID,!1),new Z2({kind:"placement-refused",providerID:z,sessionID:G.sessionID,requestKind:G.kind,message:V(P[0]?.[0]??"")})}return w(G.sessionID,F),F},$2=!1,k=!1,g=new Map,W=0,T=!1,E=new Map,K=(G,X)=>{try{N?.warn(G,X)}catch{}},A=(G)=>G instanceof Error?G.message:String(G),C=new Map,M=(G,X)=>{let V=(C.get(G)??Promise.resolve()).then(X),P=V.then(()=>{},()=>{});return C.set(G,P),P.then(()=>{if(C.get(G)===P)C.delete(G)}),V},h=(G,X)=>{let V=C.get(G);return V?V.then(()=>h(G,X)):X()},q=async(G)=>{try{await Z.dropChoice?.({...G.input,accountId:G.accountId})}catch(X){K("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:G.input.sessionID,error:A(X)})}},m=(G)=>{let X=L.get(G);if(L.delete(G),X?.next){let V=X.next;M(X.sessionID,()=>q(V))}},l=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(F){K("opencode2 auth listener threw; the request is unaffected",{event:G,error:A(F)})}}))},u=async(G,X)=>{try{await Z.onAttemptEnd?.(G,X)}catch(V){K("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:G.attemptId,error:A(V)})}},t=(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=u(G.attempt,V)},p=(G,X)=>t(G,{reason:"abandoned",message:X}),n=(G)=>[...j.values()].filter((X)=>X.key===G),v=(G)=>n(G).at(-1),y=(G)=>{if(j.delete(G.id),L.get(G.key)?.attemptId===G.id||!n(G.key).length)m(G.key)},f=(G)=>{j.set(G.id,G);while(j.size>H){let X=j.values().next().value;if(X===void 0)break;p(X,"dropped to keep the record bound"),y(X)}},o=(G)=>G.accountId===void 0?void 0:{...G.scope,accountId:G.accountId},c=(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)},J2=async(G,X)=>{let V=()=>c(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 F={};P.add(F);let D=()=>{if(!P.has(F))throw V()};try{return await X(D)}finally{if(P.delete(F),P.size===0&&E.get(G.sessionID)===P)E.delete(G.sessionID)}},_2=(G,X)=>{for(let[V,P]of X)if(U.some((F)=>P.includes(F)))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`})},A2=(G)=>{for(let X of n(G))if(X.ended||!X.attempt)y(X);else if(X.transport==="ws"||X.judged)p(X,"a newer attempt of its session and kind began"),y(X)},M2=async(G,X,V,P)=>{let F=P2(G.sessionID,G.kind),{input:D,accountId:R}=await h(G.sessionID,async()=>{V();let r=L.get(F);L.delete(F);let j2=r?.accountId??v(F)?.accountId;A2(F);let B2=r?.next,e=B2!==void 0&&B2.input.modelID===G.modelID&&B2.input.agent===G.agent,R2={...G,phase:"request",...j2===void 0?{}:{previousAccountId:j2},...r?.rerouteFrom?{rerouteFrom:r.rerouteFrom}:{}};if(B2&&!e)await M(G.sessionID,()=>q(B2)),V();let N2=e?B2.accountId:await Z.chooseAccount(R2);return{input:R2,accountId:typeof N2==="string"?N2:void 0}});V();let S={},i;if(R!==void 0){let r=await Z.accountHeaders({...G,accountId:R});if(V(),L0(r))S=r.headers,i=r.attempt;else S=r}let K2=`attempt-${++W}`,z2={id:K2,key:F,scope:G,accountId:R,headers:S,attempt:R===void 0?void 0:{...G,accountId:R,attemptId:K2,transport:P,data:i},...P===void 0?{}:{transport:P},outputStarted:!1};if(f(z2),z2.attempt)l("select",{...G,accountId:z2.attempt.accountId,hook:X,...D.previousAccountId===void 0?{}:{previousAccountId:D.previousAccountId},...D.rerouteFrom===void 0?{}:{rerouteFrom:D.rerouteFrom},handle:z2.attempt});return z2},O=async(G,X,V,P,F)=>{let D=P2(G.sessionID,G.kind),R=P===void 0?void 0:j.get(P);if(R?.key!==D)R=void 0;if(!R){if(R=v(D),n(D).filter((i)=>i.transport===void 0&&!i.ended).length>1&&!k)k=!0,K("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 M2(G,X,F,V);else if(R.transport=V,R.attempt)R.attempt.transport=V;if(V==="ws"){for(let S of n(D))if(S!==R&&S.transport==="ws")p(S,"a newer attempt of its session and kind went out over WebSocket")}return R},d=async(G,X)=>{try{return await X()}catch(V){throw t(G,{reason:"failed",message:A(V)}),V}},X2=(G,X)=>{let V=n(P2(G,X)).filter((P)=>P.transport==="ws").at(-1);return V?.attempt!==void 0&&!V.ended?V:void 0},Z1=(G,X,V)=>{let P=o(G);if(!P||!G.attempt||G.limit)return;G.limit={signal:X,delivered:l("limit",{...P,via:V,limit:X,outputStarted:G.outputStarted,handle:G.attempt})}},w1=(G,X,V,P)=>{let F=o(G);if(!F||!G.attempt)return;l("quota",{...F,transport:X,...P===void 0?{}:{status:P},quota:V,handle:G.attempt})},y1=(G,X,V,P)=>{let F=G.attempt;if(!F)return;let D=Z.inspectEvent?.(P===void 0?{transport:X,data:V,attempt:F}:{transport:X,data:V,event:P,attempt:F});if(!D)return;if(D.quota!==void 0)w1(G,X,D.quota);if(D.outputStarted)G.outputStarted=!0;if(D.limit)Z1(G,D.limit,X);if(D.error!==void 0)t(G,{reason:"failed",message:D.error});else if(D.done)t(G)},H0=(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},N0=(G)=>!G.attempt||G.endError!==void 0||G.status!==void 0&&G.status>=400,F0=(G)=>{let X=[...j.values()].filter((S)=>S.scope.sessionID===G),V=X.filter((S)=>S.limit&&!S.rerouted).at(-1);if(V)return V;let P=X.filter((S)=>S.scope.kind==="primary"),F=P.length>0?P:X;if(F.length<=1)return F[0];let D=F.filter((S)=>!S.judged&&N0(S)).at(-1);if(D)return D;let R=F.filter((S)=>S.attempt&&!S.ended);if(R.length>1)return"ambiguous";return R[0]??F.at(-1)},F2={providerID:z},H2=[];H2.push(await $.session.hook("model.request",(G)=>{if(Q)return;return J2(G2(G),async(X)=>{let V=await M2(G2(G),"model.request",X);if(X(),V.accountId===void 0)throw c(V.scope);v2(G.headers,{...V.headers,[C2]:V.id})})},F2)),H2.push(await $.session.hook("http.request",(G)=>{if(Q){if(!Q2(G2(G),G.request.headers))return}return J2(G2(G),async(X)=>{let V=G.request.headers.get(C2)??void 0,P=Q?await M2(G2(G),"http.request",X,"http"):await O(G2(G),"http.request","http",V,X);X();let F=o(P),D=P.attempt;if(!F||!D)throw c(P.scope);await d(P,async()=>{let R=G.request;if(Z.rewriteRequest){if(V!==void 0){let K2=new Headers(R.headers);K2.delete(C2),R=new Request(R,{headers:K2})}R=await Z.rewriteRequest({...F,request:R,attempt:D})??R,X()}let S=new Headers(R.headers);S.delete(C2),T0(S,P.headers),_2(P.scope,S.entries());let i=new Request(R,{headers:S});B.set(i,P),G.request=i})})},F2)),H2.push(await $.session.hook("http.response",async(G)=>{let X=B.get(G.request);if(!X){if(Q)return;if(!$2)$2=!0,K("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 S=X.attempt,i=await d(X,async()=>Z.answeredBy?.({request:G.request,response:V,attempt:S}));if(i)H0(X,i)}let P=o(X),F=X.attempt;if(!P||!F)return;X.status=V.status;let D=Z.quotaFromHeaders?.(V.headers,V.status,F);if(D!==void 0)w1(X,"http",D,V.status);if(!V.ok&&Z.limitFromResponse){let S=await Z.limitFromResponse({status:V.status,headers:V.headers,body:()=>V.clone().text(),attempt:F});if(S)Z1(X,S,"http")}if(!V.ok||!V.body)t(X);let R=V;if(V.body&&(Z.inspectEvent||Z.onAttemptEnd)){let S=V.body;if(Z.inspectEvent)S=S.pipeThrough(Q1((i)=>y1(X,"http",i.data,i.event),(i)=>K("opencode2 auth event inspection threw",{error:A(i)})));R=new Response(P0(S,(i)=>t(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:F})??R;if(R!==V)G.response=R},F2)),H2.push(await $.session.hook("experimental.ws.handshake",(G)=>{if(Q){let X=P2(G.sessionID,G.kind);if(_.delete(X),!Q2(G2(G),new Headers(G.headers)))return}return J2(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 M2(G2(G),"experimental.ws.handshake",X,"ws"):await O(G2(G),"experimental.ws.handshake","ws",V,X);X();let F=o(P),D=P.attempt;if(!F||!D)throw c(P.scope);await d(P,async()=>{if(!Q?.refuseMisplaced)v2(G.headers,P.headers);let R=Z.rewriteHandshakeURL?.({...F,url:G.url,attempt:D});if(R!==void 0)G.url=R;if(Q?.refuseMisplaced)v2(G.headers,P.headers);if(_2(P.scope,Object.entries(G.headers)),Q)_.add(P.key)})})},F2));let f1=Z.rewriteWebSocketFrame?.bind(Z);if(f1)H2.push(await $.session.hook("experimental.ws.send",async(G)=>{let X=G2(G);if(Q&&!_.has(P2(X.sessionID,X.kind)))return;let V=X2(X.sessionID,X.kind),P=await f1({...X,attempt:V?.attempt,frame:G.frame});if(P!==void 0)G.frame=P},F2));H2.push(await $.session.hook("experimental.ws.receive",(G)=>{if(Q&&!_.has(P2(G.sessionID,G.kind)))return;let X=X2(G.sessionID,G.kind);if(!X)return;try{y1(X,"ws",G.frame)}catch(V){K("opencode2 auth frame inspection threw",{error:A(V)})}},F2)),H2.push(await $.session.hook("retry",async(G)=>{if(Q&&I.get(G.sessionID)!==!0)return;let X=G.decision,V=()=>l("retry",{sessionID:G.sessionID,attempt:G.attempt,reason:"host-decides",hostDecision:X,decision:X});if(x(G.sessionID)){await V();return}let P=F0(G.sessionID);if(!P)return;if(P==="ambiguous"){await l("retry",{sessionID:G.sessionID,attempt:G.attempt,reason:"host-decides",hostDecision:X,decision:X});return}let F=P;await J2(F.scope,async(D)=>{let R=D;if(x(G.sessionID)){await V();return}F.judged=!0;let S=F.attempt;if(S&&!F.outputStarted){if(!F.limit){let z2=Z.limitFromError?.(G.error,S);if(z2)Z1(F,z2,"error")}if(F.ended)await F.ended;if(F.limit)await F.limit.delivered}R();let{decision:i,reason:K2}=await M(F.scope.sessionID,async()=>{if(R(),x(G.sessionID))return{decision:X,reason:"host-decides"};let z2=L.get(F.key);if(L.delete(F.key),z2?.next)await q(z2.next);if(R(),x(G.sessionID))return{decision:X,reason:"host-decides"};let r=X,j2,B2,e;if(F.accountId===void 0||!S)r={retry:!1},j2="no-account";else if(F.outputStarted)r={retry:!1},j2="output-started";else if(F.limit){let R2={accountId:F.accountId,limit:F.limit.signal},N2,z1={...F.scope,phase:"retry",previousAccountId:F.accountId,rerouteFrom:R2};try{N2=await Z.chooseAccount(z1)}catch(G1){K("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:F.scope.sessionID,error:A(G1)})}let L2=typeof N2==="object"?N2.hold:void 0,I2=typeof N2==="string"?N2:L2?F.accountId:void 0;if(I2!==void 0)e={accountId:I2,input:z1};try{R()}catch(G1){if(e)await q(e);throw G1}if(x(G.sessionID)){if(e)await q(e);return{decision:X,reason:"host-decides"}}if(L2&&Number.isFinite(L2.delayMs)&&L2.delayMs>=0)r={retry:!0,delay:Math.min(L2.delayMs,l1)},j2="hold";else if(!L2&&I2!==void 0&&I2!==F.accountId)F.rerouted=!0,B2=R2,r={retry:!0,delay:0},j2="reroute";else{if(L2&&e)await q(e),e=void 0;j2="host-decides-last-account"}}else j2="host-decides";if(G.decision=r,r.retry&&F.accountId!==void 0&&j.has(F.id))L.set(F.key,{attemptId:F.id,sessionID:F.scope.sessionID,order:++b,accountId:F.accountId,...B2===void 0?{}:{rerouteFrom:B2},...e===void 0?{}:{next:e}});else if(e)await q(e);return{decision:r,reason:j2}});R(),await l("retry",{sessionID:G.sessionID,...F.accountId===void 0?{}:{accountId:F.accountId},kind:F.scope.kind,attempt:G.attempt,reason:K2,hostDecision:X,decision:i,...S===void 0?{}:{handle:S}})})},F2));let I1=(G)=>{if(s(G),I.delete(G),!a.get(G)?.foreignSeen)a.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;p(X,"its session was forgotten"),j.delete(X.id)}for(let[X,V]of L)if(V.sessionID===G)m(X)},J1=new AbortController,v1=$.event;if(v1)(async()=>{try{for await(let G of v1.subscribe({signal:J1.signal}))if(G.type==="session.deleted")I1(G.data.sessionID);else if(G.type==="session.status"&&G.data.status.type==="idle"){let X=G.data.sessionID,V=++b;M(X,async()=>{for(let[P,F]of L)if(F.sessionID===X&&F.order<V){if(L.delete(P),F.next)await q(F.next)}})}}catch(G){if(!J1.signal.aborted)K("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 v(P2(G,X))?.accountId},forgetSession:I1,get size(){return j.size},async dispose(){if(T)return;T=!0;for(let G of E.keys())s(G);J1.abort();for(let G of j.values())p(G,"the installation was disposed");j.clear();for(let G of L.keys())m(G);_.clear(),I.clear(),a.clear(),g.clear(),await Promise.all(C.values()),await Promise.all(H2.map(async(G)=>{try{await G.dispose()}catch(X){K("opencode2 auth hook did not dispose cleanly",{error:A(X)})}}))}}}import{createHash as _0}from"node:crypto";var M0=1024,C0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),u1=($)=>p1($,"user"),E0=($)=>C0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function O0($){return _0("sha256").update(JSON.stringify($)).digest("hex")}class q2{runtime;maxSessions;#$=new Map;constructor($,Z=M0){this.runtime=$;this.maxSessions=Z}advance($,Z,J=this.runtime){let z=this.#$.get($),Q=Array.isArray(Z.input)?Z.input:[],Y=Q.filter(u1),N=Q.findLastIndex(u1),H=N<0?void 0:O0(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(E0),I=z!==void 0&&!z.completed&&z.fingerprint===B&&z.userCount===L;j=_&&!I}let b=j||!z?{turnID:(J?.uuid??T2)(),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 j1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var c1=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function A0(){let $=globalThis;return $[c1]??=crypto.randomUUID(),$[c1]}class S2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,J){this.runtime=$;this.store=J;this.installationID=Z??A0(),this.sessions=J?.sessions??new Map,this.frameTurns=J?.frameTurns??new q2}get($){let Z=this.runtime?.uuid??T2;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(h2(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($),this.frameTurns.forget($)}}var B1={version:d1,"user-agent":a1,originator:"codex_exec"};var R0=1024,x0=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,g2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),o1=($)=>g2($)&&($.type==="message"||("role"in $))&&$.role==="user",r1=($)=>g2($)&&$.type==="configuration_update";class V1{http;#$=new Map;constructor($=new S2){this.http=$}apply($,Z,J){if(Z.kind!=="primary")return!1;let z=typeof $.model==="string"?$.model:"";if(!i1.has(z))return!1;if(x0.test(z))return!1;let Q=g2($.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(o1);if(U<0){if(J==="http")return!1;return $.reasoning={...Q,effort:N},!0}if($.reasoning={...Q,effort:N},!r1(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>R0){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function h2($){try{let Z=JSON.parse($);return g2(Z)?Z:void 0}catch{return}}async function s1($,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=h2(Y);if(N)delete N.max_output_tokens;let H=new Headers($.headers),U=m2({rewriteLite:n1,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 t1($,Z,J,z){let Q=z.sessions.get($.sessionID),Y=z.frameTurns.get($.sessionID);if(!Q||!Y)return;let N=j1(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)}m2({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 q0($,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&&r1(Z[J])&&o1(Z[J+1])&&JSON.stringify(Z.slice(J+1))===JSON.stringify($.slice(J))}function e1($,Z,J){let z=h2($);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=m2({rewriteLite:()=>{},init:{body:JSON.stringify(z)},headers:new Headers,metadata:j1(Y,Q),installationID:J.http.installationID,runtime:J.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(U)=>{J.apply(U,Z,"ws")}}),H=h2(String(N.init?.body));if(!H)return;if(!q0(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 W1($,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 $$}from"node:path";var b0=1024;class l2{accounts=new Map;limit;constructor($=b0){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 Z$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),J$=globalThis,U1=J$[Z$]??new Map;J$[Z$]=U1;function H1($){let Z=JSON.stringify([$$($.configPath),$$($.statePath)]),J=U1.get(Z);if(!J)J=new l2,U1.set(Z,J);return J}var Y2="openai",k0=60000,N1=1,D0="request refused: no account with a usable credential",U2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function w0($){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 K1($){try{return JSON.parse($)}catch{return}}function z$($){let Z=p2($);return Z?c2(Z):void 0}var y0=new Set(["usage_limit_reached","rate_limit_exceeded"]);function L1($,Z,J){return{reason:$.window,...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function f0($,Z){let J=u2($);if(J){let Y=typeof $.status==="number"?$.status:void 0;return L1(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&&y0.has(Y))return{reason:Y}}return}function I0($,Z){let J=K1($);if(!U2(J))return;let z=typeof J.type==="string"?J.type:void 0;if(z==="codex.rate_limits")return{quota:{snapshot:X$(J),complete:!0}};let Q=f0(J,Z);if(Q)return{limit:Q};if(z===void 0||z==="error")return;return E$(z)?void 0:{outputStarted:!0}}function v0($){let Z=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:Y$($),complete:Q$($)}}function h0($){let Z=$.get("retry-after");if(Z===null)return;let J=Number(Z);return Number.isFinite(J)&&J>=0?J*1000:void 0}function O$($){let{source:Z,pins:J}=$,z=$.now??Date.now,Q=$.log,Y=$.vault,N=new V1($.codex),H=new Map,U=new Map,j=(W)=>`${W.sessionID}\x00${W.kind}\x00${W.accountId}`,B=new Map,L=$.sessionAccounts??new l2,b=new P$,_=(W,T,E)=>{let K=E?[]:C$(Z.peek().rows,W,T,Y?.identities()??new Set),A=(Y?.routes()??[]).filter((C)=>C.kind==="oauth"&&B$(b2(C.quota),W,T));return[...K.map((C)=>({id:C.id,...C.identity!==void 0?{identity:C.identity}:{},quota:C.quota,row:C})),...A.map((C)=>({id:C.id,...C.identity!==void 0?{identity:C.identity}:{},quota:C.quota}))]},I=(W,T,E)=>{let K=F$(W,T,E),A=W.map((q)=>({id:q.id,kind:"oauth",...G$(q.quota)?{quota:q.quota}:{}})),C=W.flatMap((q)=>q.row?[q.row]:[]),M=new Set(W.filter((q)=>!q.row).map((q)=>q.id)),h=Z.rateLimitMarks(C);for(let q of M){let m=B.get(q);if(m===void 0)continue;if(m<=E)B.delete(q);else h.set(q,m)}return{rows:A,now:E,rateLimitMarks:h,refreshBackoff:Z.refreshBackoffFor(C),killswitch:K,requestPull:(q)=>M.has(q)?Y?.requestReading(q):Z.requestReading(q)}},a=(W,T,E,K,A)=>{let C=T$({...W,placement:K$(T),mainId:A});if(C.kind==="block"){Q?.debug("pool admission refused the request",{reason:C.block.reason});return}let M=C.order.filter((h)=>!E.has(h));if(K!==void 0&&M.includes(K))return K;return M[0]},x=(W,T,E,K,A,C,M)=>{let h=new Map(T.map((v)=>[v.id,v.quota])),q={requestBytes:N1,reservePercent:(v)=>V$(E,v===H$?void 0:v),resetCredits:(v)=>w0(h.get(v))},m=F1(W),l=(v,y)=>d2(M,{sessionId:K,requestBytes:N1,validPinnedAccountIds:W.rows.map((f)=>f.id).filter((f)=>!m.excluded.has(f)),excludeAccountIds:v,quotaCheckedAtByAccount:Object.fromEntries(W.rows.map((f)=>[f.id,m.projections.get(f.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(T.map((f)=>[f.id,f.identity])),select:(f)=>_$(W,q,new Set(v),f),persist:y},(f,o)=>M.set(f,o)),u=[...A],t=l(u,C);if(!t)return;let p=t.accountId,n=M$(W,q,p);if(n.kind==="none")return;if(n.kind==="move"){let v=l([...u,p],C);if(v)return v.accountId;return n.reason==="killswitch"?void 0:p}if(n.kind==="detour")return l([...u,p],!1)?.accountId;return p},$2={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(),K=T!==void 0&&T!=="local",A=()=>{throw new Z2({kind:"no-account",providerID:Y2,sessionID:W.sessionID,requestKind:W.kind,message:a2})};if(K)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 C=z(),M=_(E,C,K),h=L$(I(M.filter((f)=>f.id!==W.rerouteFrom?.accountId),E,C));if(h)await h,C=z(),M=_(E,C,K);let q=new Map(M.map((f)=>[f.id,f])),m=I(M,E,C),l=new Set(W.rerouteFrom?[W.rerouteFrom.accountId]:[]),u=E?.routing?.mode??"main-first",t=W.kind==="primary",p=new Set,n,v,y;try{for(;;){let f=new Set([...l,...p]);if(y=void 0,n=void 0,u==="sticky-balanced"){let c=new Map(J.placementSnapshot(W.sessionID)),s=c.get(W.sessionID);if(y=x(m,M,E,W.sessionID,f,t&&p.size===0,c),y!==void 0&&c.get(W.sessionID)!==s)n=c.get(W.sessionID)}if(y??=a(m,u,f,t?void 0:L.activeAccount(W.sessionID),K?u==="sticky-balanced"?null:N$(Y?.routes()??[]):void 0),y===void 0||p.has(y)){if(l.size>0){let c=new Map(m.rateLimitMarks);for(let s of l)c.delete(s);m={...m,rateLimitMarks:c},l.clear();continue}y=void 0;break}if(t&&u==="sticky-balanced"){let c=F1(m).projections.get(y)?.checkedAt,s=q.get(y)?.identity;v=J.reserve(W.sessionID,{accountId:y,inputBytes:N1,...c!==void 0?{quotaCheckedAt:c}:{},...s!==void 0?{wireIdentity:s}:{}})}let o=q.get(y)?.row;if(o){if(Z.usableToken(o)!==void 0)break;Q?.debug("pool row holds no usable token; choosing again",{accountId:y})}else{if(!Y)break;let c=await Y.authorize(y);if(c){H.set(j({...W,accountId:y}),c);break}Q?.debug("the vault refused to serve an account; choosing again",{accountId:y})}if(v)J.rollback(v);v=void 0,p.add(y)}if(y===void 0&&!K&&M.length===0&&await $.slotPlaceholderWithoutMain?.())A();if(y===void 0&&K&&Y&&(M.length===0||p.size>0)){let f=p.size>0?"vault-refused":U$(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:W$(f,Y.name)})}if(y!==void 0){let f=y,o=v,c=n,s=()=>{if(o)J.finish(o,c);if(t)L.record(W.sessionID,f),$.onRoute?.(W.sessionID,f,u)};if(W.phase==="retry")U.set(j({...W,accountId:y}),{commit:s,drop:()=>{if(o)J.rollback(o)}}),v=void 0;else s();let J2=Q?.info;b.served(m,y,Q&&J2?{info:(_2,A2)=>J2.call(Q,_2,A2)}:void 0)}return Q?.debug("pool account chosen",{kind:W.kind,accountId:y,mode:u,...W.rerouteFrom?{rerouteFrom:W.rerouteFrom.accountId}:{}}),y}finally{if(v)J.rollback(v)}},accountHeaders:async(W)=>{let{accountId:T}=W,E=j(W),K=U.get(E);U.delete(E);let A=()=>{K?.commit()};try{let C=()=>new Z2({kind:"no-account",providerID:Y2,sessionID:W.sessionID,requestKind:W.kind,message:D0}),M=Y&&await Y.authority()!=="local"?void 0:Z.peek().rows.find((m)=>m.id===T);if(!M&&Y){let m=j(W),l=H.get(m)??await Y.authorize(T);if(H.delete(m),!l)throw Q?.warn("the vault refused to serve an account; refusing the request",{accountId:T}),C();return A(),{headers:{...B1,"session-id":W.sessionID,authorization:`Bearer ${l.accessToken}`,"chatgpt-account-id":l.accountIdentity??z$(l.accessToken)??null},attempt:{kind:"vault",routeId:T,receipt:l}}}let h=M?Z.usableToken(M):void 0;if(!M||!h)throw Q?.warn("pool row holds no usable token; refusing the request",{accountId:T}),C();let q=M.identity??z$(h);return A(),{headers:{...B1,"session-id":W.sessionID,authorization:`Bearer ${h}`,"chatgpt-account-id":q??null},attempt:{kind:"pool",token:h,credentialEpoch:M.credentialEpoch}}}finally{K?.drop()}},async rewriteRequest({request:W,sessionID:T,kind:E}){let K=$.codexEndpoint?W1(W.url,$.codexEndpoint()):W.url,A=K===W.url?W:new Request(K,W);return await s1(A,{sessionID:T,kind:E},N,$.responsesLite?.()??!1)??A},rewriteHandshakeURL:({url:W})=>$.codexEndpoint?W1(W,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:W,sessionID:T,kind:E})=>e1(W,{sessionID:T,kind:E},N),quotaFromHeaders:(W)=>v0(W),async limitFromResponse({status:W,headers:T,body:E}){if(W<400)return;let K=K1(await E().catch(()=>"")),A=u2({...U2(K)?K:{},status:W});if(!A)return;let C=z(),M=L1(A,C,W);if(M.retryAfterMs!==void 0)return M;let h=h0(T);return h===void 0?M:{...M,retryAfterMs:h}},inspectEvent:({data:W})=>I0(W,z()),limitFromError(W){let T=K1(W.message),E=u2({...U2(T)?T:{},...W.status!==void 0?{status:W.status}:{}})??(W.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return E?L1(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)}},k=(W,T,E)=>{let K=E.data;if(K?.kind==="vault"){Y?.recordSnapshot(W,T.snapshot,T.complete,K.receipt);return}if(K?.kind!=="pool")return;if(Z.peek().rows.find((C)=>C.id===W)?.credentialEpoch!==K.credentialEpoch){Q?.debug("quota reading dropped: the row holds another credential",{accountId:W});return}Z.recordSnapshot(W,T.snapshot,K.token,T.complete)},g=(W,T,E)=>{let K=z(),A=E.data?.kind==="vault",C=A?Y?.routes().find((q)=>q.id===W)?.quota:Z.peek().rows.find((q)=>q.id===W)?.quota,M=j$(b2(C),T.reason,K,k0,T.retryAfterMs!==void 0?K+T.retryAfterMs:void 0);if(!A){Z.markRateLimited(W,M);return}let h=B.get(W);if(h===void 0||h<M)B.set(W,M)};return{adapter:$2,attach(W){W.on("quota",(T)=>k(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 b$}from"node:path";import{Buffer as m0}from"node:buffer";import{resolve as A$}from"node:path";function k2($){return m0.byteLength(JSON.stringify($))}function g0($){return $.reduce((Z,J)=>Z+k2(J),0)}function P1($,Z){return 2+$+Math.max(0,Z-1)}function l0($){let{head:Z,pending:J}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+P1(Z.inputBytes,Z.input.length)+1:0)+(J?20+P1(J.inputBytes,J.input.length)+10+P1(J.outputBytes,J.output.length)+(J.responseID===void 0?0:14+J.responseIDBytes)+1:0)}function R$($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class x${enabled;caps=i2;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=R$(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:k2(j),...z&&Y?{head:Y}:{},pending:{input:U,inputBytes:g0(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=R$(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=k2(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+=k2(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:k2(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=l0(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 q$=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),S$=globalThis,T1=S$[q$]??new Map;S$[q$]=T1;function n2($){let Z=JSON.stringify([A$($.configPath),A$($.statePath)]),J=T1.get(Z);if(!J)J=new x$,T1.set(Z,J);return J}var u0=5000,p0=["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"],c0=["x-opencode-parent-session-id","x-parent-session-id"];function y$($){let Z=k$($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:D$($?{...$,cachekeep:Z}:$)}}var f$=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),I$=globalThis,D2=I$[f$]??new Map;I$[f$]=D2;function d0($,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=w$({...i2,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??u0}}function a0($){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 i0($){let Z={};for(let J of p0){let z=$.get(J);if(z)Z[J]=z}return Z}function v$($,Z,J){let z=JSON.stringify([b$($.configPath),b$($.statePath)]),Q=D2.get(z);if(!Q)Q=d0(J,Z.settings()),D2.set(z,Q);let Y=Q,N=n2($);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"&&a0(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,a=c0.some((Q2)=>I.has(Q2))||Z.parentOf!==void 0&&await Z.parentOf(B.sessionID)!==void 0;if(a&&!L.subagents)return;let x=await B.request.clone().text();if(U)return;let w=I.get("chatgpt-account-id")??void 0;Y.manager.track({sessionKey:B.sessionID,bodyText:x,accountId:B.attempt.accountId,isSubagent:a,meta:{replayHeaders:i0(I),...w?{chatgptAccountId:w}:{},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(D2.get(z)===Y)D2.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 n0}from"node:fs";import{dirname as o0,resolve as r0}from"node:path";function s0(){return h$("opencode2")}var t0=2000;class p${path;options;sessions;frameTurns=new q2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Y=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=l$($,Z.uuid??T2)}get($,Z=T2){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??t0),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{$=_1(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(n0(o0(this.path),{recursive:!0}),J=await this.#B(),!J)return;let z;try{z=_1(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)u$(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 g$(this.path,this.options.lockWaitMs??m$)}}var c$=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),d$=globalThis,M1=d$[c$]??new Map;d$[c$]=M1;function a$($=s0()){let Z=r0($),J=M1.get(Z);if(!J)J=new p$(Z),M1.set(Z,J);return J}var i$=Symbol.for("cortexkit.openai-auth.v2.commands"),e0=W2("v2-command");function C1($){e0.warn(`/openai needs the terminal UI (session state: ${$}).`)}function $4(){let $=globalThis;return $[i$]??={locations:new Map},$[i$]}async function $Z($,Z){let J=$4(),z=$.location.directory,Q={menu:Z,session:$.session,closed:new AbortController},Y=await o$(z),N=await n$(t$,Y.dir,()=>e$({...Y,drain:s$,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 C1("no live location");let b=await L.get({sessionID:B.sessionID}),_=J.locations.get(b.location.directory);if(!_)return C1("location closed");let I=await r$(B.sessionID,_.closed.signal);if(!I||J.locations.get(b.location.directory)!==_){if(!I&&!_.closed.signal.aborted)E1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},B.sessionID);return C1(_.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let a=await _.menu.open(B.sessionID);E1(a,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 Z4="openai-auth-pool-browser",J4="openai-auth-pool-headless",z4="openai-auth-vault",G4="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 w2($){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 QZ($){return{method:{id:z4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await ZZ($.paths,$.name)!=="vault")throw Error(G4)}}}function XZ($){let Z=(J,z,Q)=>({method:{id:J,type:"oauth",label:z},async authorize(){if($.vault)await w2($.vault);let Y=await $.beginLogin({version:$.version,headless:Q});return{url:Y.url,instructions:Y.instructions,mode:"auto",callback:Y.completion}}});return[Z(Z4,"ChatGPT (openai-auth pool, browser)",!1),Z(J4,"ChatGPT (openai-auth pool, headless)",!0)]}function O1($){let Z=(J)=>typeof J==="string"?J:"";return x2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===GZ||JZ($)}function Y4($){if($.accountId)return $.accountId;let Z=$.access?p2($.access):void 0;return Z?c2(Z):void 0}async function jZ($,Z,J,z={}){if(z.vault)await w2(z.vault);if(O1(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Q=zZ($,{rowLocks:(_)=>YZ(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=Y4(J);if(z.vault)await w2(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===o2);if(B)return{id:(await Q.replace(B.id,N,U)).id,operation:"replaced"};if(!L){let _=await Q.add({id:o2,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(o2,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 Q4($){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 WZ($){let Z={...$,allowAction:Q4,unavailableSections:[]};return{open:(J)=>BZ(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 VZ(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 X4($,Z){if(!UZ($.modelID??$.id)){$.enabled=!1;return}let J=HZ($.id);if(J)$.limit={...J};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((z)=>[z.id,z])).values()]}function FZ($){return $.model.transform((Z)=>{let J=Z.list(Y2);for(let z of J){let Q=NZ(String(z.id)),Y=Q?J.find((N)=>String(N.id)===Q):void 0;Z.update(Y2,String(z.id),(N)=>X4(N,Y?.variants?.map((H)=>({...H,id:String(H.id)}))))}})}class A1{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(!KZ())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(()=>r2({...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(()=>r2({...z,error:s2(N,J?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>r2({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 R1{counts=new Map;record($,Z){let J=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof J==="number"&&Number.isFinite(J)?J:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function MZ($){return async(Z)=>{let J=Z.credential;if(J.type!=="oauth"||!J.access)throw Error("the row holds no access token to poll with");let z=await LZ({accessToken:J.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,z),PZ(z,$.now(),!0)}}function CZ($){let{source:Z,counts:J,now:z}=$,Q=async(j)=>{let B=await Z.rowAccess(j,await $.storage());if(!B?.row)throw new TZ("unknown_account",`${j==="main"?"Main":"Fallback"} account ${j} was not found.`);return _Z(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=b2(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 EZ}from"node:path";var j4=1024;class x1{pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=j4){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 d2(this.placementSnapshot($.sessionId),$,(Z,J)=>this.set(Z,J))}}var OZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),AZ=globalThis,q1=AZ[OZ]??new Map;AZ[OZ]=q1;function RZ($){let Z=JSON.stringify([EZ($.configPath),EZ($.statePath)]),J=q1.get(Z);if(!J)J=new x1,q1.set(Z,J);return J}import{statSync as B4}from"node:fs";import{resolve as V4}from"node:path";function fZ($){return $.map((Z)=>{try{let J=B4(Z);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}function S1($){return fZ([$.vault.paths.tokenPath,$.vault.paths.statePath])}function xZ($){return fZ([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+S1($)}class IZ{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:xZ($),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:xZ(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=S1($),Y=()=>this.producers.has($)&&$.vault.enrolled()===z&&S1($)===Q,N=await(z?f2($.paths):E2($.paths)),H=z?wZ($.vault.snapshot()?.rows,new Set($.vault.routes().map((j)=>j.id)),N,Date.now()):yZ((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 kZ(Z.sessionId,U,this.file,{canWrite:Y});return}if(Z.pin){let j=Date.now();await DZ({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 bZ({sessionId:Z.sessionId,activeId:Z.accountId,route:Z.route??H.route,updatedAt:Date.now()},U,this.file,{canWrite:Y})}).catch(()=>{W2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var vZ=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),hZ=globalThis,y2=hZ[vZ]??new Map;hZ[vZ]=y2;function mZ($,Z=qZ(),J=2000){let z=V4(Z),Q=y2.get(z);if(!Q)Q=new IZ(z,J),y2.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&&y2.get(z)===Y)y2.delete(z)}}}var $1="cortexkit-openai-auth",H4=5000;async function gZ($,Z,J,z=new S2,Q,Y,N){let H=new A1(J),U=new W4,j=new Map,B=new Map,L=(x)=>{B.delete(x);for(let w of j.keys())if(w.startsWith(`${x}:`))j.delete(w)},b=(x)=>{N?.(x.sessionID),Y?.send(x.sessionID,x.frame)},I=await X1({session:{hook:(x,w,Q2)=>$.session.hook(x,async($2)=>{let k=x==="http.request"?$2:void 0,g=x==="experimental.ws.handshake"?$2:void 0,T=(k?k.request.headers:g?new Headers(g.headers):void 0)?.get("authorization")===`Bearer ${V2(Z.providerID)}`,E={};if(g)j.delete(`${g.sessionID}:${g.kind}`);try{await U.run(E,()=>w($2))}catch(K){if(T&&!(K instanceof Z2))throw aZ(K);throw K}if(k&&T&&E.attempt){let K=k.request.headers.get("thread-id");if(K)k.request.headers.set("session-id",K)}if(k&&T&&E.attempt)await H.captureHttp(k.request,E.attempt);if(k&&T&&E.attempt)await Q?.({sessionID:k.sessionID,kind:k.kind,request:k.request,attempt:E.attempt});if(g&&T&&E.attempt)g.headers["session-id"]=z.get(g.sessionID).threadID;if(x==="experimental.ws.send"){let K=$2,A=j.get(`${K.sessionID}:${K.kind}`);if(A)await H.frame(K.frame,A.attempt);if(A&&K.kind==="primary")b(K)}if(k||g){let K=k??g;if(!K)return;let C=(k?k.request.headers:new Headers(K.headers)).get("authorization")?.replace(/^Bearer /,"");if(T&&C)B.set(K.sessionID,C);else B.delete(K.sessionID);if(g){let M=`${g.sessionID}:${g.kind}`;if(T&&C&&E.attempt)j.set(M,{bearer:C,attempt:E.attempt,url:g.url,headers:new Headers(Object.entries(g.headers).filter(([h])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(h.toLowerCase())))});else j.delete(M)}if(B.size>512){let M=B.keys().next().value;if(M)B.delete(M)}if(j.size>512){let M=j.keys().next().value;if(M)j.delete(M)}}else if(x==="experimental.ws.receive"){let K=$2,A=j.get(`${K.sessionID}:${K.kind}`);if(A){if(z.frameReceived(K.sessionID,K.frame),K.kind==="primary"){let C;if(Y?.receive(K.sessionID,K.frame,(M)=>{C=M}),C)try{let M=t1(C,A.url,A.headers,z);if(M)await Q?.({sessionID:K.sessionID,kind:"primary",request:M,attempt:A.attempt})}catch(M){J.warn("cachekeep WebSocket capture failed",{error:M instanceof Error?M.message:String(M)})}}K.frame=iZ(K.frame,A.bearer)}}else if(x==="retry"){let K=$2,A=B.get(K.sessionID);if(A)Object.assign(K.error,{message:s2(K.error.message,A)})}},Q2)},event:{subscribe:(x)=>async function*(){for await(let w of $.event.subscribe(x)){if(w.type==="session.deleted")L(w.data.sessionID);yield w}}()}},{...Z,rewriteRequest:async(x)=>{let w=U.getStore();if(w)w.attempt=x.attempt;return Z.rewriteRequest?.(x)},rewriteHandshakeURL:(x)=>{let w=U.getStore();if(w)w.attempt=x.attempt;return Z.rewriteHandshakeURL?.(x)},onAttemptEnd:async(x,w)=>{await H.end(x,w),await Z.onAttemptEnd?.(x,w)},rewriteResponse:async(x)=>{await H.response(x.request,x.response.status);let w=await Z.rewriteResponse?.(x)??x.response;return nZ(w,x.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(x)=>{let w=x.get("authorization");return w?.startsWith("Bearer ")?w.slice(7):void 0}},logger:{warn:(x,w)=>J.warn(x,{data:w})}}),a=I.dispose;return{...I,dispose:async()=>{B.clear(),j.clear(),await a(),await H.settle(),H.clear()}}}function D1($={}){return{id:$1,setup:(Z)=>N4(Z,$)}}async function N4($,Z={}){let J2=[];try{let J=W2("opencode2");let z=W2("quota");let Q=Z.version??rZ;await j0({version:Q,...Z.runtimeLayout});let Y=Z.paths??(()=>tZ(oZ()));let N=await f2(Y());let H=N?.logging?.level;if(H&&typeof H==="string")uZ(H);let U=Z.fetch??fetch;let j=Z.now??Date.now;let B=Z.poolMigration??V0;if(!B&&!O2(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 O=(X2)=>{throw new Z2({kind:"no-account",providerID:Y2,sessionID:X2.sessionID,requestKind:X2.kind,message:a2})},d=await gZ($,{providerID:Y2,chooseAccount:O,accountHeaders:O},J);return()=>d.dispose()}let L=Z.vault?.firstRosterWaitMs??z0;let b=B0({host:"opencode",stateDir:Z.vault?.stateDir??dZ(Y().statePath),reservedRouteIds:()=>k.peek().rows.map((O)=>O.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=async()=>await _.authority()==="local"?E2(Y()):f2(Y());let a=!1;let x=!1;const w=t2(J2,{[Symbol.dispose](){if(!a)b.release()}},0);await _.authority();let Q2=b.firstRoster;let $2=new R1;let k=new G0({paths:Y,refreshProvider:async(O)=>{let d=await cZ({refreshToken:O.refresh,fetchImpl:U,now:j}),X2=pZ({id_token:"",access_token:d.access,refresh_token:d.refresh});return{...d,...X2?{identity:X2}:{}}},pullQuota:MZ({fetchImpl:U,now:j,counts:$2,logger:z}),now:j,vaultIdentities:()=>_.identities(),vaultMode:()=>_.enrolled(),vaultAuthority:()=>_.authority(),vaultFirstRoster:Q2,vaultFirstRosterBackgroundWaitMs:L,log:W2("pool")});if(await _.authority()==="local")await k.load();let g=Z.heartbeat===!1?void 0:await Q0({version:Q,logger:W2("heartbeat")});let W=Z.fence??(()=>sZ({currentVersion:Q}));let T=Z.slot??W0();let E=async()=>eZ(Y(),await T.get({path:{id:"openai"}}));let K=!1;let A=B?Y0({paths:Y,slot:T,version:Q,fence:W,runDeps:{vaultServes:()=>_.serves()},paused:async()=>await _.authority()!=="local",migrate:async(O)=>{let d=await $0(O);if(K=d.status==="refused",!x)await k.load();return d},adopt:async(O)=>{if(x)return{status:"retry",reason:"unsettled"};if(!await k1(Q2,L))return{status:"retry",reason:"vault-roster-pending"};if(x)return{status:"retry",reason:"unsettled"};let d=await Z0(O);if(!x)await k.load();return d}}):void 0;A?.start();b.start();let C=RZ(Y());let M=mZ({paths:Y(),source:k,pins:C,vault:_},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const h=t2(J2,{[Symbol.dispose](){if(!a)M.release()}},0);M.publish();let q=Z.codex??new S2(void 0,void 0,a$());let m=y$(N);let l=n2(Y());let u=v$(Y(),{source:k,storage:I,vault:_,accounts:H1(Y()),settings:()=>m,parentOf:async(O)=>(await $.session.get({sessionID:O}))?.parentID??void 0,fetch:U,log:W2("cachekeep")},{now:j,codexResponsesUrl:e2().codexApiEndpoint,...Z.cacheKeep});const t=t2(J2,{[Symbol.dispose](){if(!a)u.release()}},0);let p=O$({codex:q,onRoute:M.route,source:k,slotPlaceholderWithoutMain:E,storage:I,pins:C,sessionAccounts:H1(Y()),vault:_,awaitVaultRoster:async()=>{await k1(_.awaitRequestRoster(),J0)},responsesLite:()=>e2().responsesLite,codexEndpoint:()=>e2().codexApiEndpoint,now:j,log:J});let n=await gZ($,p.adapter,J,q,(O)=>u.capture(O),l,(O)=>u.forget(O));p.attach(n);let v=async(O)=>{if(await w2(_),O2(Y().configPath))return;if(await A?.idle(),O2(Y().configPath))return;if(K&&!O1(O)&&(await W()).open){await k.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let y=async(O)=>{await v(O);let d=await jZ(k.poolStore(),Y(),O,{vault:_});if(!O2(Y().configPath))await A?.requestAdoption();await k.load(),J.info("ChatGPT login stored in the account pool",d)};let f=await Y1($,{integrationID:Y2,methods:XZ({beginLogin:Z.beginLogin??b1,version:Q,vault:_}),onLogin:(O)=>y(O),label:"ChatGPT (openai-auth account pool)",vault:QZ(_)});let o=await FZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let c=$.command&&$.location?await $Z({session:$.session,command:$.command,location:$.location},Z.controlPlane??WZ({...CZ({source:k,storage:I,counts:$2,now:j,authority:()=>_.authority()}),fetchImpl:U,now:j,randomUUID:U4,accountStoragePath:Y().configPath,accountStatePath:Y().statePath,packageVersion:Q,layoutNotice:X0,loadAccounts:E2,store:()=>k.poolStore(),migration:async()=>{if(O2(Y().configPath))return{migrated:!0};let O=await W();return{migrated:!1,blockers:O.open?[]:O.blockers}},beginAccountLogin:Z.beginLogin??b1,refreshAllQuota:async()=>(await k.pollRows(await E2(Y()))).map((O)=>({...O,account:O.id})),getStickyRouting:async(O)=>C.get(O),cacheKeepManager:u.manager,setCacheKeepEnabled:(O)=>u.configure({enabled:O}),setCacheKeepSubagents:(O)=>u.configure({subagents:O}),setCacheKeepSustain:(O)=>u.configure({sustain:O}),setCacheKeepWindow:(O)=>u.configure({window:O}),afterWrite:()=>k.load(),refreshSidebar:()=>M.publish(),clearStickyRouting:async(O)=>{let d=C.get(O)!==void 0;return C.forget(O),d},vault:_})):void 0;let s=new AbortController;(async()=>{try{for await(let O of $.event.subscribe({signal:s.signal}))if(O.type==="session.deleted")p.forgetSession(O.data.sessionID),u.forget(O.data.sessionID),l.forget(O.data.sessionID)}catch(O){if(!s.signal.aborted)J.warn("stopped listening for session deletion",{error:O instanceof Error?O.message:String(O)})}})();a=!0;return async()=>{x=!0,s.abort();let O=u.release();await c?.(),A?.dispose(),await k.dispose(),await M.release(),await Promise.allSettled([n.dispose(),f.dispose(),o.dispose()]);let d;try{await Promise.race([Promise.all([A?.idle(),k.settled(),q.store?.settled(),O]),new Promise((X2)=>{d=setTimeout(X2,H4),d.unref?.()})])}finally{clearTimeout(d),b.release(),await g?.release()}}}catch(_2){var A2=_2,M2=1}finally{lZ(J2,A2,M2)}}var F4=D1(),m6={id:$1,setup:F4.setup,server:U0.server};export{m6 as default,D1 as createOpenAIAuthPlugin,$1 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.7.0",
3
+ "version": "1.8.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -66,17 +66,17 @@
66
66
  },
67
67
  "devDependencies": {
68
68
  "@ai-sdk/openai": "3.0.88",
69
- "@cortexkit/common-auth": "^0.26.0",
69
+ "@cortexkit/common-auth": "^0.27.1",
70
70
  "@cortexkit/openai-auth-core": "workspace:*",
71
- "@opencode/plugin": "2.0.32"
71
+ "@opencode/plugin": "2.2.0"
72
72
  },
73
73
  "dependencies": {
74
74
  "@cortexkit/claustrum-client": "^0.13.0",
75
75
  "@cortexkit/private-files": "^0.2.1",
76
76
  "@cortexkit/subc-client": "^0.22.0",
77
- "@opentui/core": ">=0.6.1",
78
- "@opentui/solid": ">=0.6.1",
79
- "ai": "^7.0.143",
77
+ "@opentui/core": ">=0.7.0",
78
+ "@opentui/solid": ">=0.7.0",
79
+ "ai": "^7.0.155",
80
80
  "jsonc-parser": "^3.3.1",
81
81
  "solid-js": "1.9.12"
82
82
  }
@@ -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
  }