@cortexkit/opencode-openai-auth 1.10.0 → 1.10.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.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{$ as w,K as f,L as g,M as h,N as i,O as j,P as k,Q as l,R as m,S as n,T as o,U as p,V as q,W as r,X as s,Y as t,Z as u,_ as v,aa as x,ba as y,ca as z,da as A,ea as B,fa as C,ga as D,ha as E,ia as F,j as c,ja as G,k as d,l as e}from"./index-ya96m6wr.js";import"./index-3r9thx6n.js";import"./index-fd3f8vw2.js";import{Jd as a,Kd as b}from"./index-3p1tc2e2.js";import"./index-dcyhv7eh.js";import"./index-361xxyg2.js";import"./index-29ztc0ay.js";import"./index-mf3dqvbn.js";import"./index-95z5dpe1.js";import"./index-dkhy2peg.js";import"./index-mkda7acs.js";export{D as rewriteResponsesLiteBody,B as resolveSidebarSessionId,s as poolResetTarget,a as parseJwtClaims,y as mergePushedQuotaMetadata,l as getMainRefreshLockName,x as findCachekeepFallbackAccount,b as extractAccountIdFromClaims,G as default,t as createResetTargetResolver,j as codexOAuthModelVariantSource,h as codexOAuthModelListed,i as codexOAuthModelLimit,A as buildSidebarState,z as buildSidebarMachineState,u as buildResetRedemptionDeps,p as __resetBootQuotaSeedForTest,v as __menuContextForTest,o as __bootQuotaSeedPromiseForTest,r as ResetTargetResolutionError,c as RESPONSES_LITE_MODELS,w as POOL_MIGRATION_ENABLED,F as OpenAIAuthPlugin,C as MID_CONVERSATION_EFFORT_MODELS,m as MAIN_REFRESH_LOCK_TTL_MS,n as MAIN_REFRESH_LEASE_TTL_MS,k as EMPTY_BEARER_MESSAGE,g as DISALLOWED_MODELS,E as CodexAuthPlugin,d as CODEX_VERSION,e as CODEX_USER_AGENT,q as AuthPersistError,f as ALLOWED_MODELS};
1
+ import{$ as w,K as f,L as g,M as h,N as i,O as j,P as k,Q as l,R as m,S as n,T as o,U as p,V as q,W as r,X as s,Y as t,Z as u,_ as v,aa as x,ba as y,ca as z,da as A,ea as B,fa as C,ga as D,ha as E,ia as F,j as c,ja as G,k as d,l as e}from"./index-44b5y56b.js";import"./index-vpjmexm5.js";import"./index-4gkfz4zp.js";import{Jd as a,Kd as b}from"./index-7fdcb97f.js";import"./index-8xgeh2zt.js";import"./index-7xqb1m44.js";import"./index-r0kv780p.js";import"./index-2py81t0v.js";import"./index-hq4gdm6f.js";import"./index-dkhy2peg.js";import"./index-mkda7acs.js";export{D as rewriteResponsesLiteBody,B as resolveSidebarSessionId,s as poolResetTarget,a as parseJwtClaims,y as mergePushedQuotaMetadata,l as getMainRefreshLockName,x as findCachekeepFallbackAccount,b as extractAccountIdFromClaims,G as default,t as createResetTargetResolver,j as codexOAuthModelVariantSource,h as codexOAuthModelListed,i as codexOAuthModelLimit,A as buildSidebarState,z as buildSidebarMachineState,u as buildResetRedemptionDeps,p as __resetBootQuotaSeedForTest,v as __menuContextForTest,o as __bootQuotaSeedPromiseForTest,r as ResetTargetResolutionError,c as RESPONSES_LITE_MODELS,w as POOL_MIGRATION_ENABLED,F as OpenAIAuthPlugin,C as MID_CONVERSATION_EFFORT_MODELS,m as MAIN_REFRESH_LOCK_TTL_MS,n as MAIN_REFRESH_LEASE_TTL_MS,k as EMPTY_BEARER_MESSAGE,g as DISALLOWED_MODELS,E as CodexAuthPlugin,d as CODEX_VERSION,e as CODEX_USER_AGENT,q as AuthPersistError,f as ALLOWED_MODELS};
@@ -1 +1 @@
1
- import{uf as b,vf as c}from"../index-361xxyg2.js";import{zf as a}from"../index-29ztc0ay.js";import"../index-95z5dpe1.js";import"../index-dkhy2peg.js";import"../index-mkda7acs.js";export{b as writePortFile,c as isOpenaiRpcStateDir,a as discoverPortFile};
1
+ import{uf as b,vf as c}from"../index-7xqb1m44.js";import{zf as a}from"../index-r0kv780p.js";import"../index-hq4gdm6f.js";import"../index-dkhy2peg.js";import"../index-mkda7acs.js";export{b as writePortFile,c as isOpenaiRpcStateDir,a as discoverPortFile};
@@ -1 +1 @@
1
- import{Nf as b}from"../index-mf3dqvbn.js";import"../index-95z5dpe1.js";import"../index-mkda7acs.js";export{b as isNotifyPayload};
1
+ import{Nf as b}from"../index-2py81t0v.js";import"../index-hq4gdm6f.js";import"../index-mkda7acs.js";export{b as isNotifyPayload};
@@ -1 +1 @@
1
- import{Af as F,Bf as f}from"../index-29ztc0ay.js";import"../index-95z5dpe1.js";import"../index-mkda7acs.js";function y(r,s,v){return f(r,s,v)}export{y as createRpcClient,F as DEFAULT_RPC_TIMEOUT_MS};
1
+ import{Af as F,Bf as f}from"../index-r0kv780p.js";import"../index-hq4gdm6f.js";import"../index-mkda7acs.js";function y(r,s,v){return f(r,s,v)}export{y as createRpcClient,F as DEFAULT_RPC_TIMEOUT_MS};
@@ -1 +1 @@
1
- import{$c as M,Ac as l,Bc as m,Cc as n,Dc as o,Ec as p,Fc as q,Gc as r,Hc as s,Ic as t,Jc as u,Kc as v,Lc as w,Mc as x,Nc as y,Oc as z,Pc as A,Qc as B,Rc as C,Sc as D,Tc as E,Uc as F,Vc as G,Wc as H,Xc as I,Yc as J,Zc as K,_c as L,ad as N,bd as O,cd as P,dd as Q,ed as R,fd as S,gd as T,pc as a,qc as b,rc as c,sc as d,tc as e,uc as f,vc as g,wc as h,xc as i,yc as j,zc as k}from"./index-fd3f8vw2.js";import"./index-3p1tc2e2.js";import"./index-dcyhv7eh.js";import"./index-mf3dqvbn.js";import"./index-95z5dpe1.js";import"./index-mkda7acs.js";export{y as upsertSidebarActiveRouting,p as spendControlExhaustedResetAt,O as sidebarQuotaProjection,I as settleWithinBudget,w as setSidebarState,x as setSidebarMachineState,z as setSidebarLegacyRouting,e as setLegacySidebarStateFileForTest,C as resolveSidebarStickyAssignment,s as resolveSessionStickyAccount,t as resolveSessionSidebarRouting,N as resolveActiveAccount,A as removeSidebarActiveRouting,K as rememberStickyPin,v as pruneStickyAssignments,u as pruneActiveRouting,D as planSidebarStickyAssignmentFromSnapshot,B as planSidebarStickyAssignment,E as persistSidebarStickyAssignment,k as normalizeSidebarState,o as isUsableRoutingEntry,r as isQuotaExhausted,h as hashSidebarSessionId,i as getSidebarStateFile,l as getSidebarState,d as getPresentQuotaWindows,P as getCollapsedQuotaSummary,Q as getCollapsedAccountLines,c as formatWindowLabel,S as fitCollapsedLabel,q as exhaustedQuotaResetAt,G as drainSidebarWrites,R as displayWidth,J as createSidebarStateCache,M as createSidebarBookkeepingQueue,T as computeQuotaPacing,F as clearSidebarStickyAssignment,L as applyStickyPinOverlay,b as accountServesOnCredits,a as accountCreditsText,g as STICKY_ASSIGNMENT_MAX_ENTRIES,f as STICKY_ASSIGNMENT_MAX_AGE_MS,H as HOT_PATH_READ_BUDGET_MS,j as DEFAULT_SIDEBAR_STATE,n as ACTIVE_ROUTING_MAX_ENTRIES,m as ACTIVE_ROUTING_MAX_AGE_MS};
1
+ import{$c as M,Ac as l,Bc as m,Cc as n,Dc as o,Ec as p,Fc as q,Gc as r,Hc as s,Ic as t,Jc as u,Kc as v,Lc as w,Mc as x,Nc as y,Oc as z,Pc as A,Qc as B,Rc as C,Sc as D,Tc as E,Uc as F,Vc as G,Wc as H,Xc as I,Yc as J,Zc as K,_c as L,ad as N,bd as O,cd as P,dd as Q,ed as R,fd as S,gd as T,pc as a,qc as b,rc as c,sc as d,tc as e,uc as f,vc as g,wc as h,xc as i,yc as j,zc as k}from"./index-4gkfz4zp.js";import"./index-7fdcb97f.js";import"./index-8xgeh2zt.js";import"./index-2py81t0v.js";import"./index-hq4gdm6f.js";import"./index-mkda7acs.js";export{y as upsertSidebarActiveRouting,p as spendControlExhaustedResetAt,O as sidebarQuotaProjection,I as settleWithinBudget,w as setSidebarState,x as setSidebarMachineState,z as setSidebarLegacyRouting,e as setLegacySidebarStateFileForTest,C as resolveSidebarStickyAssignment,s as resolveSessionStickyAccount,t as resolveSessionSidebarRouting,N as resolveActiveAccount,A as removeSidebarActiveRouting,K as rememberStickyPin,v as pruneStickyAssignments,u as pruneActiveRouting,D as planSidebarStickyAssignmentFromSnapshot,B as planSidebarStickyAssignment,E as persistSidebarStickyAssignment,k as normalizeSidebarState,o as isUsableRoutingEntry,r as isQuotaExhausted,h as hashSidebarSessionId,i as getSidebarStateFile,l as getSidebarState,d as getPresentQuotaWindows,P as getCollapsedQuotaSummary,Q as getCollapsedAccountLines,c as formatWindowLabel,S as fitCollapsedLabel,q as exhaustedQuotaResetAt,G as drainSidebarWrites,R as displayWidth,J as createSidebarStateCache,M as createSidebarBookkeepingQueue,T as computeQuotaPacing,F as clearSidebarStickyAssignment,L as applyStickyPinOverlay,b as accountServesOnCredits,a as accountCreditsText,g as STICKY_ASSIGNMENT_MAX_ENTRIES,f as STICKY_ASSIGNMENT_MAX_AGE_MS,H as HOT_PATH_READ_BUDGET_MS,j as DEFAULT_SIDEBAR_STATE,n as ACTIVE_ROUTING_MAX_ENTRIES,m as ACTIVE_ROUTING_MAX_AGE_MS};
@@ -1,4 +1,4 @@
1
- import{ff as h,mf as u,nf as P}from"./index-dcyhv7eh.js";import{Pf as M,Qf as R,Wf as S}from"./index-95z5dpe1.js";import"./index-mkda7acs.js";import{mkdir as Yq,writeFile as Vq}from"node:fs/promises";import{homedir as Wq}from"node:os";import{dirname as Dq,join as b}from"node:path";import{applyEdits as t,modify as r,parse as e}from"jsonc-parser";function qq(z){return z!==null&&typeof z==="object"&&!Array.isArray(z)}async function k(z){try{let q=[],H=e(await S(z,M),q,{allowTrailingComma:!0});return q.length===0&&qq(H)?H:{}}catch(q){if(q instanceof R&&q.code!=="ENOENT")throw q;return{}}}var zq=`// Shared preferences for TUI plugins.
1
+ import{ff as h,mf as u,nf as P}from"./index-8xgeh2zt.js";import{Pf as M,Qf as R,Wf as S}from"./index-hq4gdm6f.js";import"./index-mkda7acs.js";import{mkdir as Yq,writeFile as Vq}from"node:fs/promises";import{homedir as Wq}from"node:os";import{dirname as Dq,join as b}from"node:path";import{applyEdits as t,modify as r,parse as e}from"jsonc-parser";function qq(z){return z!==null&&typeof z==="object"&&!Array.isArray(z)}async function k(z){try{let q=[],H=e(await S(z,M),q,{allowTrailingComma:!0});return q.length===0&&qq(H)?H:{}}catch(q){if(q instanceof R&&q.code!=="ENOENT")throw q;return{}}}var zq=`// Shared preferences for TUI plugins.
2
2
  // Plugins update individual keys in place and preserve comments.
3
3
  {}
4
4
  `;function g(z){let{file:q,pluginKey:H,beforeCommit:Q}=z,$={...P.preferences,timeoutMs:z.timeoutMs??P.preferences.timeoutMs},Z=Promise.resolve();async function X(U,j){await u(q,$,async(K)=>{let J;try{J=await S(q,M)}catch(G){if(G.code!=="ENOENT")throw G;J=""}if(J.trim()==="")J=zq;let B=t(J,r(J,[H,...U],j,{formattingOptions:{insertSpaces:!0,tabSize:2}}));await h(q,B,{serialize:(G)=>String(G),beforeRename:async()=>{await Q?.(),await K.assertOwned()}})})}return{queueTuiPreferenceUpdate(U,j){let K=[...U],J=structuredClone(j),B=Z.then(()=>X(K,J));return Z=B.catch(()=>{}),B}}}import{readFileSync as Hq,realpathSync as Qq,statSync as Xq,watch as Zq}from"node:fs";import{readFile as $q,stat as Bq}from"node:fs/promises";import{basename as p,dirname as s,join as Gq,resolve as Jq}from"node:path";import{clearTimeout as w,setTimeout as c}from"node:timers";function n(z){let q=Jq(z);if(M)return q;try{return Qq(q)}catch{let H=s(q);return H===q?q:Gq(n(H),p(q))}}function d(z){return z&&`${z.dev}:${z.ino}:${z.mtimeMs}:${z.size}`}function T(z,q,H={}){let Q=globalThis,$=Symbol.for("cortexkit.common-auth.tui-prefs.watchers.v1"),Z=Q[$]??new Map;Q[$]=Z;let X=n(z),U=Z.get(X);if(U)return U.subscribe(q);let j=p(X),K=M?(Y)=>S(Y):H.fs?.readFile??((Y)=>$q(Y,"utf8")),J=H.fs?.stat??Bq,B=null,G=null,x=null,C=null;if(!M)try{let Y=d((H.fs?.statSync??Xq)(X));C=(H.fs?.readFileSync??((V)=>Hq(V,"utf8")))(X),x=Y}catch{}let N=!1,L=new Set,E=Promise.resolve(),v=(Y)=>{return E=E.then(async()=>{if(N)return;let V=d(await J(X).catch(()=>null));if(!Y&&V===x)return;if(V===null){x=null;return}let I=await K(X).catch((W)=>{if(W instanceof R&&W.code!=="ENOENT")if(H.onError)H.onError(W);else process.emitWarning(W.message,W.name);return null});if(N)return;if(I===null)return;if(x=V,I===C)return;C=I;for(let W of[...L]){if(!L.has(W))continue;try{W.notify()}catch{}}}),E},i=()=>{if(N)return;if(B)w(B);B=c(()=>{B=null,v(!0)},150)},O=null;try{O=(H.watchDirectory??Zq)(s(X),(Y,V)=>{let I=V?.toString(),W=I===j||I?.startsWith(`${j}.`)&&I.endsWith(".tmp");if(I!=null&&!W)return;i()}),O.on("error",()=>{O?.close(),O=null})}catch{}let f=()=>{if(N||G)return;G=c(()=>{if(G=null,N)return;v(!1).finally(f)},1000),G.unref()},F={subscribe:(Y)=>{let V={notify:Y};return L.add(V),()=>{if(!L.delete(V)||L.size>0)return;if(N=!0,B)w(B);if(G)w(G);if(O?.close(),Z.get(X)===F)Z.delete(X)}}};return Z.set(X,F),f(),F.subscribe(q)}var Uq="OPENCODE_TUI_PREFERENCES_FILE",Iq="tui-preferences.jsonc";function m(){let z=process.env[Uq];if(z)return z;let q=process.env.OPENCODE_CONFIG_DIR||b(process.env.XDG_CONFIG_HOME||b(Wq(),".config"),"opencode");return b(q,Iq)}function _(z){return typeof z==="object"&&z!==null&&!Array.isArray(z)}function dq(){return k(m())}var Mq="openai-auth",Aq=160,l={forceToTop:!1,order:Aq,startCollapsed:!1,rememberCollapsed:!0,collapsed:null,pollMs:1500,refreshDebounceMs:200,header:{label:"OPENAI",showVersion:!0},sections:{quota:!0,fallbackAccounts:!0,routing:!0,health:!0,pacing:!0},appearance:{barWidth:10,barFilledChar:"█",barEmptyChar:"░",warnThreshold:50,errorThreshold:80}};function D(z,q){return typeof z==="boolean"?z:q}function A(z,q,H,Q){if(typeof z!=="number"||!Number.isFinite(z))return q;return Math.min(Math.max(Math.round(z),H),Q)}function jq(z,q,H){if(typeof z!=="string"||z.length===0)return q;return z.slice(0,H)}function o(z,q){if(typeof z!=="string")return q;return[...z][0]??q}function pq(z){let q=z[Mq];if(!_(q))return structuredClone(l);let H=l,Q=_(q.header)?q.header:{},$=_(q.sections)?q.sections:{},Z=_(q.appearance)?q.appearance:{},X=A(Z.warnThreshold,H.appearance.warnThreshold,0,99),U=Math.max(A(Z.errorThreshold,H.appearance.errorThreshold,0,100),Math.min(X+1,100));return{forceToTop:D(q.forceToTop,H.forceToTop),order:A(q.order,H.order,-1e4,1e4),startCollapsed:D(q.startCollapsed,H.startCollapsed),rememberCollapsed:D(q.rememberCollapsed,H.rememberCollapsed),collapsed:typeof q.collapsed==="boolean"?q.collapsed:null,pollMs:A(q.pollMs,H.pollMs,500,30000),refreshDebounceMs:A(q.refreshDebounceMs,H.refreshDebounceMs,50,5000),header:{label:jq(Q.label,H.header.label,20),showVersion:D(Q.showVersion,H.header.showVersion)},sections:{quota:D($.quota,H.sections.quota),fallbackAccounts:D($.fallbackAccounts,H.sections.fallbackAccounts),routing:D($.routing,H.sections.routing),health:D($.health,H.sections.health),pacing:D($.pacing,H.sections.pacing)},appearance:{barWidth:A(Z.barWidth,H.appearance.barWidth,4,40),barFilledChar:o(Z.barFilledChar,H.appearance.barFilledChar),barEmptyChar:o(Z.barEmptyChar,H.appearance.barEmptyChar),warnThreshold:X,errorThreshold:U}}}var Nq=-1e5;function sq(z,q,H){let Q=z[q];if(!_(Q))return H;if(Q.forceToTop===!0)return Nq+Object.keys(z).indexOf(q);return A(Q.order,H,-1e4,1e4)}var Kq=`// Shared preferences for opencode TUI plugins.
package/dist/v2/server.js CHANGED
@@ -1,3 +1,3 @@
1
- import{c as Z4}from"../index-17rh67pr.js";import{$ as $4,A as n0,B as o0,C as E1,D as WZ,E as VZ,F as T0,G as _0,H as e0,I as mZ,J as lZ,M as $0,N as Z0,O as z0,W as Y0,X as Q0,d as g0,e as J0,f as v1,fa as b$,g as e2,ga as R$,h as q1,i as y1,ja as z4,k as q$,l as S$,m as x$,n as M1,o as hZ,p as N$,q as gZ,r as rZ,s as tZ,t as b1,u as TZ,v as _Z,w as S1,x as i0,y as C$,z as a0}from"../index-ya96m6wr.js";import{Ab as Q1,Cb as YZ,Db as _1,Eb as QZ,Fb as BZ,Hb as l0,Ib as qZ,Kb as u0,Lb as iZ,Ra as dZ,Ub as p0,Vb as c0,Wb as d0,Xb as aZ,ab as $Z,cb as ZZ,db as X$,dc as d2,eb as j$,ec as SZ,fb as zZ,fc as bZ,gc as W$,hb as A1,hc as RZ,ic as DZ,lc as s0,mc as r0,na as s2,nc as t0,oa as u$,pb as GZ,qa as r1,qb as Y$,rb as JZ,ua as I0,ub as XZ,vb as jZ,wb as I1,xb as f0,ya as n$,yb as v0,za as o$,zb as h0}from"../index-3r9thx6n.js";import{Mc as L0,Nc as P0,Pc as M0,Tc as C0,xc as K0}from"../index-fd3f8vw2.js";import{$e as z$,Be as i$,Ce as a$,De as CZ,Ee as t1,Jd as O1,Kd as x1,Ke as w1,Ld as w0,Re as j0,Sd as M$,Se as i2,Td as p$,Te as e1,Ud as c$,Ue as $$,Vd as d$,Ve as s$,Xe as Z$,Ye as r$,_e as t$,af as G$,be as pZ,bf as e$,cf as J$,hd as s1,ie as cZ,ke as y0,le as X0,pd as m$,qd as l$,ve as t2,we as H1}from"../index-3p1tc2e2.js";import"../index-dcyhv7eh.js";import{sf as fZ,tf as m0}from"../index-361xxyg2.js";import"../index-29ztc0ay.js";import{Ef as k0,Gf as w2}from"../index-mf3dqvbn.js";import"../index-95z5dpe1.js";import{cg as vZ}from"../index-dkhy2peg.js";import{gg as F1,hg as D0}from"../index-mkda7acs.js";import{AsyncLocalStorage as e4}from"node:async_hooks";import{randomUUID as $5}from"node:crypto";class L2 extends Error{kind;providerID;sessionID;requestKind;constructor($){super($.message??`${$.providerID} ${$.requestKind} request refused (${$.kind})`);this.name="OpenCode2AuthError",this.kind=$.kind,this.providerID=$.providerID,this.sessionID=$.sessionID,this.requestKind=$.requestKind}}function k2($){return`common-auth-placeholder.${$}`}function _$($){let Z=k2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function J1($,Z){if($?.type!=="oauth")return!1;let G=Z===void 0?void 0:k2(Z),J=(Y)=>G===void 0?Y.startsWith("common-auth-placeholder."):Y===G;return J($.access)&&J($.refresh)}var E$="No browser sign-in: this connects the plugin to the accounts in its vault.";async function m1($,Z){let G=Z.now??Date.now,{integrationID:J}=Z,Y=(H)=>_$({integrationID:J,methodID:H,now:G()}),j=async(H,V)=>{return await Z.onLogin(H,{integrationID:J,methodID:V}),Y(V)},K=(H)=>async(V)=>{let L=H.method.id,U=await H.authorize(V),T={url:U.url,instructions:U.instructions,...U.expiresAt===void 0?{}:{expiresAt:U.expiresAt}};if(U.mode==="auto")return{...T,mode:"auto",callback:U.callback.then((A)=>j(A,L))};let S=U.callback;return{...T,mode:"code",callback:async(A)=>j(await S(A),L)}};return $.integration.transform((H)=>{let V=Z.label===void 0?{}:{label:()=>Z.label};for(let T of Z.methods)H.method.update({integrationID:J,method:T.method,authorize:K(T),refresh:async(S)=>{if(!J1(S,J))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return Y(S.methodID)},...V});let L=Z.vault;if(L===void 0)return;let U=L.method.id;H.method.update({integrationID:J,method:L.method,authorize:async()=>({url:"",instructions:L.instructions??E$,mode:"auto",callback:Promise.resolve().then(()=>L.activate({integrationID:J,methodID:U})).then(()=>Y(U))}),refresh:async(T)=>{if(!J1(T,J)||T.methodID!==U)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return Y(U)},...V})})}function J4($){let Z=[],G;for(let J of $.split(/\r?\n/))if(J.startsWith("data:"))Z.push(J.slice(5).replace(/^ /,""));else if(J.startsWith("event:"))G=J.slice(6).trim();if(Z.length===0)return;return G===void 0?{data:Z.join(`
1
+ import{c as z4}from"../index-ct658ahq.js";import{$ as Z4,A as o0,B as s0,C as O1,D as VZ,E as UZ,F as _0,G as E0,H as $4,I as lZ,J as uZ,M as Z0,N as z0,O as G0,W as Q0,X as B0,d as m0,e as X0,f as h1,fa as R$,g as e2,ga as D$,h as S1,i as I1,ja as G4,k as S$,l as b$,m as A$,n as C1,o as gZ,p as H$,q as mZ,r as tZ,s as eZ,t as R1,u as _Z,v as EZ,w as b1,x as n0,y as T$,z as a0}from"../index-44b5y56b.js";import{Ab as B1,Cb as QZ,Db as E1,Eb as BZ,Fb as WZ,Hb as u0,Ib as SZ,Kb as p0,Lb as nZ,Ra as iZ,Ub as c0,Vb as d0,Wb as i0,Xb as aZ,ab as ZZ,cb as zZ,db as j$,dc as c2,eb as Y$,ec as bZ,fb as GZ,fc as RZ,gc as V$,hb as q1,hc as DZ,ic as kZ,lc as r0,mc as t0,na as s2,nc as e0,oa as p$,pb as JZ,qa as t1,qb as Q$,rb as XZ,ua as f0,ub as jZ,vb as YZ,wb as f1,xb as v0,ya as o$,yb as h0,za as s$,zb as g0}from"../index-vpjmexm5.js";import{Mc as P0,Nc as M0,Pc as C0,Tc as T0,xc as L0}from"../index-4gkfz4zp.js";import{$e as G$,Be as n$,Ce as a$,De as TZ,Ee as e1,Jd as x1,Kd as A1,Ke as y1,Ld as y0,Re as Y0,Sd as C$,Se as d2,Td as c$,Te as $$,Ud as d$,Ue as Z$,Vd as i$,Ve as r$,Xe as z$,Ye as t$,_e as e$,af as J$,be as cZ,bf as $Z,cf as X$,hd as r1,ie as dZ,ke as I0,le as j0,pd as l$,qd as u$,ve as t2,we as F1}from"../index-7fdcb97f.js";import"../index-8xgeh2zt.js";import{sf as vZ,tf as l0}from"../index-7xqb1m44.js";import"../index-r0kv780p.js";import{Ef as w0,Gf as I2}from"../index-2py81t0v.js";import"../index-hq4gdm6f.js";import{cg as hZ}from"../index-dkhy2peg.js";import{gg as K1,hg as k0}from"../index-mkda7acs.js";import{AsyncLocalStorage as $5}from"node:async_hooks";import{randomUUID as Z5}from"node:crypto";class L2 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 y2($){return`common-auth-placeholder.${$}`}function E$($){let Z=y2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function X1($,Z){if($?.type!=="oauth")return!1;let G=Z===void 0?void 0:y2(Z),J=(Q)=>G===void 0?Q.startsWith("common-auth-placeholder."):Q===G;return J($.access)&&J($.refresh)}var O$="No browser sign-in: this connects the plugin to the accounts in its vault.";async function l1($,Z){let G=Z.now??Date.now,{integrationID:J}=Z,Q=(N)=>E$({integrationID:J,methodID:N,now:G()}),Y=async(N,V)=>{return await Z.onLogin(N,{integrationID:J,methodID:V}),Q(V)},K=(N)=>async(V)=>{let L=N.method.id,U=await N.authorize(V),_={url:U.url,instructions:U.instructions,...U.expiresAt===void 0?{}:{expiresAt:U.expiresAt}};if(U.mode==="auto")return{..._,mode:"auto",callback:U.callback.then((A)=>Y(A,L))};let q=U.callback;return{..._,mode:"code",callback:async(A)=>Y(await q(A),L)}};return $.integration.transform((N)=>{let V=Z.label===void 0?{}:{label:()=>Z.label};for(let _ of Z.methods)N.method.update({integrationID:J,method:_.method,authorize:K(_),refresh:async(q)=>{if(!X1(q,J))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return Q(q.methodID)},...V});let L=Z.vault;if(L===void 0)return;let U=L.method.id;N.method.update({integrationID:J,method:L.method,authorize:async()=>({url:"",instructions:L.instructions??O$,mode:"auto",callback:Promise.resolve().then(()=>L.activate({integrationID:J,methodID:U})).then(()=>Q(U))}),refresh:async(_)=>{if(!X1(_,J)||_.methodID!==U)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return Q(U)},...V})})}function X4($){let Z=[],G;for(let J of $.split(/\r?\n/))if(J.startsWith("data:"))Z.push(J.slice(5).replace(/^ /,""));else if(J.startsWith("event:"))G=J.slice(6).trim();if(Z.length===0)return;return G===void 0?{data:Z.join(`
2
2
  `)}:{event:G,data:Z.join(`
3
- `)}}function l1($,Z){let G=new TextDecoder,J="",Y=(K)=>{let H=J4(K);if(!H)return;try{$(H)}catch(V){Z(V)}},j=()=>{for(;;){let K=/\r?\n\r?\n/.exec(J);if(!K)return;let H=J.slice(0,K.index);J=J.slice(K.index+K[0].length),Y(H)}};return new TransformStream({transform(K,H){H.enqueue(K),J+=G.decode(K,{stream:!0}),j()},flush(){if(J+=G.decode(),j(),J.trim()!=="")Y(J);J=""}})}var n2=512,c2=3621000,a2="x-common-auth-attempt",p2=($,Z)=>JSON.stringify([$,Z]),b2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function X4($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function j4($,Z){let G=$.getReader();return new ReadableStream({async pull(J){let Y;try{Y=await G.read()}catch(j){Z({reason:"failed",message:j instanceof Error?j.message:String(j)}),J.error(j);return}if(Y.done)Z(),J.close();else J.enqueue(Y.value)},async cancel(J){Z({reason:"cancelled",...J===void 0?{}:{message:String(J)}}),await G.cancel(J)}})}function L1($,Z){for(let[G,J]of Object.entries(Z)){let Y=G.toLowerCase();for(let j of Object.keys($))if(j.toLowerCase()===Y)delete $[j];if(J!==null)$[G]=J}}function Y4($,Z){for(let[G,J]of Object.entries(Z))if(J===null)$.delete(G);else $.set(G,J)}async function u1($,Z,G={}){let{providerID:J}=Z,Y=G.gateOnPlaceholder,j=(z)=>Y===void 0||Y.credential(z)===k2(J),K=G.logger,H=Math.max(1,G.maxRecords??n2),V=G.hostRetryLimit??10,L=[...G.hostCredentials??[k2(J)],...Y?[k2(J)]:[]].filter((z)=>z!==""),U=new Map,T=new WeakMap,S=new Map,A=0,f=new Set,Z2=new Map,b=new Map,D=(z)=>{let Q=b.get(z);return Q?.ownedSeen===!0&&Q.foreignSeen},H2=(z,Q)=>{Z2.set(z,Q);let B=b.get(z)??{ownedSeen:!1,foreignSeen:!1};if(Q)B.ownedSeen=!0;else B.foreignSeen=!0;b.set(z,B)},X2=(z,Q)=>{let B=Y?.refuseMisplaced,F=B?[...Q].filter(([,E])=>E.includes(k2(J))):[],W=j(Q)&&(!B||F.length>0);if(B){if(F.length>0&&(F.length!==1||!W))throw H2(z.sessionID,!1),new L2({kind:"placement-refused",providerID:J,sessionID:z.sessionID,requestKind:z.kind,message:B(F[0]?.[0]??"")})}return H2(z.sessionID,W),W},I=!1,p=!1,I2=new Map,M2=0,t=!1,w=new Map,u=(z,Q)=>{try{K?.warn(z,Q)}catch{}},o=(z)=>z instanceof Error?z.message:String(z),m=(z)=>z.excluded.clear(),E2=(z)=>z.excluded.size===0?{}:{excluded:[...z.excluded]},A2=(z,Q,B)=>{if(!G.enforceRequestExclusion||z===void 0||!B.excluded.has(z))return!1;return u("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:Q.sessionID,kind:Q.kind,phase:Q.phase,accountId:z}),!0},R2=new Map,F2=(z,Q)=>{let B=(R2.get(z)??Promise.resolve()).then(Q),F=B.then(()=>{},()=>{});return R2.set(z,F),F.then(()=>{if(R2.get(z)===F)R2.delete(z)}),B},$1=(z,Q)=>{let B=R2.get(z);return B?B.then(()=>$1(z,Q)):Q()},V2=async(z)=>{try{await Z.dropChoice?.({...z.input,accountId:z.accountId})}catch(Q){u("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:z.input.sessionID,error:o(Q)})}},z2=async(z)=>{try{await Z.dropSameAccountRetry?.({...z.input,accountId:z.accountId})}catch(Q){u("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:z.input.sessionID,error:o(Q)})}},g2=async(z)=>{if(z.next)await V2(z.next);if(z.sameAccount)await z2(z.sameAccount)},X=(z)=>{let Q=S.get(z);if(S.delete(z),Q)F2(Q.sessionID,()=>g2(Q))},N=async(z,Q)=>{let B=I2.get(z);if(!B||B.size===0)return;await Promise.all([...B].map(async(F)=>{try{await F(Q)}catch(W){u("opencode2 auth listener threw; the request is unaffected",{event:z,error:o(W)})}}))},M=async(z,Q)=>{try{await Z.onAttemptEnd?.(z,Q)}catch(B){u("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:z.attemptId,error:o(B)})}},P=(z,Q)=>{if(z.ended||!z.attempt)return;let B={...z.status===void 0?{}:{status:z.status},outputStarted:z.outputStarted,...z.limit?{limit:z.limit.signal}:{},...Q?{error:Q}:{}};if(Q)z.endError=Q;if(Q?.reason==="cancelled"||!Q&&!z.limit&&(z.status===void 0||z.status<400))m(z.request);z.ended=M(z.attempt,B)},R=(z,Q)=>P(z,{reason:"abandoned",message:Q}),x=(z)=>[...U.values()].filter((Q)=>Q.key===z),q=(z)=>x(z).at(-1),y=(z)=>{if(U.delete(z.id),S.get(z.key)?.attemptId===z.id||!x(z.key).length)X(z.key)},v=(z)=>{U.set(z.id,z);while(U.size>H){let Q=U.values().next().value;if(Q===void 0)break;R(Q,"dropped to keep the record bound"),y(Q)}},h=(z)=>z.accountId===void 0?void 0:{...z.scope,accountId:z.accountId},k=(z,Q)=>new L2({kind:"no-account",providerID:J,sessionID:z.sessionID,requestKind:z.kind,...Q===void 0?{}:{message:Q}}),a=(z)=>{w.get(z)?.clear(),w.delete(z)},G2=async(z,Q)=>{let B=()=>k(z,`${J} ${z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(t)throw B();let F=w.get(z.sessionID);if(!F)F=new Set,w.set(z.sessionID,F);let W={};F.add(W);let E=()=>{if(!F.has(W))throw B()};try{return await Q(E)}finally{if(F.delete(W),F.size===0&&w.get(z.sessionID)===F)w.delete(z.sessionID)}},_=(z,Q)=>{for(let[B,F]of Q)if(L.some((W)=>F.includes(W)))throw new L2({kind:"host-credential-on-wire",providerID:J,sessionID:z.sessionID,requestKind:z.kind,message:`${J} ${z.kind} request still carries the host's placeholder credential in ${B}; the adapter's account headers must replace it`})},g=(z)=>{for(let Q of x(z))if(Q.ended||!Q.attempt)y(Q);else if(Q.transport==="ws"||Q.judged)R(Q,"a newer attempt of its session and kind began"),y(Q)},s=async(z,Q,B,F)=>{let W=p2(z.sessionID,z.kind),{input:E,accountId:C,sameAccountRetry:O,request:i}=await $1(z.sessionID,async()=>{B();let Y2=S.get(W);S.delete(W);let G1=x(W);if(Y2&&G1.some(($2)=>$2.id!==Y2.attemptId&&$2.attempt&&!$2.ended))u("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:z.sessionID,kind:z.kind});if(!Y2){let $2=new Set(G1.filter((_2)=>_2.attempt&&!_2.ended).map((_2)=>_2.request));for(let _2 of G1)if(!$2.has(_2.request))m(_2.request)}let K2=Y2?.request??{excluded:new Set},J2=Y2?.accountId??q(W)?.accountId;g(W);let r=Y2?.next,Q2=Y2?.sameAccount,d=Q2!==void 0&&Q2.input.modelID===z.modelID&&Q2.input.agent===z.agent,T2=r!==void 0&&r.input.modelID===z.modelID&&r.input.agent===z.agent,D2=Y2?.wake,n={...z,phase:"request",...E2(K2),...J2===void 0?{}:{previousAccountId:J2},...Y2?.rerouteFrom?{rerouteFrom:Y2.rerouteFrom}:{},...D2===void 0?{}:{wake:D2,hostAttempt:r?.input.hostAttempt}};if(r&&(!T2||D2!==void 0))await F2(z.sessionID,()=>V2(r)),B();if(Q2&&!d)await F2(z.sessionID,()=>z2(Q2)),B();if(Q2?.continuation&&(!d||D(z.sessionID))){if(d)await F2(z.sessionID,()=>z2(Q2));throw k(z)}let u2=d?Q2.accountId:T2&&D2===void 0?r.accountId:await Z.chooseAccount(n),h2=typeof u2==="string"?u2:void 0;if(A2(h2,n,K2)){let $2=h2;if(d&&Q2)await F2(z.sessionID,()=>z2(Q2));else if($2!==void 0)await F2(z.sessionID,()=>V2(T2&&r?r:{accountId:$2,input:n}));h2=void 0,B()}return{input:n,accountId:h2,sameAccountRetry:d,request:K2}});B();let W2={},q2;if(C!==void 0){let Y2=await Z.accountHeaders({...z,accountId:C});if(B(),X4(Y2))W2=Y2.headers,q2=Y2.attempt;else W2=Y2}let z1=`attempt-${++M2}`,S2={id:z1,key:W,scope:z,request:i,accountId:C,headers:W2,attempt:C===void 0?void 0:{...z,accountId:C,attemptId:z1,transport:F,data:q2},...F===void 0?{}:{transport:F},outputStarted:!1,sameAccountRetry:O};if(v(S2),S2.attempt)N("select",{...z,accountId:S2.attempt.accountId,hook:Q,...E.previousAccountId===void 0?{}:{previousAccountId:E.previousAccountId},...E.rerouteFrom===void 0?{}:{rerouteFrom:E.rerouteFrom},handle:S2.attempt});return S2},O2=async(z,Q,B,F,W)=>{let E=p2(z.sessionID,z.kind),C=F===void 0?void 0:U.get(F);if(C?.key!==E)C=void 0;if(!C){if(C=q(E),x(E).filter((i)=>i.transport===void 0&&!i.ended).length>1&&!p)p=!0,u("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:z.sessionID,kind:z.kind})}if(!C||C.transport!==void 0||C.ended)C=await s(z,Q,W,B);else if(C.transport=B,C.attempt)C.attempt.transport=B;if(B==="ws"){for(let O of x(E))if(O!==C&&O.transport==="ws")R(O,"a newer attempt of its session and kind went out over WebSocket")}return C},c=async(z,Q)=>{try{return await Q()}catch(B){throw P(z,{reason:"failed",message:o(B)}),B}},e=(z,Q)=>{let B=x(p2(z,Q)).filter((F)=>F.transport==="ws").at(-1);return B?.attempt!==void 0&&!B.ended?B:void 0},U2=(z,Q,B)=>{let F=h(z);if(!F||!z.attempt||z.limit)return;z.limit={signal:Q,delivered:N("limit",{...F,via:B,limit:Q,outputStarted:z.outputStarted,handle:z.attempt})}},f2=(z,Q,B,F)=>{let W=h(z);if(!W||!z.attempt)return;N("quota",{...W,transport:Q,...F===void 0?{}:{status:F},quota:B,handle:z.attempt})},Z1=(z,Q,B,F)=>{let W=z.attempt;if(!W)return;let E=Z.inspectEvent?.(F===void 0?{transport:Q,data:B,attempt:W}:{transport:Q,data:B,event:F,attempt:W});if(!E)return;if(E.quota!==void 0)f2(z,Q,E.quota);if(E.outputStarted)z.outputStarted=!0;if(E.hostRetry==="veto")z.hostRetry="veto";if(E.limit)U2(z,E.limit,Q);if(E.error!==void 0)P(z,{reason:"failed",message:E.error});else if(E.done)P(z)},C2=(z,Q)=>{let B=z.attempt;if(!B||Q.accountId===z.accountId)return;if(B.reboundFrom??=B.accountId,B.accountId=Q.accountId,"data"in Q)B.data=Q.data;z.accountId=Q.accountId},m2=(z)=>!z.attempt||z.endError!==void 0||z.status!==void 0&&z.status>=400,l2=(z)=>{let Q=[...U.values()].filter((O)=>O.scope.sessionID===z),B=Q.filter((O)=>O.limit&&!O.rerouted).at(-1);if(B)return B;let F=Q.filter((O)=>O.scope.kind==="primary"),W=F.length>0?F:Q;if(W.length<=1)return W[0];let E=W.filter((O)=>!O.judged&&m2(O)).at(-1);if(E)return E;let C=W.filter((O)=>O.attempt&&!O.ended);if(C.length>1)return"ambiguous";return C[0]??W.at(-1)},j2={providerID:J},N2=[];N2.push(await $.session.hook("model.request",(z)=>{if(Y)return;return G2(b2(z),async(Q)=>{let B=await s(b2(z),"model.request",Q);if(Q(),B.accountId===void 0)throw k(B.scope);L1(z.headers,{...B.headers,[a2]:B.id})})},j2)),N2.push(await $.session.hook("http.request",(z)=>{if(Y){if(!X2(b2(z),z.request.headers))return}return G2(b2(z),async(Q)=>{let B=z.request.headers.get(a2)??void 0,F=Y?await s(b2(z),"http.request",Q,"http"):await O2(b2(z),"http.request","http",B,Q);Q();let W=h(F),E=F.attempt;if(!W||!E)throw k(F.scope);await c(F,async()=>{let C=z.request;if(Z.rewriteRequest){if(B!==void 0){let W2=new Headers(C.headers);W2.delete(a2),C=new Request(C,{headers:W2})}C=await Z.rewriteRequest({...W,request:C,attempt:E})??C,Q()}let O=new Headers(C.headers);O.delete(a2),Y4(O,F.headers),_(F.scope,O.entries());let i=new Request(C,{headers:O});T.set(i,F),z.request=i})})},j2)),N2.push(await $.session.hook("http.response",async(z)=>{let Q=T.get(z.request);if(!Q){if(Y)return;if(!I)I=!0,u("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:z.sessionID,kind:z.kind});return}let B=z.response;if(Z.answeredBy&&Q.attempt){let O=Q.attempt,i=await c(Q,async()=>Z.answeredBy?.({request:z.request,response:B,attempt:O}));if(i)C2(Q,i)}let F=h(Q),W=Q.attempt;if(!F||!W)return;Q.status=B.status;let E=Z.quotaFromHeaders?.(B.headers,B.status,W);if(E!==void 0)f2(Q,"http",E,B.status);if(!B.ok&&Z.limitFromResponse){let O=await Z.limitFromResponse({status:B.status,headers:B.headers,body:()=>B.clone().text(),attempt:W});if(O)U2(Q,O,"http")}if(!B.ok||!B.body)P(Q);let C=B;if(B.body&&(Z.inspectEvent||Z.onAttemptEnd)){let O=B.body;if(Z.inspectEvent)O=O.pipeThrough(l1((i)=>Z1(Q,"http",i.data,i.event),(i)=>u("opencode2 auth event inspection threw",{error:o(i)})));C=new Response(j4(O,(i)=>{if(i?.reason==="failed")Q.httpReadFailed=!0;P(Q,i)}),{status:B.status,statusText:B.statusText,headers:B.headers})}if(Z.rewriteResponse)C=await Z.rewriteResponse({...F,request:z.request,response:C,attempt:W})??C;if(Z.responseRetry){if(await Z.responseRetry({...F,request:z.request,response:C,attempt:W})==="veto")Q.hostRetry="veto"}if(C!==B)z.response=C},j2)),N2.push(await $.session.hook("experimental.ws.handshake",(z)=>{if(Y){let Q=p2(z.sessionID,z.kind);if(f.delete(Q),!X2(b2(z),new Headers(z.headers)))return}return G2(b2(z),async(Q)=>{let B;for(let C of Object.keys(z.headers)){if(C.toLowerCase()!==a2)continue;B??=z.headers[C],delete z.headers[C]}let F=Y?await s(b2(z),"experimental.ws.handshake",Q,"ws"):await O2(b2(z),"experimental.ws.handshake","ws",B,Q);Q();let W=h(F),E=F.attempt;if(!W||!E)throw k(F.scope);await c(F,async()=>{if(!Y?.refuseMisplaced)L1(z.headers,F.headers);let C=Z.rewriteHandshakeURL?.({...W,url:z.url,attempt:E});if(C!==void 0)z.url=C;if(Y?.refuseMisplaced)L1(z.headers,F.headers);if(_(F.scope,Object.entries(z.headers)),Y)f.add(F.key)})})},j2));let y2=Z.rewriteWebSocketFrame?.bind(Z);if(y2)N2.push(await $.session.hook("experimental.ws.send",async(z)=>{let Q=b2(z);if(Y&&!f.has(p2(Q.sessionID,Q.kind)))return;let B=e(Q.sessionID,Q.kind),F=await y2({...Q,attempt:B?.attempt,frame:z.frame});if(F!==void 0)z.frame=F},j2));N2.push(await $.session.hook("experimental.ws.receive",(z)=>{if(Y&&!f.has(p2(z.sessionID,z.kind)))return;let Q=e(z.sessionID,z.kind);if(!Q)return;try{Z1(Q,"ws",z.frame)}catch(B){u("opencode2 auth frame inspection threw",{error:o(B)})}},j2)),N2.push(await $.session.hook("retry",async(z)=>{if(Y&&Z2.get(z.sessionID)!==!0)return;let Q=z.decision,B=()=>N("retry",{sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:Q,decision:Q});if(D(z.sessionID)&&!Z.retrySameAccount){await B();return}let F=l2(z.sessionID);if(!F)return;if(F==="ambiguous"){await N("retry",{sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:Q,decision:Q});return}let W=F,E=()=>W.hostRetry==="veto";await G2(W.scope,async(C)=>{let O=C,i=Z.retrySameAccount?.bind(Z),W2=W.attempt,q2=W.outputStarted;if(q2&&W.httpReadFailed&&i&&W2&&!D(z.sessionID)){if(!W.limit){let K2=Z.limitFromError?.(z.error,W2);if(K2)U2(W,K2,"error")}if(W.ended)await W.ended;if(W.limit)await W.limit.delivered;O()}let z1=()=>W.httpReadFailed===!0&&z.error.type==="provider.transport"&&Q.retry&&V-z.attempt>=1&&!W.limit&&!(W.status!==void 0&&W.status>=400)&&!(z.error.status!==void 0&&z.error.status>=400)&&!W2?.reboundFrom&&!E()&&!D(z.sessionID);if(i&&W2&&(!q2||z1())&&(!E()||D(z.sessionID))&&!W.sameAccountRetry){if(W.ended)await W.ended;if(W.limit)await W.limit.delivered;let K2=await F2(W.scope.sessionID,async()=>{O();let J2=W2.accountId,r=()=>U.has(W.id)&&W.accountId===J2&&l2(z.sessionID)===W&&W.outputStarted===q2&&(!q2||z1())&&(!E()||D(z.sessionID))&&(!Y||Z2.get(z.sessionID)===!0);if(!r()||W.sameAccountRetry)return!1;W.sameAccountRetry=!0;let Q2={...W.scope,accountId:J2,error:z.error,attempt:z.attempt,...W.limit?{limit:W.limit.signal}:{},...q2?{continuation:"interrupted-read"}:{}},d;try{d=await i(Q2)}catch(n){u("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:z.sessionID,error:o(n)})}if(!d)return O(),!1;let T2={accountId:d.accountId,input:Q2,...q2?{continuation:!0}:{}};try{O()}catch(n){throw await z2(T2),n}if(!r()||d.accountId!==J2)return await z2(T2),!1;let D2=S.get(W.key);if(S.delete(W.key),D2)await g2(D2);try{O()}catch(n){throw await z2(T2),n}if(!r())return await z2(T2),!1;return S.set(W.key,{request:W.request,attemptId:W.id,sessionID:W.scope.sessionID,order:++A,accountId:J2,sameAccount:T2}),W.judged=!0,z.decision=q2?Q:{retry:!0,delay:0},!0});if(O(),K2){await N("retry",{sessionID:z.sessionID,accountId:W.accountId,kind:W.scope.kind,attempt:z.attempt,reason:q2?"continue-same-account":"same-account",hostDecision:Q,decision:z.decision,handle:W.attempt});return}}if(D(z.sessionID)){await B();return}W.judged=!0;let S2=W.attempt;if(S2&&!W.outputStarted){if(!W.limit){let K2=Z.limitFromError?.(z.error,S2);if(K2)U2(W,K2,"error")}if(W.ended)await W.ended;if(W.limit)await W.limit.delivered}O();let{decision:Y2,reason:G1}=await F2(W.scope.sessionID,async()=>{if(O(),D(z.sessionID))return{decision:Q,reason:"host-decides"};let K2=S.get(W.key);if(S.delete(W.key),K2)await g2(K2);if(O(),D(z.sessionID))return{decision:Q,reason:"host-decides"};let J2=Q,r,Q2,d,T2;if(W.accountId===void 0||!S2)J2={retry:!1},r="no-account";else if(W.outputStarted)J2={retry:!1},r="output-started";else if(E())J2={retry:!1},r="adapter-veto";else if(W.limit){let D2={accountId:W.accountId,limit:W.limit.signal},n,u2={...W.scope,phase:"retry",...E2(W.request),hostAttempt:z.attempt,previousAccountId:W.accountId,rerouteFrom:D2};try{n=await Z.chooseAccount(u2)}catch(g1){u("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:W.scope.sessionID,error:o(g1)})}let h2=typeof n==="string"?n:typeof n==="object"&&("hold"in n)?W.accountId:void 0;if(A2(h2,u2,W.request)){if(h2!==void 0)await V2({accountId:h2,input:u2});n=void 0}let $2=typeof n==="object"&&"hold"in n?n.hold:void 0,_2=typeof n==="object"&&"waitThenReselect"in n?n.waitThenReselect:void 0,G4=typeof n==="object"&&"hostRetry"in n?n.hostRetry:void 0,K1=typeof n==="string"?n:$2?W.accountId:void 0;if(K1!==void 0)d={accountId:K1,input:u2};try{O()}catch(g1){if(d)await V2(d);throw g1}if(D(z.sessionID)){if(d)await V2(d);return{decision:Q,reason:"host-decides"}}if(E()||G4==="veto"){if(d)await V2(d);if(d=void 0,O(),D(z.sessionID))return{decision:Q,reason:"host-decides"};W.hostRetry="veto",J2={retry:!1},r="adapter-veto"}else if(!(V-z.attempt>=1)){if(d)await V2(d);d=void 0,r="host-decides-last-account"}else if(_2&&Number.isFinite(_2.delayMs)&&_2.delayMs>=0&&_2.delayMs<=c2)J2={retry:!0,delay:Math.ceil(_2.delayMs)},r="wait-then-reselect";else if($2&&Number.isFinite($2.delayMs)&&$2.delayMs>=0&&$2.delayMs<=c2){if(J2={retry:!0,delay:Math.ceil($2.delayMs)},$2.target!==void 0)T2={target:$2.target,...$2.checkpoint===void 0?{}:{checkpoint:$2.checkpoint},...$2.kind===void 0?{}:{kind:$2.kind}};r="hold"}else if(!$2&&K1!==void 0&&K1!==W.accountId)W.rerouted=!0,W.request.excluded.add(W.accountId),Q2=D2,J2={retry:!0,delay:0},r="reroute";else{if($2&&d)await V2(d),d=void 0;r="host-decides-last-account"}}else r="host-decides";if(z.decision=J2,J2.retry&&W.accountId!==void 0&&U.has(W.id))S.set(W.key,{request:W.request,attemptId:W.id,sessionID:W.scope.sessionID,order:++A,accountId:W.accountId,...Q2===void 0?{}:{rerouteFrom:Q2},...d===void 0?{}:{next:d},...T2===void 0?{}:{wake:T2}});else if(d)await V2(d);if(!J2.retry)m(W.request);return{decision:J2,reason:r}});O(),await N("retry",{sessionID:z.sessionID,...W.accountId===void 0?{}:{accountId:W.accountId},kind:W.scope.kind,attempt:z.attempt,reason:G1,hostDecision:Q,decision:Y2,...S2===void 0?{}:{handle:S2}})})},j2));let v2=(z)=>{if(a(z),Z2.delete(z),!b.get(z)?.foreignSeen)b.delete(z);for(let Q of f)if(JSON.parse(Q)[0]===z)f.delete(Q);for(let Q of[...U.values()]){if(Q.scope.sessionID!==z)continue;R(Q,"its session was forgotten"),m(Q.request),U.delete(Q.id)}for(let[Q,B]of S)if(B.sessionID===z)X(Q)},B2=new AbortController,l=$.event;if(l)(async()=>{try{for await(let z of l.subscribe({signal:B2.signal}))if(z.type==="session.deleted")v2(z.data.sessionID);else if(z.type==="session.status"&&z.data.status.type==="idle"){let Q=z.data.sessionID,B=++A;F2(Q,async()=>{for(let[F,W]of S)if(W.sessionID===Q&&W.order<B)S.delete(F),m(W.request),await g2(W)})}}catch(z){if(!B2.signal.aborted)u("opencode2 auth stopped listening for session deletion",{error:o(z)})}})();return{on(z,Q){let B=I2.get(z);if(!B)B=new Set,I2.set(z,B);let F=Q;return B.add(F),()=>{B.delete(F)}},accountFor(z,Q){return q(p2(z,Q))?.accountId},forgetSession:v2,get size(){return U.size},async dispose(){if(t)return;t=!0;for(let z of w.keys())a(z);B2.abort();for(let z of U.values())R(z,"the installation was disposed");U.clear();for(let z of S.keys())X(z);f.clear(),Z2.clear(),b.clear(),I2.clear(),await Promise.all(R2.values()),await Promise.all(N2.map(async(z)=>{try{await z.dispose()}catch(Q){u("opencode2 auth hook did not dispose cleanly",{error:o(Q)})}}))}}}import{randomUUID as g$}from"node:crypto";import{createHash as Q4}from"node:crypto";var B4=1024,W4=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),O$=($)=>x$($,"user"),V4=($)=>W4($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function U4($){return Q4("sha256").update(JSON.stringify($)).digest("hex")}class o2{runtime;maxSessions;#$=new Map;constructor($,Z=B4){this.runtime=$;this.maxSessions=Z}advance($,Z,G=this.runtime){let J=this.#$.get($),Y=Array.isArray(Z.input)?Z.input:[],j=Y.filter(O$),K=Y.findLastIndex(O$),H=K<0?void 0:U4(Y[K]),V=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,L,U,T;if(V)L=j.length>0,U=H??J?.fingerprint,T=J?.userCount===void 0?void 0:J.userCount+j.length;else{U=H,T=j.length;let A=K>=0&&K>Y.findLastIndex(V4),f=J!==void 0&&!J.completed&&J.fingerprint===U&&J.userCount===T;L=A&&!f}let S=L||!J?{turnID:(G?.uuid??d2)(),turnStartedAt:(G?.now??Date.now)()}:{turnID:J.turnID,turnStartedAt:J.turnStartedAt};return this.#Z($,{...S,completed:!1,fingerprint:U,userCount:T}),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 G=this.#$.keys().next().value;if(G===void 0)break;this.#$.delete(G)}}}function p1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var A$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function N4(){let $=globalThis;return $[A$]??=crypto.randomUUID(),$[A$]}class X1{runtime;store;sessions;frameTurns;installationID;constructor($,Z,G){this.runtime=$;this.store=G;this.installationID=Z??N4(),this.sessions=G?.sessions??new Map,this.frameTurns=G?.frameTurns??new o2}get($){let Z=this.runtime?.uuid??d2;if(this.store)return this.store.get($,Z);let G=this.sessions.get($);if(!G){let J=Z();G={threadID:J,turnID:Z(),windowID:`${J}:0`},this.sessions.set($,G)}return G}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(P1(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var c1={version:q$,"user-agent":S$,originator:"codex_exec"};var H4=1024,F4=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,C1=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),D$=($)=>C1($)&&($.type==="message"||("role"in $))&&$.role==="user",k$=($)=>C1($)&&$.type==="configuration_update";class d1{http;#$=new Map;constructor($=new X1){this.http=$}apply($,Z,G){if(Z.kind!=="primary")return!1;let J=typeof $.model==="string"?$.model:"";if(!b$.has(J))return!1;if(F4.test(J))return!1;let Y=C1($.reasoning)?$.reasoning:void 0,j=typeof Y?.effort==="string"?Y.effort:void 0;if(!j)return!1;let K=this.#$.get(Z.sessionID);if(K===void 0)return this.#Z(Z.sessionID,j),!1;if(j===K)return!1;let H=Array.isArray($.input)?$.input:void 0;if(!H||H.length===0)return!1;let V=H.findLastIndex(D$);if(V<0){if(G==="http")return!1;return $.reasoning={...Y,effort:K},!0}if($.reasoning={...Y,effort:K},!k$(H[V-1]))H.splice(V,0,{type:"configuration_update",reasoning:{effort:j}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>H4){let G=this.#$.keys().next().value;if(G===void 0)break;this.#$.delete(G)}}}function P1($){try{let Z=JSON.parse($);return C1(Z)?Z:void 0}catch{return}}async function w$($,Z,G,J,Y=G.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let j=await $.clone().text(),K=P1(j);if(K)delete K.max_output_tokens;let H=new Headers($.headers),V=M1({rewriteLite:R$,init:{body:K?JSON.stringify(K):$.body===null?void 0:j},headers:H,metadata:Y.get(Z.sessionID),installationID:Y.installationID,runtime:Y.runtime,websocket:!1,responsesLite:J,applyEffort:(L)=>{G.apply(L,Z,"http")}});return new Request($,{headers:H,body:V.init?.body})}function y$($,Z,G,J){let Y=J.sessions.get($.sessionID),j=J.frameTurns.get($.sessionID);if(!Y||!j)return;let K=p1(Y,j),H=new Headers({"content-type":"application/json"});for(let L of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let U=G.get(L);if(U!==null)H.set(L,U)}M1({init:{body:$.bodyText},headers:H,metadata:K,installationID:J.installationID,runtime:J.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let V=new URL(Z);if(V.protocol==="wss:")V.protocol="https:";if(V.protocol==="ws:")V.protocol="http:";return new Request(V,{method:"POST",headers:H,body:$.bodyText})}function K4($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let G=Z.findIndex((J,Y)=>JSON.stringify(J)!==JSON.stringify($[Y]));return G>=0&&k$(Z[G])&&D$(Z[G+1])&&JSON.stringify(Z.slice(G+1))===JSON.stringify($.slice(G))}function I$($,Z,G){let J=P1($);if(J?.type!=="response.create")return;let Y=G.http.advanceFrame(Z.sessionID,J),j=G.http.get(Z.sessionID);delete J.max_output_tokens;let K=M1({rewriteLite:()=>{},init:{body:JSON.stringify(J)},headers:new Headers,metadata:p1(j,Y),installationID:G.http.installationID,runtime:G.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(V)=>{G.apply(V,Z,"ws")}}),H=P1(String(K.init?.body));if(!H)return;if(!K4(J.input,H.input)){if("input"in J)H.input=J.input;else delete H.input;return JSON.stringify(H)}return String(K.init?.body)}function L4($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function i1($,Z){let G=new URL($);if(G.origin!=="https://api.openai.com"&&G.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(G.pathname))return $;let J=new URL(`${L4(Z)}/responses`);if(J.search=G.search,G.protocol==="ws:"||G.protocol==="wss:")J.protocol=J.protocol==="https:"?"wss:":"ws:";return J.href}import{resolve as f$}from"node:path";var P4=1024;class T1{accounts=new Map;limit;constructor($=P4){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let G=this.accounts.keys().next().value;if(G===void 0)break;this.accounts.delete(G)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var v$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),h$=globalThis,a1=h$[v$]??new Map;h$[v$]=a1;function n1($){let Z=JSON.stringify([f$($.configPath),f$($.statePath)]),G=a1.get(Z);if(!G)G=new T1,a1.set(Z,G);return G}var x2="openai",r2=10;var o1=1,M4="request refused: no account with a usable credential",P2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function C4($){let Z=P2($)?$.counters:void 0,G=P2(Z)?Z.resetCredits:void 0,J=P2(G)?G.value:void 0;return typeof J==="number"&&Number.isFinite(J)?J:void 0}function j1($){try{return JSON.parse($)}catch{return}}function Y1($){let Z=O1($);return Z?x1(Z):void 0}var T4=new Set(["usage_limit_reached","rate_limit_exceeded"]);function B1($,Z,G,J){return{reason:$.window,windows:$Z($,Z,J,Z),observedAt:Z,...$.resetAt!==void 0?{resetAt:$.resetAt,resetSource:"provider"}:{},...G!==void 0?{status:G}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function UZ($,Z,G){if($.type!=="response.failed"){let j=E1($,Z),K=typeof $.status==="number"?$.status:void 0;return j?B1(j,Z,K,G):void 0}if(!P2($.response))return;let J=$.response.failed;if(P2(J)&&typeof J.rate_limit_reached_type==="string")return B1({window:J.rate_limit_reached_type},Z,void 0,G);let Y=$.response.error;if(P2(Y)){let j=typeof Y.code==="string"?Y.code:typeof Y.type==="string"?Y.type:void 0;if(j&&T4.has(j)){let K=typeof $.status==="number"?$.status:void 0,H=E1({error:{...Y,type:j},status:K},Z);return B1(H??{window:j},Z,K,G)}}return}function _4($,Z,G){if(!P2($))return;let J=typeof $.type==="string"?$.type:void 0;if(J==="codex.rate_limits")return{quota:{snapshot:d$($),complete:!0}};let Y=UZ($,Z,G);if(Y)return{limit:Y};if(J===void 0||J==="error")return;return WZ(J)?void 0:{outputStarted:!0}}function E4($){let Z=!1;for(let G of $.keys())if(G.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:p$($),complete:c$($)}}function O4($){let Z=$.get("retry-after");if(Z===null)return;let G=Z.trim()?Number(Z):NaN;return Number.isFinite(G)&&G>=0?G*1000:void 0}function NZ($){let Z=new WeakMap,G=new WeakSet,{source:J,pins:Y}=$,j=$.now??Date.now,K=$.log,H=$.vault,V=$.limits,L=g$(),U=new WeakMap,T=new Map,S=(X,N)=>i2(N?H?.routes().find((M)=>M.id===X)?.quota:J.peek().rows.find((M)=>M.id===X)?.quota),A=new d1($.codex),f=new Map,Z2=(X)=>{for(let[N,M]of f)if(M===X)f.delete(N)},b=new Map,D=new Map,H2=(X)=>`${X.sessionID}\x00${X.kind}`,X2=new Map,I=new Map,p=(X)=>{let N=I.get(X);if(N)clearTimeout(N.timer);I.delete(X)},I2=(X,N,M)=>{let P=t({...X,accountId:N});p(P);let R={request:M,sessionID:X.sessionID,expiresAt:performance.now()+5000,timer:setTimeout(()=>{if(I.get(P)===R)p(P)},5000)};if(R.timer.unref(),I.set(P,R),I.size>n2){let x=I.keys().next().value;if(x!==void 0)p(x)}},M2=(X)=>{let N=I.get(X);return p(X),N&&performance.now()<N.expiresAt?N.request:void 0},t=(X)=>`${X.sessionID}\x00${X.kind}\x00${X.accountId}`,w=$.sessionAccounts??new T1,u=new t$,o=(X,N,M)=>{let P=M?[]:VZ(J.peek().rows,X,N,H?.identities()??new Set),R=(H?.routes()??[]).filter((x)=>x.kind==="oauth"&&i$(i2(x.quota),X,N));return[...P.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota,row:x})),...R.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota}))]},m=(X,N,M)=>{let P=s$(X,N,M),R=X.map((v)=>({id:v.id,kind:"oauth",...s1(v.quota)?{quota:v.quota}:{}})),x=X.flatMap((v)=>v.row?[v.row]:[]),q=new Set(X.filter((v)=>!v.row).map((v)=>v.id)),y=V?.marks()??new Map;return{rows:R,now:M,rateLimitMarks:y,refreshBackoff:J.refreshBackoffFor(x),killswitch:P,requestPull:(v)=>q.has(v)?H?.requestReading(v):J.requestReading(v)}},E2=(X,N,M,P,R)=>{let x=z$({...X,rows:X.rows.filter((y)=>!M.has(y.id)),placement:Z$(N),mainId:R});if(x.kind==="block"){K?.debug("pool admission refused the request",{reason:x.block.reason});return}let q=x.order.filter((y)=>!M.has(y));if(P!==void 0&&q.includes(P))return P;return q[0]},A2=(X,N)=>{let M=new Map(X.map((P)=>[P.id,P.quota]));return{requestBytes:o1,reservePercent:(P)=>t1(N,P===e1?void 0:P),resetCredits:(P)=>C4(M.get(P))}},R2=(X,N,M,P,R,x,q,y)=>{let v=A2(N,M),h=G$(X),k=(s,O2)=>A1(q,{sessionId:P,requestBytes:o1,validPinnedAccountIds:X.rows.map((c)=>c.id).filter((c)=>!h.excluded.has(c)),excludeAccountIds:s,quotaCheckedAtByAccount:Object.fromEntries(X.rows.map((c)=>[c.id,h.projections.get(c.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(N.map((c)=>[c.id,c.identity])),select:(c)=>y?{accountId:y,source:"mode-fallback",quotaCheckedAt:h.projections.get(y)?.checkedAt}:e$(X,v,new Set(s),c),persist:O2},(c,e)=>q.set(c,e)),a=[...R],G2=k(a,x);if(!G2)return;let _=G2.accountId,g=J$(X,v,_);if(g.kind==="none")return;if(g.kind==="move"){let s=k([...a,_],x);if(s)return s.accountId;return g.reason==="killswitch"?void 0:_}if(g.kind==="detour")return k([...a,_],!1)?.accountId;return _},V2={providerID:x2,async retrySameAccount(X){if(X.continuation!=="interrupted-read")return;let N=D.get(H2(X));if(D.delete(H2(X)),!N||N.accountId!==X.accountId||N.modelID!==X.modelID||N.agent!==X.agent||X.limit)return;let M=H!==void 0&&await H.authority()!=="local",P=await $.storage();if(!M&&!(await J.current()).active)return;let R=j(),x=o(P,R,M),q=x.find((k)=>k.id===X.accountId);if(!q)return;let y=m(x,P,R),v=P?.routing?.mode??"main-first";if(v==="sticky-balanced"){let k=J$(y,A2(x,P),X.accountId);if(k.kind!=="serve"&&k.kind!=="last-path")return}else{let k=z$({...y,placement:Z$(v),...M?{mainId:$$(H?.routes()??[])}:{}});if(k.kind==="block"||!k.order.includes(X.accountId))return}let h=N.data;if(q.row){if(h?.kind!=="pool")return;let k=J.usableToken(q.row),a=q.row.identity??(k&&Y1(k));if(!k||!h.identity||a!==h.identity)return}else{if(h?.kind!=="vault"||!H)return;let k=await H.authorize(X.accountId);if(!k||k.credentialId!==h.credentialId||k.accountIdentity!==h.accountIdentity||(k.accountIdentity??Y1(k.accessToken))!==h.wireIdentity||q.identity!==void 0&&q.identity!==h.wireIdentity)return}return{accountId:X.accountId}},dropSameAccountRetry(){},dropChoice(X){let N=t(X);p(N),X2.get(N)?.drop(),X2.delete(N),b.delete(N)},chooseAccount:async(X)=>{let N,M=await H?.authority(),P=await $.storage(),R=M!==void 0&&M!=="local",x=()=>{throw new L2({kind:"no-account",providerID:x2,sessionID:X.sessionID,requestKind:X.kind,message:q1})};if(R){let B=performance.now()+S1;await $.awaitVaultRoster?.(),N=await V?.forRequest(B)}else{if(N=await V?.forRequest(),!(await J.current()).active){if(await $.slotPlaceholderWithoutMain?.())x();K?.warn("the account pool does not serve requests yet; refusing the request",{kind:X.kind});return}await J.prepareTokens(J.peek().rows,P)}let q=j(),y=o(P,q,R),v=r$(m(y.filter((B)=>B.id!==X.rerouteFrom?.accountId),P,q));if(v)await v,q=j(),y=o(P,q,R);let h=new Map(y.map((B)=>[B.id,B])),k=m(y,P,q),a=P?.routing?.maxSameAccountWait,G2=JSON.stringify([X.sessionID,X.kind]),_=[...f.values()].includes(X.sessionID),g=V?.activity.get(X.sessionID),s=g&&V?.accountKey(g.accountKey.accountId),O2=X.previousAccountId??X.rerouteFrom?.accountId,c=O2&&V?.accountKey(O2),e=X.rerouteFrom?.limit,U2=y.flatMap((B)=>{let F=V?.accountKey(B.id);if(!F)return[];let W=i2(B.quota),E=ZZ(e&&B.id===O2?{account:F,kind:"rate-limit",reason:e.reason,scope:{kind:"pool"},windows:e.windows??[],observedAt:e.observedAt??q}:void 0,W,q),C=k.rateLimitMarks.get(B.id),O=k.refreshBackoff.get(B.id),i=[...C&&C>q?[{kind:"hard",until:C,cause:"rate-limit"}]:[],...O&&O>q?[{kind:"cooldown",until:O}]:[]],W2=k.killswitch.get(B.id)!==!1&&!!(W?.primary||W?.secondary)&&!l$(m$(s1(B.quota)?B.quota:void 0),q)&&!(O&&O>q)&&(!B.row||!!J.usableToken(B.row));return[{account:F,admitted:W2,placementEligible:W2,ready:W2&&!i.length&&!E.length,blockers:i,confirmedBlockers:E}]}),f2={phase:X.phase==="retry"?"after-limit":"pre-send",host:"opencode2",hostPhase:X.phase,now:q,clockNow:q,sessionId:X.sessionID,requestScope:{kind:"pool"},history:u$({requestId:X.sessionID,originalUrl:"https://api.openai.com/v1/responses",clockNow:q}),delivery:{owned:!0,attributable:!0,replayable:!0},candidates:U2,...X.phase==="retry"&&c?{attempted:c}:{},...X.phase==="retry"&&c&&e?{signal:{account:c,kind:"rate-limit",reason:e.reason,scope:{kind:"pool"},windows:e.windows??[],observedAt:e.observedAt??q},status:e.status}:{},remainingRetries:r2-(X.hostAttempt??r2)},Z1=()=>{let B=V?.owner();return GZ({accounts:U2.flatMap((F)=>{let W=h.get(F.account.accountId);if(!W)return[];return[{account:F.account,reading:i2(W.quota),usable:!W.row||!!J.usableToken(W.row),confirmedBlockers:F.confirmedBlockers,floors:a$(P)?t1(P,W.id===e1?void 0:W.id):void 0,marks:B?.snapshot()?.marks.filter((E)=>E.key.window==="account"&&E.key.scope.kind==="pool"&&s2(E.key.account,F.account)).flatMap((E)=>E.entries.map((C)=>({until:C.until,evidenceAt:C.evidenceAt})))}]}),now:q,effectiveModel:X.modelID,maxSameAccountWait:a,activity:g,currentAccountKey:s,provenance:B?.provenance})},C2=U2.find((B)=>c&&s2(B.account,c));if(X.phase==="retry"&&e&&C2){let B=X$({candidate:C2,activity:g,maxSameAccountWait:a,now:q,maxDelayMs:c2}),F=j$({...f2,hold:B},{mode:"sticky"});if(F?.action==="hold"&&!_)return f.set(G2,X.sessionID),{hold:{delayMs:F.delayMs,target:F.target,checkpoint:F.checkpoint,kind:"hold"}};let W=y.filter((C)=>C.id!==O2);if(C2.confirmedBlockers?.some((C)=>C.confirmed)&&W.length>0&&W.every((C)=>{let O=U2.find((i)=>i.account.accountId===C.id);return O&&(!O.admitted||(k.rateLimitMarks.get(C.id)??0)>q)})){if(_)return{hostRetry:"veto"};let C=Y$(f2,Z1());if(r1(a)===0)return{hostRetry:"veto"};let O="delayMs"in C?C.delayMs:("retryAfterMs"in C)?C.retryAfterMs:void 0;if((f2.remainingRetries??0)<1||O===void 0||O>c2)return{hostRetry:"leave"};if(C.action==="hold"&&s2(C.account,C2.account))return f.set(G2,X.sessionID),{hold:{delayMs:O,target:C.target,checkpoint:C.checkpoint,kind:"terminal"}};return f.set(G2,X.sessionID),{waitThenReselect:{delayMs:O}}}}let m2;if(X.phase==="request"&&X.wake?.checkpoint&&C2&&(X.hostAttempt??r2)<r2&&r1(a)!==0&&s2(C2.account,X.wake.checkpoint.accountKey)){let B=X.wake.checkpoint,F=new Map(B.blockers.map((O)=>[O.window,{...O,confirmed:!0,confirmedByReading:!1,observedAt:B.decidedAt,provenance:"provider"}]));for(let O of C2.confirmedBlockers??[])F.set(O.window,O);let W={...C2,confirmedBlockers:[...F.values()]},E=X$({candidate:W,activity:g,maxSameAccountWait:a,now:q,maxDelayMs:c2});if(j$({...f2,attempted:C2.account,candidates:U2.map((O)=>O===C2?W:O),hold:E,wake:{...X.wake,checkpoint:B}},{mode:"sticky"})?.action==="retain")m2=C2.account.accountId}let l2=new Set(X.rerouteFrom?[X.rerouteFrom.accountId]:[]),j2=P?.routing?.mode??"main-first",N2=X.kind==="primary",y2=new Set,v2,B2,l,z=!1,Q=(B)=>{let F=G$(k).projections.get(B)?.checkedAt,W=h.get(B)?.identity;return Y.reserve(X.sessionID,{accountId:B,inputBytes:o1,...F!==void 0?{quotaCheckedAt:F}:{},...W!==void 0?{wireIdentity:W}:{}})};try{for(;;){let B=new Set([...l2,...y2]);l=void 0,v2=void 0;let F=j2!=="sticky-balanced";if(m2&&!B.has(m2))l=m2,m2=void 0;else if(j2==="sticky-balanced"){let E=new Map(Y.placementSnapshot(X.sessionID)),C=E.get(X.sessionID);if(F=C===void 0,l=R2(k,y,P,X.sessionID,B,N2&&y2.size===0,E),l!==void 0&&E.get(X.sessionID)!==C)v2=E.get(X.sessionID)}if(l??=E2(k,j2,B,N2?void 0:w.activeAccount(X.sessionID),R?j2==="sticky-balanced"?null:$$(H?.routes()??[]):void 0),l===void 0||y2.has(l)){if(l2.size>0){let E=new Map(k.rateLimitMarks);for(let C of l2)E.delete(C);k={...k,rateLimitMarks:E},l2.clear();continue}if(k.rateLimitMarks.size>0){k={...k,rateLimitMarks:new Map};continue}l=void 0;break}if(N2&&j2==="sticky-balanced")B2=Q(l);if(!z){z=!0;let E=X.wake?void 0:await YZ({vaultMode:R,fresh:F,sessionId:X.sessionID,request:{modelId:X.modelID,kind:X.kind,retry:X.phase==="retry"||X.rerouteFrom!==void 0},routes:H?.routes()??[],routing:k,wait:{activity:g,accountKey:s,maxSameAccountWait:a},eligibleIds:y.filter((C)=>!B.has(C.id)).map((C)=>C.id)});if(E&&E!==l){if(B2)Y.rollback(B2);if(B2=void 0,j2==="sticky-balanced"){let C=new Map(Y.placementSnapshot(X.sessionID));l=R2(k,y,P,X.sessionID,B,N2,C,E)??l,v2=C.get(X.sessionID)??v2}else l=E;if(N2&&j2==="sticky-balanced")B2=Q(l)}}let W=h.get(l)?.row;if(W){if(J.usableToken(W)!==void 0)break;K?.debug("pool row holds no usable token; choosing again",{accountId:l})}else{if(!H)break;let E=await H.authorize(l);if(E){b.set(t({...X,accountId:l}),E);break}K?.debug("the vault refused to serve an account; choosing again",{accountId:l})}if(B2)Y.rollback(B2);B2=void 0,y2.add(l)}if(l===void 0&&!R&&y.length===0&&await $.slotPlaceholderWithoutMain?.())x();if(l===void 0&&R&&H&&(y.length===0||y2.size>0)){let B=y2.size>0?"vault-refused":o$(H);throw K?.warn("vault mode: no vault account can serve; refusing the request",{cause:B}),new L2({kind:"no-account",providerID:x2,sessionID:X.sessionID,requestKind:X.kind,message:n$(B,H.name)})}if(l!==void 0){if(N)I2(X,l,N);let B=l,F=B2,W=v2,E=()=>{if(F)Y.finish(F,W);if(N2)w.record(X.sessionID,B),$.onRoute?.(X.sessionID,B,j2)};if(X.phase==="retry")X2.set(t({...X,accountId:l}),{commit:E,drop:()=>{if(F)Y.rollback(F)}}),B2=void 0;else E();let C=K?.info;u.served(k,l,K&&C?{info:(O,i)=>C.call(K,O,i)}:void 0)}if(l===void 0&&X.phase==="request"&&U2.length>0&&U2.every((B)=>!B.admitted)&&U2.some((B)=>k.killswitch.get(B.account.accountId)===!1||B.confirmedBlockers?.length)){let B=Y$(f2,Z1()),F=JZ({decision:B,now:q,host:"opencode2",requestThrow:!0,maxSameAccountWait:a});if(F.kind==="http"){let W=JSON.parse(F.body);throw new L2({kind:"no-account",providerID:x2,sessionID:X.sessionID,requestKind:X.kind,message:W.error.message})}}return K?.debug("pool account chosen",{kind:X.kind,accountId:l,mode:j2,...X.rerouteFrom?{rerouteFrom:X.rerouteFrom.accountId}:{}}),l}finally{if(B2)Y.rollback(B2)}},accountHeaders:async(X)=>{let{accountId:N}=X;D.delete(H2(X));let M=t(X),P=X2.get(M);X2.delete(M);let R=()=>{P?.commit()};try{let x=()=>new L2({kind:"no-account",providerID:x2,sessionID:X.sessionID,requestKind:X.kind,message:M4}),q=async(a)=>{if(!V)return;let G2=M2(M)??await V.forRequest();if(a.kind==="pool"){let e=J.peek().rows.find((U2)=>U2.id===N);if(!e||e.credentialEpoch!==a.credentialEpoch||J.usableToken(e)!==a.token)throw x()}let _=V.bindings().find((e)=>e.account.accountId===N),g=await G2?.beforeDispatch(_,()=>V.ownershipBindings(),N),s=V.accountKey(N);if(g&&g.status!=="ready"||_&&(!s||!s2(_.account,s)))throw x();let O2=V.owner(),c=_?{sessionId:X.sessionID,accountKey:_.account,dispatchedAt:j(),ttlMs:XZ(JSON.stringify({model:X.modelID}))}:void 0;if(c){if(T.delete(c.sessionId),T.set(c.sessionId,c),T.size>n2){let e=T.keys().next().value;if(e!==void 0)T.delete(e)}}U.set(a,{owner:O2,probe:O2?.observe(_),dispatch:c,failed:!1,completed:!1})},y=H&&await H.authority()!=="local"?void 0:J.peek().rows.find((a)=>a.id===N);if(!y&&H){let a=t(X),G2=b.get(a)??await H.authorize(N);if(b.delete(a),!G2)throw K?.warn("the vault refused to serve an account; refusing the request",{accountId:N}),x();let _={kind:"vault",routeId:N,receipt:G2};return await q(_),R(),{headers:{...c1,"session-id":X.sessionID,authorization:`Bearer ${G2.accessToken}`,"chatgpt-account-id":G2.accountIdentity??Y1(G2.accessToken)??null},attempt:_}}let v=y?J.usableToken(y):void 0;if(!y||!v)throw K?.warn("pool row holds no usable token; refusing the request",{accountId:N}),x();let h=y.identity??Y1(v),k={kind:"pool",token:v,credentialEpoch:y.credentialEpoch,...h!==void 0?{identity:h}:{}};return await q(k),R(),{headers:{...c1,"session-id":X.sessionID,authorization:`Bearer ${v}`,"chatgpt-account-id":h??null},attempt:k}}finally{P?.drop()}},async rewriteRequest({request:X,sessionID:N,kind:M}){let P=$.codexEndpoint?i1(X.url,$.codexEndpoint()):X.url,R=P===X.url?X:new Request(P,X);return await w$(R,{sessionID:N,kind:M},A,$.responsesLite?.()??!1)??R},rewriteHandshakeURL:({url:X})=>$.codexEndpoint?i1(X,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:X,sessionID:N,kind:M})=>I$(X,{sessionID:N,kind:M},A),quotaFromHeaders:(X,N,M)=>{if(M.data?.kind==="vault")H?.reportUsage(M.data.routeId,{headers:X},M.data.receipt);if(M.data?.kind==="vault"&&Q1()&&N>=200&&N<300)Z.set(M,{status:N,headers:X});return E4(X)},async limitFromResponse({status:X,headers:N,body:M,attempt:P}){if(X<400)return;let R=j1(await M().catch(()=>"")),x=j(),q=E1({...P2(R)?R:{},status:X},x);if(P.data?.kind==="vault"&&Q1())_1(P.sessionID,P.data.receipt,{status:X,headers:N,body:R,limit:q,quota:H?.routes().find((h)=>h.id===P.accountId)?.quota,now:j()});if(!q)return;let y=B1(q,x,X,S(P.accountId,P.data?.kind==="vault"));if(y.retryAfterMs!==void 0)return y;let v=O4(N);return v===void 0?y:{...y,retryAfterMs:v,resetAt:x+v,resetSource:"retry-after"}},inspectEvent:({data:X,transport:N,attempt:M})=>{let P=j1(X),R=M.data&&U.get(M.data);if(R&&P2(P)&&(P.type==="response.failed"||P.type==="error"))R.failed=!0;if(R&&P2(P)&&P.type==="response.completed")R.completed=!0;if(M.data?.kind==="vault"&&X.includes("codex.rate_limits")){let q=j1(X);if(P2(q)&&q.type==="codex.rate_limits")H?.reportUsage(M.data.routeId,{frame:q},M.data.receipt)}if(M.data?.kind==="vault"&&Q1()&&(BZ(X)||N==="ws"&&X.includes('"response.completed"'))){let q=j1(X);if(QZ(q))G.add(M);if(N==="ws"&&P2(q)&&q.type==="response.completed")_1(M.sessionID,M.data.receipt,{status:200,headers:new Headers,failed:G.has(M)})}let x=_4(P,j(),S(M.accountId,M.data?.kind==="vault"));return N==="ws"&&P2(P)&&P.type==="response.completed"?{...x,done:!0}:x},limitFromError(X,N){let M=j1(X.message),P=j(),R=S(N.accountId,N.data?.kind==="vault");return UZ({...P2(M)?M:{},...X.status!==void 0?{status:X.status}:{}},P,R)??(X.message.includes("usage_limit_reached")?B1({window:"usage_limit_reached"},P,X.status,R):void 0)},async onAttemptEnd(X,N){let M=X.data,P=M&&U.get(M);if(P){let x=!N.error&&!N.limit&&!P.failed&&(X.transport==="ws"?P.completed:N.status!==void 0&&N.status>=200&&N.status<300);if(x&&P.dispatch&&V){let q=T.get(P.dispatch.sessionId);jZ(V.activity,P.dispatch,q===P.dispatch?V.accountKey(X.accountId):void 0,X.transport==="ws"?{kind:"ws",event:"response.completed",aborted:!1}:{kind:"http",completed:!0,failed:!1,aborted:!1})}P.owner?.afterProbe(P.probe,x,Boolean(N.limit))}if(M&&N.outputStarted&&N.error?.reason==="failed"){if(D.set(H2(X),{accountId:X.accountId,modelID:X.modelID,agent:X.agent,sessionID:X.sessionID,data:M.kind==="pool"?{kind:"pool",identity:M.identity}:{kind:"vault",credentialId:M.receipt.credentialId,accountIdentity:M.receipt.accountIdentity,wireIdentity:M.receipt.accountIdentity??Y1(M.receipt.accessToken)}}),D.size>n2){let x=D.keys().next().value;if(x!==void 0)D.delete(x)}}let R=M?.kind==="vault"&&Q1()?Z.get(X):void 0;if(Z.delete(X),M?.kind==="vault"&&R&&!N.error&&!N.limit)_1(X.sessionID,M.receipt,{...R,failed:G.has(X)});if(M?.kind!=="vault"||N.status!==401)return;K?.warn("a vault account answered 401; reporting it to the vault",{accountId:X.accountId}),await H?.reportFailure(M.receipt,401)}},z2=(X,N,M)=>{let P=M.data;if(P?.kind==="vault"){H?.recordSnapshot(X,N.snapshot,N.complete,P.receipt);return}if(P?.kind!=="pool")return;if(J.peek().rows.find((x)=>x.id===X)?.credentialEpoch!==P.credentialEpoch){K?.debug("quota reading dropped: the row holds another credential",{accountId:X});return}J.recordSnapshot(X,N.snapshot,P.token,N.complete)},g2=(X,N,M)=>{let P=j(),R=M.data?.kind==="vault";if(V){let x=M.data&&U.get(M.data),q=x?.owner??V.owner();if(!q)return;if(!x?.probe||q.registry!==x.probe.registry){q.dropSignal();return}let y=N,{command:v,provenance:h}=zZ({binding:x.probe.binding,baseRevision:x.probe.baseRevision,producerId:L,operationId:g$(),parsed:{window:N.reason,resetAt:y.resetAt??(N.retryAfterMs!==void 0?P+N.retryAfterMs:void 0)},reading:S(X,R),now:P,observedAt:y.observedAt??P,evidenceAt:P,resetSource:y.resetSource});q.enqueue(v,h);return}};return{adapter:V2,beginTurn:Z2,dispose:()=>f.clear(),attach(X){X.on("quota",(N)=>z2(N.accountId,N.quota,N.handle)),X.on("limit",(N)=>{g2(N.accountId,N.limit,N.handle),K?.debug("pool row refused the request",{accountId:N.accountId,via:N.via,reason:N.limit.reason,outputStarted:N.outputStarted})})},forgetSession(X){Z2(X);for(let[N,M]of I)if(M.sessionID===X)p(N);T.delete(X),V?.forget(X);for(let[N,M]of D)if(M.sessionID===X)D.delete(N);Y.forget(X),w.forget(X),A.forget(X)},activeAccount:(X)=>w.activeAccount(X)}}import{resolve as MZ}from"node:path";import{Buffer as x4}from"node:buffer";import{resolve as HZ}from"node:path";function W1($){return x4.byteLength(JSON.stringify($))}function A4($){return $.reduce((Z,G)=>Z+W1(G),0)}function Q$($,Z){return 2+$+Math.max(0,Z-1)}function q4($){let{head:Z,pending:G}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+Q$(Z.inputBytes,Z.input.length)+1:0)+(G?20+Q$(G.inputBytes,G.input.length)+10+Q$(G.outputBytes,G.output.length)+(G.responseID===void 0?0:14+G.responseIDBytes)+1:0)}function FZ($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class KZ{enabled;caps=b1;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 G=FZ(Z);if(G?.type!=="response.create")return;if(!Array.isArray(G.input)){this.forget($);return}let J=G.previous_response_id,Y=this.entries.get($),j=Y?.head;if(J&&J!==j?.responseID){this.forget($);return}let{type:K,previous_response_id:H,input:V,...L}=G;this.keep($,{fields:J&&Y?Y.fields:L,fieldsBytes:J&&Y?Y.fieldsBytes:W1(L),...J&&j?{head:j}:{},pending:{input:V,inputBytes:A4(V),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,G){if(!this.enabled||!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed"))return;let J=this.entries.get($);if(!J?.pending)return;let Y=FZ(Z);if(!Y)return;let j=J.pending,K=Y.response;if(Y.type==="response.created"&&typeof K?.id==="string")j.responseID=K.id,j.responseIDBytes=W1(K.id),this.keep($,J);else if(Y.type==="response.output_item.done"&&Y.item){if(typeof Y.response_id==="string"&&j.responseID!==void 0&&Y.response_id!==j.responseID)return;j.output.push(Y.item),j.outputBytes+=W1(Y.item),this.keep($,J)}else if(Y.type==="response.completed"&&typeof K?.id==="string"){if(K.id===J.head?.responseID||j.responseID!==void 0&&K.id!==j.responseID)return;let H={responseID:K.id,responseIDBytes:j.responseID===K.id?j.responseIDBytes:W1(K.id),input:[...J.head?.input??[],...j.input,...j.output],inputBytes:(J.head?.inputBytes??0)+j.inputBytes+j.outputBytes},V={...J,head:H,pending:void 0};if(!this.keep($,V))return;G?.({sessionID:$,responseID:H.responseID,bodyText:this.body(J.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 G=q4(Z);if(this.forget($),G>this.caps.maxBytes)return!1;Z.bytes=G,this.entries.set($,Z),this.bytes+=G;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let J=this.entries.keys().next().value;if(J===void 0)break;this.forget(J)}return this.entries.has($)}}var LZ=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),PZ=globalThis,B$=PZ[LZ]??new Map;PZ[LZ]=B$;function R1($){let Z=JSON.stringify([HZ($.configPath),HZ($.statePath)]),G=B$.get(Z);if(!G)G=new KZ,B$.set(Z,G);return G}var S4=5000,b4=["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"],R4=["x-opencode-parent-session-id","x-parent-session-id"];function EZ($){let Z=CZ($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:TZ($?{...$,cachekeep:Z}:$)}}var OZ=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),xZ=globalThis,V1=xZ[OZ]??new Map;xZ[OZ]=V1;function D4($,Z){let G=[],J=()=>G.at(-1)?.location,Y=()=>{let V=J();if(!V)throw Error("no location holds keep-warm");return V},j=(V,L)=>{H.remove(V),J()?.log?.debug(`cachekeep dropped target (${L})`,{sessionKey:V})},K=async(V)=>{if(V.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let L=V.accountId??"main",U=Y(),T=await U.source.accessFor(L,await U.storage());if(!T)throw Error(`pool row ${L} has no usable token`);return{token:T.token,identity:T.row.identity}},H=_Z({...b1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(V,L)=>Y().fetch(V,L),logger:{debug:(V,L)=>J()?.log?.debug(V,L),warn:(V,L)=>J()?.log?.warn(V,L)},getWindow:()=>J()?.settings().window,getSustain:()=>J()?.settings().sustain===!0,resolveLocal:K,activity:{store:{get size(){return J()?.limits?.activity.size??0},get:(V)=>J()?.limits?.activity.get(V),forgetSession:(V)=>J()?.limits?.activity.forgetSession(V),recordAccepted:(V)=>J()?.limits?.activity.recordAccepted(V)??!1},accountKey:({target:V})=>{let L=J(),U=V.meta.routingSessionId??V.sessionKey,T=V.accountId??"main";return L?.accounts.activeAccount(U)===T?L.limits?.accountKey(T):void 0}},vault:{owns:(V)=>J()?.vault.owns(V)===!0,authority:()=>Y().vault.authority(),reportUsage:(...V)=>J()?.vault.reportUsage(...V),send:async(V,L,U)=>{let T=Y();if(await T.vault.authority()!=="vault")return;return T.vault.send(V,L,U)}},activeAccount:(V)=>{if(V===void 0)throw Error("target has no session");let L=J(),U=L?.settings();if(!L||!U?.enabled){j(V,"keep-warm is off");return}if(!U.subagents&&H.status().targets.some((S)=>S.sessionKey===V&&S.isSubagent)){j(V,"subagent warming is off");return}let T=L.accounts.activeAccount(V);if(T===void 0){j(V,"no account recorded for the session");return}return T},verifyCredential:({target:V,mode:L,identity:U})=>{if(V.meta.credentialMode!==L)throw Error(`a target captured in ${V.meta.credentialMode??"an unknown"} mode is not warmed with a ${L} credential`);if(U!==V.meta.chatgptAccountId)throw j(V.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:H,settings:Z,holders:G,joinTimeoutMs:$.joinTimeoutMs??S4}}function k4($){try{let Z=JSON.parse($),G=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(G?.role!=="user")return!1;return(typeof G.content==="string"?G.content:Array.isArray(G.content)?G.content.map((Y)=>typeof Y?.text==="string"?Y.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function w4($){let Z={};for(let G of b4){let J=$.get(G);if(J)Z[G]=J}return Z}function AZ($,Z,G){let J=JSON.stringify([MZ($.configPath),MZ($.statePath)]),Y=V1.get(J);if(!Y)Y=D4(G,Z.settings()),V1.set(J,Y);let j=Y,K=R1($);K.setEnabled(j.settings.enabled);let H={location:{...Z,settings:()=>j.settings}};j.holders.push(H);let V=!1,L=async(U)=>{try{let T=H.location.settings();if(V||!T.enabled)return;if(U.kind!=="primary"){if(U.kind==="generate"&&k4(await U.request.clone().text())){if(V)return;j.manager.remove(U.sessionID)}return}let S=U.attempt.data,A=S?.kind==="pool"?"local":S?.kind==="vault"?"vault":void 0;if(!A)return;let f=U.request.headers,Z2=R4.some((H2)=>f.has(H2))||Z.parentOf!==void 0&&await Z.parentOf(U.sessionID)!==void 0;if(Z2&&!T.subagents)return;let b=await U.request.clone().text();if(V)return;let D=f.get("chatgpt-account-id")??void 0;j.manager.track({sessionKey:U.sessionID,bodyText:b,accountId:U.attempt.accountId,isSubagent:Z2,meta:{replayHeaders:w4(f),...D?{chatgptAccountId:D}:{},routingSessionId:U.sessionID,url:U.request.url,credentialMode:A}})}catch(T){Z.log?.warn("cachekeep capture failed",{error:T instanceof Error?T.message:String(T)})}};return{manager:j.manager,configure:(U)=>{Object.assign(j.settings,U),K.setEnabled(j.settings.enabled)},capture:L,forget:(U)=>j.manager.remove(U),async release(){if(V)return;V=!0;let U=j.holders.indexOf(H);if(U>=0)j.holders.splice(U,1);if(j.holders.length>0)return;if(V1.get(J)===j)V1.delete(J);j.manager.stop();let T;try{await Promise.race([j.manager.tick().catch(()=>{}),new Promise((S)=>{T=setTimeout(S,j.joinTimeoutMs),T.unref?.()})])}finally{clearTimeout(T)}}}}import{mkdirSync as y4}from"node:fs";import{dirname as I4,resolve as f4}from"node:path";function v4(){return qZ("opencode2")}var h4=2000;class kZ{path;options;sessions;frameTurns=new o2;#$=new Set;#Z=new Set;#G=new Set;#J=Promise.resolve();#X=!1;#z;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=RZ($,Z.uuid??d2)}get($,Z=d2){let G=this.sessions.get($);if(!G){let J=Z();G={threadID:J,turnID:Z(),windowID:`${J}:0`},this.sessions.set($,G),this.#Z.delete($),this.#G.delete($),this.#$.add($),this.#j()}return G}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#G.add($);this.#j()}#j(){if(this.#z)return;this.#z=setTimeout(()=>{this.#z=void 0,this.save()},this.options.saveDelayMs??h4),this.#z.unref?.()}save(){if(clearTimeout(this.#z),this.#z=void 0,!this.#X)this.#X=!0,this.#J=this.#J.then(()=>{return this.#X=!1,this.#Q()});return this.#J}settled(){return this.#z?this.save():this.#J}#Y(){if(this.#G.size===0)return;let $;try{$=W$(this.path)}catch{$=new Map}for(let Z of this.#G)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#G.clear()}async#Q(){if(this.#Y(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((J)=>{let Y=this.sessions.get(J);return Y?[[J,Y]]:[]}),Z=[...this.#Z],G=null;try{if(y4(I4(this.path),{recursive:!0}),G=await this.#B(),!G)return;let J;try{J=W$(this.path)}catch{J=new Map}await this.options.afterRead?.();let Y=!1;for(let j of Z)if(J.delete(j))Y=!0;for(let[j,K]of $){if(J.get(j)===K.threadID)continue;J.set(j,K.threadID),Y=!0}if(Y)DZ(this.path,J)}catch{return}finally{await G?.release().catch(()=>{})}for(let[J,Y]of $)if(this.sessions.get(J)===Y)this.#$.delete(J);for(let J of Z)if(!this.sessions.has(J))this.#Z.delete(J)}#B(){return bZ(this.path,this.options.lockWaitMs??SZ)}}var wZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),yZ=globalThis,D1=yZ[wZ]??new Map;yZ[wZ]=D1;function g4($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.sessions instanceof Map&&typeof Z.get==="function"&&typeof Z.delete==="function"&&typeof Z.save==="function"&&typeof Z.settled==="function"&&(Z.frameTurns===void 0||Z.frameTurns!==null&&typeof Z.frameTurns.advance==="function"&&typeof Z.frameTurns.get==="function"&&typeof Z.frameTurns.completed==="function"&&typeof Z.frameTurns.forget==="function")}function IZ($=v4()){let Z=f4($),G=D1,J=D1.get(Z),Y=D1;if(J!==void 0&&!g4(J))G.compatible??=new Map,Y=G.compatible;let j=Y.get(Z);if(!j)j=new kZ(Z),Y.set(Z,j);let K=j;return K.frameTurns??=new o2,j}var V$=Symbol.for("cortexkit.openai-auth.v2.commands"),m4=w2("v2-command");function k1($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.closed instanceof AbortController&&typeof Z.menu?.open==="function"&&typeof Z.menu?.apply==="function"&&typeof Z.session?.get==="function"&&(Z.registration===void 0||Z.registration!==null&&typeof Z.registration.dispose==="function")}function U$($){m4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function l4(){let $=globalThis;return $[V$]??={locations:new Map},$[V$].locations??=new Map,$[V$]}async function uZ($,Z){let G=l4(),J=$.location.directory,Y={menu:Z,session:$.session,closed:new AbortController},j=await vZ(J),K=await fZ(mZ,j.dir,()=>lZ({...j,drain:gZ,apply:(T)=>{let S=G.locations.get(J);if(!k1(S))throw Error("The OpenAI menu location was closed");return S.menu.apply(T)}})),H=G.locations.get(J);if(G.locations.set(J,Y),k1(H))H.closed.abort(),await H.registration?.dispose();let V={name:"openai",description:"OpenAI account menu",async execute(T){let S=[...G.locations.values()].find(k1)?.session;if(!S)return U$("no live location");let A=await S.get({sessionID:T.sessionID}),f=G.locations.get(A.location.directory);if(!k1(f))return U$("location closed");let Z2=await hZ(T.sessionID,f.closed.signal);if(!Z2||G.locations.get(A.location.directory)!==f){if(!Z2&&!f.closed.signal.aborted)N$({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},T.sessionID);return U$(f.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let b=await f.menu.open(T.sessionID);N$(b,T.sessionID)}};G.command??=V,G.command.execute=V.execute;let L=G.command;try{Y.registration=await $.command.transform((T)=>{T.add(L)})}catch(T){if(Y.closed.abort(),G.locations.get(J)===Y)G.locations.delete(J);throw await K.release(),T}let U=!1;return async()=>{if(U)return;if(U=!0,Y.closed.abort(),G.locations.get(J)===Y)G.locations.delete(J);await K.release(),await Y.registration?.dispose()}}var u4="openai-auth-pool-browser",p4="openai-auth-pool-headless",c4="openai-auth-vault",d4="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 U1($){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 nZ($){return{method:{id:c4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await pZ($.paths,$.name)!=="vault")throw Error(d4)}}}function oZ($){let Z=(G,J,Y)=>({method:{id:G,type:"oauth",label:J},async authorize(){if($.vault)await U1($.vault);let j=await $.beginLogin({version:$.version,headless:Y});return{url:j.url,instructions:j.instructions,mode:"auto",callback:j.completion}}});return[Z(u4,"ChatGPT (openai-auth pool, browser)",!1),Z(p4,"ChatGPT (openai-auth pool, headless)",!0)]}function H$($){let Z=(G)=>typeof G==="string"?G:"";return J1({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===iZ||cZ($)}function i4($){if($.accountId)return $.accountId;let Z=$.access?O1($.access):void 0;return Z?x1(Z):void 0}async function sZ($,Z,G,J={}){if(J.vault)await U1(J.vault);if(H$(G))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Y=dZ($,{rowLocks:(A)=>aZ(Z,A)}),j=await Y.read();if(j.status!=="ready")throw Error(`the account pool cannot be read (${j.status}); the login was not stored`);let K={type:"oauth",refresh:G.refresh,...G.access!==void 0?{access:G.access}:{},...G.expires!==void 0?{expires:G.expires}:{}},H=i4(G);if(J.vault)await U1(J.vault);let V=H!==void 0?{identity:H}:{};if(J.origin==="import"){let A=j.rows.find((f)=>H!==void 0&&f.identity===H||f.credential?.type==="oauth"&&f.credential.refresh===G.refresh);if(A)return{id:A.id,operation:"kept"}}let L=j.rows.filter((A)=>A.type==="oauth"&&!A.invalid),U=H?L.find((A)=>A.identity===H):void 0,T=j.rows.find((A)=>A.id===w1);if(U)return{id:(await Y.replace(U.id,K,V)).id,operation:"replaced"};if(!T){let A=await Y.add({id:w1,credential:K,...V,...G.label!==void 0?{label:G.label}:{}});return{id:A.id,operation:A.outcome==="added-disabled"?"added-disabled":"added"}}if(!T.invalid&&!T.credential)return{id:(await Y.replace(w1,K,V)).id,operation:"replaced"};let S=await Y.add({id:G.id,credential:K,...V,...G.label!==void 0?{label:G.label}:{}});return{id:S.id,operation:S.outcome==="added-disabled"?"added-disabled":S.outcome==="rotated"?"replaced":"added"}}function a4($){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","maxSameAccountWait"].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 eZ($){let Z={...$,allowAction:a4,unavailableSections:[]};return{open:(G)=>rZ(Z,G),apply:(G)=>{let J=G!==null&&typeof G==="object"?G:{},Y=J.values&&typeof J.values==="object"&&!Array.isArray(J.values)?Object.fromEntries(Object.entries(J.values).filter(([,j])=>j===null||["string","number","boolean"].includes(typeof j))):void 0;return tZ(Z,{command:"openai",sectionId:typeof J.sectionId==="string"?J.sectionId:"",actionId:typeof J.actionId==="string"?J.actionId:"",...Y?{values:Y}:{},...J.confirmed===!0?{confirmed:!0}:{},...typeof J.itemId==="string"?{itemId:J.itemId}:{},...typeof J.sessionId==="string"?{sessionId:J.sessionId}:{}})}}}function n4($,Z){if(!$0($.modelID??$.id)){$.enabled=!1;return}let G=Z0($.id);if(G)$.limit={...G};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((J)=>[J.id,J])).values()]}function G0($){return $.model.transform((Z)=>{let G=Z.list(x2);for(let J of G){let Y=z0(String(J.id)),j=Y?G.find((K)=>String(K.id)===Y):void 0;Z.update(x2,String(J.id),(K)=>n4(K,j?.variants?.map((H)=>({...H,id:String(H.id)}))))}})}class F${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(!J0())return;await this.safely(async()=>{let G={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:G}),this.requests.set(Z.attemptId,$),this.pending.size>512){let J=this.pending.keys().next().value;if(J)this.take(J)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let G=this.take($);if(G)await this.safely(()=>y1({...G,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let G=this.requests.get($.attemptId),J=G&&this.take(G);if(!J)return;let{reason:Y,message:j}=Z.error,K=j?`${Y}: ${j}`:Y;await this.safely(()=>y1({...J,error:I1(K,G?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>y1({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 K${counts=new Map;record($,Z){let G=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof G==="number"&&Number.isFinite(G)?G:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function B0($){return async(Z)=>{let G=Z.credential;if(G.type!=="oauth"||!G.access)throw Error("the row holds no access token to poll with");let J=await X0({accessToken:G.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,J),j0(J,$.now(),!0)}}function W0($){let{source:Z,counts:G,now:J}=$,Y=async(L)=>{let U=await Z.rowAccess(L,await $.storage());if(!U?.row)throw new Y0("unknown_account",`${L==="main"?"Main":"Fallback"} account ${L} was not found.`);return Q0(L,U)},j=async(L)=>{if($.authority&&await $.authority()!=="local")return{account:L,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[U]=await Z.pollRows(await $.storage(),{ids:[L]});if(!U)return{account:L,ok:!1,error:"targeted quota refresh returned no result"};return{account:U.id,ok:U.ok,...U.error!==void 0?{error:U.error}:{}}},K=(L)=>Z.peek().rows.find((U)=>U.id===L),H=(L)=>{let U=K(L);if(!U)return null;let T=i2(U.quota)??{},S=G.applicable(U),A=Math.max(0,...[T.primary?.checkedAt,T.secondary?.checkedAt].filter((f)=>typeof f==="number"));return{quota:{...T,...S!==void 0?{resetCreditsApplicable:S}:{}},checkedAt:A,refreshAfter:A,...U.identity!==void 0?{accountId:U.identity}:{}}};return{resolveResetTarget:Y,refreshResetTargetQuota:j,quotaManager:{isRateLimited:(L)=>{let U=K(L);if(!U)return!1;let T=$.rateLimitMarks().get(U.id);return T!==void 0&&T>J()},getMain:()=>H("main"),getFallback:(L)=>H(L)}}}import{resolve as V0}from"node:path";var o4=1024;class L${pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=o4){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 G of this.reservations.values())if(G.sessionId!==$)Z.set(G.sessionId,G.pin);return Z}reserve($,Z){let G={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,G),G}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 G of this.listeners)G($,Z);while(this.pins.size>this.limit){let G=this.pins.keys().next().value;if(G===void 0)break;this.forget(G)}}place($){return A1(this.placementSnapshot($.sessionId),$,(Z,G)=>this.set(Z,G))}}var U0=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),N0=globalThis,f1=N0[U0]??new Map;N0[U0]=f1;function s4($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.get==="function"&&typeof Z.forget==="function"&&typeof Z.subscribe==="function"&&typeof Z.snapshot==="function"&&typeof Z.place==="function"&&typeof Z.placementSnapshot==="function"&&typeof Z.reserve==="function"&&typeof Z.rollback==="function"&&typeof Z.finish==="function"}function H0($){let Z=JSON.stringify([V0($.configPath),V0($.statePath)]),G=f1,J=f1.get(Z);if(J!==void 0&&!s4(J)){let j=f1;j.compatibleV1??=new Map,G=j.compatibleV1}let Y=G.get(Z);if(!Y)Y=new L$,G.set(Z,Y);return Y}import{statSync as r4}from"node:fs";import{resolve as t4}from"node:path";function E0($){return $.map((Z)=>{try{let G=r4(Z);return`${G.ino}:${G.size}:${G.mtimeMs}:${G.ctimeMs}`}catch{return"?"}}).join("|")}function P$($){return E0([$.vault.paths.tokenPath,$.vault.paths.statePath])}function F0($){return E0([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+P$($)}class O0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;protocol=A0;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:F0($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),G=this.subscriptions.get($.pins);if(!G){let J=new Set;G={producers:J,stop:$.pins.subscribe((Y,j)=>{let K=J.values().next().value;if(K)this.publish(K,{sessionId:Y,pin:j,accountId:j?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,G)}return G.producers.add($),this.timer??=setInterval(()=>{for(let J of this.producers){let Y={stamp:F0(J),roster:J.vault.snapshot()},j=this.observations.get(J);if(Y.stamp!==j?.stamp||Y.roster!==j?.roster)this.observations.set(J,Y),this.publish(J)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),G.producers.delete($),!G.producers.size)G.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;await($.write??x0)(this.file,$,Z,()=>this.producers.has($))}).catch(()=>{w2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var x0=async($,Z,G,J)=>{let j=await Z.vault.authority()!=="local",K=P$(Z),H=()=>J()&&Z.vault.enrolled()===j&&P$(Z)===K,V=await(j?H1(Z.paths):t2(Z.paths)),L=j?T0(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((S)=>S.id)),V,Date.now()):_0((await Z.source.sidebarView()).rows,V,Date.now()),U={canWrite:H,vaultMode:j};if(await L0(L,$,U),!H()||!G)return;let T=L.vaultAccounts??L.fallbacks;if(G.accountId===void 0){await M0(G.sessionId,T,$,U);return}if(G.pin){let S=Date.now();await C0({sessionId:G.sessionId,assignment:{accountId:G.pin.accountId,wireAccountId:G.pin.wireIdentity,inputBytes:G.pin.inputBytes??0,quotaCheckedAt:G.pin.quotaCheckedAt,assignedAt:S,lastSeenAt:S},validPinnedAccountIds:[...j?[]:["main"],...T.filter((A)=>A.enabled).map((A)=>A.id)]},$,U)}await P0({sessionId:G.sessionId,activeId:G.accountId,route:G.route??L.route,updatedAt:Date.now()},T,$,U)},A0=2,q0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),S0=globalThis,N1=S0[q0]??new Map;S0[q0]=N1;function b0($,Z=K0(),G=2000){let J=t4(Z),Y=N1.get(J);if(Y?.protocol!==A0)Y=new O0(J,G),N1.set(J,Y);let j=Y;$={...$,write:$.write??x0};let K=j.add($),H=!1;for(let[V,L]of $.pins.snapshot())j.publish($,{sessionId:V,pin:L,accountId:L.accountId,route:"sticky-balanced"});return{publish:()=>j.publish($),route:(V,L,U)=>{j.publish($,{sessionId:V,accountId:L,route:U})},async release(){if(H)return;if(H=!0,K(),await j.settled(),j.empty&&N1.get(J)===j)N1.delete(J)}}}var h1="cortexkit-openai-auth",Z5=5000;async function R0($,Z,G,J=new X1,Y,j,K){let H=new F$(G),V=new e4,L=new Map,U=new Map,T=(b)=>{U.delete(b);for(let D of L.keys())if(D.startsWith(`${b}:`))L.delete(D)},S=(b)=>{K?.(b.sessionID),j?.send(b.sessionID,b.frame)},f=await u1({session:{hook:(b,D,H2)=>$.session.hook(b,async(X2)=>{let I=b==="http.request"?X2:void 0,p=b==="experimental.ws.handshake"?X2:void 0,M2=(I?I.request.headers:p?new Headers(p.headers):void 0)?.get("authorization")===`Bearer ${k2(Z.providerID)}`,t={};if(p)L.delete(`${p.sessionID}:${p.kind}`);try{await V.run(t,()=>D(X2))}catch(w){if(M2&&!(w instanceof L2))throw f0(w);throw w}if(I&&M2&&t.attempt){let w=I.request.headers.get("thread-id");if(w)I.request.headers.set("session-id",w)}if(I&&M2&&t.attempt)await H.captureHttp(I.request,t.attempt);if(I&&M2&&t.attempt)await Y?.({sessionID:I.sessionID,kind:I.kind,request:I.request,attempt:t.attempt});if(p&&M2&&t.attempt)p.headers["session-id"]=J.get(p.sessionID).threadID;if(b==="experimental.ws.send"){let w=X2,u=L.get(`${w.sessionID}:${w.kind}`);if(u)await H.frame(w.frame,u.attempt);if(u&&w.kind==="primary")S(w)}if(I||p){let w=I??p;if(!w)return;let o=(I?I.request.headers:new Headers(w.headers)).get("authorization")?.replace(/^Bearer /,"");if(M2&&o)U.set(w.sessionID,o);else U.delete(w.sessionID);if(p){let m=`${p.sessionID}:${p.kind}`;if(M2&&o&&t.attempt)L.set(m,{bearer:o,attempt:t.attempt,url:p.url,headers:new Headers(Object.entries(p.headers).filter(([E2])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(E2.toLowerCase())))});else L.delete(m)}if(U.size>512){let m=U.keys().next().value;if(m)U.delete(m)}if(L.size>512){let m=L.keys().next().value;if(m)L.delete(m)}}else if(b==="experimental.ws.receive"){let w=X2,u=L.get(`${w.sessionID}:${w.kind}`);if(u){if(J.frameReceived(w.sessionID,w.frame),w.kind==="primary"){let o;if(j?.receive(w.sessionID,w.frame,(m)=>{o=m}),o)try{let m=y$(o,u.url,u.headers,J);if(m)await Y?.({sessionID:w.sessionID,kind:"primary",request:m,attempt:u.attempt})}catch(m){G.warn("cachekeep WebSocket capture failed",{error:m instanceof Error?m.message:String(m)})}}w.frame=v0(w.frame,u.bearer)}}else if(b==="retry"){let w=X2,u=U.get(w.sessionID);if(u)Object.assign(w.error,{message:I1(w.error.message,u)})}},H2)},event:{subscribe:(b)=>async function*(){for await(let D of $.event.subscribe(b)){if(D.type==="session.deleted")T(D.data.sessionID);yield D}}()}},{...Z,rewriteRequest:async(b)=>{let D=V.getStore();if(D)D.attempt=b.attempt;return Z.rewriteRequest?.(b)},rewriteHandshakeURL:(b)=>{let D=V.getStore();if(D)D.attempt=b.attempt;return Z.rewriteHandshakeURL?.(b)},onAttemptEnd:async(b,D)=>{await H.end(b,D),await Z.onAttemptEnd?.(b,D)},rewriteResponse:async(b)=>{await H.response(b.request,b.response.status);let D=await Z.rewriteResponse?.(b)??b.response;return h0(D,b.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(b)=>{let D=b.get("authorization");return D?.startsWith("Bearer ")?D.slice(7):void 0}},hostRetryLimit:r2,logger:{warn:(b,D)=>G.warn(b,{data:D})}}),Z2=f.dispose;return{...f,dispose:async()=>{U.clear(),L.clear(),await Z2(),await H.settle(),H.clear()}}}function T$($={}){return{id:h1,setup:(Z)=>z5(Z,$)}}async function z5($,Z={}){let h=[];try{let G=w2("opencode2");let J=w2("quota");let Y=Z.version??m0;await t0({version:Y,...Z.runtimeLayout});let j=Z.paths??(()=>u0(g0()));let K=await H1(j());let H=K?.logging?.level;if(H&&typeof H==="string")k0(H);let V=Z.fetch??fetch;let L=Z.now??Date.now;let U=Z.poolMigration??$4;if(!U&&!e2(j().configPath)){G.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 _=(s)=>{throw new L2({kind:"no-account",providerID:x2,sessionID:s.sessionID,requestKind:s.kind,message:q1})},g=await R0($,{providerID:x2,chooseAccount:_,accountHeaders:_},G);return()=>g.dispose()}let T=Z.vault?.firstRosterWaitMs??i0;let S=e0({host:"opencode",stateDir:Z.vault?.stateDir??I0(j().statePath),reservedRouteIds:()=>I.peek().rows.map((_)=>_.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>V},j());let A=S.vault;let f=async()=>await A.authority()==="local"?t2(j()):H1(j());let Z2=!1;let b=!1;const D=F1(h,{[Symbol.dispose](){if(!Z2)S.release()}},0);await A.authority();let H2=S.firstRoster;let X2=new K$;let I=new a0({paths:j,refreshProvider:async(_)=>{let g=await y0({refreshToken:_.refresh,fetchImpl:V,now:L}),s=w0({id_token:"",access_token:g.access,refresh_token:g.refresh});return{...g,...s?{identity:s}:{}}},pullQuota:B0({fetchImpl:V,now:L,counts:X2,logger:J}),now:L,vaultIdentities:()=>A.identities(),vaultMode:()=>A.enrolled(),vaultAuthority:()=>A.authority(),vaultFirstRoster:H2,vaultFirstRosterBackgroundWaitMs:T,log:w2("pool")});if(await A.authority()==="local")await I.load();let p=new n0({pool:I,vault:A,log:(_)=>G.warn(_)});const I2=F1(h,{[Symbol.dispose](){if(!Z2)p.dispose()}},0);let M2=Z.heartbeat===!1?void 0:await s0({version:Y,logger:w2("heartbeat")});let t=Z.fence??(()=>l0({currentVersion:Y}));let w=Z.slot??Z4();let u=async()=>p0(j(),await w.get({path:{id:"openai"}}));let o=!1;let m=U?o0({paths:j,slot:w,version:Y,fence:t,runDeps:{vaultServes:()=>A.serves()},paused:async()=>await A.authority()!=="local",migrate:async(_)=>{let g=await c0(_);if(o=g.status==="refused",!b)await I.load();return g},adopt:async(_)=>{if(b)return{status:"retry",reason:"unsettled"};if(!await C$(H2,T))return{status:"retry",reason:"vault-roster-pending"};if(b)return{status:"retry",reason:"unsettled"};let g=await d0(_);if(!b)await I.load();return g}}):void 0;m?.start();S.start();let E2=H0(j());let A2=b0({paths:j(),source:I,pins:E2,vault:A},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const R2=F1(h,{[Symbol.dispose](){if(!Z2)A2.release()}},0);A2.publish();let F2=Z.codex??new X1(void 0,void 0,IZ());let $1=EZ(K);let V2=R1(j());let z2=AZ(j(),{source:I,limits:p,storage:f,vault:A,accounts:n1(j()),settings:()=>$1,parentOf:async(_)=>(await $.session.get({sessionID:_}))?.parentID??void 0,fetch:V,log:w2("cachekeep")},{now:L,codexResponsesUrl:v1().codexApiEndpoint,...Z.cacheKeep});const g2=F1(h,{[Symbol.dispose](){if(!Z2)z2.release()}},0);let X=NZ({limits:p,codex:F2,onRoute:A2.route,source:I,slotPlaceholderWithoutMain:u,storage:f,pins:E2,sessionAccounts:n1(j()),vault:A,awaitVaultRoster:async()=>{await C$(A.awaitRequestRoster(),S1)},responsesLite:()=>v1().responsesLite,codexEndpoint:()=>v1().codexApiEndpoint,now:L,log:G});let N=await R0($,X.adapter,G,F2,(_)=>z2.capture(_),V2,(_)=>z2.forget(_));X.attach(N);let M=await $.session.hook("prompt",(_)=>{X.beginTurn(_.sessionID)});let P=async(_)=>{if(await U1(A),e2(j().configPath))return;if(await m?.idle(),e2(j().configPath))return;if(o&&!H$(_)&&(await t()).open){await I.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let R=async(_)=>{await P(_);let g=await sZ(I.poolStore(),j(),_,{vault:A});if(!e2(j().configPath))await m?.requestAdoption();await I.load(),G.info("ChatGPT login stored in the account pool",g)};let x=await m1($,{integrationID:x2,methods:oZ({beginLogin:Z.beginLogin??M$,version:Y,vault:A}),onLogin:(_)=>R(_),label:"ChatGPT (openai-auth account pool)",vault:nZ(A)});let q=await G0($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let y=$.command&&$.location?await uZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??eZ({...W0({rateLimitMarks:()=>p.marks(),source:I,storage:f,counts:X2,now:L,authority:()=>A.authority()}),fetchImpl:V,now:L,randomUUID:$5,accountStoragePath:j().configPath,accountStatePath:j().statePath,packageVersion:Y,layoutNotice:r0,loadAccounts:t2,store:()=>I.poolStore(),migration:async()=>{if(e2(j().configPath))return{migrated:!0};let _=await t();return{migrated:!1,blockers:_.open?[]:_.blockers}},beginAccountLogin:Z.beginLogin??M$,refreshAllQuota:async()=>(await I.pollRows(await t2(j()))).map((_)=>({..._,account:_.id})),getStickyRouting:async(_)=>E2.get(_),cacheKeepManager:z2.manager,setCacheKeepEnabled:(_)=>z2.configure({enabled:_}),setCacheKeepSubagents:(_)=>z2.configure({subagents:_}),setCacheKeepSustain:(_)=>z2.configure({sustain:_}),setCacheKeepWindow:(_)=>z2.configure({window:_}),afterWrite:()=>I.load(),refreshSidebar:()=>A2.publish(),clearStickyRouting:async(_)=>{let g=E2.get(_)!==void 0;return E2.forget(_),g},vault:A})):void 0;let v=new AbortController;(async()=>{try{for await(let _ of $.event.subscribe({signal:v.signal}))if(_.type==="session.deleted")X.forgetSession(_.data.sessionID),z2.forget(_.data.sessionID),V2.forget(_.data.sessionID)}catch(_){if(!v.signal.aborted)G.warn("stopped listening for session deletion",{error:_ instanceof Error?_.message:String(_)})}})();Z2=!0;return async()=>{b=!0,v.abort(),X.dispose();let _=z2.release();await y?.(),m?.dispose(),await p.dispose(),await A2.release(),await Promise.allSettled([N.dispose(),M.dispose(),x.dispose(),q.dispose()]);let g;try{await Promise.race([Promise.all([m?.idle(),I.settled(),F2.store?.settled(),_]),new Promise((s)=>{g=setTimeout(s,Z5),g.unref?.()})])}finally{clearTimeout(g),await S.release(),await M2?.release()}}}catch(k){var a=k,G2=1}finally{D0(h,a,G2)}}var G5=T$(),D7={id:h1,setup:G5.setup,server:z4.server};export{D7 as default,T$ as createOpenAIAuthPlugin,h1 as OPENAI_AUTH_PLUGIN_ID};
3
+ `)}}function u1($,Z){let G=new TextDecoder,J="",Q=(K)=>{let N=X4(K);if(!N)return;try{$(N)}catch(V){Z(V)}},Y=()=>{for(;;){let K=/\r?\n\r?\n/.exec(J);if(!K)return;let N=J.slice(0,K.index);J=J.slice(K.index+K[0].length),Q(N)}};return new TransformStream({transform(K,N){N.enqueue(K),J+=G.decode(K,{stream:!0}),Y()},flush(){if(J+=G.decode(),Y(),J.trim()!=="")Q(J);J=""}})}var a2=512,p2=3621000,n2="x-common-auth-attempt",u2=($,Z)=>JSON.stringify([$,Z]),R2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function j4($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function Y4($,Z){let G=$.getReader();return new ReadableStream({async pull(J){let Q;try{Q=await G.read()}catch(Y){Z({reason:"failed",message:Y instanceof Error?Y.message:String(Y)}),J.error(Y);return}if(Q.done)Z(),J.close();else J.enqueue(Q.value)},async cancel(J){Z({reason:"cancelled",...J===void 0?{}:{message:String(J)}}),await G.cancel(J)}})}function P1($,Z){for(let[G,J]of Object.entries(Z)){let Q=G.toLowerCase();for(let Y of Object.keys($))if(Y.toLowerCase()===Q)delete $[Y];if(J!==null)$[G]=J}}function Q4($,Z){for(let[G,J]of Object.entries(Z))if(J===null)$.delete(G);else $.set(G,J)}async function p1($,Z,G={}){let{providerID:J}=Z,Q=G.gateOnPlaceholder,Y=(z)=>Q===void 0||Q.credential(z)===y2(J),K=G.logger,N=Math.max(1,G.maxRecords??a2),V=G.hostRetryLimit??10,L=[...G.hostCredentials??[y2(J)],...Q?[y2(J)]:[]].filter((z)=>z!==""),U=new Map,_=new WeakMap,q=new Map,A=0,v=new Set,$2=new Map,S=new Map,D=(z)=>{let X=S.get(z);return X?.ownedSeen===!0&&X.foreignSeen},V2=(z,X)=>{$2.set(z,X);let W=S.get(z)??{ownedSeen:!1,foreignSeen:!1};if(X)W.ownedSeen=!0;else W.foreignSeen=!0;S.set(z,W)},X2=(z,X)=>{let W=Q?.refuseMisplaced,F=W?[...X].filter(([,T])=>T.includes(y2(J))):[],B=Y(X)&&(!W||F.length>0);if(W){if(F.length>0&&(F.length!==1||!B))throw V2(z.sessionID,!1),new L2({kind:"placement-refused",providerID:J,sessionID:z.sessionID,requestKind:z.kind,message:W(F[0]?.[0]??"")})}return V2(z.sessionID,B),B},I=!1,p=!1,f2=new Map,M2=0,t=!1,w=new Map,l=(z,X)=>{try{K?.warn(z,X)}catch{}},a=(z)=>z instanceof Error?z.message:String(z),m=(z)=>z.excluded.clear(),E2=(z)=>z.excluded.size===0?{}:{excluded:[...z.excluded]},S2=(z,X,W)=>{if(!G.enforceRequestExclusion||z===void 0||!W.excluded.has(z))return!1;return l("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:X.sessionID,kind:X.kind,phase:X.phase,accountId:z}),!0},D2=new Map,U2=(z,X)=>{let W=(D2.get(z)??Promise.resolve()).then(X),F=W.then(()=>{},()=>{});return D2.set(z,F),F.then(()=>{if(D2.get(z)===F)D2.delete(z)}),W},$1=(z,X)=>{let W=D2.get(z);return W?W.then(()=>$1(z,X)):X()},Q2=async(z)=>{try{await Z.dropChoice?.({...z.input,accountId:z.accountId})}catch(X){l("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:z.input.sessionID,error:a(X)})}},z2=async(z)=>{try{await Z.dropSameAccountRetry?.({...z.input,accountId:z.accountId})}catch(X){l("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:z.input.sessionID,error:a(X)})}},g2=async(z)=>{if(z.next)await Q2(z.next);if(z.sameAccount)await z2(z.sameAccount)},j=(z)=>{let X=q.get(z);if(q.delete(z),X)U2(X.sessionID,()=>g2(X))},H=async(z,X)=>{let W=f2.get(z);if(!W||W.size===0)return;await Promise.all([...W].map(async(F)=>{try{await F(X)}catch(B){l("opencode2 auth listener threw; the request is unaffected",{event:z,error:a(B)})}}))},P=async(z)=>{let X=new Set([...U.values()].filter((F)=>F.scope.sessionID===z.sessionID).map((F)=>F.transport).filter((F)=>F!==void 0)),W=z.handle?.transport??(X.size===1?[...X][0]:"unknown");try{K?.info?.("opencode2 auth retry decision",{sessionID:z.sessionID,transport:W,attempt:z.attempt,reason:z.reason==="host-decides"&&D(z.sessionID)?"mixed-session":z.reason,retry:z.decision.retry})}catch{}await H("retry",z)},M=async(z,X)=>{try{await Z.onAttemptEnd?.(z,X)}catch(W){l("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:z.attemptId,error:a(W)})}},b=(z,X)=>{if(z.ended||!z.attempt)return;let W={...z.status===void 0?{}:{status:z.status},outputStarted:z.outputStarted,...z.limit?{limit:z.limit.signal}:{},...X?{error:X}:{}};if(X)z.endError=X;if(X?.reason==="cancelled"||!X&&!z.limit&&(z.status===void 0||z.status<400))m(z.request);z.ended=M(z.attempt,W)},x=(z,X)=>b(z,{reason:"abandoned",message:X}),O=(z)=>[...U.values()].filter((X)=>X.key===z),y=(z)=>O(z).at(-1),f=(z)=>{if(U.delete(z.id),q.get(z.key)?.attemptId===z.id||!O(z.key).length)j(z.key)},u=(z)=>{U.set(z.id,z);while(U.size>N){let X=U.values().next().value;if(X===void 0)break;x(X,"dropped to keep the record bound"),f(X)}},k=(z)=>z.accountId===void 0?void 0:{...z.scope,accountId:z.accountId},c=(z,X)=>new L2({kind:"no-account",providerID:J,sessionID:z.sessionID,requestKind:z.kind,...X===void 0?{}:{message:X}}),G2=(z)=>{w.get(z)?.clear(),w.delete(z)},C=async(z,X)=>{let W=()=>c(z,`${J} ${z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(t)throw W();let F=w.get(z.sessionID);if(!F)F=new Set,w.set(z.sessionID,F);let B={};F.add(B);let T=()=>{if(!F.has(B))throw W()};try{return await X(T)}finally{if(F.delete(B),F.size===0&&w.get(z.sessionID)===F)w.delete(z.sessionID)}},h=(z,X)=>{for(let[W,F]of X)if(L.some((B)=>F.includes(B)))throw new L2({kind:"host-credential-on-wire",providerID:J,sessionID:z.sessionID,requestKind:z.kind,message:`${J} ${z.kind} request still carries the host's placeholder credential in ${W}; the adapter's account headers must replace it`})},Z2=(z)=>{for(let X of O(z))if(X.ended||!X.attempt)f(X);else if(X.transport==="ws"||X.judged)x(X,"a newer attempt of its session and kind began"),f(X)},N2=async(z,X,W,F)=>{let B=u2(z.sessionID,z.kind),{input:T,accountId:E,sameAccountRetry:R,request:o}=await $1(z.sessionID,async()=>{W();let j2=q.get(B);q.delete(B);let J1=O(B);if(j2&&J1.some((e)=>e.id!==j2.attemptId&&e.attempt&&!e.ended))l("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:z.sessionID,kind:z.kind});if(!j2){let e=new Set(J1.filter((_2)=>_2.attempt&&!_2.ended).map((_2)=>_2.request));for(let _2 of J1)if(!e.has(_2.request))m(_2.request)}let K2=j2?.request??{excluded:new Set},J2=j2?.accountId??y(B)?.accountId;Z2(B);let r=j2?.next,Y2=j2?.sameAccount,d=Y2!==void 0&&Y2.input.modelID===z.modelID&&Y2.input.agent===z.agent,T2=r!==void 0&&r.input.modelID===z.modelID&&r.input.agent===z.agent,w2=j2?.wake,n={...z,phase:"request",...E2(K2),...J2===void 0?{}:{previousAccountId:J2},...j2?.rerouteFrom?{rerouteFrom:j2.rerouteFrom}:{},...w2===void 0?{}:{wake:w2,hostAttempt:r?.input.hostAttempt}};if(r&&(!T2||w2!==void 0))await U2(z.sessionID,()=>Q2(r)),W();if(Y2&&!d)await U2(z.sessionID,()=>z2(Y2)),W();if(Y2?.continuation&&(!d||D(z.sessionID))){if(d)await U2(z.sessionID,()=>z2(Y2));throw c(z)}let l2=d?Y2.accountId:T2&&w2===void 0?r.accountId:await Z.chooseAccount(n),h2=typeof l2==="string"?l2:void 0;if(S2(h2,n,K2)){let e=h2;if(d&&Y2)await U2(z.sessionID,()=>z2(Y2));else if(e!==void 0)await U2(z.sessionID,()=>Q2(T2&&r?r:{accountId:e,input:n}));h2=void 0,W()}return{input:n,accountId:h2,sameAccountRetry:d,request:K2}});W();let x2={},A2;if(E!==void 0){let j2=await Z.accountHeaders({...z,accountId:E});if(W(),j4(j2))x2=j2.headers,A2=j2.attempt;else x2=j2}let G1=`attempt-${++M2}`,b2={id:G1,key:B,scope:z,request:o,accountId:E,headers:x2,attempt:E===void 0?void 0:{...z,accountId:E,attemptId:G1,transport:F,data:A2},...F===void 0?{}:{transport:F},outputStarted:!1,sameAccountRetry:R};if(u(b2),b2.attempt)H("select",{...z,accountId:b2.attempt.accountId,hook:X,...T.previousAccountId===void 0?{}:{previousAccountId:T.previousAccountId},...T.rerouteFrom===void 0?{}:{rerouteFrom:T.rerouteFrom},handle:b2.attempt});return b2},i=async(z,X,W,F,B)=>{let T=u2(z.sessionID,z.kind),E=F===void 0?void 0:U.get(F);if(E?.key!==T)E=void 0;if(!E){if(E=y(T),O(T).filter((o)=>o.transport===void 0&&!o.ended).length>1&&!p)p=!0,l("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:z.sessionID,kind:z.kind})}if(!E||E.transport!==void 0||E.ended)E=await N2(z,X,B,W);else if(E.transport=W,E.attempt)E.attempt.transport=W;if(W==="ws"){for(let R of O(T))if(R!==E&&R.transport==="ws")x(R,"a newer attempt of its session and kind went out over WebSocket")}return E},s=async(z,X)=>{try{return await X()}catch(W){throw b(z,{reason:"failed",message:a(W)}),W}},C2=(z,X)=>{let W=O(u2(z,X)).filter((F)=>F.transport==="ws").at(-1);return W?.attempt!==void 0&&!W.ended?W:void 0},k2=(z,X,W)=>{let F=k(z);if(!F||!z.attempt||z.limit)return;z.limit={signal:X,delivered:H("limit",{...F,via:W,limit:X,outputStarted:z.outputStarted,handle:z.attempt})}},Z1=(z,X,W,F)=>{let B=k(z);if(!B||!z.attempt)return;H("quota",{...B,transport:X,...F===void 0?{}:{status:F},quota:W,handle:z.attempt})},H2=(z,X,W,F)=>{let B=z.attempt;if(!B)return;let T=Z.inspectEvent?.(F===void 0?{transport:X,data:W,attempt:B}:{transport:X,data:W,event:F,attempt:B});if(!T)return;if(T.quota!==void 0)Z1(z,X,T.quota);if(T.outputStarted)z.outputStarted=!0;if(T.hostRetry==="veto")z.hostRetry="veto";if(T.limit)k2(z,T.limit,X);if(T.error!==void 0)b(z,{reason:"failed",message:T.error});else if(T.done)b(z)},m2=(z,X)=>{let W=z.attempt;if(!W||X.accountId===z.accountId)return;if(W.reboundFrom??=W.accountId,W.accountId=X.accountId,"data"in X)W.data=X.data;z.accountId=X.accountId},i2=(z)=>!z.attempt||z.endError!==void 0||z.status!==void 0&&z.status>=400,O2=(z)=>{let X=[...U.values()].filter((R)=>R.scope.sessionID===z),W=X.filter((R)=>R.limit&&!R.rerouted).at(-1);if(W)return W;let F=X.filter((R)=>R.scope.kind==="primary"),B=F.length>0?F:X;if(B.length<=1)return B[0];let T=B.filter((R)=>!R.judged&&i2(R)).at(-1);if(T)return T;let E=B.filter((R)=>R.attempt&&!R.ended);if(E.length>1)return"ambiguous";return E[0]??B.at(-1)},F2={providerID:J},B2=[];B2.push(await $.session.hook("model.request",(z)=>{if(Q)return;return C(R2(z),async(X)=>{let W=await N2(R2(z),"model.request",X);if(X(),W.accountId===void 0)throw c(W.scope);P1(z.headers,{...W.headers,[n2]:W.id})})},F2)),B2.push(await $.session.hook("http.request",(z)=>{if(Q){if(!X2(R2(z),z.request.headers))return}return C(R2(z),async(X)=>{let W=z.request.headers.get(n2)??void 0,F=Q?await N2(R2(z),"http.request",X,"http"):await i(R2(z),"http.request","http",W,X);X();let B=k(F),T=F.attempt;if(!B||!T)throw c(F.scope);await s(F,async()=>{let E=z.request;if(Z.rewriteRequest){if(W!==void 0){let x2=new Headers(E.headers);x2.delete(n2),E=new Request(E,{headers:x2})}E=await Z.rewriteRequest({...B,request:E,attempt:T})??E,X()}let R=new Headers(E.headers);R.delete(n2),Q4(R,F.headers),h(F.scope,R.entries());let o=new Request(E,{headers:R});_.set(o,F),z.request=o})})},F2)),B2.push(await $.session.hook("http.response",async(z)=>{let X=_.get(z.request);if(!X){if(Q)return;if(!I)I=!0,l("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:z.sessionID,kind:z.kind});return}let W=z.response;if(Z.answeredBy&&X.attempt){let R=X.attempt,o=await s(X,async()=>Z.answeredBy?.({request:z.request,response:W,attempt:R}));if(o)m2(X,o)}let F=k(X),B=X.attempt;if(!F||!B)return;X.status=W.status;let T=Z.quotaFromHeaders?.(W.headers,W.status,B);if(T!==void 0)Z1(X,"http",T,W.status);if(!W.ok&&Z.limitFromResponse){let R=await Z.limitFromResponse({status:W.status,headers:W.headers,body:()=>W.clone().text(),attempt:B});if(R)k2(X,R,"http")}if(!W.ok||!W.body)b(X);let E=W;if(W.body&&(Z.inspectEvent||Z.onAttemptEnd)){let R=W.body;if(Z.inspectEvent)R=R.pipeThrough(u1((o)=>H2(X,"http",o.data,o.event),(o)=>l("opencode2 auth event inspection threw",{error:a(o)})));E=new Response(Y4(R,(o)=>{if(o?.reason==="failed")X.readFailed=!0;b(X,o)}),{status:W.status,statusText:W.statusText,headers:W.headers})}if(Z.rewriteResponse)E=await Z.rewriteResponse({...F,request:z.request,response:E,attempt:B})??E;if(Z.responseRetry){if(await Z.responseRetry({...F,request:z.request,response:E,attempt:B})==="veto")X.hostRetry="veto"}if(E!==W)z.response=E},F2)),B2.push(await $.session.hook("experimental.ws.handshake",(z)=>{if(Q){let X=u2(z.sessionID,z.kind);if(v.delete(X),!X2(R2(z),new Headers(z.headers)))return}return C(R2(z),async(X)=>{let W;for(let E of Object.keys(z.headers)){if(E.toLowerCase()!==n2)continue;W??=z.headers[E],delete z.headers[E]}let F=Q?await N2(R2(z),"experimental.ws.handshake",X,"ws"):await i(R2(z),"experimental.ws.handshake","ws",W,X);X();let B=k(F),T=F.attempt;if(!B||!T)throw c(F.scope);await s(F,async()=>{if(!Q?.refuseMisplaced)P1(z.headers,F.headers);let E=Z.rewriteHandshakeURL?.({...B,url:z.url,attempt:T});if(E!==void 0)z.url=E;if(Q?.refuseMisplaced)P1(z.headers,F.headers);if(h(F.scope,Object.entries(z.headers)),Q)v.add(F.key)})})},F2));let v2=Z.rewriteWebSocketFrame?.bind(Z);if(v2)B2.push(await $.session.hook("experimental.ws.send",async(z)=>{let X=R2(z);if(Q&&!v.has(u2(X.sessionID,X.kind)))return;let W=C2(X.sessionID,X.kind),F=await v2({...X,attempt:W?.attempt,frame:z.frame});if(F!==void 0)z.frame=F},F2));B2.push(await $.session.hook("experimental.ws.receive",(z)=>{if(Q&&!v.has(u2(z.sessionID,z.kind)))return;let X=C2(z.sessionID,z.kind);if(!X)return;try{H2(X,"ws",z.frame)}catch(W){l("opencode2 auth frame inspection threw",{error:a(W)})}},F2)),B2.push(await $.session.hook("retry",async(z)=>{if(Q&&$2.get(z.sessionID)!==!0)return;let X=z.decision,W=()=>P({sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:X,decision:X});if(D(z.sessionID)&&!Z.retrySameAccount){await W();return}let F=O2(z.sessionID);if(!F)return;if(F==="ambiguous"){await P({sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:X,decision:X});return}let B=F,T=()=>B.hostRetry==="veto";await C(B.scope,async(E)=>{let R=E,o=Z.retrySameAccount?.bind(Z),x2=B.attempt,A2=B.outputStarted;if(B.transport==="ws"&&A2&&!B.ended&&!B.limit&&!(B.status!==void 0&&B.status>=400)&&!(z.error.status!==void 0&&z.error.status>=400)&&z.error.type==="provider.transport")B.readFailed=!0,b(B,{reason:"failed",message:z.error.message});if(A2&&B.readFailed&&o&&x2&&!D(z.sessionID)){if(!B.limit){let K2=Z.limitFromError?.(z.error,x2);if(K2)k2(B,K2,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;R()}let G1=()=>B.readFailed===!0&&z.error.type==="provider.transport"&&X.retry&&V-z.attempt>=1&&!B.limit&&!(B.status!==void 0&&B.status>=400)&&!(z.error.status!==void 0&&z.error.status>=400)&&!x2?.reboundFrom&&!T()&&!D(z.sessionID);if(o&&x2&&(!A2||G1())&&(!T()||D(z.sessionID))&&!B.sameAccountRetry){if(B.ended)await B.ended;if(B.limit)await B.limit.delivered;let K2=await U2(B.scope.sessionID,async()=>{R();let J2=x2.accountId,r=()=>U.has(B.id)&&B.accountId===J2&&O2(z.sessionID)===B&&B.outputStarted===A2&&(!A2||G1())&&(!T()||D(z.sessionID))&&(!Q||$2.get(z.sessionID)===!0);if(!r()||B.sameAccountRetry)return!1;B.sameAccountRetry=!0;let Y2={...B.scope,accountId:J2,error:z.error,attempt:z.attempt,...B.limit?{limit:B.limit.signal}:{},...A2?{continuation:"interrupted-read"}:{}},d;try{d=await o(Y2)}catch(n){l("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:z.sessionID,error:a(n)})}if(!d)return R(),!1;let T2={accountId:d.accountId,input:Y2,...A2?{continuation:!0}:{}};try{R()}catch(n){throw await z2(T2),n}if(!r()||d.accountId!==J2)return await z2(T2),!1;let w2=q.get(B.key);if(q.delete(B.key),w2)await g2(w2);try{R()}catch(n){throw await z2(T2),n}if(!r())return await z2(T2),!1;return q.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++A,accountId:J2,sameAccount:T2}),B.judged=!0,z.decision=A2?X:{retry:!0,delay:0},!0});if(R(),K2){await P({sessionID:z.sessionID,accountId:B.accountId,kind:B.scope.kind,attempt:z.attempt,reason:A2?"continue-same-account":"same-account",hostDecision:X,decision:z.decision,handle:B.attempt});return}}if(D(z.sessionID)){await W();return}B.judged=!0;let b2=B.attempt;if(b2&&!B.outputStarted){if(!B.limit){let K2=Z.limitFromError?.(z.error,b2);if(K2)k2(B,K2,"error")}if(B.ended)await B.ended;if(B.limit)await B.limit.delivered}R();let{decision:j2,reason:J1}=await U2(B.scope.sessionID,async()=>{if(R(),D(z.sessionID))return{decision:X,reason:"host-decides"};let K2=q.get(B.key);if(q.delete(B.key),K2)await g2(K2);if(R(),D(z.sessionID))return{decision:X,reason:"host-decides"};let J2=X,r,Y2,d,T2;if(B.accountId===void 0||!b2)J2={retry:!1},r="no-account";else if(B.outputStarted)J2={retry:!1},r="output-started";else if(T())J2={retry:!1},r="adapter-veto";else if(B.limit){let w2={accountId:B.accountId,limit:B.limit.signal},n,l2={...B.scope,phase:"retry",...E2(B.request),hostAttempt:z.attempt,previousAccountId:B.accountId,rerouteFrom:w2};try{n=await Z.chooseAccount(l2)}catch(m1){l("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:B.scope.sessionID,error:a(m1)})}let h2=typeof n==="string"?n:typeof n==="object"&&("hold"in n)?B.accountId:void 0;if(S2(h2,l2,B.request)){if(h2!==void 0)await Q2({accountId:h2,input:l2});n=void 0}let e=typeof n==="object"&&"hold"in n?n.hold:void 0,_2=typeof n==="object"&&"waitThenReselect"in n?n.waitThenReselect:void 0,J4=typeof n==="object"&&"hostRetry"in n?n.hostRetry:void 0,L1=typeof n==="string"?n:e?B.accountId:void 0;if(L1!==void 0)d={accountId:L1,input:l2};try{R()}catch(m1){if(d)await Q2(d);throw m1}if(D(z.sessionID)){if(d)await Q2(d);return{decision:X,reason:"host-decides"}}if(T()||J4==="veto"){if(d)await Q2(d);if(d=void 0,R(),D(z.sessionID))return{decision:X,reason:"host-decides"};B.hostRetry="veto",J2={retry:!1},r="adapter-veto"}else if(!(V-z.attempt>=1)){if(d)await Q2(d);d=void 0,r="host-decides-last-account"}else if(_2&&Number.isFinite(_2.delayMs)&&_2.delayMs>=0&&_2.delayMs<=p2)J2={retry:!0,delay:Math.ceil(_2.delayMs)},r="wait-then-reselect";else if(e&&Number.isFinite(e.delayMs)&&e.delayMs>=0&&e.delayMs<=p2){if(J2={retry:!0,delay:Math.ceil(e.delayMs)},e.target!==void 0)T2={target:e.target,...e.checkpoint===void 0?{}:{checkpoint:e.checkpoint},...e.kind===void 0?{}:{kind:e.kind}};r="hold"}else if(!e&&L1!==void 0&&L1!==B.accountId)B.rerouted=!0,B.request.excluded.add(B.accountId),Y2=w2,J2={retry:!0,delay:0},r="reroute";else{if(e&&d)await Q2(d),d=void 0;r="host-decides-last-account"}}else r="host-decides";if(z.decision=J2,J2.retry&&B.accountId!==void 0&&U.has(B.id))q.set(B.key,{request:B.request,attemptId:B.id,sessionID:B.scope.sessionID,order:++A,accountId:B.accountId,...Y2===void 0?{}:{rerouteFrom:Y2},...d===void 0?{}:{next:d},...T2===void 0?{}:{wake:T2}});else if(d)await Q2(d);if(!J2.retry)m(B.request);return{decision:J2,reason:r}});R(),await P({sessionID:z.sessionID,...B.accountId===void 0?{}:{accountId:B.accountId},kind:B.scope.kind,attempt:z.attempt,reason:J1,hostDecision:X,decision:j2,...b2===void 0?{}:{handle:b2}})})},F2));let W2=(z)=>{if(G2(z),$2.delete(z),!S.get(z)?.foreignSeen)S.delete(z);for(let X of v)if(JSON.parse(X)[0]===z)v.delete(X);for(let X of[...U.values()]){if(X.scope.sessionID!==z)continue;x(X,"its session was forgotten"),m(X.request),U.delete(X.id)}for(let[X,W]of q)if(W.sessionID===z)j(X)},g=new AbortController,z1=$.event;if(z1)(async()=>{try{for await(let z of z1.subscribe({signal:g.signal}))if(z.type==="session.deleted")W2(z.data.sessionID);else if(z.type==="session.status"&&z.data.status.type==="idle"){let X=z.data.sessionID,W=++A;U2(X,async()=>{for(let[F,B]of q)if(B.sessionID===X&&B.order<W)q.delete(F),m(B.request),await g2(B)})}}catch(z){if(!g.signal.aborted)l("opencode2 auth stopped listening for session deletion",{error:a(z)})}})();return{on(z,X){let W=f2.get(z);if(!W)W=new Set,f2.set(z,W);let F=X;return W.add(F),()=>{W.delete(F)}},accountFor(z,X){return y(u2(z,X))?.accountId},forgetSession:W2,get size(){return U.size},async dispose(){if(t)return;t=!0;for(let z of w.keys())G2(z);g.abort();for(let z of U.values())x(z,"the installation was disposed");U.clear();for(let z of q.keys())j(z);v.clear(),$2.clear(),S.clear(),f2.clear(),await Promise.all(D2.values()),await Promise.all(B2.map(async(z)=>{try{await z.dispose()}catch(X){l("opencode2 auth hook did not dispose cleanly",{error:a(X)})}}))}}}import{randomUUID as m$}from"node:crypto";import{createHash as B4}from"node:crypto";var W4=1024,V4=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),x$=($)=>A$($,"user"),U4=($)=>V4($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function N4($){return B4("sha256").update(JSON.stringify($)).digest("hex")}class o2{runtime;maxSessions;#$=new Map;constructor($,Z=W4){this.runtime=$;this.maxSessions=Z}advance($,Z,G=this.runtime){let J=this.#$.get($),Q=Array.isArray(Z.input)?Z.input:[],Y=Q.filter(x$),K=Q.findLastIndex(x$),N=K<0?void 0:N4(Q[K]),V=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,L,U,_;if(V)L=Y.length>0,U=N??J?.fingerprint,_=J?.userCount===void 0?void 0:J.userCount+Y.length;else{U=N,_=Y.length;let A=K>=0&&K>Q.findLastIndex(U4),v=J!==void 0&&!J.completed&&J.fingerprint===U&&J.userCount===_;L=A&&!v}let q=L||!J?{turnID:(G?.uuid??c2)(),turnStartedAt:(G?.now??Date.now)()}:{turnID:J.turnID,turnStartedAt:J.turnStartedAt};return this.#Z($,{...q,completed:!1,fingerprint:U,userCount:_}),q}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 G=this.#$.keys().next().value;if(G===void 0)break;this.#$.delete(G)}}}function c1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var q$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function H4(){let $=globalThis;return $[q$]??=crypto.randomUUID(),$[q$]}class j1{runtime;store;sessions;frameTurns;installationID;constructor($,Z,G){this.runtime=$;this.store=G;this.installationID=Z??H4(),this.sessions=G?.sessions??new Map,this.frameTurns=G?.frameTurns??new o2}get($){let Z=this.runtime?.uuid??c2;if(this.store)return this.store.get($,Z);let G=this.sessions.get($);if(!G){let J=Z();G={threadID:J,turnID:Z(),windowID:`${J}:0`},this.sessions.set($,G)}return G}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(M1(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var d1={version:S$,"user-agent":b$,originator:"codex_exec"};var F4=1024,K4=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,T1=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),k$=($)=>T1($)&&($.type==="message"||("role"in $))&&$.role==="user",w$=($)=>T1($)&&$.type==="configuration_update";class i1{http;#$=new Map;constructor($=new j1){this.http=$}apply($,Z,G){if(Z.kind!=="primary")return!1;let J=typeof $.model==="string"?$.model:"";if(!R$.has(J))return!1;if(K4.test(J))return!1;let Q=T1($.reasoning)?$.reasoning:void 0,Y=typeof Q?.effort==="string"?Q.effort:void 0;if(!Y)return!1;let K=this.#$.get(Z.sessionID);if(K===void 0)return this.#Z(Z.sessionID,Y),!1;if(Y===K)return!1;let N=Array.isArray($.input)?$.input:void 0;if(!N||N.length===0)return!1;let V=N.findLastIndex(k$);if(V<0){if(G==="http")return!1;return $.reasoning={...Q,effort:K},!0}if($.reasoning={...Q,effort:K},!w$(N[V-1]))N.splice(V,0,{type:"configuration_update",reasoning:{effort:Y}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>F4){let G=this.#$.keys().next().value;if(G===void 0)break;this.#$.delete(G)}}}function M1($){try{let Z=JSON.parse($);return T1(Z)?Z:void 0}catch{return}}async function y$($,Z,G,J,Q=G.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Y=await $.clone().text(),K=M1(Y);if(K)delete K.max_output_tokens;let N=new Headers($.headers),V=C1({rewriteLite:D$,init:{body:K?JSON.stringify(K):$.body===null?void 0:Y},headers:N,metadata:Q.get(Z.sessionID),installationID:Q.installationID,runtime:Q.runtime,websocket:!1,responsesLite:J,applyEffort:(L)=>{G.apply(L,Z,"http")}});return new Request($,{headers:N,body:V.init?.body})}function I$($,Z,G,J){let Q=J.sessions.get($.sessionID),Y=J.frameTurns.get($.sessionID);if(!Q||!Y)return;let K=c1(Q,Y),N=new Headers({"content-type":"application/json"});for(let L of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let U=G.get(L);if(U!==null)N.set(L,U)}C1({init:{body:$.bodyText},headers:N,metadata:K,installationID:J.installationID,runtime:J.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let V=new URL(Z);if(V.protocol==="wss:")V.protocol="https:";if(V.protocol==="ws:")V.protocol="http:";return new Request(V,{method:"POST",headers:N,body:$.bodyText})}function L4($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let G=Z.findIndex((J,Q)=>JSON.stringify(J)!==JSON.stringify($[Q]));return G>=0&&w$(Z[G])&&k$(Z[G+1])&&JSON.stringify(Z.slice(G+1))===JSON.stringify($.slice(G))}function f$($,Z,G){let J=M1($);if(J?.type!=="response.create")return;let Q=G.http.advanceFrame(Z.sessionID,J),Y=G.http.get(Z.sessionID);delete J.max_output_tokens;let K=C1({rewriteLite:()=>{},init:{body:JSON.stringify(J)},headers:new Headers,metadata:c1(Y,Q),installationID:G.http.installationID,runtime:G.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(V)=>{G.apply(V,Z,"ws")}}),N=M1(String(K.init?.body));if(!N)return;if(!L4(J.input,N.input)){if("input"in J)N.input=J.input;else delete N.input;return JSON.stringify(N)}return String(K.init?.body)}function P4($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function n1($,Z){let G=new URL($);if(G.origin!=="https://api.openai.com"&&G.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(G.pathname))return $;let J=new URL(`${P4(Z)}/responses`);if(J.search=G.search,G.protocol==="ws:"||G.protocol==="wss:")J.protocol=J.protocol==="https:"?"wss:":"ws:";return J.href}import{resolve as v$}from"node:path";var M4=1024;class _1{accounts=new Map;limit;constructor($=M4){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let G=this.accounts.keys().next().value;if(G===void 0)break;this.accounts.delete(G)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var h$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),g$=globalThis,a1=g$[h$]??new Map;g$[h$]=a1;function o1($){let Z=JSON.stringify([v$($.configPath),v$($.statePath)]),G=a1.get(Z);if(!G)G=new _1,a1.set(Z,G);return G}var q2="openai",r2=10;var s1=1,C4="request refused: no account with a usable credential",P2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function T4($){let Z=P2($)?$.counters:void 0,G=P2(Z)?Z.resetCredits:void 0,J=P2(G)?G.value:void 0;return typeof J==="number"&&Number.isFinite(J)?J:void 0}function Y1($){try{return JSON.parse($)}catch{return}}function Q1($){let Z=x1($);return Z?A1(Z):void 0}var _4=new Set(["usage_limit_reached","rate_limit_exceeded"]);function W1($,Z,G,J){return{reason:$.window,windows:ZZ($,Z,J,Z),observedAt:Z,...$.resetAt!==void 0?{resetAt:$.resetAt,resetSource:"provider"}:{},...G!==void 0?{status:G}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function NZ($,Z,G){if($.type!=="response.failed"){let Y=O1($,Z),K=typeof $.status==="number"?$.status:void 0;return Y?W1(Y,Z,K,G):void 0}if(!P2($.response))return;let J=$.response.failed;if(P2(J)&&typeof J.rate_limit_reached_type==="string")return W1({window:J.rate_limit_reached_type},Z,void 0,G);let Q=$.response.error;if(P2(Q)){let Y=typeof Q.code==="string"?Q.code:typeof Q.type==="string"?Q.type:void 0;if(Y&&_4.has(Y)){let K=typeof $.status==="number"?$.status:void 0,N=O1({error:{...Q,type:Y},status:K},Z);return W1(N??{window:Y},Z,K,G)}}return}function E4($,Z,G){if(!P2($))return;let J=typeof $.type==="string"?$.type:void 0;if(J==="codex.rate_limits")return{quota:{snapshot:i$($),complete:!0}};let Q=NZ($,Z,G);if(Q)return{limit:Q};if(J===void 0||J==="error")return;return VZ(J)?void 0:{outputStarted:!0}}function O4($){let Z=!1;for(let G of $.keys())if(G.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:c$($),complete:d$($)}}function x4($){let Z=$.get("retry-after");if(Z===null)return;let G=Z.trim()?Number(Z):NaN;return Number.isFinite(G)&&G>=0?G*1000:void 0}function HZ($){let Z=new WeakMap,G=new WeakSet,{source:J,pins:Q}=$,Y=$.now??Date.now,K=$.log,N=$.vault,V=$.limits,L=m$(),U=new WeakMap,_=new Map,q=(j,H)=>d2(H?N?.routes().find((P)=>P.id===j)?.quota:J.peek().rows.find((P)=>P.id===j)?.quota),A=new i1($.codex),v=new Map,$2=(j)=>{for(let[H,P]of v)if(P===j)v.delete(H)},S=new Map,D=new Map,V2=(j)=>`${j.sessionID}\x00${j.kind}`,X2=new Map,I=new Map,p=(j)=>{let H=I.get(j);if(H)clearTimeout(H.timer);I.delete(j)},f2=(j,H,P)=>{let M=t({...j,accountId:H});p(M);let b={request:P,sessionID:j.sessionID,expiresAt:performance.now()+5000,timer:setTimeout(()=>{if(I.get(M)===b)p(M)},5000)};if(b.timer.unref(),I.set(M,b),I.size>a2){let x=I.keys().next().value;if(x!==void 0)p(x)}},M2=(j)=>{let H=I.get(j);return p(j),H&&performance.now()<H.expiresAt?H.request:void 0},t=(j)=>`${j.sessionID}\x00${j.kind}\x00${j.accountId}`,w=$.sessionAccounts??new _1,l=new e$,a=(j,H,P)=>{let M=P?[]:UZ(J.peek().rows,j,H,N?.identities()??new Set),b=(N?.routes()??[]).filter((x)=>x.kind==="oauth"&&n$(d2(x.quota),j,H));return[...M.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota,row:x})),...b.map((x)=>({id:x.id,...x.identity!==void 0?{identity:x.identity}:{},quota:x.quota}))]},m=(j,H,P)=>{let M=r$(j,H,P),b=j.map((f)=>({id:f.id,kind:"oauth",...r1(f.quota)?{quota:f.quota}:{}})),x=j.flatMap((f)=>f.row?[f.row]:[]),O=new Set(j.filter((f)=>!f.row).map((f)=>f.id)),y=V?.marks()??new Map;return{rows:b,now:P,rateLimitMarks:y,refreshBackoff:J.refreshBackoffFor(x),killswitch:M,requestPull:(f)=>O.has(f)?N?.requestReading(f):J.requestReading(f)}},E2=(j,H,P,M,b)=>{let x=G$({...j,rows:j.rows.filter((y)=>!P.has(y.id)),placement:z$(H),mainId:b});if(x.kind==="block"){K?.debug("pool admission refused the request",{reason:x.block.reason});return}let O=x.order.filter((y)=>!P.has(y));if(M!==void 0&&O.includes(M))return M;return O[0]},S2=(j,H)=>{let P=new Map(j.map((M)=>[M.id,M.quota]));return{requestBytes:s1,reservePercent:(M)=>e1(H,M===$$?void 0:M),resetCredits:(M)=>T4(P.get(M))}},D2=(j,H,P,M,b,x,O,y)=>{let f=S2(H,P),u=J$(j),k=(Z2,N2)=>q1(O,{sessionId:M,requestBytes:s1,validPinnedAccountIds:j.rows.map((i)=>i.id).filter((i)=>!u.excluded.has(i)),excludeAccountIds:Z2,quotaCheckedAtByAccount:Object.fromEntries(j.rows.map((i)=>[i.id,u.projections.get(i.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(H.map((i)=>[i.id,i.identity])),select:(i)=>y?{accountId:y,source:"mode-fallback",quotaCheckedAt:u.projections.get(y)?.checkedAt}:$Z(j,f,new Set(Z2),i),persist:N2},(i,s)=>O.set(i,s)),c=[...b],G2=k(c,x);if(!G2)return;let C=G2.accountId,h=X$(j,f,C);if(h.kind==="none")return;if(h.kind==="move"){let Z2=k([...c,C],x);if(Z2)return Z2.accountId;return h.reason==="killswitch"?void 0:C}if(h.kind==="detour")return k([...c,C],!1)?.accountId;return C},Q2={providerID:q2,async retrySameAccount(j){if(j.continuation!=="interrupted-read")return;let H=D.get(V2(j));if(D.delete(V2(j)),!H||H.accountId!==j.accountId||H.modelID!==j.modelID||H.agent!==j.agent||j.limit)return;let P=N!==void 0&&await N.authority()!=="local",M=await $.storage();if(!P&&!(await J.current()).active)return;let b=Y(),x=a(M,b,P),O=x.find((k)=>k.id===j.accountId);if(!O)return;let y=m(x,M,b),f=M?.routing?.mode??"main-first";if(f==="sticky-balanced"){let k=X$(y,S2(x,M),j.accountId);if(k.kind!=="serve"&&k.kind!=="last-path")return}else{let k=G$({...y,placement:z$(f),...P?{mainId:Z$(N?.routes()??[])}:{}});if(k.kind==="block"||!k.order.includes(j.accountId))return}let u=H.data;if(O.row){if(u?.kind!=="pool")return;let k=J.usableToken(O.row),c=O.row.identity??(k&&Q1(k));if(!k||!u.identity||c!==u.identity)return}else{if(u?.kind!=="vault"||!N)return;let k=await N.authorize(j.accountId);if(!k||k.credentialId!==u.credentialId||k.accountIdentity!==u.accountIdentity||(k.accountIdentity??Q1(k.accessToken))!==u.wireIdentity||O.identity!==void 0&&O.identity!==u.wireIdentity)return}return{accountId:j.accountId}},dropSameAccountRetry(){},dropChoice(j){let H=t(j);p(H),X2.get(H)?.drop(),X2.delete(H),S.delete(H)},chooseAccount:async(j)=>{let H,P=await N?.authority(),M=await $.storage(),b=P!==void 0&&P!=="local",x=()=>{throw new L2({kind:"no-account",providerID:q2,sessionID:j.sessionID,requestKind:j.kind,message:S1})};if(b){let X=performance.now()+b1;await $.awaitVaultRoster?.(),H=await V?.forRequest(X)}else{if(H=await V?.forRequest(),!(await J.current()).active){if(await $.slotPlaceholderWithoutMain?.())x();K?.warn("the account pool does not serve requests yet; refusing the request",{kind:j.kind});return}await J.prepareTokens(J.peek().rows,M)}let O=Y(),y=a(M,O,b),f=t$(m(y.filter((X)=>X.id!==j.rerouteFrom?.accountId),M,O));if(f)await f,O=Y(),y=a(M,O,b);let u=new Map(y.map((X)=>[X.id,X])),k=m(y,M,O),c=M?.routing?.maxSameAccountWait,G2=JSON.stringify([j.sessionID,j.kind]),C=[...v.values()].includes(j.sessionID),h=V?.activity.get(j.sessionID),Z2=h&&V?.accountKey(h.accountKey.accountId),N2=j.previousAccountId??j.rerouteFrom?.accountId,i=N2&&V?.accountKey(N2),s=j.rerouteFrom?.limit,C2=y.flatMap((X)=>{let W=V?.accountKey(X.id);if(!W)return[];let F=d2(X.quota),B=zZ(s&&X.id===N2?{account:W,kind:"rate-limit",reason:s.reason,scope:{kind:"pool"},windows:s.windows??[],observedAt:s.observedAt??O}:void 0,F,O),T=k.rateLimitMarks.get(X.id),E=k.refreshBackoff.get(X.id),R=[...T&&T>O?[{kind:"hard",until:T,cause:"rate-limit"}]:[],...E&&E>O?[{kind:"cooldown",until:E}]:[]],o=k.killswitch.get(X.id)!==!1&&!!(F?.primary||F?.secondary)&&!u$(l$(r1(X.quota)?X.quota:void 0),O)&&!(E&&E>O)&&(!X.row||!!J.usableToken(X.row));return[{account:W,admitted:o,placementEligible:o,ready:o&&!R.length&&!B.length,blockers:R,confirmedBlockers:B}]}),k2={phase:j.phase==="retry"?"after-limit":"pre-send",host:"opencode2",hostPhase:j.phase,now:O,clockNow:O,sessionId:j.sessionID,requestScope:{kind:"pool"},history:p$({requestId:j.sessionID,originalUrl:"https://api.openai.com/v1/responses",clockNow:O}),delivery:{owned:!0,attributable:!0,replayable:!0},candidates:C2,...j.phase==="retry"&&i?{attempted:i}:{},...j.phase==="retry"&&i&&s?{signal:{account:i,kind:"rate-limit",reason:s.reason,scope:{kind:"pool"},windows:s.windows??[],observedAt:s.observedAt??O},status:s.status}:{},remainingRetries:r2-(j.hostAttempt??r2)},Z1=()=>{let X=V?.owner();return JZ({accounts:C2.flatMap((W)=>{let F=u.get(W.account.accountId);if(!F)return[];return[{account:W.account,reading:d2(F.quota),usable:!F.row||!!J.usableToken(F.row),confirmedBlockers:W.confirmedBlockers,floors:a$(M)?e1(M,F.id===$$?void 0:F.id):void 0,marks:X?.snapshot()?.marks.filter((B)=>B.key.window==="account"&&B.key.scope.kind==="pool"&&s2(B.key.account,W.account)).flatMap((B)=>B.entries.map((T)=>({until:T.until,evidenceAt:T.evidenceAt})))}]}),now:O,effectiveModel:j.modelID,maxSameAccountWait:c,activity:h,currentAccountKey:Z2,provenance:X?.provenance})},H2=C2.find((X)=>i&&s2(X.account,i));if(j.phase==="retry"&&s&&H2){let X=j$({candidate:H2,activity:h,maxSameAccountWait:c,now:O,maxDelayMs:p2}),W=Y$({...k2,hold:X},{mode:"sticky"});if(W?.action==="hold"&&!C)return v.set(G2,j.sessionID),{hold:{delayMs:W.delayMs,target:W.target,checkpoint:W.checkpoint,kind:"hold"}};let F=y.filter((T)=>T.id!==N2);if(H2.confirmedBlockers?.some((T)=>T.confirmed)&&F.length>0&&F.every((T)=>{let E=C2.find((R)=>R.account.accountId===T.id);return E&&(!E.admitted||(k.rateLimitMarks.get(T.id)??0)>O)})){if(C)return{hostRetry:"veto"};let T=Q$(k2,Z1());if(t1(c)===0)return{hostRetry:"veto"};let E="delayMs"in T?T.delayMs:("retryAfterMs"in T)?T.retryAfterMs:void 0;if((k2.remainingRetries??0)<1||E===void 0||E>p2)return{hostRetry:"leave"};if(T.action==="hold"&&s2(T.account,H2.account))return v.set(G2,j.sessionID),{hold:{delayMs:E,target:T.target,checkpoint:T.checkpoint,kind:"terminal"}};return v.set(G2,j.sessionID),{waitThenReselect:{delayMs:E}}}}let m2;if(j.phase==="request"&&j.wake?.checkpoint&&H2&&(j.hostAttempt??r2)<r2&&t1(c)!==0&&s2(H2.account,j.wake.checkpoint.accountKey)){let X=j.wake.checkpoint,W=new Map(X.blockers.map((E)=>[E.window,{...E,confirmed:!0,confirmedByReading:!1,observedAt:X.decidedAt,provenance:"provider"}]));for(let E of H2.confirmedBlockers??[])W.set(E.window,E);let F={...H2,confirmedBlockers:[...W.values()]},B=j$({candidate:F,activity:h,maxSameAccountWait:c,now:O,maxDelayMs:p2});if(Y$({...k2,attempted:H2.account,candidates:C2.map((E)=>E===H2?F:E),hold:B,wake:{...j.wake,checkpoint:X}},{mode:"sticky"})?.action==="retain")m2=H2.account.accountId}let i2=new Set(j.rerouteFrom?[j.rerouteFrom.accountId]:[]),O2=M?.routing?.mode??"main-first",F2=j.kind==="primary",B2=new Set,v2,W2,g,z1=!1,z=(X)=>{let W=J$(k).projections.get(X)?.checkedAt,F=u.get(X)?.identity;return Q.reserve(j.sessionID,{accountId:X,inputBytes:s1,...W!==void 0?{quotaCheckedAt:W}:{},...F!==void 0?{wireIdentity:F}:{}})};try{for(;;){let X=new Set([...i2,...B2]);g=void 0,v2=void 0;let W=O2!=="sticky-balanced";if(m2&&!X.has(m2))g=m2,m2=void 0;else if(O2==="sticky-balanced"){let B=new Map(Q.placementSnapshot(j.sessionID)),T=B.get(j.sessionID);if(W=T===void 0,g=D2(k,y,M,j.sessionID,X,F2&&B2.size===0,B),g!==void 0&&B.get(j.sessionID)!==T)v2=B.get(j.sessionID)}if(g??=E2(k,O2,X,F2?void 0:w.activeAccount(j.sessionID),b?O2==="sticky-balanced"?null:Z$(N?.routes()??[]):void 0),g===void 0||B2.has(g)){if(i2.size>0){let B=new Map(k.rateLimitMarks);for(let T of i2)B.delete(T);k={...k,rateLimitMarks:B},i2.clear();continue}if(k.rateLimitMarks.size>0){k={...k,rateLimitMarks:new Map};continue}g=void 0;break}if(F2&&O2==="sticky-balanced")W2=z(g);if(!z1){z1=!0;let B=j.wake?void 0:await QZ({vaultMode:b,fresh:W,sessionId:j.sessionID,request:{modelId:j.modelID,kind:j.kind,retry:j.phase==="retry"||j.rerouteFrom!==void 0},routes:N?.routes()??[],routing:k,wait:{activity:h,accountKey:Z2,maxSameAccountWait:c},eligibleIds:y.filter((T)=>!X.has(T.id)).map((T)=>T.id)});if(B&&B!==g){if(W2)Q.rollback(W2);if(W2=void 0,O2==="sticky-balanced"){let T=new Map(Q.placementSnapshot(j.sessionID));g=D2(k,y,M,j.sessionID,X,F2,T,B)??g,v2=T.get(j.sessionID)??v2}else g=B;if(F2&&O2==="sticky-balanced")W2=z(g)}}let F=u.get(g)?.row;if(F){if(J.usableToken(F)!==void 0)break;K?.debug("pool row holds no usable token; choosing again",{accountId:g})}else{if(!N)break;let B=await N.authorize(g);if(B){S.set(t({...j,accountId:g}),B);break}K?.debug("the vault refused to serve an account; choosing again",{accountId:g})}if(W2)Q.rollback(W2);W2=void 0,B2.add(g)}if(g===void 0&&!b&&y.length===0&&await $.slotPlaceholderWithoutMain?.())x();if(g===void 0&&b&&N&&(y.length===0||B2.size>0)){let X=B2.size>0?"vault-refused":s$(N);throw K?.warn("vault mode: no vault account can serve; refusing the request",{cause:X}),new L2({kind:"no-account",providerID:q2,sessionID:j.sessionID,requestKind:j.kind,message:o$(X,N.name)})}if(g!==void 0){if(H)f2(j,g,H);let X=g,W=W2,F=v2,B=()=>{if(W)Q.finish(W,F);if(F2)w.record(j.sessionID,X),$.onRoute?.(j.sessionID,X,O2)};if(j.phase==="retry")X2.set(t({...j,accountId:g}),{commit:B,drop:()=>{if(W)Q.rollback(W)}}),W2=void 0;else B();let T=K?.info;l.served(k,g,K&&T?{info:(E,R)=>T.call(K,E,R)}:void 0)}if(g===void 0&&j.phase==="request"&&C2.length>0&&C2.every((X)=>!X.admitted)&&C2.some((X)=>k.killswitch.get(X.account.accountId)===!1||X.confirmedBlockers?.length)){let X=Q$(k2,Z1()),W=XZ({decision:X,now:O,host:"opencode2",requestThrow:!0,maxSameAccountWait:c});if(W.kind==="http"){let F=JSON.parse(W.body);throw new L2({kind:"no-account",providerID:q2,sessionID:j.sessionID,requestKind:j.kind,message:F.error.message})}}return K?.debug("pool account chosen",{kind:j.kind,accountId:g,mode:O2,...j.rerouteFrom?{rerouteFrom:j.rerouteFrom.accountId}:{}}),g}finally{if(W2)Q.rollback(W2)}},accountHeaders:async(j)=>{let{accountId:H}=j;D.delete(V2(j));let P=t(j),M=X2.get(P);X2.delete(P);let b=()=>{M?.commit()};try{let x=()=>new L2({kind:"no-account",providerID:q2,sessionID:j.sessionID,requestKind:j.kind,message:C4}),O=async(c)=>{if(!V)return;let G2=M2(P)??await V.forRequest();if(c.kind==="pool"){let s=J.peek().rows.find((C2)=>C2.id===H);if(!s||s.credentialEpoch!==c.credentialEpoch||J.usableToken(s)!==c.token)throw x()}let C=V.bindings().find((s)=>s.account.accountId===H),h=await G2?.beforeDispatch(C,()=>V.ownershipBindings(),H),Z2=V.accountKey(H);if(h&&h.status!=="ready"||C&&(!Z2||!s2(C.account,Z2)))throw x();let N2=V.owner(),i=C?{sessionId:j.sessionID,accountKey:C.account,dispatchedAt:Y(),ttlMs:jZ(JSON.stringify({model:j.modelID}))}:void 0;if(i){if(_.delete(i.sessionId),_.set(i.sessionId,i),_.size>a2){let s=_.keys().next().value;if(s!==void 0)_.delete(s)}}U.set(c,{owner:N2,probe:N2?.observe(C),dispatch:i,failed:!1,completed:!1})},y=N&&await N.authority()!=="local"?void 0:J.peek().rows.find((c)=>c.id===H);if(!y&&N){let c=t(j),G2=S.get(c)??await N.authorize(H);if(S.delete(c),!G2)throw K?.warn("the vault refused to serve an account; refusing the request",{accountId:H}),x();let C={kind:"vault",routeId:H,receipt:G2};return await O(C),b(),{headers:{...d1,"session-id":j.sessionID,authorization:`Bearer ${G2.accessToken}`,"chatgpt-account-id":G2.accountIdentity??Q1(G2.accessToken)??null},attempt:C}}let f=y?J.usableToken(y):void 0;if(!y||!f)throw K?.warn("pool row holds no usable token; refusing the request",{accountId:H}),x();let u=y.identity??Q1(f),k={kind:"pool",token:f,credentialEpoch:y.credentialEpoch,...u!==void 0?{identity:u}:{}};return await O(k),b(),{headers:{...d1,"session-id":j.sessionID,authorization:`Bearer ${f}`,"chatgpt-account-id":u??null},attempt:k}}finally{M?.drop()}},async rewriteRequest({request:j,sessionID:H,kind:P}){let M=$.codexEndpoint?n1(j.url,$.codexEndpoint()):j.url,b=M===j.url?j:new Request(M,j);return await y$(b,{sessionID:H,kind:P},A,$.responsesLite?.()??!1)??b},rewriteHandshakeURL:({url:j})=>$.codexEndpoint?n1(j,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:j,sessionID:H,kind:P})=>f$(j,{sessionID:H,kind:P},A),quotaFromHeaders:(j,H,P)=>{if(P.data?.kind==="vault")N?.reportUsage(P.data.routeId,{headers:j},P.data.receipt);if(P.data?.kind==="vault"&&B1()&&H>=200&&H<300)Z.set(P,{status:H,headers:j});return O4(j)},async limitFromResponse({status:j,headers:H,body:P,attempt:M}){if(j<400)return;let b=Y1(await P().catch(()=>"")),x=Y(),O=O1({...P2(b)?b:{},status:j},x);if(M.data?.kind==="vault"&&B1())E1(M.sessionID,M.data.receipt,{status:j,headers:H,body:b,limit:O,quota:N?.routes().find((u)=>u.id===M.accountId)?.quota,now:Y()});if(!O)return;let y=W1(O,x,j,q(M.accountId,M.data?.kind==="vault"));if(y.retryAfterMs!==void 0)return y;let f=x4(H);return f===void 0?y:{...y,retryAfterMs:f,resetAt:x+f,resetSource:"retry-after"}},inspectEvent:({data:j,transport:H,attempt:P})=>{let M=Y1(j),b=P.data&&U.get(P.data);if(b&&P2(M)&&(M.type==="response.failed"||M.type==="error"))b.failed=!0;if(b&&P2(M)&&M.type==="response.completed")b.completed=!0;if(P.data?.kind==="vault"&&j.includes("codex.rate_limits")){let O=Y1(j);if(P2(O)&&O.type==="codex.rate_limits")N?.reportUsage(P.data.routeId,{frame:O},P.data.receipt)}if(P.data?.kind==="vault"&&B1()&&(WZ(j)||H==="ws"&&j.includes('"response.completed"'))){let O=Y1(j);if(BZ(O))G.add(P);if(H==="ws"&&P2(O)&&O.type==="response.completed")E1(P.sessionID,P.data.receipt,{status:200,headers:new Headers,failed:G.has(P)})}let x=E4(M,Y(),q(P.accountId,P.data?.kind==="vault"));return H==="ws"&&P2(M)&&M.type==="response.completed"?{...x,done:!0}:x},limitFromError(j,H){let P=Y1(j.message),M=Y(),b=q(H.accountId,H.data?.kind==="vault");return NZ({...P2(P)?P:{},...j.status!==void 0?{status:j.status}:{}},M,b)??(j.message.includes("usage_limit_reached")?W1({window:"usage_limit_reached"},M,j.status,b):void 0)},async onAttemptEnd(j,H){let P=j.data,M=P&&U.get(P);if(M){let x=!H.error&&!H.limit&&!M.failed&&(j.transport==="ws"?M.completed:H.status!==void 0&&H.status>=200&&H.status<300);if(x&&M.dispatch&&V){let O=_.get(M.dispatch.sessionId);YZ(V.activity,M.dispatch,O===M.dispatch?V.accountKey(j.accountId):void 0,j.transport==="ws"?{kind:"ws",event:"response.completed",aborted:!1}:{kind:"http",completed:!0,failed:!1,aborted:!1})}M.owner?.afterProbe(M.probe,x,Boolean(H.limit))}if(P&&H.outputStarted&&H.error?.reason==="failed"){if(D.set(V2(j),{accountId:j.accountId,modelID:j.modelID,agent:j.agent,sessionID:j.sessionID,data:P.kind==="pool"?{kind:"pool",identity:P.identity}:{kind:"vault",credentialId:P.receipt.credentialId,accountIdentity:P.receipt.accountIdentity,wireIdentity:P.receipt.accountIdentity??Q1(P.receipt.accessToken)}}),D.size>a2){let x=D.keys().next().value;if(x!==void 0)D.delete(x)}}let b=P?.kind==="vault"&&B1()?Z.get(j):void 0;if(Z.delete(j),P?.kind==="vault"&&b&&!H.error&&!H.limit)E1(j.sessionID,P.receipt,{...b,failed:G.has(j)});if(P?.kind!=="vault"||H.status!==401)return;K?.warn("a vault account answered 401; reporting it to the vault",{accountId:j.accountId}),await N?.reportFailure(P.receipt,401)}},z2=(j,H,P)=>{let M=P.data;if(M?.kind==="vault"){N?.recordSnapshot(j,H.snapshot,H.complete,M.receipt);return}if(M?.kind!=="pool")return;if(J.peek().rows.find((x)=>x.id===j)?.credentialEpoch!==M.credentialEpoch){K?.debug("quota reading dropped: the row holds another credential",{accountId:j});return}J.recordSnapshot(j,H.snapshot,M.token,H.complete)},g2=(j,H,P)=>{let M=Y(),b=P.data?.kind==="vault";if(V){let x=P.data&&U.get(P.data),O=x?.owner??V.owner();if(!O)return;if(!x?.probe||O.registry!==x.probe.registry){O.dropSignal();return}let y=H,{command:f,provenance:u}=GZ({binding:x.probe.binding,baseRevision:x.probe.baseRevision,producerId:L,operationId:m$(),parsed:{window:H.reason,resetAt:y.resetAt??(H.retryAfterMs!==void 0?M+H.retryAfterMs:void 0)},reading:q(j,b),now:M,observedAt:y.observedAt??M,evidenceAt:M,resetSource:y.resetSource});O.enqueue(f,u);return}};return{adapter:Q2,beginTurn:$2,dispose:()=>v.clear(),attach(j){j.on("quota",(H)=>z2(H.accountId,H.quota,H.handle)),j.on("limit",(H)=>{g2(H.accountId,H.limit,H.handle),K?.debug("pool row refused the request",{accountId:H.accountId,via:H.via,reason:H.limit.reason,outputStarted:H.outputStarted})})},forgetSession(j){$2(j);for(let[H,P]of I)if(P.sessionID===j)p(H);_.delete(j),V?.forget(j);for(let[H,P]of D)if(P.sessionID===j)D.delete(H);Q.forget(j),w.forget(j),A.forget(j)},activeAccount:(j)=>w.activeAccount(j)}}import{resolve as CZ}from"node:path";import{Buffer as A4}from"node:buffer";import{resolve as FZ}from"node:path";function V1($){return A4.byteLength(JSON.stringify($))}function q4($){return $.reduce((Z,G)=>Z+V1(G),0)}function B$($,Z){return 2+$+Math.max(0,Z-1)}function S4($){let{head:Z,pending:G}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+B$(Z.inputBytes,Z.input.length)+1:0)+(G?20+B$(G.inputBytes,G.input.length)+10+B$(G.outputBytes,G.output.length)+(G.responseID===void 0?0:14+G.responseIDBytes)+1:0)}function KZ($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class LZ{enabled;caps=R1;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 G=KZ(Z);if(G?.type!=="response.create")return;if(!Array.isArray(G.input)){this.forget($);return}let J=G.previous_response_id,Q=this.entries.get($),Y=Q?.head;if(J&&J!==Y?.responseID){this.forget($);return}let{type:K,previous_response_id:N,input:V,...L}=G;this.keep($,{fields:J&&Q?Q.fields:L,fieldsBytes:J&&Q?Q.fieldsBytes:V1(L),...J&&Y?{head:Y}:{},pending:{input:V,inputBytes:q4(V),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,G){if(!this.enabled||!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed"))return;let J=this.entries.get($);if(!J?.pending)return;let Q=KZ(Z);if(!Q)return;let Y=J.pending,K=Q.response;if(Q.type==="response.created"&&typeof K?.id==="string")Y.responseID=K.id,Y.responseIDBytes=V1(K.id),this.keep($,J);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+=V1(Q.item),this.keep($,J)}else if(Q.type==="response.completed"&&typeof K?.id==="string"){if(K.id===J.head?.responseID||Y.responseID!==void 0&&K.id!==Y.responseID)return;let N={responseID:K.id,responseIDBytes:Y.responseID===K.id?Y.responseIDBytes:V1(K.id),input:[...J.head?.input??[],...Y.input,...Y.output],inputBytes:(J.head?.inputBytes??0)+Y.inputBytes+Y.outputBytes},V={...J,head:N,pending:void 0};if(!this.keep($,V))return;G?.({sessionID:$,responseID:N.responseID,bodyText:this.body(J.fields,N)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let G=S4(Z);if(this.forget($),G>this.caps.maxBytes)return!1;Z.bytes=G,this.entries.set($,Z),this.bytes+=G;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let J=this.entries.keys().next().value;if(J===void 0)break;this.forget(J)}return this.entries.has($)}}var PZ=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),MZ=globalThis,W$=MZ[PZ]??new Map;MZ[PZ]=W$;function D1($){let Z=JSON.stringify([FZ($.configPath),FZ($.statePath)]),G=W$.get(Z);if(!G)G=new LZ,W$.set(Z,G);return G}var b4=5000,R4=["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"],D4=["x-opencode-parent-session-id","x-parent-session-id"];function OZ($){let Z=TZ($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:_Z($?{...$,cachekeep:Z}:$)}}var xZ=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),AZ=globalThis,U1=AZ[xZ]??new Map;AZ[xZ]=U1;function k4($,Z){let G=[],J=()=>G.at(-1)?.location,Q=()=>{let V=J();if(!V)throw Error("no location holds keep-warm");return V},Y=(V,L)=>{N.remove(V),J()?.log?.debug(`cachekeep dropped target (${L})`,{sessionKey:V})},K=async(V)=>{if(V.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let L=V.accountId??"main",U=Q(),_=await U.source.accessFor(L,await U.storage());if(!_)throw Error(`pool row ${L} has no usable token`);return{token:_.token,identity:_.row.identity}},N=EZ({...R1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(V,L)=>Q().fetch(V,L),logger:{debug:(V,L)=>J()?.log?.debug(V,L),warn:(V,L)=>J()?.log?.warn(V,L)},getWindow:()=>J()?.settings().window,getSustain:()=>J()?.settings().sustain===!0,resolveLocal:K,activity:{store:{get size(){return J()?.limits?.activity.size??0},get:(V)=>J()?.limits?.activity.get(V),forgetSession:(V)=>J()?.limits?.activity.forgetSession(V),recordAccepted:(V)=>J()?.limits?.activity.recordAccepted(V)??!1},accountKey:({target:V})=>{let L=J(),U=V.meta.routingSessionId??V.sessionKey,_=V.accountId??"main";return L?.accounts.activeAccount(U)===_?L.limits?.accountKey(_):void 0}},vault:{owns:(V)=>J()?.vault.owns(V)===!0,authority:()=>Q().vault.authority(),reportUsage:(...V)=>J()?.vault.reportUsage(...V),send:async(V,L,U)=>{let _=Q();if(await _.vault.authority()!=="vault")return;return _.vault.send(V,L,U)}},activeAccount:(V)=>{if(V===void 0)throw Error("target has no session");let L=J(),U=L?.settings();if(!L||!U?.enabled){Y(V,"keep-warm is off");return}if(!U.subagents&&N.status().targets.some((q)=>q.sessionKey===V&&q.isSubagent)){Y(V,"subagent warming is off");return}let _=L.accounts.activeAccount(V);if(_===void 0){Y(V,"no account recorded for the session");return}return _},verifyCredential:({target:V,mode:L,identity:U})=>{if(V.meta.credentialMode!==L)throw Error(`a target captured in ${V.meta.credentialMode??"an unknown"} mode is not warmed with a ${L} credential`);if(U!==V.meta.chatgptAccountId)throw Y(V.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:N,settings:Z,holders:G,joinTimeoutMs:$.joinTimeoutMs??b4}}function w4($){try{let Z=JSON.parse($),G=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(G?.role!=="user")return!1;return(typeof G.content==="string"?G.content:Array.isArray(G.content)?G.content.map((Q)=>typeof Q?.text==="string"?Q.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function y4($){let Z={};for(let G of R4){let J=$.get(G);if(J)Z[G]=J}return Z}function qZ($,Z,G){let J=JSON.stringify([CZ($.configPath),CZ($.statePath)]),Q=U1.get(J);if(!Q)Q=k4(G,Z.settings()),U1.set(J,Q);let Y=Q,K=D1($);K.setEnabled(Y.settings.enabled);let N={location:{...Z,settings:()=>Y.settings}};Y.holders.push(N);let V=!1,L=async(U)=>{try{let _=N.location.settings();if(V||!_.enabled)return;if(U.kind!=="primary"){if(U.kind==="generate"&&w4(await U.request.clone().text())){if(V)return;Y.manager.remove(U.sessionID)}return}let q=U.attempt.data,A=q?.kind==="pool"?"local":q?.kind==="vault"?"vault":void 0;if(!A)return;let v=U.request.headers,$2=D4.some((V2)=>v.has(V2))||Z.parentOf!==void 0&&await Z.parentOf(U.sessionID)!==void 0;if($2&&!_.subagents)return;let S=await U.request.clone().text();if(V)return;let D=v.get("chatgpt-account-id")??void 0;Y.manager.track({sessionKey:U.sessionID,bodyText:S,accountId:U.attempt.accountId,isSubagent:$2,meta:{replayHeaders:y4(v),...D?{chatgptAccountId:D}:{},routingSessionId:U.sessionID,url:U.request.url,credentialMode:A}})}catch(_){Z.log?.warn("cachekeep capture failed",{error:_ instanceof Error?_.message:String(_)})}};return{manager:Y.manager,configure:(U)=>{Object.assign(Y.settings,U),K.setEnabled(Y.settings.enabled)},capture:L,forget:(U)=>Y.manager.remove(U),async release(){if(V)return;V=!0;let U=Y.holders.indexOf(N);if(U>=0)Y.holders.splice(U,1);if(Y.holders.length>0)return;if(U1.get(J)===Y)U1.delete(J);Y.manager.stop();let _;try{await Promise.race([Y.manager.tick().catch(()=>{}),new Promise((q)=>{_=setTimeout(q,Y.joinTimeoutMs),_.unref?.()})])}finally{clearTimeout(_)}}}}import{mkdirSync as I4}from"node:fs";import{dirname as f4,resolve as v4}from"node:path";function h4(){return SZ("opencode2")}var g4=2000;class wZ{path;options;sessions;frameTurns=new o2;#$=new Set;#Z=new Set;#G=new Set;#J=Promise.resolve();#X=!1;#z;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=DZ($,Z.uuid??c2)}get($,Z=c2){let G=this.sessions.get($);if(!G){let J=Z();G={threadID:J,turnID:Z(),windowID:`${J}:0`},this.sessions.set($,G),this.#Z.delete($),this.#G.delete($),this.#$.add($),this.#j()}return G}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#G.add($);this.#j()}#j(){if(this.#z)return;this.#z=setTimeout(()=>{this.#z=void 0,this.save()},this.options.saveDelayMs??g4),this.#z.unref?.()}save(){if(clearTimeout(this.#z),this.#z=void 0,!this.#X)this.#X=!0,this.#J=this.#J.then(()=>{return this.#X=!1,this.#Q()});return this.#J}settled(){return this.#z?this.save():this.#J}#Y(){if(this.#G.size===0)return;let $;try{$=V$(this.path)}catch{$=new Map}for(let Z of this.#G)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#G.clear()}async#Q(){if(this.#Y(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((J)=>{let Q=this.sessions.get(J);return Q?[[J,Q]]:[]}),Z=[...this.#Z],G=null;try{if(I4(f4(this.path),{recursive:!0}),G=await this.#B(),!G)return;let J;try{J=V$(this.path)}catch{J=new Map}await this.options.afterRead?.();let Q=!1;for(let Y of Z)if(J.delete(Y))Q=!0;for(let[Y,K]of $){if(J.get(Y)===K.threadID)continue;J.set(Y,K.threadID),Q=!0}if(Q)kZ(this.path,J)}catch{return}finally{await G?.release().catch(()=>{})}for(let[J,Q]of $)if(this.sessions.get(J)===Q)this.#$.delete(J);for(let J of Z)if(!this.sessions.has(J))this.#Z.delete(J)}#B(){return RZ(this.path,this.options.lockWaitMs??bZ)}}var yZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),IZ=globalThis,k1=IZ[yZ]??new Map;IZ[yZ]=k1;function m4($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.sessions instanceof Map&&typeof Z.get==="function"&&typeof Z.delete==="function"&&typeof Z.save==="function"&&typeof Z.settled==="function"&&(Z.frameTurns===void 0||Z.frameTurns!==null&&typeof Z.frameTurns.advance==="function"&&typeof Z.frameTurns.get==="function"&&typeof Z.frameTurns.completed==="function"&&typeof Z.frameTurns.forget==="function")}function fZ($=h4()){let Z=v4($),G=k1,J=k1.get(Z),Q=k1;if(J!==void 0&&!m4(J))G.compatible??=new Map,Q=G.compatible;let Y=Q.get(Z);if(!Y)Y=new wZ(Z),Q.set(Z,Y);let K=Y;return K.frameTurns??=new o2,Y}var U$=Symbol.for("cortexkit.openai-auth.v2.commands"),l4=I2("v2-command");function w1($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.closed instanceof AbortController&&typeof Z.menu?.open==="function"&&typeof Z.menu?.apply==="function"&&typeof Z.session?.get==="function"&&(Z.registration===void 0||Z.registration!==null&&typeof Z.registration.dispose==="function")}function N$($){l4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function u4(){let $=globalThis;return $[U$]??={locations:new Map},$[U$].locations??=new Map,$[U$]}async function pZ($,Z){let G=u4(),J=$.location.directory,Q={menu:Z,session:$.session,closed:new AbortController},Y=await hZ(J),K=await vZ(lZ,Y.dir,()=>uZ({...Y,drain:mZ,apply:(_)=>{let q=G.locations.get(J);if(!w1(q))throw Error("The OpenAI menu location was closed");return q.menu.apply(_)}})),N=G.locations.get(J);if(G.locations.set(J,Q),w1(N))N.closed.abort(),await N.registration?.dispose();let V={name:"openai",description:"OpenAI account menu",async execute(_){let q=[...G.locations.values()].find(w1)?.session;if(!q)return N$("no live location");let A=await q.get({sessionID:_.sessionID}),v=G.locations.get(A.location.directory);if(!w1(v))return N$("location closed");let $2=await gZ(_.sessionID,v.closed.signal);if(!$2||G.locations.get(A.location.directory)!==v){if(!$2&&!v.closed.signal.aborted)H$({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},_.sessionID);return N$(v.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let S=await v.menu.open(_.sessionID);H$(S,_.sessionID)}};G.command??=V,G.command.execute=V.execute;let L=G.command;try{Q.registration=await $.command.transform((_)=>{_.add(L)})}catch(_){if(Q.closed.abort(),G.locations.get(J)===Q)G.locations.delete(J);throw await K.release(),_}let U=!1;return async()=>{if(U)return;if(U=!0,Q.closed.abort(),G.locations.get(J)===Q)G.locations.delete(J);await K.release(),await Q.registration?.dispose()}}var p4="openai-auth-pool-browser",c4="openai-auth-pool-headless",d4="openai-auth-vault",i4="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Run /openai → Vault → Connect and approve the request before trying again.";async function N1($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function oZ($){return{method:{id:d4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await cZ($.paths,$.name)!=="vault")throw Error(i4)}}}function sZ($){let Z=(G,J,Q)=>({method:{id:G,type:"oauth",label:J},async authorize(){if($.vault)await N1($.vault);let Y=await $.beginLogin({version:$.version,headless:Q});return{url:Y.url,instructions:Y.instructions,mode:"auto",callback:Y.completion}}});return[Z(p4,"ChatGPT (openai-auth pool, browser)",!1),Z(c4,"ChatGPT (openai-auth pool, headless)",!0)]}function F$($){let Z=(G)=>typeof G==="string"?G:"";return X1({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===nZ||dZ($)}function n4($){if($.accountId)return $.accountId;let Z=$.access?x1($.access):void 0;return Z?A1(Z):void 0}async function rZ($,Z,G,J={}){if(J.vault)await N1(J.vault);if(F$(G))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Q=iZ($,{rowLocks:(A)=>aZ(Z,A)}),Y=await Q.read();if(Y.status!=="ready")throw Error(`the account pool cannot be read (${Y.status}); the login was not stored`);let K={type:"oauth",refresh:G.refresh,...G.access!==void 0?{access:G.access}:{},...G.expires!==void 0?{expires:G.expires}:{}},N=n4(G);if(J.vault)await N1(J.vault);let V=N!==void 0?{identity:N}:{};if(J.origin==="import"){let A=Y.rows.find((v)=>N!==void 0&&v.identity===N||v.credential?.type==="oauth"&&v.credential.refresh===G.refresh);if(A)return{id:A.id,operation:"kept"}}let L=Y.rows.filter((A)=>A.type==="oauth"&&!A.invalid),U=N?L.find((A)=>A.identity===N):void 0,_=Y.rows.find((A)=>A.id===y1);if(U)return{id:(await Q.replace(U.id,K,V)).id,operation:"replaced"};if(!_){let A=await Q.add({id:y1,credential:K,...V,...G.label!==void 0?{label:G.label}:{}});return{id:A.id,operation:A.outcome==="added-disabled"?"added-disabled":"added"}}if(!_.invalid&&!_.credential)return{id:(await Q.replace(y1,K,V)).id,operation:"replaced"};let q=await Q.add({id:G.id,credential:K,...V,...G.label!==void 0?{label:G.label}:{}});return{id:q.id,operation:q.outcome==="added-disabled"?"added-disabled":q.outcome==="rotated"?"replaced":"added"}}function a4($){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","maxSameAccountWait"].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 $0($){let Z={...$,allowAction:a4,unavailableSections:[]};return{open:(G)=>tZ(Z,G),apply:(G)=>{let J=G!==null&&typeof G==="object"?G:{},Q=J.values&&typeof J.values==="object"&&!Array.isArray(J.values)?Object.fromEntries(Object.entries(J.values).filter(([,Y])=>Y===null||["string","number","boolean"].includes(typeof Y))):void 0;return eZ(Z,{command:"openai",sectionId:typeof J.sectionId==="string"?J.sectionId:"",actionId:typeof J.actionId==="string"?J.actionId:"",...Q?{values:Q}:{},...J.confirmed===!0?{confirmed:!0}:{},...typeof J.itemId==="string"?{itemId:J.itemId}:{},...typeof J.sessionId==="string"?{sessionId:J.sessionId}:{}})}}}function o4($,Z){if(!Z0($.modelID??$.id)){$.enabled=!1;return}let G=z0($.id);if(G)$.limit={...G};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((J)=>[J.id,J])).values()]}function J0($){return $.model.transform((Z)=>{let G=Z.list(q2);for(let J of G){let Q=G0(String(J.id)),Y=Q?G.find((K)=>String(K.id)===Q):void 0;Z.update(q2,String(J.id),(K)=>o4(K,Y?.variants?.map((N)=>({...N,id:String(N.id)}))))}})}class K${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(!X0())return;await this.safely(async()=>{let G={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:G}),this.requests.set(Z.attemptId,$),this.pending.size>512){let J=this.pending.keys().next().value;if(J)this.take(J)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let G=this.take($);if(G)await this.safely(()=>I1({...G,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let G=this.requests.get($.attemptId),J=G&&this.take(G);if(!J)return;let{reason:Q,message:Y}=Z.error,K=Y?`${Q}: ${Y}`:Q;await this.safely(()=>I1({...J,error:f1(K,G?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>I1({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 L${counts=new Map;record($,Z){let G=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof G==="number"&&Number.isFinite(G)?G:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function W0($){return async(Z)=>{let G=Z.credential;if(G.type!=="oauth"||!G.access)throw Error("the row holds no access token to poll with");let J=await j0({accessToken:G.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,J),Y0(J,$.now(),!0)}}function V0($){let{source:Z,counts:G,now:J}=$,Q=async(L)=>{let U=await Z.rowAccess(L,await $.storage());if(!U?.row)throw new Q0("unknown_account",`${L==="main"?"Main":"Fallback"} account ${L} was not found.`);return B0(L,U)},Y=async(L)=>{if($.authority&&await $.authority()!=="local")return{account:L,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[U]=await Z.pollRows(await $.storage(),{ids:[L]});if(!U)return{account:L,ok:!1,error:"targeted quota refresh returned no result"};return{account:U.id,ok:U.ok,...U.error!==void 0?{error:U.error}:{}}},K=(L)=>Z.peek().rows.find((U)=>U.id===L),N=(L)=>{let U=K(L);if(!U)return null;let _=d2(U.quota)??{},q=G.applicable(U),A=Math.max(0,...[_.primary?.checkedAt,_.secondary?.checkedAt].filter((v)=>typeof v==="number"));return{quota:{..._,...q!==void 0?{resetCreditsApplicable:q}:{}},checkedAt:A,refreshAfter:A,...U.identity!==void 0?{accountId:U.identity}:{}}};return{resolveResetTarget:Q,refreshResetTargetQuota:Y,quotaManager:{isRateLimited:(L)=>{let U=K(L);if(!U)return!1;let _=$.rateLimitMarks().get(U.id);return _!==void 0&&_>J()},getMain:()=>N("main"),getFallback:(L)=>N(L)}}}import{resolve as U0}from"node:path";var s4=1024;class P${pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=s4){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 G of this.reservations.values())if(G.sessionId!==$)Z.set(G.sessionId,G.pin);return Z}reserve($,Z){let G={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,G),G}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 G of this.listeners)G($,Z);while(this.pins.size>this.limit){let G=this.pins.keys().next().value;if(G===void 0)break;this.forget(G)}}place($){return q1(this.placementSnapshot($.sessionId),$,(Z,G)=>this.set(Z,G))}}var N0=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),H0=globalThis,v1=H0[N0]??new Map;H0[N0]=v1;function r4($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.get==="function"&&typeof Z.forget==="function"&&typeof Z.subscribe==="function"&&typeof Z.snapshot==="function"&&typeof Z.place==="function"&&typeof Z.placementSnapshot==="function"&&typeof Z.reserve==="function"&&typeof Z.rollback==="function"&&typeof Z.finish==="function"}function F0($){let Z=JSON.stringify([U0($.configPath),U0($.statePath)]),G=v1,J=v1.get(Z);if(J!==void 0&&!r4(J)){let Y=v1;Y.compatibleV1??=new Map,G=Y.compatibleV1}let Q=G.get(Z);if(!Q)Q=new P$,G.set(Z,Q);return Q}import{statSync as t4}from"node:fs";import{resolve as e4}from"node:path";function O0($){return $.map((Z)=>{try{let G=t4(Z);return`${G.ino}:${G.size}:${G.mtimeMs}:${G.ctimeMs}`}catch{return"?"}}).join("|")}function M$($){return O0([$.vault.paths.tokenPath,$.vault.paths.statePath])}function K0($){return O0([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+M$($)}class x0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;protocol=q0;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:K0($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),G=this.subscriptions.get($.pins);if(!G){let J=new Set;G={producers:J,stop:$.pins.subscribe((Q,Y)=>{let K=J.values().next().value;if(K)this.publish(K,{sessionId:Q,pin:Y,accountId:Y?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,G)}return G.producers.add($),this.timer??=setInterval(()=>{for(let J of this.producers){let Q={stamp:K0(J),roster:J.vault.snapshot()},Y=this.observations.get(J);if(Q.stamp!==Y?.stamp||Q.roster!==Y?.roster)this.observations.set(J,Q),this.publish(J)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),G.producers.delete($),!G.producers.size)G.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;await($.write??A0)(this.file,$,Z,()=>this.producers.has($))}).catch(()=>{I2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var A0=async($,Z,G,J)=>{let Y=await Z.vault.authority()!=="local",K=M$(Z),N=()=>J()&&Z.vault.enrolled()===Y&&M$(Z)===K,V=await(Y?F1(Z.paths):t2(Z.paths)),L=Y?_0(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((q)=>q.id)),V,Date.now()):E0((await Z.source.sidebarView()).rows,V,Date.now()),U={canWrite:N,vaultMode:Y};if(await P0(L,$,U),!N()||!G)return;let _=L.vaultAccounts??L.fallbacks;if(G.accountId===void 0){await C0(G.sessionId,_,$,U);return}if(G.pin){let q=Date.now();await T0({sessionId:G.sessionId,assignment:{accountId:G.pin.accountId,wireAccountId:G.pin.wireIdentity,inputBytes:G.pin.inputBytes??0,quotaCheckedAt:G.pin.quotaCheckedAt,assignedAt:q,lastSeenAt:q},validPinnedAccountIds:[...Y?[]:["main"],..._.filter((A)=>A.enabled).map((A)=>A.id)]},$,U)}await M0({sessionId:G.sessionId,activeId:G.accountId,route:G.route??L.route,updatedAt:Date.now()},_,$,U)},q0=2,S0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),b0=globalThis,H1=b0[S0]??new Map;b0[S0]=H1;function R0($,Z=L0(),G=2000){let J=e4(Z),Q=H1.get(J);if(Q?.protocol!==q0)Q=new x0(J,G),H1.set(J,Q);let Y=Q;$={...$,write:$.write??A0};let K=Y.add($),N=!1;for(let[V,L]of $.pins.snapshot())Y.publish($,{sessionId:V,pin:L,accountId:L.accountId,route:"sticky-balanced"});return{publish:()=>Y.publish($),route:(V,L,U)=>{Y.publish($,{sessionId:V,accountId:L,route:U})},async release(){if(N)return;if(N=!0,K(),await Y.settled(),Y.empty&&H1.get(J)===Y)H1.delete(J)}}}var g1="cortexkit-openai-auth",z5=5000;async function D0($,Z,G,J=new j1,Q,Y,K){let N=new K$(G),V=new $5,L=new Map,U=new Map,_=(S)=>{U.delete(S);for(let D of L.keys())if(D.startsWith(`${S}:`))L.delete(D)},q=(S)=>{K?.(S.sessionID),Y?.send(S.sessionID,S.frame)},v=await p1({session:{hook:(S,D,V2)=>$.session.hook(S,async(X2)=>{let I=S==="http.request"?X2:void 0,p=S==="experimental.ws.handshake"?X2:void 0,M2=(I?I.request.headers:p?new Headers(p.headers):void 0)?.get("authorization")===`Bearer ${y2(Z.providerID)}`,t={};if(p)L.delete(`${p.sessionID}:${p.kind}`);try{await V.run(t,()=>D(X2))}catch(w){if(M2&&!(w instanceof L2))throw v0(w);throw w}if(I&&M2&&t.attempt){let w=I.request.headers.get("thread-id");if(w)I.request.headers.set("session-id",w)}if(I&&M2&&t.attempt)await N.captureHttp(I.request,t.attempt);if(I&&M2&&t.attempt)await Q?.({sessionID:I.sessionID,kind:I.kind,request:I.request,attempt:t.attempt});if(p&&M2&&t.attempt)p.headers["session-id"]=J.get(p.sessionID).threadID;if(S==="experimental.ws.send"){let w=X2,l=L.get(`${w.sessionID}:${w.kind}`);if(l)await N.frame(w.frame,l.attempt);if(l&&w.kind==="primary")q(w)}if(I||p){let w=I??p;if(!w)return;let a=(I?I.request.headers:new Headers(w.headers)).get("authorization")?.replace(/^Bearer /,"");if(M2&&a)U.set(w.sessionID,a);else U.delete(w.sessionID);if(p){let m=`${p.sessionID}:${p.kind}`;if(M2&&a&&t.attempt)L.set(m,{bearer:a,attempt:t.attempt,url:p.url,headers:new Headers(Object.entries(p.headers).filter(([E2])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(E2.toLowerCase())))});else L.delete(m)}if(U.size>512){let m=U.keys().next().value;if(m)U.delete(m)}if(L.size>512){let m=L.keys().next().value;if(m)L.delete(m)}}else if(S==="experimental.ws.receive"){let w=X2,l=L.get(`${w.sessionID}:${w.kind}`);if(l){if(J.frameReceived(w.sessionID,w.frame),w.kind==="primary"){let a;if(Y?.receive(w.sessionID,w.frame,(m)=>{a=m}),a)try{let m=I$(a,l.url,l.headers,J);if(m)await Q?.({sessionID:w.sessionID,kind:"primary",request:m,attempt:l.attempt})}catch(m){G.warn("cachekeep WebSocket capture failed",{error:m instanceof Error?m.message:String(m)})}}w.frame=h0(w.frame,l.bearer)}}else if(S==="retry"){let w=X2,l=U.get(w.sessionID);if(l)Object.assign(w.error,{message:f1(w.error.message,l)})}},V2)},event:{subscribe:(S)=>async function*(){for await(let D of $.event.subscribe(S)){if(D.type==="session.deleted")_(D.data.sessionID);yield D}}()}},{...Z,rewriteRequest:async(S)=>{let D=V.getStore();if(D)D.attempt=S.attempt;return Z.rewriteRequest?.(S)},rewriteHandshakeURL:(S)=>{let D=V.getStore();if(D)D.attempt=S.attempt;return Z.rewriteHandshakeURL?.(S)},onAttemptEnd:async(S,D)=>{await N.end(S,D),await Z.onAttemptEnd?.(S,D)},rewriteResponse:async(S)=>{await N.response(S.request,S.response.status);let D=await Z.rewriteResponse?.(S)??S.response;return g0(D,S.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(S)=>{let D=S.get("authorization");return D?.startsWith("Bearer ")?D.slice(7):void 0}},hostRetryLimit:r2,logger:{info:(S,D)=>G.info?.(S,{data:D}),warn:(S,D)=>G.warn(S,{data:D})}}),$2=v.dispose;return{...v,dispose:async()=>{U.clear(),L.clear(),await $2(),await N.settle(),N.clear()}}}function _$($={}){return{id:g1,setup:(Z)=>G5(Z,$)}}async function G5($,Z={}){let u=[];try{let G=I2("opencode2");let J=I2("quota");let Q=Z.version??l0;await e0({version:Q,...Z.runtimeLayout});let Y=Z.paths??(()=>p0(m0()));let K=await F1(Y());let N=K?.logging?.level;if(N&&typeof N==="string")w0(N);let V=Z.fetch??fetch;let L=Z.now??Date.now;let U=Z.poolMigration??Z4;if(!U&&!e2(Y().configPath)){G.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let C=(Z2)=>{throw new L2({kind:"no-account",providerID:q2,sessionID:Z2.sessionID,requestKind:Z2.kind,message:S1})},h=await D0($,{providerID:q2,chooseAccount:C,accountHeaders:C},G);return()=>h.dispose()}let _=Z.vault?.firstRosterWaitMs??n0;let q=$4({host:"opencode",stateDir:Z.vault?.stateDir??f0(Y().statePath),reservedRouteIds:()=>I.peek().rows.map((C)=>C.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>V},Y());let A=q.vault;let v=async()=>await A.authority()==="local"?t2(Y()):F1(Y());let $2=!1;let S=!1;const D=K1(u,{[Symbol.dispose](){if(!$2)q.release()}},0);await A.authority();let V2=q.firstRoster;let X2=new L$;let I=new a0({paths:Y,refreshProvider:async(C)=>{let h=await I0({refreshToken:C.refresh,fetchImpl:V,now:L}),Z2=y0({id_token:"",access_token:h.access,refresh_token:h.refresh});return{...h,...Z2?{identity:Z2}:{}}},pullQuota:W0({fetchImpl:V,now:L,counts:X2,logger:J}),now:L,vaultIdentities:()=>A.identities(),vaultMode:()=>A.enrolled(),vaultAuthority:()=>A.authority(),vaultFirstRoster:V2,vaultFirstRosterBackgroundWaitMs:_,log:I2("pool")});if(await A.authority()==="local")await I.load();let p=new o0({pool:I,vault:A,log:(C)=>G.warn(C)});const f2=K1(u,{[Symbol.dispose](){if(!$2)p.dispose()}},0);let M2=Z.heartbeat===!1?void 0:await r0({version:Q,logger:I2("heartbeat")});let t=Z.fence??(()=>u0({currentVersion:Q}));let w=Z.slot??z4();let l=async()=>c0(Y(),await w.get({path:{id:"openai"}}));let a=!1;let m=U?s0({paths:Y,slot:w,version:Q,fence:t,runDeps:{vaultServes:()=>A.serves()},paused:async()=>await A.authority()!=="local",migrate:async(C)=>{let h=await d0(C);if(a=h.status==="refused",!S)await I.load();return h},adopt:async(C)=>{if(S)return{status:"retry",reason:"unsettled"};if(!await T$(V2,_))return{status:"retry",reason:"vault-roster-pending"};if(S)return{status:"retry",reason:"unsettled"};let h=await i0(C);if(!S)await I.load();return h}}):void 0;m?.start();q.start();let E2=F0(Y());let S2=R0({paths:Y(),source:I,pins:E2,vault:A},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const D2=K1(u,{[Symbol.dispose](){if(!$2)S2.release()}},0);S2.publish();let U2=Z.codex??new j1(void 0,void 0,fZ());let $1=OZ(K);let Q2=D1(Y());let z2=qZ(Y(),{source:I,limits:p,storage:v,vault:A,accounts:o1(Y()),settings:()=>$1,parentOf:async(C)=>(await $.session.get({sessionID:C}))?.parentID??void 0,fetch:V,log:I2("cachekeep")},{now:L,codexResponsesUrl:h1().codexApiEndpoint,...Z.cacheKeep});const g2=K1(u,{[Symbol.dispose](){if(!$2)z2.release()}},0);let j=HZ({limits:p,codex:U2,onRoute:S2.route,source:I,slotPlaceholderWithoutMain:l,storage:v,pins:E2,sessionAccounts:o1(Y()),vault:A,awaitVaultRoster:async()=>{await T$(A.awaitRequestRoster(),b1)},responsesLite:()=>h1().responsesLite,codexEndpoint:()=>h1().codexApiEndpoint,now:L,log:G});let H=await D0($,j.adapter,G,U2,(C)=>z2.capture(C),Q2,(C)=>z2.forget(C));j.attach(H);let P=await $.session.hook("prompt",(C)=>{j.beginTurn(C.sessionID)});let M=async(C)=>{if(await N1(A),e2(Y().configPath))return;if(await m?.idle(),e2(Y().configPath))return;if(a&&!F$(C)&&(await t()).open){await I.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let b=async(C)=>{await M(C);let h=await rZ(I.poolStore(),Y(),C,{vault:A});if(!e2(Y().configPath))await m?.requestAdoption();await I.load(),G.info("ChatGPT login stored in the account pool",h)};let x=await l1($,{integrationID:q2,methods:sZ({beginLogin:Z.beginLogin??C$,version:Q,vault:A}),onLogin:(C)=>b(C),label:"ChatGPT (openai-auth account pool)",vault:oZ(A)});let O=await J0($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let y=$.command&&$.location?await pZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??$0({...V0({rateLimitMarks:()=>p.marks(),source:I,storage:v,counts:X2,now:L,authority:()=>A.authority()}),fetchImpl:V,now:L,randomUUID:Z5,accountStoragePath:Y().configPath,accountStatePath:Y().statePath,packageVersion:Q,layoutNotice:t0,loadAccounts:t2,store:()=>I.poolStore(),migration:async()=>{if(e2(Y().configPath))return{migrated:!0};let C=await t();return{migrated:!1,blockers:C.open?[]:C.blockers}},beginAccountLogin:Z.beginLogin??C$,refreshAllQuota:async()=>(await I.pollRows(await t2(Y()))).map((C)=>({...C,account:C.id})),getStickyRouting:async(C)=>E2.get(C),cacheKeepManager:z2.manager,setCacheKeepEnabled:(C)=>z2.configure({enabled:C}),setCacheKeepSubagents:(C)=>z2.configure({subagents:C}),setCacheKeepSustain:(C)=>z2.configure({sustain:C}),setCacheKeepWindow:(C)=>z2.configure({window:C}),afterWrite:()=>I.load(),refreshSidebar:()=>S2.publish(),clearStickyRouting:async(C)=>{let h=E2.get(C)!==void 0;return E2.forget(C),h},vault:A})):void 0;let f=new AbortController;(async()=>{try{for await(let C of $.event.subscribe({signal:f.signal}))if(C.type==="session.deleted")j.forgetSession(C.data.sessionID),z2.forget(C.data.sessionID),Q2.forget(C.data.sessionID)}catch(C){if(!f.signal.aborted)G.warn("stopped listening for session deletion",{error:C instanceof Error?C.message:String(C)})}})();$2=!0;return async()=>{S=!0,f.abort(),j.dispose();let C=z2.release();await y?.(),m?.dispose(),await p.dispose(),await S2.release(),await Promise.allSettled([H.dispose(),P.dispose(),x.dispose(),O.dispose()]);let h;try{await Promise.race([Promise.all([m?.idle(),I.settled(),U2.store?.settled(),C]),new Promise((Z2)=>{h=setTimeout(Z2,z5),h.unref?.()})])}finally{clearTimeout(h),await q.release(),await M2?.release()}}}catch(k){var c=k,G2=1}finally{k0(u,c,G2)}}var J5=_$(),k7={id:g1,setup:J5.setup,server:G4.server};export{k7 as default,_$ as createOpenAIAuthPlugin,g1 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.10.0",
3
+ "version": "1.10.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -66,7 +66,7 @@
66
66
  },
67
67
  "devDependencies": {
68
68
  "@ai-sdk/openai": "3.0.88",
69
- "@cortexkit/common-auth": "^0.39.1",
69
+ "@cortexkit/common-auth": "^0.39.2",
70
70
  "@cortexkit/openai-auth-core": "workspace:*",
71
71
  "@opencode/plugin": "2.2.5"
72
72
  },
File without changes