@cortexkit/opencode-openai-auth 1.9.2 → 1.9.4

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 x,J as f,K as g,L as h,M as i,N as j,O as k,P as l,Q as m,R as n,S as o,T as p,U as q,V as r,W as s,X as t,Y as u,Z as v,_ as w,aa as y,ba as z,ca as A,da as B,ea as C,fa as D,ga as E,ha as F,ia as G,j as c,k as d,l as e}from"./index-qdy57ej9.js";import"./index-cb1kwn36.js";import"./index-5sgqz46z.js";import{ld as a,md as b}from"./index-6r27fz5a.js";import"./index-mtf8pv2w.js";import"./index-hpev556z.js";import"./index-6j3059fy.js";import"./index-k1dfzavn.js";import"./index-hpb6k6st.js";import"./index-bvswyxpt.js";import"./index-2f9w48sc.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 x,J as f,K as g,L as h,M as i,N as j,O as k,P as l,Q as m,R as n,S as o,T as p,U as q,V as r,W as s,X as t,Y as u,Z as v,_ as w,aa as y,ba as z,ca as A,da as B,ea as C,fa as D,ga as E,ha as F,ia as G,j as c,k as d,l as e}from"./index-4p45bmbz.js";import"./index-xx3k2qbv.js";import"./index-7bjgmbx4.js";import{md as a,nd as b}from"./index-6xz3n4qh.js";import"./index-81yvwra9.js";import"./index-rrtsaz80.js";import"./index-2esezxst.js";import"./index-cmybrjbd.js";import"./index-hz6f9gpq.js";import"./index-g3gbp1m4.js";import"./index-v1ztg103.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{Xe as b,Ye as c}from"../index-hpev556z.js";import{af as a}from"../index-6j3059fy.js";import"../index-hpb6k6st.js";import"../index-bvswyxpt.js";import"../index-2f9w48sc.js";export{b as writePortFile,c as isOpenaiRpcStateDir,a as discoverPortFile};
1
+ import{Ye as b,Ze as c}from"../index-rrtsaz80.js";import{bf as a}from"../index-2esezxst.js";import"../index-hz6f9gpq.js";import"../index-g3gbp1m4.js";import"../index-v1ztg103.js";export{b as writePortFile,c as isOpenaiRpcStateDir,a as discoverPortFile};
@@ -1 +1 @@
1
- import{of as b}from"../index-k1dfzavn.js";import"../index-hpb6k6st.js";import"../index-2f9w48sc.js";export{b as isNotifyPayload};
1
+ import{pf as b}from"../index-cmybrjbd.js";import"../index-hz6f9gpq.js";import"../index-v1ztg103.js";export{b as isNotifyPayload};
@@ -1 +1 @@
1
- import{bf as F,cf as f}from"../index-6j3059fy.js";import"../index-hpb6k6st.js";import"../index-2f9w48sc.js";function y(r,s,v){return f(r,s,v)}export{y as createRpcClient,F as DEFAULT_RPC_TIMEOUT_MS};
1
+ import{cf as F,df as f}from"../index-2esezxst.js";import"../index-hz6f9gpq.js";import"../index-v1ztg103.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{Bf as a,Cf as b,Df as c,Ef as d}from"../index-bvswyxpt.js";import"../index-2f9w48sc.js";export{a as tmpdir,d as resolveRpcDir,c as getRpcDir,b as RPC_DIRECTORY_PREFIX};
1
+ import{Cf as a,Df as b,Ef as c,Ff as d}from"../index-g3gbp1m4.js";import"../index-v1ztg103.js";export{a as tmpdir,d as resolveRpcDir,c as getRpcDir,b as RPC_DIRECTORY_PREFIX};
@@ -1 +1 @@
1
- import{$b as h,Ac as I,Bc as J,Cc as K,Dc as L,Ec as M,Fc as N,Gc as O,Hc as P,Ic as Q,Jc as R,Kc as S,Lc as T,Ub as a,Vb as b,Wb as c,Xb as d,Yb as e,Zb as f,_b as g,ac as i,bc as j,cc as k,dc as l,ec as m,fc as n,gc as o,hc as p,ic as q,jc as r,kc as s,lc as t,mc as u,nc as v,oc as w,pc as x,qc as y,rc as z,sc as A,tc as B,uc as C,vc as D,wc as E,xc as F,yc as G,zc as H}from"./index-5sgqz46z.js";import"./index-6r27fz5a.js";import"./index-mtf8pv2w.js";import"./index-k1dfzavn.js";import"./index-hpb6k6st.js";import"./index-2f9w48sc.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{$b as g,Ac as H,Bc as I,Cc as J,Dc as K,Ec as L,Fc as M,Gc as N,Hc as O,Ic as P,Jc as Q,Kc as R,Lc as S,Mc as T,Vb as a,Wb as b,Xb as c,Yb as d,Zb as e,_b as f,ac as h,bc as i,cc as j,dc as k,ec as l,fc as m,gc as n,hc as o,ic as p,jc as q,kc as r,lc as s,mc as t,nc as u,oc as v,pc as w,qc as x,rc as y,sc as z,tc as A,uc as B,vc as C,wc as D,xc as E,yc as F,zc as G}from"./index-7bjgmbx4.js";import"./index-6xz3n4qh.js";import"./index-81yvwra9.js";import"./index-cmybrjbd.js";import"./index-hz6f9gpq.js";import"./index-v1ztg103.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 +1 @@
1
- import{a as U,b as V}from"./index-96971sba.js";import{Ff as R}from"./index-2f9w48sc.js";var E=R((M,Q)=>{var{defineProperty:H,getOwnPropertyDescriptor:W,getOwnPropertyNames:X}=Object,Y=Object.prototype.hasOwnProperty,Z=(z,q)=>{for(var B in q)H(z,B,{get:q[B],enumerable:!0})},$=(z,q,B,F)=>{if(q&&typeof q==="object"||typeof q==="function"){for(let v of X(q))if(!Y.call(z,v)&&v!==B)H(z,v,{get:()=>q[v],enumerable:!(F=W(q,v))||F.enumerable})}return z},A=(z)=>$(H({},"__esModule",{value:!0}),z),L={};Z(L,{refreshToken:()=>D});Q.exports=A(L);var K=U(),G=V();async function D(z){let q=z?.project,B=z?.team;if(!q&&!B){let v=(0,G.findProjectInfo)();q=v.projectId,B=v.teamId}else if(!q||!B){let v=(0,G.findProjectInfo)();q=q??v.projectId,B=B??v.teamId}if(!q)throw new K.VercelOidcTokenError("Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`");let F=(0,G.loadToken)(q);if(!F||(0,G.isExpired)((0,G.getTokenPayload)(F.token),z?.expirationBufferMs)){let v=await(0,G.getVercelToken)({expirationBufferMs:z?.expirationBufferMs});if(F=await(0,G.getVercelOidcToken)(v,q,B),!F)throw new K.VercelOidcTokenError("Failed to refresh OIDC token");(0,G.saveToken)(F,q)}process.env.VERCEL_OIDC_TOKEN=F.token;return}});export default E();
1
+ import{a as U,b as V}from"./index-2bf808fw.js";import{Gf as R}from"./index-v1ztg103.js";var E=R((M,Q)=>{var{defineProperty:H,getOwnPropertyDescriptor:W,getOwnPropertyNames:X}=Object,Y=Object.prototype.hasOwnProperty,Z=(z,q)=>{for(var B in q)H(z,B,{get:q[B],enumerable:!0})},$=(z,q,B,F)=>{if(q&&typeof q==="object"||typeof q==="function"){for(let v of X(q))if(!Y.call(z,v)&&v!==B)H(z,v,{get:()=>q[v],enumerable:!(F=W(q,v))||F.enumerable})}return z},A=(z)=>$(H({},"__esModule",{value:!0}),z),L={};Z(L,{refreshToken:()=>D});Q.exports=A(L);var K=U(),G=V();async function D(z){let q=z?.project,B=z?.team;if(!q&&!B){let v=(0,G.findProjectInfo)();q=v.projectId,B=v.teamId}else if(!q||!B){let v=(0,G.findProjectInfo)();q=q??v.projectId,B=B??v.teamId}if(!q)throw new K.VercelOidcTokenError("Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`");let F=(0,G.loadToken)(q);if(!F||(0,G.isExpired)((0,G.getTokenPayload)(F.token),z?.expirationBufferMs)){let v=await(0,G.getVercelToken)({expirationBufferMs:z?.expirationBufferMs});if(F=await(0,G.getVercelOidcToken)(v,q,B),!F)throw new K.VercelOidcTokenError("Failed to refresh OIDC token");(0,G.saveToken)(F,q)}process.env.VERCEL_OIDC_TOKEN=F.token;return}});export default E();
@@ -0,0 +1 @@
1
+ import{b as a}from"./index-2bf808fw.js";import"./index-v1ztg103.js";export default a();
@@ -1,4 +1,4 @@
1
- import{Ie as h,Pe as u,Qe as P}from"./index-mtf8pv2w.js";import{qf as M,rf as R,wf as S}from"./index-hpb6k6st.js";import"./index-2f9w48sc.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{Je as h,Qe as u,Re as P}from"./index-81yvwra9.js";import{rf as M,sf as R,xf as S}from"./index-hz6f9gpq.js";import"./index-v1ztg103.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 S0}from"../index-85w1x19b.js";import{A as E0,B as o2,C as l$,D as u$,E as rZ,F as tZ,G as x0,H as KZ,I as TZ,L as bZ,M as kZ,N as DZ,V as vZ,W as hZ,_ as q0,d as H0,e as yZ,ea as G$,f as B1,fa as Q$,g as S2,h as e2,i as Q1,ia as b0,k as J$,l as z$,m as $$,n as c2,o as NZ,p as w1,q as FZ,r as xZ,s as qZ,t as $1,u as r$,v as t$,w as P0,x as M0,y as g1,z as C0}from"../index-qdy57ej9.js";import{Ab as _0,Bb as EZ,Jb as R2,Kb as GZ,La as MZ,Lb as QZ,Mb as b1,Nb as YZ,Ob as XZ,Qb as O0,Rb as R0,Sa as t2,Sb as A0,ab as Y1,bb as V0,cb as U0,db as W0,eb as w2,gb as h$,hb as a2,ib as m$,jb as g$,lb as F0,mb as zZ,ob as K0,pa as B0,pb as CZ,ta as x$,ua as q$,yb as T0,zb as L0}from"../index-cb1kwn36.js";import{ac as iZ,pc as aZ,qc as nZ,sc as oZ,wc as sZ}from"../index-5sgqz46z.js";import{Be as y$,Ce as f$,De as A1,Ee as I$,Fd as _Z,Fe as v$,Ld as PZ,Mc as P$,Nd as j0,Od as fZ,Pd as O$,Yd as q2,Zd as m2,ce as R$,ee as s$,fe as A$,ld as s2,le as G1,md as r2,nd as X0,se as IZ,te as y2,ud as m1,ue as S$,vd as M$,ve as b$,wd as C$,we as k$,xd as E$,ye as D$,ze as w$}from"../index-6r27fz5a.js";import"../index-mtf8pv2w.js";import{Ve as WZ,We as N0}from"../index-hpev556z.js";import"../index-6j3059fy.js";import{ff as Y0,hf as L2}from"../index-k1dfzavn.js";import"../index-hpb6k6st.js";import{Ef as HZ}from"../index-bvswyxpt.js";import{If as j1,Jf as Q0}from"../index-2f9w48sc.js";import{AsyncLocalStorage as b4}from"node:async_hooks";import{randomUUID as k4}from"node:crypto";class Y2 extends Error{kind;providerID;sessionID;requestKind;constructor($){super($.message??`${$.providerID} ${$.requestKind} request refused (${$.kind})`);this.name="OpenCode2AuthError",this.kind=$.kind,this.providerID=$.providerID,this.sessionID=$.sessionID,this.requestKind=$.requestKind}}function K2($){return`common-auth-placeholder.${$}`}function o1($){let Z=K2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function k2($,Z){if($?.type!=="oauth")return!1;let J=Z===void 0?void 0:K2(Z),G=(Q)=>J===void 0?Q.startsWith("common-auth-placeholder."):Q===J;return G($.access)&&G($.refresh)}var s1="No browser sign-in: this connects the plugin to the accounts in its vault.";async function N1($,Z){let J=Z.now??Date.now,{integrationID:G}=Z,Q=(V)=>o1({integrationID:G,methodID:V,now:J()}),Y=async(V,N)=>{return await Z.onLogin(V,{integrationID:G,methodID:N}),Q(N)},F=(V)=>async(N)=>{let B=V.method.id,H=await V.authorize(N),T={url:H.url,instructions:H.instructions,...H.expiresAt===void 0?{}:{expiresAt:H.expiresAt}};if(H.mode==="auto")return{...T,mode:"auto",callback:H.callback.then((C)=>Y(C,B))};let q=H.callback;return{...T,mode:"code",callback:async(C)=>Y(await q(C),B)}};return $.integration.transform((V)=>{let N=Z.label===void 0?{}:{label:()=>Z.label};for(let T of Z.methods)V.method.update({integrationID:G,method:T.method,authorize:F(T),refresh:async(q)=>{if(!k2(q,G))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return Q(q.methodID)},...N});let B=Z.vault;if(B===void 0)return;let H=B.method.id;V.method.update({integrationID:G,method:B.method,authorize:async()=>({url:"",instructions:B.instructions??s1,mode:"auto",callback:Promise.resolve().then(()=>B.activate({integrationID:G,methodID:H})).then(()=>Q(H))}),refresh:async(T)=>{if(!k2(T,G)||T.methodID!==H)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return Q(H)},...N})})}function w0($){let Z=[],J;for(let G of $.split(/\r?\n/))if(G.startsWith("data:"))Z.push(G.slice(5).replace(/^ /,""));else if(G.startsWith("event:"))J=G.slice(6).trim();if(Z.length===0)return;return J===void 0?{data:Z.join(`
1
+ import{c as k0}from"../index-jej9cfk7.js";import{A as A0,B as o2,C as l$,D as u$,E as rZ,F as tZ,G as S0,H as KZ,I as TZ,L as bZ,M as kZ,N as DZ,V as vZ,W as hZ,_ as b0,d as F0,e as yZ,ea as G$,f as B1,fa as Q$,g as S2,h as e2,i as Q1,ia as D0,k as J$,l as z$,m as $$,n as c2,o as NZ,p as w1,q as FZ,r as xZ,s as qZ,t as $1,u as r$,v as t$,w as C0,x as E0,y as g1,z as O0}from"../index-4p45bmbz.js";import{Ab as P0,Bb as M0,Cb as EZ,Kb as A2,Lb as GZ,Ma as MZ,Mb as QZ,Nb as b1,Ob as YZ,Pb as XZ,Rb as R0,Sb as x0,Ta as t2,Tb as q0,bb as Y1,cb as U0,db as H0,eb as N0,fb as w2,hb as h$,ib as a2,jb as m$,kb as g$,mb as T0,nb as zZ,pa as W0,pb as _0,qb as CZ,ta as x$,ua as q$,zb as L0}from"../index-xx3k2qbv.js";import{bc as iZ,qc as aZ,rc as nZ,tc as oZ,xc as sZ}from"../index-7bjgmbx4.js";import{Ae as w$,Ce as y$,De as I$,Ee as R1,Fe as f$,Gd as LZ,Ge as v$,Md as PZ,Nc as P$,Od as V0,Pd as IZ,Qd as O$,Zd as q2,_d as m2,de as A$,fe as s$,ge as R$,md as s2,me as G1,nd as r2,od as B0,te as fZ,ue as y2,vd as m1,ve as S$,wd as M$,we as b$,xd as C$,xe as k$,yd as E$,ze as D$}from"../index-6xz3n4qh.js";import"../index-81yvwra9.js";import{We as UZ,Xe as K0}from"../index-rrtsaz80.js";import"../index-2esezxst.js";import{gf as j0,if as _2}from"../index-cmybrjbd.js";import"../index-hz6f9gpq.js";import{Ff as HZ}from"../index-g3gbp1m4.js";import{Jf as j1,Kf as X0}from"../index-v1ztg103.js";import{AsyncLocalStorage as D4}from"node:async_hooks";import{randomUUID as w4}from"node:crypto";class Y2 extends Error{kind;providerID;sessionID;requestKind;constructor($){super($.message??`${$.providerID} ${$.requestKind} request refused (${$.kind})`);this.name="OpenCode2AuthError",this.kind=$.kind,this.providerID=$.providerID,this.sessionID=$.sessionID,this.requestKind=$.requestKind}}function K2($){return`common-auth-placeholder.${$}`}function o1($){let Z=K2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function k2($,Z){if($?.type!=="oauth")return!1;let J=Z===void 0?void 0:K2(Z),G=(Y)=>J===void 0?Y.startsWith("common-auth-placeholder."):Y===J;return G($.access)&&G($.refresh)}var s1="No browser sign-in: this connects the plugin to the accounts in its vault.";async function N1($,Z){let J=Z.now??Date.now,{integrationID:G}=Z,Y=(W)=>o1({integrationID:G,methodID:W,now:J()}),Q=async(W,N)=>{return await Z.onLogin(W,{integrationID:G,methodID:N}),Y(N)},F=(W)=>async(N)=>{let B=W.method.id,H=await W.authorize(N),T={url:H.url,instructions:H.instructions,...H.expiresAt===void 0?{}:{expiresAt:H.expiresAt}};if(H.mode==="auto")return{...T,mode:"auto",callback:H.callback.then((C)=>Q(C,B))};let R=H.callback;return{...T,mode:"code",callback:async(C)=>Q(await R(C),B)}};return $.integration.transform((W)=>{let N=Z.label===void 0?{}:{label:()=>Z.label};for(let T of Z.methods)W.method.update({integrationID:G,method:T.method,authorize:F(T),refresh:async(R)=>{if(!k2(R,G))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return Y(R.methodID)},...N});let B=Z.vault;if(B===void 0)return;let H=B.method.id;W.method.update({integrationID:G,method:B.method,authorize:async()=>({url:"",instructions:B.instructions??s1,mode:"auto",callback:Promise.resolve().then(()=>B.activate({integrationID:G,methodID:H})).then(()=>Y(H))}),refresh:async(T)=>{if(!k2(T,G)||T.methodID!==H)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return Y(H)},...N})})}function I0($){let Z=[],J;for(let G of $.split(/\r?\n/))if(G.startsWith("data:"))Z.push(G.slice(5).replace(/^ /,""));else if(G.startsWith("event:"))J=G.slice(6).trim();if(Z.length===0)return;return J===void 0?{data:Z.join(`
2
2
  `)}:{event:J,data:Z.join(`
3
- `)}}function F1($,Z){let J=new TextDecoder,G="",Q=(F)=>{let V=w0(F);if(!V)return;try{$(V)}catch(N){Z(N)}},Y=()=>{for(;;){let F=/\r?\n\r?\n/.exec(G);if(!F)return;let V=G.slice(0,F.index);G=G.slice(F.index+F[0].length),Q(V)}};return new TransformStream({transform(F,V){V.enqueue(F),G+=J.decode(F,{stream:!0}),Y()},flush(){if(G+=J.decode(),Y(),G.trim()!=="")Q(G);G=""}})}var r1=512,t1=1200000,A2="x-common-auth-attempt",O2=($,Z)=>JSON.stringify([$,Z]),N2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function y0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function f0($,Z){let J=$.getReader();return new ReadableStream({async pull(G){let Q;try{Q=await J.read()}catch(Y){Z({reason:"failed",message:Y instanceof Error?Y.message:String(Y)}),G.error(Y);return}if(Q.done)Z(),G.close();else G.enqueue(Q.value)},async cancel(G){Z({reason:"cancelled",...G===void 0?{}:{message:String(G)}}),await J.cancel(G)}})}function u2($,Z){for(let[J,G]of Object.entries(Z)){let Q=J.toLowerCase();for(let Y of Object.keys($))if(Y.toLowerCase()===Q)delete $[Y];if(G!==null)$[J]=G}}function I0($,Z){for(let[J,G]of Object.entries(Z))if(G===null)$.delete(J);else $.set(J,G)}async function K1($,Z,J={}){let{providerID:G}=Z,Q=J.gateOnPlaceholder,Y=(z)=>Q===void 0||Q.credential(z)===K2(G),F=J.logger,V=Math.max(1,J.maxRecords??r1),N=[...J.hostCredentials??[K2(G)],...Q?[K2(G)]:[]].filter((z)=>z!==""),B=new Map,H=new WeakMap,T=new Map,q=0,C=new Set,D=new Map,d=new Map,O=(z)=>{let j=d.get(z);return j?.ownedSeen===!0&&j.foreignSeen},I=(z,j)=>{D.set(z,j);let U=d.get(z)??{ownedSeen:!1,foreignSeen:!1};if(j)U.ownedSeen=!0;else U.foreignSeen=!0;d.set(z,U)},B2=(z,j)=>{let U=Q?.refuseMisplaced,P=U?[...j].filter(([,k])=>k.includes(K2(G))):[],W=Y(j)&&(!U||P.length>0);if(U){if(P.length>0&&(P.length!==1||!W))throw I(z.sessionID,!1),new Y2({kind:"placement-refused",providerID:G,sessionID:z.sessionID,requestKind:z.kind,message:U(P[0]?.[0]??"")})}return I(z.sessionID,W),W},J2=!1,w=!1,l=new Map,_2=0,Z2=!1,i=new Map,X=(z,j)=>{try{F?.warn(z,j)}catch{}},K=(z)=>z instanceof Error?z.message:String(z),M=new Map,L=(z,j)=>{let U=(M.get(z)??Promise.resolve()).then(j),P=U.then(()=>{},()=>{});return M.set(z,P),P.then(()=>{if(M.get(z)===P)M.delete(z)}),U},h=(z,j)=>{let U=M.get(z);return U?U.then(()=>h(z,j)):j()},R=async(z)=>{try{await Z.dropChoice?.({...z.input,accountId:z.accountId})}catch(j){X("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:z.input.sessionID,error:K(j)})}},S=async(z)=>{try{await Z.dropSameAccountRetry?.({...z.input,accountId:z.accountId})}catch(j){X("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:z.input.sessionID,error:K(j)})}},v=async(z)=>{if(z.next)await R(z.next);if(z.sameAccount)await S(z.sameAccount)},A=(z)=>{let j=T.get(z);if(T.delete(z),j)L(j.sessionID,()=>v(j))},f=async(z,j)=>{let U=l.get(z);if(!U||U.size===0)return;await Promise.all([...U].map(async(P)=>{try{await P(j)}catch(W){X("opencode2 auth listener threw; the request is unaffected",{event:z,error:K(W)})}}))},n=async(z,j)=>{try{await Z.onAttemptEnd?.(z,j)}catch(U){X("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:z.attemptId,error:K(U)})}},u=(z,j)=>{if(z.ended||!z.attempt)return;let U={...z.status===void 0?{}:{status:z.status},outputStarted:z.outputStarted,...z.limit?{limit:z.limit.signal}:{},...j?{error:j}:{}};if(j)z.endError=j;z.ended=n(z.attempt,U)},o=(z,j)=>u(z,{reason:"abandoned",message:j}),s=(z)=>[...B.values()].filter((j)=>j.key===z),e=(z)=>s(z).at(-1),p=(z)=>{if(B.delete(z.id),T.get(z.key)?.attemptId===z.id||!s(z.key).length)A(z.key)},x=(z)=>{B.set(z.id,z);while(B.size>V){let j=B.values().next().value;if(j===void 0)break;o(j,"dropped to keep the record bound"),p(j)}},G2=(z)=>z.accountId===void 0?void 0:{...z.scope,accountId:z.accountId},g=(z,j)=>new Y2({kind:"no-account",providerID:G,sessionID:z.sessionID,requestKind:z.kind,...j===void 0?{}:{message:j}}),m=(z)=>{i.get(z)?.clear(),i.delete(z)},$2=async(z,j)=>{let U=()=>g(z,`${G} ${z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(Z2)throw U();let P=i.get(z.sessionID);if(!P)P=new Set,i.set(z.sessionID,P);let W={};P.add(W);let k=()=>{if(!P.has(W))throw U()};try{return await j(k)}finally{if(P.delete(W),P.size===0&&i.get(z.sessionID)===P)i.delete(z.sessionID)}},X2=(z,j)=>{for(let[U,P]of j)if(N.some((W)=>P.includes(W)))throw new Y2({kind:"host-credential-on-wire",providerID:G,sessionID:z.sessionID,requestKind:z.kind,message:`${G} ${z.kind} request still carries the host's placeholder credential in ${U}; the adapter's account headers must replace it`})},_=(z)=>{for(let j of s(z))if(j.ended||!j.attempt)p(j);else if(j.transport==="ws"||j.judged)o(j,"a newer attempt of its session and kind began"),p(j)},b=async(z,j,U,P)=>{let W=O2(z.sessionID,z.kind),{input:k,accountId:E,sameAccountRetry:y}=await h(z.sessionID,async()=>{U();let r=T.get(W);T.delete(W);let z2=r?.accountId??e(W)?.accountId;_(W);let t=r?.next,Q2=r?.sameAccount,a=Q2!==void 0&&Q2.input.modelID===z.modelID&&Q2.input.agent===z.agent,U2=t!==void 0&&t.input.modelID===z.modelID&&t.input.agent===z.agent,W2={...z,phase:"request",...z2===void 0?{}:{previousAccountId:z2},...r?.rerouteFrom?{rerouteFrom:r.rerouteFrom}:{}};if(t&&!U2)await L(z.sessionID,()=>R(t)),U();if(Q2&&!a)await L(z.sessionID,()=>S(Q2)),U();let H2=a?Q2.accountId:U2?t.accountId:await Z.chooseAccount(W2);return{input:W2,accountId:typeof H2==="string"?H2:void 0,sameAccountRetry:a}});U();let c={},V2;if(E!==void 0){let r=await Z.accountHeaders({...z,accountId:E});if(U(),y0(r))c=r.headers,V2=r.attempt;else c=r}let g2=`attempt-${++_2}`,E2={id:g2,key:W,scope:z,accountId:E,headers:c,attempt:E===void 0?void 0:{...z,accountId:E,attemptId:g2,transport:P,data:V2},...P===void 0?{}:{transport:P},outputStarted:!1,sameAccountRetry:y};if(x(E2),E2.attempt)f("select",{...z,accountId:E2.attempt.accountId,hook:j,...k.previousAccountId===void 0?{}:{previousAccountId:k.previousAccountId},...k.rerouteFrom===void 0?{}:{rerouteFrom:k.rerouteFrom},handle:E2.attempt});return E2},j2=async(z,j,U,P,W)=>{let k=O2(z.sessionID,z.kind),E=P===void 0?void 0:B.get(P);if(E?.key!==k)E=void 0;if(!E){if(E=e(k),s(k).filter((c)=>c.transport===void 0&&!c.ended).length>1&&!w)w=!0,X("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:z.sessionID,kind:z.kind})}if(!E||E.transport!==void 0||E.ended)E=await b(z,j,W,U);else if(E.transport=U,E.attempt)E.attempt.transport=U;if(U==="ws"){for(let y of s(k))if(y!==E&&y.transport==="ws")o(y,"a newer attempt of its session and kind went out over WebSocket")}return E},b2=async(z,j)=>{try{return await j()}catch(U){throw u(z,{reason:"failed",message:K(U)}),U}},u1=(z,j)=>{let U=s(O2(z,j)).filter((P)=>P.transport==="ws").at(-1);return U?.attempt!==void 0&&!U.ended?U:void 0},U1=(z,j,U)=>{let P=G2(z);if(!P||!z.attempt||z.limit)return;z.limit={signal:j,delivered:f("limit",{...P,via:U,limit:j,outputStarted:z.outputStarted,handle:z.attempt})}},p1=(z,j,U,P)=>{let W=G2(z);if(!W||!z.attempt)return;f("quota",{...W,transport:j,...P===void 0?{}:{status:P},quota:U,handle:z.attempt})},c1=(z,j,U,P)=>{let W=z.attempt;if(!W)return;let k=Z.inspectEvent?.(P===void 0?{transport:j,data:U,attempt:W}:{transport:j,data:U,event:P,attempt:W});if(!k)return;if(k.quota!==void 0)p1(z,j,k.quota);if(k.outputStarted)z.outputStarted=!0;if(k.limit)U1(z,k.limit,j);if(k.error!==void 0)u(z,{reason:"failed",message:k.error});else if(k.done)u(z)},k0=(z,j)=>{let U=z.attempt;if(!U||j.accountId===z.accountId)return;if(U.reboundFrom??=U.accountId,U.accountId=j.accountId,"data"in j)U.data=j.data;z.accountId=j.accountId},D0=(z)=>!z.attempt||z.endError!==void 0||z.status!==void 0&&z.status>=400,d1=(z)=>{let j=[...B.values()].filter((y)=>y.scope.sessionID===z),U=j.filter((y)=>y.limit&&!y.rerouted).at(-1);if(U)return U;let P=j.filter((y)=>y.scope.kind==="primary"),W=P.length>0?P:j;if(W.length<=1)return W[0];let k=W.filter((y)=>!y.judged&&D0(y)).at(-1);if(k)return k;let E=W.filter((y)=>y.attempt&&!y.ended);if(E.length>1)return"ambiguous";return E[0]??W.at(-1)},C2={providerID:G},P2=[];P2.push(await $.session.hook("model.request",(z)=>{if(Q)return;return $2(N2(z),async(j)=>{let U=await b(N2(z),"model.request",j);if(j(),U.accountId===void 0)throw g(U.scope);u2(z.headers,{...U.headers,[A2]:U.id})})},C2)),P2.push(await $.session.hook("http.request",(z)=>{if(Q){if(!B2(N2(z),z.request.headers))return}return $2(N2(z),async(j)=>{let U=z.request.headers.get(A2)??void 0,P=Q?await b(N2(z),"http.request",j,"http"):await j2(N2(z),"http.request","http",U,j);j();let W=G2(P),k=P.attempt;if(!W||!k)throw g(P.scope);await b2(P,async()=>{let E=z.request;if(Z.rewriteRequest){if(U!==void 0){let V2=new Headers(E.headers);V2.delete(A2),E=new Request(E,{headers:V2})}E=await Z.rewriteRequest({...W,request:E,attempt:k})??E,j()}let y=new Headers(E.headers);y.delete(A2),I0(y,P.headers),X2(P.scope,y.entries());let c=new Request(E,{headers:y});H.set(c,P),z.request=c})})},C2)),P2.push(await $.session.hook("http.response",async(z)=>{let j=H.get(z.request);if(!j){if(Q)return;if(!J2)J2=!0,X("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:z.sessionID,kind:z.kind});return}let U=z.response;if(Z.answeredBy&&j.attempt){let y=j.attempt,c=await b2(j,async()=>Z.answeredBy?.({request:z.request,response:U,attempt:y}));if(c)k0(j,c)}let P=G2(j),W=j.attempt;if(!P||!W)return;j.status=U.status;let k=Z.quotaFromHeaders?.(U.headers,U.status,W);if(k!==void 0)p1(j,"http",k,U.status);if(!U.ok&&Z.limitFromResponse){let y=await Z.limitFromResponse({status:U.status,headers:U.headers,body:()=>U.clone().text(),attempt:W});if(y)U1(j,y,"http")}if(!U.ok||!U.body)u(j);let E=U;if(U.body&&(Z.inspectEvent||Z.onAttemptEnd)){let y=U.body;if(Z.inspectEvent)y=y.pipeThrough(F1((c)=>c1(j,"http",c.data,c.event),(c)=>X("opencode2 auth event inspection threw",{error:K(c)})));E=new Response(f0(y,(c)=>u(j,c)),{status:U.status,statusText:U.statusText,headers:U.headers})}if(Z.rewriteResponse)E=await Z.rewriteResponse({...P,request:z.request,response:E,attempt:W})??E;if(E!==U)z.response=E},C2)),P2.push(await $.session.hook("experimental.ws.handshake",(z)=>{if(Q){let j=O2(z.sessionID,z.kind);if(C.delete(j),!B2(N2(z),new Headers(z.headers)))return}return $2(N2(z),async(j)=>{let U;for(let E of Object.keys(z.headers)){if(E.toLowerCase()!==A2)continue;U??=z.headers[E],delete z.headers[E]}let P=Q?await b(N2(z),"experimental.ws.handshake",j,"ws"):await j2(N2(z),"experimental.ws.handshake","ws",U,j);j();let W=G2(P),k=P.attempt;if(!W||!k)throw g(P.scope);await b2(P,async()=>{if(!Q?.refuseMisplaced)u2(z.headers,P.headers);let E=Z.rewriteHandshakeURL?.({...W,url:z.url,attempt:k});if(E!==void 0)z.url=E;if(Q?.refuseMisplaced)u2(z.headers,P.headers);if(X2(P.scope,Object.entries(z.headers)),Q)C.add(P.key)})})},C2));let i1=Z.rewriteWebSocketFrame?.bind(Z);if(i1)P2.push(await $.session.hook("experimental.ws.send",async(z)=>{let j=N2(z);if(Q&&!C.has(O2(j.sessionID,j.kind)))return;let U=u1(j.sessionID,j.kind),P=await i1({...j,attempt:U?.attempt,frame:z.frame});if(P!==void 0)z.frame=P},C2));P2.push(await $.session.hook("experimental.ws.receive",(z)=>{if(Q&&!C.has(O2(z.sessionID,z.kind)))return;let j=u1(z.sessionID,z.kind);if(!j)return;try{c1(j,"ws",z.frame)}catch(U){X("opencode2 auth frame inspection threw",{error:K(U)})}},C2)),P2.push(await $.session.hook("retry",async(z)=>{if(Q&&D.get(z.sessionID)!==!0)return;let j=z.decision,U=()=>f("retry",{sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:j,decision:j});if(O(z.sessionID)&&!Z.retrySameAccount){await U();return}let P=d1(z.sessionID);if(!P)return;if(P==="ambiguous"){await f("retry",{sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:j,decision:j});return}let W=P;await $2(W.scope,async(k)=>{let E=k,y=Z.retrySameAccount?.bind(Z),c=W.attempt;if(y&&c&&!W.outputStarted&&!W.sameAccountRetry){if(W.ended)await W.ended;if(W.limit)await W.limit.delivered;let r=await L(W.scope.sessionID,async()=>{E();let z2=c.accountId,t=()=>B.has(W.id)&&W.accountId===z2&&d1(z.sessionID)===W&&!W.outputStarted&&(!Q||D.get(z.sessionID)===!0);if(!t()||W.sameAccountRetry)return!1;W.sameAccountRetry=!0;let Q2={...W.scope,accountId:z2,error:z.error,attempt:z.attempt,...W.limit?{limit:W.limit.signal}:{}},a;try{a=await y(Q2)}catch(H2){X("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:z.sessionID,error:K(H2)})}if(!a)return E(),!1;let U2={accountId:a.accountId,input:Q2};try{E()}catch(H2){throw await S(U2),H2}if(!t()||a.accountId!==z2)return await S(U2),!1;let W2=T.get(W.key);if(T.delete(W.key),W2)await v(W2);try{E()}catch(H2){throw await S(U2),H2}if(!t())return await S(U2),!1;return T.set(W.key,{attemptId:W.id,sessionID:W.scope.sessionID,order:++q,accountId:z2,sameAccount:U2}),W.judged=!0,z.decision={retry:!0,delay:0},!0});if(E(),r){await f("retry",{sessionID:z.sessionID,accountId:W.accountId,kind:W.scope.kind,attempt:z.attempt,reason:"same-account",hostDecision:j,decision:z.decision,handle:W.attempt});return}}if(O(z.sessionID)){await U();return}W.judged=!0;let V2=W.attempt;if(V2&&!W.outputStarted){if(!W.limit){let r=Z.limitFromError?.(z.error,V2);if(r)U1(W,r,"error")}if(W.ended)await W.ended;if(W.limit)await W.limit.delivered}E();let{decision:g2,reason:E2}=await L(W.scope.sessionID,async()=>{if(E(),O(z.sessionID))return{decision:j,reason:"host-decides"};let r=T.get(W.key);if(T.delete(W.key),r)await v(r);if(E(),O(z.sessionID))return{decision:j,reason:"host-decides"};let z2=j,t,Q2,a;if(W.accountId===void 0||!V2)z2={retry:!1},t="no-account";else if(W.outputStarted)z2={retry:!1},t="output-started";else if(W.limit){let U2={accountId:W.accountId,limit:W.limit.signal},W2,H2={...W.scope,phase:"retry",previousAccountId:W.accountId,rerouteFrom:U2};try{W2=await Z.chooseAccount(H2)}catch(H1){X("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:W.scope.sessionID,error:K(H1)})}let M2=typeof W2==="object"?W2.hold:void 0,l2=typeof W2==="string"?W2:M2?W.accountId:void 0;if(l2!==void 0)a={accountId:l2,input:H2};try{E()}catch(H1){if(a)await R(a);throw H1}if(O(z.sessionID)){if(a)await R(a);return{decision:j,reason:"host-decides"}}if(M2&&Number.isFinite(M2.delayMs)&&M2.delayMs>=0)z2={retry:!0,delay:Math.min(M2.delayMs,t1)},t="hold";else if(!M2&&l2!==void 0&&l2!==W.accountId)W.rerouted=!0,Q2=U2,z2={retry:!0,delay:0},t="reroute";else{if(M2&&a)await R(a),a=void 0;t="host-decides-last-account"}}else t="host-decides";if(z.decision=z2,z2.retry&&W.accountId!==void 0&&B.has(W.id))T.set(W.key,{attemptId:W.id,sessionID:W.scope.sessionID,order:++q,accountId:W.accountId,...Q2===void 0?{}:{rerouteFrom:Q2},...a===void 0?{}:{next:a}});else if(a)await R(a);return{decision:z2,reason:t}});E(),await f("retry",{sessionID:z.sessionID,...W.accountId===void 0?{}:{accountId:W.accountId},kind:W.scope.kind,attempt:z.attempt,reason:E2,hostDecision:j,decision:g2,...V2===void 0?{}:{handle:V2}})})},C2));let a1=(z)=>{if(m(z),D.delete(z),!d.get(z)?.foreignSeen)d.delete(z);for(let j of C)if(JSON.parse(j)[0]===z)C.delete(j);for(let j of[...B.values()]){if(j.scope.sessionID!==z)continue;o(j,"its session was forgotten"),B.delete(j.id)}for(let[j,U]of T)if(U.sessionID===z)A(j)},W1=new AbortController,n1=$.event;if(n1)(async()=>{try{for await(let z of n1.subscribe({signal:W1.signal}))if(z.type==="session.deleted")a1(z.data.sessionID);else if(z.type==="session.status"&&z.data.status.type==="idle"){let j=z.data.sessionID,U=++q;L(j,async()=>{for(let[P,W]of T)if(W.sessionID===j&&W.order<U)T.delete(P),await v(W)})}}catch(z){if(!W1.signal.aborted)X("opencode2 auth stopped listening for session deletion",{error:K(z)})}})();return{on(z,j){let U=l.get(z);if(!U)U=new Set,l.set(z,U);let P=j;return U.add(P),()=>{U.delete(P)}},accountFor(z,j){return e(O2(z,j))?.accountId},forgetSession:a1,get size(){return B.size},async dispose(){if(Z2)return;Z2=!0;for(let z of i.keys())m(z);W1.abort();for(let z of B.values())o(z,"the installation was disposed");B.clear();for(let z of T.keys())A(z);C.clear(),D.clear(),d.clear(),l.clear(),await Promise.all(M.values()),await Promise.all(P2.map(async(z)=>{try{await z.dispose()}catch(j){X("opencode2 auth hook did not dispose cleanly",{error:K(j)})}}))}}}import{createHash as v0}from"node:crypto";var h0=1024,m0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),e1=($)=>$$($,"user"),g0=($)=>m0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function l0($){return v0("sha256").update(JSON.stringify($)).digest("hex")}class x2{runtime;maxSessions;#$=new Map;constructor($,Z=h0){this.runtime=$;this.maxSessions=Z}advance($,Z,J=this.runtime){let G=this.#$.get($),Q=Array.isArray(Z.input)?Z.input:[],Y=Q.filter(e1),F=Q.findLastIndex(e1),V=F<0?void 0:l0(Q[F]),N=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,B,H,T;if(N)B=Y.length>0,H=V??G?.fingerprint,T=G?.userCount===void 0?void 0:G.userCount+Y.length;else{H=V,T=Y.length;let C=F>=0&&F>Q.findLastIndex(g0),D=G!==void 0&&!G.completed&&G.fingerprint===H&&G.userCount===T;B=C&&!D}let q=B||!G?{turnID:(J?.uuid??R2)(),turnStartedAt:(J?.now??Date.now)()}:{turnID:G.turnID,turnStartedAt:G.turnStartedAt};return this.#Z($,{...q,completed:!1,fingerprint:H,userCount:T}),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 J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function T1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var Z$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function u0(){let $=globalThis;return $[Z$]??=crypto.randomUUID(),$[Z$]}class D2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,J){this.runtime=$;this.store=J;this.installationID=Z??u0(),this.sessions=J?.sessions??new Map,this.frameTurns=J?.frameTurns??new x2}get($){let Z=this.runtime?.uuid??R2;if(this.store)return this.store.get($,Z);let J=this.sessions.get($);if(!J){let G=Z();J={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,J)}return J}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(p2(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var L1={version:J$,"user-agent":z$,originator:"codex_exec"};var p0=1024,c0=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,d2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),Y$=($)=>d2($)&&($.type==="message"||("role"in $))&&$.role==="user",X$=($)=>d2($)&&$.type==="configuration_update";class _1{http;#$=new Map;constructor($=new D2){this.http=$}apply($,Z,J){if(Z.kind!=="primary")return!1;let G=typeof $.model==="string"?$.model:"";if(!G$.has(G))return!1;if(c0.test(G))return!1;let Q=d2($.reasoning)?$.reasoning:void 0,Y=typeof Q?.effort==="string"?Q.effort:void 0;if(!Y)return!1;let F=this.#$.get(Z.sessionID);if(F===void 0)return this.#Z(Z.sessionID,Y),!1;if(Y===F)return!1;let V=Array.isArray($.input)?$.input:void 0;if(!V||V.length===0)return!1;let N=V.findLastIndex(Y$);if(N<0){if(J==="http")return!1;return $.reasoning={...Q,effort:F},!0}if($.reasoning={...Q,effort:F},!X$(V[N-1]))V.splice(N,0,{type:"configuration_update",reasoning:{effort:Y}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>p0){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function p2($){try{let Z=JSON.parse($);return d2(Z)?Z:void 0}catch{return}}async function j$($,Z,J,G,Q=J.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Y=await $.clone().text(),F=p2(Y);if(F)delete F.max_output_tokens;let V=new Headers($.headers),N=c2({rewriteLite:Q$,init:{body:F?JSON.stringify(F):$.body===null?void 0:Y},headers:V,metadata:Q.get(Z.sessionID),installationID:Q.installationID,runtime:Q.runtime,websocket:!1,responsesLite:G,applyEffort:(B)=>{J.apply(B,Z,"http")}});return new Request($,{headers:V,body:N.init?.body})}function B$($,Z,J,G){let Q=G.sessions.get($.sessionID),Y=G.frameTurns.get($.sessionID);if(!Q||!Y)return;let F=T1(Q,Y),V=new Headers({"content-type":"application/json"});for(let B of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let H=J.get(B);if(H!==null)V.set(B,H)}c2({init:{body:$.bodyText},headers:V,metadata:F,installationID:G.installationID,runtime:G.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let N=new URL(Z);if(N.protocol==="wss:")N.protocol="https:";if(N.protocol==="ws:")N.protocol="http:";return new Request(N,{method:"POST",headers:V,body:$.bodyText})}function d0($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let J=Z.findIndex((G,Q)=>JSON.stringify(G)!==JSON.stringify($[Q]));return J>=0&&X$(Z[J])&&Y$(Z[J+1])&&JSON.stringify(Z.slice(J+1))===JSON.stringify($.slice(J))}function V$($,Z,J){let G=p2($);if(G?.type!=="response.create")return;let Q=J.http.advanceFrame(Z.sessionID,G),Y=J.http.get(Z.sessionID);delete G.max_output_tokens;let F=c2({rewriteLite:()=>{},init:{body:JSON.stringify(G)},headers:new Headers,metadata:T1(Y,Q),installationID:J.http.installationID,runtime:J.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(N)=>{J.apply(N,Z,"ws")}}),V=p2(String(F.init?.body));if(!V)return;if(!d0(G.input,V.input)){if("input"in G)V.input=G.input;else delete V.input;return JSON.stringify(V)}return String(F.init?.body)}function i0($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function P1($,Z){let J=new URL($);if(J.origin!=="https://api.openai.com"&&J.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(J.pathname))return $;let G=new URL(`${i0(Z)}/responses`);if(G.search=J.search,J.protocol==="ws:"||J.protocol==="wss:")G.protocol=G.protocol==="https:"?"wss:":"ws:";return G.href}import{resolve as M1}from"node:path";var U$=Symbol.for("@cortexkit/openai-auth/opencode2-rate-limits/v1"),W$=globalThis,C1=W$[U$]??new Map;W$[U$]=C1;function H$($){let Z=C1.get($);if(!Z)Z=new Map,C1.set($,Z);return Z}function N$($){return H$(JSON.stringify(["pool",M1($.configPath),M1($.statePath)]))}function F$($){return H$(JSON.stringify(["vault",M1($)]))}import{resolve as K$}from"node:path";var a0=1024;class i2{accounts=new Map;limit;constructor($=a0){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let J=this.accounts.keys().next().value;if(J===void 0)break;this.accounts.delete(J)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var T$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),L$=globalThis,E1=L$[T$]??new Map;L$[T$]=E1;function O1($){let Z=JSON.stringify([K$($.configPath),K$($.statePath)]),J=E1.get(Z);if(!J)J=new i2,E1.set(Z,J);return J}var F2="openai",n0=60000,R1=1,o0="request refused: no account with a usable credential",T2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function s0($){let Z=T2($)?$.counters:void 0,J=T2(Z)?Z.resetCredits:void 0,G=T2(J)?J.value:void 0;return typeof G==="number"&&Number.isFinite(G)?G:void 0}function n2($){try{return JSON.parse($)}catch{return}}function _$($){let Z=s2($);return Z?r2(Z):void 0}var r0=new Set(["usage_limit_reached","rate_limit_exceeded"]);function x1($,Z,J){return{reason:$.window,...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function t0($,Z){let J=o2($);if(J){let Y=typeof $.status==="number"?$.status:void 0;return x1(J,Z,Y)}if($.type!=="response.failed"||!T2($.response))return;let G=$.response.failed;if(T2(G)&&typeof G.rate_limit_reached_type==="string")return{reason:G.rate_limit_reached_type};let Q=$.response.error;if(T2(Q)){let Y=typeof Q.code==="string"?Q.code:typeof Q.type==="string"?Q.type:void 0;if(Y&&r0.has(Y))return{reason:Y}}return}function e0($,Z){let J=n2($);if(!T2(J))return;let G=typeof J.type==="string"?J.type:void 0;if(G==="codex.rate_limits")return{quota:{snapshot:E$(J),complete:!0}};let Q=t0(J,Z);if(Q)return{limit:Q};if(G===void 0||G==="error")return;return l$(G)?void 0:{outputStarted:!0}}function $4($){let Z=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:M$($),complete:C$($)}}function Z4($){let Z=$.get("retry-after");if(Z===null)return;let J=Number(Z);return Number.isFinite(J)&&J>=0?J*1000:void 0}function p$($){let Z=new WeakMap,J=new WeakSet,{source:G,pins:Q}=$,Y=$.now??Date.now,F=$.log,V=$.vault,N=new _1($.codex),B=new Map,H=new Map,T=(X)=>`${X.sessionID}\x00${X.kind}\x00${X.accountId}`,q=V?.paths?.rosterPath,C=q?F$(q):new Map,D=$.sessionAccounts??new i2,d=new y$,O=(X,K,M)=>{let L=M?[]:u$(G.peek().rows,X,K,V?.identities()??new Set),h=(V?.routes()??[]).filter((R)=>R.kind==="oauth"&&R$(y2(R.quota),X,K));return[...L.map((R)=>({id:R.id,...R.identity!==void 0?{identity:R.identity}:{},quota:R.quota,row:R})),...h.map((R)=>({id:R.id,...R.identity!==void 0?{identity:R.identity}:{},quota:R.quota}))]},I=(X,K,M)=>{let L=k$(X,K,M),h=X.map((A)=>({id:A.id,kind:"oauth",...P$(A.quota)?{quota:A.quota}:{}})),R=X.flatMap((A)=>A.row?[A.row]:[]),S=new Set(X.filter((A)=>!A.row).map((A)=>A.id)),v=G.rateLimitMarks(R);for(let A of S){let f=C.get(A);if(f===void 0)continue;if(f<=M)C.delete(A);else v.set(A,f)}return{rows:h,now:M,rateLimitMarks:v,refreshBackoff:G.refreshBackoffFor(R),killswitch:L,requestPull:(A)=>S.has(A)?V?.requestReading(A):G.requestReading(A)}},B2=(X,K,M,L,h)=>{let R=f$({...X,placement:D$(K),mainId:h});if(R.kind==="block"){F?.debug("pool admission refused the request",{reason:R.block.reason});return}let S=R.order.filter((v)=>!M.has(v));if(L!==void 0&&S.includes(L))return L;return S[0]},J2=(X,K,M,L,h,R,S,v)=>{let A=new Map(K.map((x)=>[x.id,x.quota])),f={requestBytes:R1,reservePercent:(x)=>A$(M,x===S$?void 0:x),resetCredits:(x)=>s0(A.get(x))},n=A1(X),u=(x,G2)=>t2(S,{sessionId:L,requestBytes:R1,validPinnedAccountIds:X.rows.map((g)=>g.id).filter((g)=>!n.excluded.has(g)),excludeAccountIds:x,quotaCheckedAtByAccount:Object.fromEntries(X.rows.map((g)=>[g.id,n.projections.get(g.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(K.map((g)=>[g.id,g.identity])),select:(g)=>v?{accountId:v,source:"mode-fallback",quotaCheckedAt:n.projections.get(v)?.checkedAt}:I$(X,f,new Set(x),g),persist:G2},(g,m)=>S.set(g,m)),o=[...h],s=u(o,R);if(!s)return;let e=s.accountId,p=v$(X,f,e);if(p.kind==="none")return;if(p.kind==="move"){let x=u([...o,e],R);if(x)return x.accountId;return p.reason==="killswitch"?void 0:e}if(p.kind==="detour")return u([...o,e],!1)?.accountId;return e},_2={providerID:F2,dropChoice(X){let K=T(X);H.get(K)?.drop(),H.delete(K),B.delete(K)},chooseAccount:async(X)=>{let K=await V?.authority(),M=await $.storage(),L=K!==void 0&&K!=="local",h=()=>{throw new Y2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:e2})};if(L)await $.awaitVaultRoster?.();else{if(!(await G.current()).active){if(await $.slotPlaceholderWithoutMain?.())h();F?.warn("the account pool does not serve requests yet; refusing the request",{kind:X.kind});return}await G.prepareTokens(G.peek().rows,M)}let R=Y(),S=O(M,R,L),v=w$(I(S.filter((m)=>m.id!==X.rerouteFrom?.accountId),M,R));if(v)await v,R=Y(),S=O(M,R,L);let A=new Map(S.map((m)=>[m.id,m])),f=I(S,M,R),n=new Set(X.rerouteFrom?[X.rerouteFrom.accountId]:[]),u=M?.routing?.mode??"main-first",o=X.kind==="primary",s=new Set,e,p,x,G2=!1,g=(m)=>{let $2=A1(f).projections.get(m)?.checkedAt,X2=A.get(m)?.identity;return Q.reserve(X.sessionID,{accountId:m,inputBytes:R1,...$2!==void 0?{quotaCheckedAt:$2}:{},...X2!==void 0?{wireIdentity:X2}:{}})};try{for(;;){let m=new Set([...n,...s]);x=void 0,e=void 0;let $2=u!=="sticky-balanced";if(u==="sticky-balanced"){let _=new Map(Q.placementSnapshot(X.sessionID)),b=_.get(X.sessionID);if($2=b===void 0,x=J2(f,S,M,X.sessionID,m,o&&s.size===0,_),x!==void 0&&_.get(X.sessionID)!==b)e=_.get(X.sessionID)}if(x??=B2(f,u,m,o?void 0:D.activeAccount(X.sessionID),L?u==="sticky-balanced"?null:b$(V?.routes()??[]):void 0),x===void 0||s.has(x)){if(n.size>0){let _=new Map(f.rateLimitMarks);for(let b of n)_.delete(b);f={...f,rateLimitMarks:_},n.clear();continue}if(f.rateLimitMarks.size>0){f={...f,rateLimitMarks:new Map};continue}x=void 0;break}if(o&&u==="sticky-balanced")p=g(x);if(!G2){G2=!0;let _=await h$({vaultMode:L,fresh:$2,sessionId:X.sessionID,request:{modelId:X.modelID,kind:X.kind,retry:X.phase==="retry"||X.rerouteFrom!==void 0},routes:V?.routes()??[],routing:f,eligibleIds:S.filter((b)=>!m.has(b.id)).map((b)=>b.id)});if(_&&_!==x){if(p)Q.rollback(p);if(p=void 0,u==="sticky-balanced"){let b=new Map(Q.placementSnapshot(X.sessionID));x=J2(f,S,M,X.sessionID,m,o,b,_)??x,e=b.get(X.sessionID)??e}else x=_;if(o&&u==="sticky-balanced")p=g(x)}}let X2=A.get(x)?.row;if(X2){if(G.usableToken(X2)!==void 0)break;F?.debug("pool row holds no usable token; choosing again",{accountId:x})}else{if(!V)break;let _=await V.authorize(x);if(_){B.set(T({...X,accountId:x}),_);break}F?.debug("the vault refused to serve an account; choosing again",{accountId:x})}if(p)Q.rollback(p);p=void 0,s.add(x)}if(x===void 0&&!L&&S.length===0&&await $.slotPlaceholderWithoutMain?.())h();if(x===void 0&&L&&V&&(S.length===0||s.size>0)){let m=s.size>0?"vault-refused":q$(V);throw F?.warn("vault mode: no vault account can serve; refusing the request",{cause:m}),new Y2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:x$(m,V.name)})}if(x!==void 0){let m=x,$2=p,X2=e,_=()=>{if($2)Q.finish($2,X2);if(o)D.record(X.sessionID,m),$.onRoute?.(X.sessionID,m,u)};if(X.phase==="retry")H.set(T({...X,accountId:x}),{commit:_,drop:()=>{if($2)Q.rollback($2)}}),p=void 0;else _();let b=F?.info;d.served(f,x,F&&b?{info:(j2,b2)=>b.call(F,j2,b2)}:void 0)}return F?.debug("pool account chosen",{kind:X.kind,accountId:x,mode:u,...X.rerouteFrom?{rerouteFrom:X.rerouteFrom.accountId}:{}}),x}finally{if(p)Q.rollback(p)}},accountHeaders:async(X)=>{let{accountId:K}=X,M=T(X),L=H.get(M);H.delete(M);let h=()=>{L?.commit()};try{let R=()=>new Y2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:o0}),S=V&&await V.authority()!=="local"?void 0:G.peek().rows.find((f)=>f.id===K);if(!S&&V){let f=T(X),n=B.get(f)??await V.authorize(K);if(B.delete(f),!n)throw F?.warn("the vault refused to serve an account; refusing the request",{accountId:K}),R();return h(),{headers:{...L1,"session-id":X.sessionID,authorization:`Bearer ${n.accessToken}`,"chatgpt-account-id":n.accountIdentity??_$(n.accessToken)??null},attempt:{kind:"vault",routeId:K,receipt:n}}}let v=S?G.usableToken(S):void 0;if(!S||!v)throw F?.warn("pool row holds no usable token; refusing the request",{accountId:K}),R();let A=S.identity??_$(v);return h(),{headers:{...L1,"session-id":X.sessionID,authorization:`Bearer ${v}`,"chatgpt-account-id":A??null},attempt:{kind:"pool",token:v,credentialEpoch:S.credentialEpoch}}}finally{L?.drop()}},async rewriteRequest({request:X,sessionID:K,kind:M}){let L=$.codexEndpoint?P1(X.url,$.codexEndpoint()):X.url,h=L===X.url?X:new Request(L,X);return await j$(h,{sessionID:K,kind:M},N,$.responsesLite?.()??!1)??h},rewriteHandshakeURL:({url:X})=>$.codexEndpoint?P1(X,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:X,sessionID:K,kind:M})=>V$(X,{sessionID:K,kind:M},N),quotaFromHeaders:(X,K,M)=>{if(M.data?.kind==="vault"&&w2()&&K>=200&&K<300)Z.set(M,{status:K,headers:X});return $4(X)},async limitFromResponse({status:X,headers:K,body:M,attempt:L}){if(X<400)return;let h=n2(await M().catch(()=>"")),R=o2({...T2(h)?h:{},status:X});if(L.data?.kind==="vault"&&w2())a2(L.sessionID,L.data.receipt,{status:X,headers:K,body:h,limit:R,quota:V?.routes().find((f)=>f.id===L.accountId)?.quota,now:Y()});if(!R)return;let S=Y(),v=x1(R,S,X);if(v.retryAfterMs!==void 0)return v;let A=Z4(K);return A===void 0?v:{...v,retryAfterMs:A}},inspectEvent:({data:X,transport:K,attempt:M})=>{if(M.data?.kind==="vault"&&w2()&&(g$(X)||K==="ws"&&X.includes('"response.completed"'))){let L=n2(X);if(m$(L))J.add(M);if(K==="ws"&&T2(L)&&L.type==="response.completed")a2(M.sessionID,M.data.receipt,{status:200,headers:new Headers,failed:J.has(M)})}return e0(X,Y())},limitFromError(X){let K=n2(X.message),M=o2({...T2(K)?K:{},...X.status!==void 0?{status:X.status}:{}})??(X.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return M?x1(M,Y(),X.status):void 0},async onAttemptEnd(X,K){let M=X.data,L=M?.kind==="vault"&&w2()?Z.get(X):void 0;if(Z.delete(X),M?.kind==="vault"&&L&&!K.error&&!K.limit)a2(X.sessionID,M.receipt,{...L,failed:J.has(X)});if(M?.kind!=="vault"||K.status!==401)return;F?.warn("a vault account answered 401; reporting it to the vault",{accountId:X.accountId}),await V?.reportFailure(M.receipt,401)}},Z2=(X,K,M)=>{let L=M.data;if(L?.kind==="vault"){V?.recordSnapshot(X,K.snapshot,K.complete,L.receipt);return}if(L?.kind!=="pool")return;if(G.peek().rows.find((R)=>R.id===X)?.credentialEpoch!==L.credentialEpoch){F?.debug("quota reading dropped: the row holds another credential",{accountId:X});return}G.recordSnapshot(X,K.snapshot,L.token,K.complete)},i=(X,K,M)=>{let L=Y(),h=M.data?.kind==="vault",R=h?V?.routes().find((A)=>A.id===X)?.quota:G.peek().rows.find((A)=>A.id===X)?.quota,S=O$(y2(R),K.reason,L,n0,K.retryAfterMs!==void 0?L+K.retryAfterMs:void 0);if(!h){G.markRateLimited(X,S);return}let v=C.get(X);if(v===void 0||v<S)C.set(X,S)};return{adapter:_2,attach(X){X.on("quota",(K)=>Z2(K.accountId,K.quota,K.handle)),X.on("limit",(K)=>{i(K.accountId,K.limit,K.handle),F?.debug("pool row refused the request",{accountId:K.accountId,via:K.via,reason:K.limit.reason,outputStarted:K.outputStarted})})},forgetSession(X){Q.forget(X),D.forget(X),N.forget(X)},activeAccount:(X)=>D.activeAccount(X)}}import{resolve as o$}from"node:path";import{Buffer as J4}from"node:buffer";import{resolve as c$}from"node:path";function f2($){return J4.byteLength(JSON.stringify($))}function z4($){return $.reduce((Z,J)=>Z+f2(J),0)}function q1($,Z){return 2+$+Math.max(0,Z-1)}function G4($){let{head:Z,pending:J}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+q1(Z.inputBytes,Z.input.length)+1:0)+(J?20+q1(J.inputBytes,J.input.length)+10+q1(J.outputBytes,J.output.length)+(J.responseID===void 0?0:14+J.responseIDBytes)+1:0)}function d$($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class i${enabled;caps=$1;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$)this.entries.clear(),this.bytes=0}send($,Z){if(!this.enabled)return;let J=d$(Z);if(J?.type!=="response.create")return;if(!Array.isArray(J.input)){this.forget($);return}let G=J.previous_response_id,Q=this.entries.get($),Y=Q?.head;if(G&&G!==Y?.responseID){this.forget($);return}let{type:F,previous_response_id:V,input:N,...B}=J;this.keep($,{fields:G&&Q?Q.fields:B,fieldsBytes:G&&Q?Q.fieldsBytes:f2(B),...G&&Y?{head:Y}:{},pending:{input:N,inputBytes:z4(N),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,J){if(!this.enabled||!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed"))return;let G=this.entries.get($);if(!G?.pending)return;let Q=d$(Z);if(!Q)return;let Y=G.pending,F=Q.response;if(Q.type==="response.created"&&typeof F?.id==="string")Y.responseID=F.id,Y.responseIDBytes=f2(F.id),this.keep($,G);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+=f2(Q.item),this.keep($,G)}else if(Q.type==="response.completed"&&typeof F?.id==="string"){if(F.id===G.head?.responseID||Y.responseID!==void 0&&F.id!==Y.responseID)return;let V={responseID:F.id,responseIDBytes:Y.responseID===F.id?Y.responseIDBytes:f2(F.id),input:[...G.head?.input??[],...Y.input,...Y.output],inputBytes:(G.head?.inputBytes??0)+Y.inputBytes+Y.outputBytes},N={...G,head:V,pending:void 0};if(!this.keep($,N))return;J?.({sessionID:$,responseID:V.responseID,bodyText:this.body(G.fields,V)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let J=G4(Z);if(this.forget($),J>this.caps.maxBytes)return!1;Z.bytes=J,this.entries.set($,Z),this.bytes+=J;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let G=this.entries.keys().next().value;if(G===void 0)break;this.forget(G)}return this.entries.has($)}}var a$=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),n$=globalThis,S1=n$[a$]??new Map;n$[a$]=S1;function Z1($){let Z=JSON.stringify([c$($.configPath),c$($.statePath)]),J=S1.get(Z);if(!J)J=new i$,S1.set(Z,J);return J}var Q4=5000,Y4=["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"],X4=["x-opencode-parent-session-id","x-parent-session-id"];function e$($){let Z=s$($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:r$($?{...$,cachekeep:Z}:$)}}var $Z=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),ZZ=globalThis,I2=ZZ[$Z]??new Map;ZZ[$Z]=I2;function j4($,Z){let J=[],G=()=>J.at(-1)?.location,Q=()=>{let N=G();if(!N)throw Error("no location holds keep-warm");return N},Y=(N,B)=>{V.remove(N),G()?.log?.debug(`cachekeep dropped target (${B})`,{sessionKey:N})},F=async(N)=>{if(N.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let B=N.accountId??"main",H=Q(),T=await H.source.accessFor(B,await H.storage());if(!T)throw Error(`pool row ${B} has no usable token`);return{token:T.token,identity:T.row.identity}},V=t$({...$1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(N,B)=>Q().fetch(N,B),logger:{debug:(N,B)=>G()?.log?.debug(N,B),warn:(N,B)=>G()?.log?.warn(N,B)},getWindow:()=>G()?.settings().window,getSustain:()=>G()?.settings().sustain===!0,resolveLocal:F,vault:{owns:(N)=>G()?.vault.owns(N)===!0,authority:()=>Q().vault.authority(),send:async(N,B,H)=>{let T=Q();if(await T.vault.authority()!=="vault")return;return T.vault.send(N,B,H)}},activeAccount:(N)=>{if(N===void 0)throw Error("target has no session");let B=G(),H=B?.settings();if(!B||!H?.enabled){Y(N,"keep-warm is off");return}if(!H.subagents&&V.status().targets.some((q)=>q.sessionKey===N&&q.isSubagent)){Y(N,"subagent warming is off");return}let T=B.accounts.activeAccount(N);if(T===void 0){Y(N,"no account recorded for the session");return}return T},verifyCredential:({target:N,mode:B,identity:H})=>{if(N.meta.credentialMode!==B)throw Error(`a target captured in ${N.meta.credentialMode??"an unknown"} mode is not warmed with a ${B} credential`);if(H!==N.meta.chatgptAccountId)throw Y(N.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:V,settings:Z,holders:J,joinTimeoutMs:$.joinTimeoutMs??Q4}}function B4($){try{let Z=JSON.parse($),J=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(J?.role!=="user")return!1;return(typeof J.content==="string"?J.content:Array.isArray(J.content)?J.content.map((Q)=>typeof Q?.text==="string"?Q.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function V4($){let Z={};for(let J of Y4){let G=$.get(J);if(G)Z[J]=G}return Z}function JZ($,Z,J){let G=JSON.stringify([o$($.configPath),o$($.statePath)]),Q=I2.get(G);if(!Q)Q=j4(J,Z.settings()),I2.set(G,Q);let Y=Q,F=Z1($);F.setEnabled(Y.settings.enabled);let V={location:{...Z,settings:()=>Y.settings}};Y.holders.push(V);let N=!1,B=async(H)=>{try{let T=V.location.settings();if(N||!T.enabled)return;if(H.kind!=="primary"){if(H.kind==="generate"&&B4(await H.request.clone().text())){if(N)return;Y.manager.remove(H.sessionID)}return}let q=H.attempt.data,C=q?.kind==="pool"?"local":q?.kind==="vault"?"vault":void 0;if(!C)return;let D=H.request.headers,d=X4.some((B2)=>D.has(B2))||Z.parentOf!==void 0&&await Z.parentOf(H.sessionID)!==void 0;if(d&&!T.subagents)return;let O=await H.request.clone().text();if(N)return;let I=D.get("chatgpt-account-id")??void 0;Y.manager.track({sessionKey:H.sessionID,bodyText:O,accountId:H.attempt.accountId,isSubagent:d,meta:{replayHeaders:V4(D),...I?{chatgptAccountId:I}:{},routingSessionId:H.sessionID,url:H.request.url,credentialMode:C}})}catch(T){Z.log?.warn("cachekeep capture failed",{error:T instanceof Error?T.message:String(T)})}};return{manager:Y.manager,configure:(H)=>{Object.assign(Y.settings,H),F.setEnabled(Y.settings.enabled)},capture:B,forget:(H)=>Y.manager.remove(H),async release(){if(N)return;N=!0;let H=Y.holders.indexOf(V);if(H>=0)Y.holders.splice(H,1);if(Y.holders.length>0)return;if(I2.get(G)===Y)I2.delete(G);Y.manager.stop();let T;try{await Promise.race([Y.manager.tick().catch(()=>{}),new Promise((q)=>{T=setTimeout(q,Y.joinTimeoutMs),T.unref?.()})])}finally{clearTimeout(T)}}}}import{mkdirSync as U4}from"node:fs";import{dirname as W4,resolve as H4}from"node:path";function N4(){return zZ("opencode2")}var F4=2000;class jZ{path;options;sessions;frameTurns=new x2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Q=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=YZ($,Z.uuid??R2)}get($,Z=R2){let J=this.sessions.get($);if(!J){let G=Z();J={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,J),this.#Z.delete($),this.#z.delete($),this.#$.add($),this.#Y()}return J}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#z.add($);this.#Y()}#Y(){if(this.#J)return;this.#J=setTimeout(()=>{this.#J=void 0,this.save()},this.options.saveDelayMs??F4),this.#J.unref?.()}save(){if(clearTimeout(this.#J),this.#J=void 0,!this.#Q)this.#Q=!0,this.#G=this.#G.then(()=>{return this.#Q=!1,this.#j()});return this.#G}settled(){return this.#J?this.save():this.#G}#X(){if(this.#z.size===0)return;let $;try{$=b1(this.path)}catch{$=new Map}for(let Z of this.#z)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#z.clear()}async#j(){if(this.#X(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((G)=>{let Q=this.sessions.get(G);return Q?[[G,Q]]:[]}),Z=[...this.#Z],J=null;try{if(U4(W4(this.path),{recursive:!0}),J=await this.#B(),!J)return;let G;try{G=b1(this.path)}catch{G=new Map}await this.options.afterRead?.();let Q=!1;for(let Y of Z)if(G.delete(Y))Q=!0;for(let[Y,F]of $){if(G.get(Y)===F.threadID)continue;G.set(Y,F.threadID),Q=!0}if(Q)XZ(this.path,G)}catch{return}finally{await J?.release().catch(()=>{})}for(let[G,Q]of $)if(this.sessions.get(G)===Q)this.#$.delete(G);for(let G of Z)if(!this.sessions.has(G))this.#Z.delete(G)}#B(){return QZ(this.path,this.options.lockWaitMs??GZ)}}var BZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),VZ=globalThis,J1=VZ[BZ]??new Map;VZ[BZ]=J1;function K4($){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 UZ($=N4()){let Z=H4($),J=J1,G=J1.get(Z),Q=J1;if(G!==void 0&&!K4(G))J.compatible??=new Map,Q=J.compatible;let Y=Q.get(Z);if(!Y)Y=new jZ(Z),Q.set(Z,Y);let F=Y;return F.frameTurns??=new x2,Y}var k1=Symbol.for("cortexkit.openai-auth.v2.commands"),T4=L2("v2-command");function z1($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.closed instanceof AbortController&&typeof Z.menu?.open==="function"&&typeof Z.menu?.apply==="function"&&typeof Z.session?.get==="function"&&(Z.registration===void 0||Z.registration!==null&&typeof Z.registration.dispose==="function")}function D1($){T4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function L4(){let $=globalThis;return $[k1]??={locations:new Map},$[k1].locations??=new Map,$[k1]}async function LZ($,Z){let J=L4(),G=$.location.directory,Q={menu:Z,session:$.session,closed:new AbortController},Y=await HZ(G),F=await WZ(KZ,Y.dir,()=>TZ({...Y,drain:FZ,apply:(T)=>{let q=J.locations.get(G);if(!z1(q))throw Error("The OpenAI menu location was closed");return q.menu.apply(T)}})),V=J.locations.get(G);if(J.locations.set(G,Q),z1(V))V.closed.abort(),await V.registration?.dispose();let N={name:"openai",description:"OpenAI account menu",async execute(T){let q=[...J.locations.values()].find(z1)?.session;if(!q)return D1("no live location");let C=await q.get({sessionID:T.sessionID}),D=J.locations.get(C.location.directory);if(!z1(D))return D1("location closed");let d=await NZ(T.sessionID,D.closed.signal);if(!d||J.locations.get(C.location.directory)!==D){if(!d&&!D.closed.signal.aborted)w1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},T.sessionID);return D1(D.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let O=await D.menu.open(T.sessionID);w1(O,T.sessionID)}};J.command??=N,J.command.execute=N.execute;let B=J.command;try{Q.registration=await $.command.transform((T)=>{T.add(B)})}catch(T){if(Q.closed.abort(),J.locations.get(G)===Q)J.locations.delete(G);throw await F.release(),T}let H=!1;return async()=>{if(H)return;if(H=!0,Q.closed.abort(),J.locations.get(G)===Q)J.locations.delete(G);await F.release(),await Q.registration?.dispose()}}var _4="openai-auth-pool-browser",P4="openai-auth-pool-headless",M4="openai-auth-vault",C4="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Run /openai → Vault → Connect and approve the request before trying again.";async function v2($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function OZ($){return{method:{id:M4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await _Z($.paths,$.name)!=="vault")throw Error(C4)}}}function RZ($){let Z=(J,G,Q)=>({method:{id:J,type:"oauth",label:G},async authorize(){if($.vault)await v2($.vault);let Y=await $.beginLogin({version:$.version,headless:Q});return{url:Y.url,instructions:Y.instructions,mode:"auto",callback:Y.completion}}});return[Z(_4,"ChatGPT (openai-auth pool, browser)",!1),Z(P4,"ChatGPT (openai-auth pool, headless)",!0)]}function y1($){let Z=(J)=>typeof J==="string"?J:"";return k2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===CZ||PZ($)}function E4($){if($.accountId)return $.accountId;let Z=$.access?s2($.access):void 0;return Z?r2(Z):void 0}async function AZ($,Z,J,G={}){if(G.vault)await v2(G.vault);if(y1(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Q=MZ($,{rowLocks:(C)=>EZ(Z,C)}),Y=await Q.read();if(Y.status!=="ready")throw Error(`the account pool cannot be read (${Y.status}); the login was not stored`);let F={type:"oauth",refresh:J.refresh,...J.access!==void 0?{access:J.access}:{},...J.expires!==void 0?{expires:J.expires}:{}},V=E4(J);if(G.vault)await v2(G.vault);let N=V!==void 0?{identity:V}:{};if(G.origin==="import"){let C=Y.rows.find((D)=>V!==void 0&&D.identity===V||D.credential?.type==="oauth"&&D.credential.refresh===J.refresh);if(C)return{id:C.id,operation:"kept"}}let B=Y.rows.filter((C)=>C.type==="oauth"&&!C.invalid),H=V?B.find((C)=>C.identity===V):void 0,T=Y.rows.find((C)=>C.id===G1);if(H)return{id:(await Q.replace(H.id,F,N)).id,operation:"replaced"};if(!T){let C=await Q.add({id:G1,credential:F,...N,...J.label!==void 0?{label:J.label}:{}});return{id:C.id,operation:C.outcome==="added-disabled"?"added-disabled":"added"}}if(!T.invalid&&!T.credential)return{id:(await Q.replace(G1,F,N)).id,operation:"replaced"};let q=await Q.add({id:J.id,credential:F,...N,...J.label!==void 0?{label:J.label}:{}});return{id:q.id,operation:q.outcome==="added-disabled"?"added-disabled":q.outcome==="rotated"?"replaced":"added"}}function O4($){let Z=$.itemId!==void 0;switch($.sectionId){case"accounts":return Z?["enable","disable","remove","move"].includes($.actionId):$.actionId==="add";case"routing":return!Z&&["order","mode"].includes($.actionId);case"quota":return $.actionId==="check";case"limits":return Z?$.actionId==="floors":$.actionId==="killswitch";case"session":return!Z&&$.actionId==="clear-pin";case"vault":return Z?["enable","disable"].includes($.actionId):["connect","disconnect"].includes($.actionId);case"diagnostics":return!Z&&["logging","dump"].includes($.actionId);case"cache":return!Z&&["enabled","subagents","sustain","window"].includes($.actionId);case"reset":return Z&&["preview","spend","retry"].includes($.actionId);default:return!1}}function SZ($){let Z={...$,allowAction:O4,unavailableSections:[]};return{open:(J)=>xZ(Z,J),apply:(J)=>{let G=J!==null&&typeof J==="object"?J:{},Q=G.values&&typeof G.values==="object"&&!Array.isArray(G.values)?Object.fromEntries(Object.entries(G.values).filter(([,Y])=>Y===null||["string","number","boolean"].includes(typeof Y))):void 0;return qZ(Z,{command:"openai",sectionId:typeof G.sectionId==="string"?G.sectionId:"",actionId:typeof G.actionId==="string"?G.actionId:"",...Q?{values:Q}:{},...G.confirmed===!0?{confirmed:!0}:{},...typeof G.itemId==="string"?{itemId:G.itemId}:{},...typeof G.sessionId==="string"?{sessionId:G.sessionId}:{}})}}}function R4($,Z){if(!bZ($.modelID??$.id)){$.enabled=!1;return}let J=kZ($.id);if(J)$.limit={...J};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((G)=>[G.id,G])).values()]}function wZ($){return $.model.transform((Z)=>{let J=Z.list(F2);for(let G of J){let Q=DZ(String(G.id)),Y=Q?J.find((F)=>String(F.id)===Q):void 0;Z.update(F2,String(G.id),(F)=>R4(F,Y?.variants?.map((V)=>({...V,id:String(V.id)}))))}})}class f1{log;pending=new Map;requests=new Map;writing=new Set;constructor($){this.log=$}async safely($){let Z=(async()=>{try{await $()}catch{this.log.warn("request dump failed")}})();this.writing.add(Z);try{await Z}finally{this.writing.delete(Z)}}async captureHttp($,Z){if(!yZ())return;await this.safely(async()=>{let J={sessionID:Z.sessionID,accountId:Z.accountId,transport:"http",phase:"http",url:$.url,method:$.method,headers:new Headers($.headers),bodyText:await $.clone().text()};if(this.pending.set($,{attemptId:Z.attemptId,input:J}),this.requests.set(Z.attemptId,$),this.pending.size>512){let G=this.pending.keys().next().value;if(G)this.take(G)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let J=this.take($);if(J)await this.safely(()=>Q1({...J,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let J=this.requests.get($.attemptId),G=J&&this.take(J);if(!G)return;let{reason:Q,message:Y}=Z.error,F=Y?`${Q}: ${Y}`:Q;await this.safely(()=>Q1({...G,error:Y1(F,J?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>Q1({sessionID:Z.sessionID,accountId:Z.accountId,transport:"websocket",phase:"observed",bodyText:$}))}clear(){this.pending.clear(),this.requests.clear()}async settle(){await Promise.all(this.writing)}}class I1{counts=new Map;record($,Z){let J=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof J==="number"&&Number.isFinite(J)?J:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function mZ($){return async(Z)=>{let J=Z.credential;if(J.type!=="oauth"||!J.access)throw Error("the row holds no access token to poll with");let G=await fZ({accessToken:J.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,G),IZ(G,$.now(),!0)}}function gZ($){let{source:Z,counts:J,now:G}=$,Q=async(B)=>{let H=await Z.rowAccess(B,await $.storage());if(!H?.row)throw new vZ("unknown_account",`${B==="main"?"Main":"Fallback"} account ${B} was not found.`);return hZ(B,H)},Y=async(B)=>{if($.authority&&await $.authority()!=="local")return{account:B,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[H]=await Z.pollRows(await $.storage(),{ids:[B]});if(!H)return{account:B,ok:!1,error:"targeted quota refresh returned no result"};return{account:H.id,ok:H.ok,...H.error!==void 0?{error:H.error}:{}}},F=(B)=>Z.peek().rows.find((H)=>H.id===B),V=(B)=>{let H=F(B);if(!H)return null;let T=y2(H.quota)??{},q=J.applicable(H),C=Math.max(0,...[T.primary?.checkedAt,T.secondary?.checkedAt].filter((D)=>typeof D==="number"));return{quota:{...T,...q!==void 0?{resetCreditsApplicable:q}:{}},checkedAt:C,refreshAfter:C,...H.identity!==void 0?{accountId:H.identity}:{}}};return{resolveResetTarget:Q,refreshResetTargetQuota:Y,quotaManager:{isRateLimited:(B)=>{let H=F(B);if(!H)return!1;let T=Z.rateLimitMarks([H]).get(H.id);return T!==void 0&&T>G()},getMain:()=>V("main"),getFallback:(B)=>V(B)}}}import{resolve as lZ}from"node:path";var A4=1024;class v1{pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=A4){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.reservations.delete($),this.pins.delete($);for(let Z of this.listeners)Z($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}snapshot(){return new Map(this.pins)}placementSnapshot($){let Z=new Map(this.pins);for(let J of this.reservations.values())if(J.sessionId!==$)Z.set(J.sessionId,J.pin);return Z}reserve($,Z){let J={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,J),J}rollback($){if(this.reservations.get($.sessionId)===$)this.reservations.delete($.sessionId)}finish($,Z){if(this.reservations.get($.sessionId)!==$)return;if(this.rollback($),Z&&this.pins.get($.sessionId)===$.previous)this.set($.sessionId,Z)}get size(){return this.pins.size}set($,Z){this.reservations.delete($),this.pins.delete($),this.pins.set($,Z);for(let J of this.listeners)J($,Z);while(this.pins.size>this.limit){let J=this.pins.keys().next().value;if(J===void 0)break;this.forget(J)}}place($){return t2(this.placementSnapshot($.sessionId),$,(Z,J)=>this.set(Z,J))}}var uZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),pZ=globalThis,X1=pZ[uZ]??new Map;pZ[uZ]=X1;function x4($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.get==="function"&&typeof Z.forget==="function"&&typeof Z.subscribe==="function"&&typeof Z.snapshot==="function"&&typeof Z.place==="function"&&typeof Z.placementSnapshot==="function"&&typeof Z.reserve==="function"&&typeof Z.rollback==="function"&&typeof Z.finish==="function"}function cZ($){let Z=JSON.stringify([lZ($.configPath),lZ($.statePath)]),J=X1,G=X1.get(Z);if(G!==void 0&&!x4(G)){let Y=X1;Y.compatibleV1??=new Map,J=Y.compatibleV1}let Q=J.get(Z);if(!Q)Q=new v1,J.set(Z,Q);return Q}import{statSync as q4}from"node:fs";import{resolve as S4}from"node:path";function eZ($){return $.map((Z)=>{try{let J=q4(Z);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}function h1($){return eZ([$.vault.paths.tokenPath,$.vault.paths.statePath])}function dZ($){return eZ([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+h1($)}class $0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:dZ($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),J=this.subscriptions.get($.pins);if(!J){let G=new Set;J={producers:G,stop:$.pins.subscribe((Q,Y)=>{let F=G.values().next().value;if(F)this.publish(F,{sessionId:Q,pin:Y,accountId:Y?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,J)}return J.producers.add($),this.timer??=setInterval(()=>{for(let G of this.producers){let Q={stamp:dZ(G),roster:G.vault.snapshot()},Y=this.observations.get(G);if(Q.stamp!==Y?.stamp||Q.roster!==Y?.roster)this.observations.set(G,Q),this.publish(G)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),J.producers.delete($),!J.producers.size)J.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;let G=await $.vault.authority()!=="local",Q=h1($),Y=()=>this.producers.has($)&&$.vault.enrolled()===G&&h1($)===Q,F=await(G?m2($.paths):q2($.paths)),V=G?rZ($.vault.snapshot()?.rows,new Set($.vault.routes().map((H)=>H.id)),F,Date.now()):tZ((await $.source.sidebarView()).rows,F,Date.now()),N={canWrite:Y,vaultMode:G};if(await aZ(V,this.file,N),!Y()||!Z)return;let B=V.vaultAccounts??V.fallbacks;if(Z.accountId===void 0){await oZ(Z.sessionId,B,this.file,N);return}if(Z.pin){let H=Date.now();await sZ({sessionId:Z.sessionId,assignment:{accountId:Z.pin.accountId,wireAccountId:Z.pin.wireIdentity,inputBytes:Z.pin.inputBytes??0,quotaCheckedAt:Z.pin.quotaCheckedAt,assignedAt:H,lastSeenAt:H},validPinnedAccountIds:[...G?[]:["main"],...B.filter((T)=>T.enabled).map((T)=>T.id)]},this.file,N)}await nZ({sessionId:Z.sessionId,activeId:Z.accountId,route:Z.route??V.route,updatedAt:Date.now()},B,this.file,N)}).catch(()=>{L2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var Z0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),J0=globalThis,h2=J0[Z0]??new Map;J0[Z0]=h2;function z0($,Z=iZ(),J=2000){let G=S4(Z),Q=h2.get(G);if(!Q)Q=new $0(G,J),h2.set(G,Q);let Y=Q,F=Y.add($),V=!1;for(let[N,B]of $.pins.snapshot())Y.publish($,{sessionId:N,pin:B,accountId:B.accountId,route:"sticky-balanced"});return{publish:()=>Y.publish($),route:(N,B,H)=>{Y.publish($,{sessionId:N,accountId:B,route:H})},async release(){if(V)return;if(V=!0,F(),await Y.settled(),Y.empty&&h2.get(G)===Y)h2.delete(G)}}}var V1="cortexkit-openai-auth",D4=5000;async function G0($,Z,J,G=new D2,Q,Y,F){let V=new f1(J),N=new b4,B=new Map,H=new Map,T=(O)=>{H.delete(O);for(let I of B.keys())if(I.startsWith(`${O}:`))B.delete(I)},q=(O)=>{F?.(O.sessionID),Y?.send(O.sessionID,O.frame)},D=await K1({session:{hook:(O,I,B2)=>$.session.hook(O,async(J2)=>{let w=O==="http.request"?J2:void 0,l=O==="experimental.ws.handshake"?J2:void 0,Z2=(w?w.request.headers:l?new Headers(l.headers):void 0)?.get("authorization")===`Bearer ${K2(Z.providerID)}`,i={};if(l)B.delete(`${l.sessionID}:${l.kind}`);try{await N.run(i,()=>I(J2))}catch(X){if(Z2&&!(X instanceof Y2))throw V0(X);throw X}if(w&&Z2&&i.attempt){let X=w.request.headers.get("thread-id");if(X)w.request.headers.set("session-id",X)}if(w&&Z2&&i.attempt)await V.captureHttp(w.request,i.attempt);if(w&&Z2&&i.attempt)await Q?.({sessionID:w.sessionID,kind:w.kind,request:w.request,attempt:i.attempt});if(l&&Z2&&i.attempt)l.headers["session-id"]=G.get(l.sessionID).threadID;if(O==="experimental.ws.send"){let X=J2,K=B.get(`${X.sessionID}:${X.kind}`);if(K)await V.frame(X.frame,K.attempt);if(K&&X.kind==="primary")q(X)}if(w||l){let X=w??l;if(!X)return;let M=(w?w.request.headers:new Headers(X.headers)).get("authorization")?.replace(/^Bearer /,"");if(Z2&&M)H.set(X.sessionID,M);else H.delete(X.sessionID);if(l){let L=`${l.sessionID}:${l.kind}`;if(Z2&&M&&i.attempt)B.set(L,{bearer:M,attempt:i.attempt,url:l.url,headers:new Headers(Object.entries(l.headers).filter(([h])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(h.toLowerCase())))});else B.delete(L)}if(H.size>512){let L=H.keys().next().value;if(L)H.delete(L)}if(B.size>512){let L=B.keys().next().value;if(L)B.delete(L)}}else if(O==="experimental.ws.receive"){let X=J2,K=B.get(`${X.sessionID}:${X.kind}`);if(K){if(G.frameReceived(X.sessionID,X.frame),X.kind==="primary"){let M;if(Y?.receive(X.sessionID,X.frame,(L)=>{M=L}),M)try{let L=B$(M,K.url,K.headers,G);if(L)await Q?.({sessionID:X.sessionID,kind:"primary",request:L,attempt:K.attempt})}catch(L){J.warn("cachekeep WebSocket capture failed",{error:L instanceof Error?L.message:String(L)})}}X.frame=U0(X.frame,K.bearer)}}else if(O==="retry"){let X=J2,K=H.get(X.sessionID);if(K)Object.assign(X.error,{message:Y1(X.error.message,K)})}},B2)},event:{subscribe:(O)=>async function*(){for await(let I of $.event.subscribe(O)){if(I.type==="session.deleted")T(I.data.sessionID);yield I}}()}},{...Z,rewriteRequest:async(O)=>{let I=N.getStore();if(I)I.attempt=O.attempt;return Z.rewriteRequest?.(O)},rewriteHandshakeURL:(O)=>{let I=N.getStore();if(I)I.attempt=O.attempt;return Z.rewriteHandshakeURL?.(O)},onAttemptEnd:async(O,I)=>{await V.end(O,I),await Z.onAttemptEnd?.(O,I)},rewriteResponse:async(O)=>{await V.response(O.request,O.response.status);let I=await Z.rewriteResponse?.(O)??O.response;return W0(I,O.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(O)=>{let I=O.get("authorization");return I?.startsWith("Bearer ")?I.slice(7):void 0}},logger:{warn:(O,I)=>J.warn(O,{data:I})}}),d=D.dispose;return{...D,dispose:async()=>{H.clear(),B.clear(),await d(),await V.settle(),V.clear()}}}function l1($={}){return{id:V1,setup:(Z)=>w4(Z,$)}}async function w4($,Z={}){let g=[];try{let J=L2("opencode2");let G=L2("quota");let Q=Z.version??N0;await A0({version:Q,...Z.runtimeLayout});let Y=Z.paths??(()=>K0(H0()));let F=await m2(Y());let V=F?.logging?.level;if(V&&typeof V==="string")Y0(V);let N=Z.fetch??fetch;let B=Z.now??Date.now;let H=Z.poolMigration??q0;if(!H&&!S2(Y().configPath)){J.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let _=(j2)=>{throw new Y2({kind:"no-account",providerID:F2,sessionID:j2.sessionID,requestKind:j2.kind,message:e2})},b=await G0($,{providerID:F2,chooseAccount:_,accountHeaders:_},J);return()=>b.dispose()}let T=Z.vault?.firstRosterWaitMs??M0;let q=x0({host:"opencode",stateDir:Z.vault?.stateDir??B0(Y().statePath),reservedRouteIds:()=>w.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:()=>N},Y());let C=q.vault;let D=async()=>await C.authority()==="local"?q2(Y()):m2(Y());let d=!1;let O=!1;const I=j1(g,{[Symbol.dispose](){if(!d)q.release()}},0);await C.authority();let B2=q.firstRoster;let J2=new I1;let w=new C0({paths:Y,rateLimitMarks:N$(Y()),refreshProvider:async(_)=>{let b=await j0({refreshToken:_.refresh,fetchImpl:N,now:B}),j2=X0({id_token:"",access_token:b.access,refresh_token:b.refresh});return{...b,...j2?{identity:j2}:{}}},pullQuota:mZ({fetchImpl:N,now:B,counts:J2,logger:G}),now:B,vaultIdentities:()=>C.identities(),vaultMode:()=>C.enrolled(),vaultAuthority:()=>C.authority(),vaultFirstRoster:B2,vaultFirstRosterBackgroundWaitMs:T,log:L2("pool")});if(await C.authority()==="local")await w.load();let l=Z.heartbeat===!1?void 0:await O0({version:Q,logger:L2("heartbeat")});let _2=Z.fence??(()=>F0({currentVersion:Q}));let Z2=Z.slot??S0();let i=async()=>T0(Y(),await Z2.get({path:{id:"openai"}}));let X=!1;let K=H?E0({paths:Y,slot:Z2,version:Q,fence:_2,runDeps:{vaultServes:()=>C.serves()},paused:async()=>await C.authority()!=="local",migrate:async(_)=>{let b=await L0(_);if(X=b.status==="refused",!O)await w.load();return b},adopt:async(_)=>{if(O)return{status:"retry",reason:"unsettled"};if(!await g1(B2,T))return{status:"retry",reason:"vault-roster-pending"};if(O)return{status:"retry",reason:"unsettled"};let b=await _0(_);if(!O)await w.load();return b}}):void 0;K?.start();q.start();let M=cZ(Y());let L=z0({paths:Y(),source:w,pins:M,vault:C},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const h=j1(g,{[Symbol.dispose](){if(!d)L.release()}},0);L.publish();let R=Z.codex??new D2(void 0,void 0,UZ());let S=e$(F);let v=Z1(Y());let A=JZ(Y(),{source:w,storage:D,vault:C,accounts:O1(Y()),settings:()=>S,parentOf:async(_)=>(await $.session.get({sessionID:_}))?.parentID??void 0,fetch:N,log:L2("cachekeep")},{now:B,codexResponsesUrl:B1().codexApiEndpoint,...Z.cacheKeep});const f=j1(g,{[Symbol.dispose](){if(!d)A.release()}},0);let n=p$({codex:R,onRoute:L.route,source:w,slotPlaceholderWithoutMain:i,storage:D,pins:M,sessionAccounts:O1(Y()),vault:C,awaitVaultRoster:async()=>{await g1(C.awaitRequestRoster(),P0)},responsesLite:()=>B1().responsesLite,codexEndpoint:()=>B1().codexApiEndpoint,now:B,log:J});let u=await G0($,n.adapter,J,R,(_)=>A.capture(_),v,(_)=>A.forget(_));n.attach(u);let o=async(_)=>{if(await v2(C),S2(Y().configPath))return;if(await K?.idle(),S2(Y().configPath))return;if(X&&!y1(_)&&(await _2()).open){await w.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let s=async(_)=>{await o(_);let b=await AZ(w.poolStore(),Y(),_,{vault:C});if(!S2(Y().configPath))await K?.requestAdoption();await w.load(),J.info("ChatGPT login stored in the account pool",b)};let e=await N1($,{integrationID:F2,methods:RZ({beginLogin:Z.beginLogin??m1,version:Q,vault:C}),onLogin:(_)=>s(_),label:"ChatGPT (openai-auth account pool)",vault:OZ(C)});let p=await wZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let x=$.command&&$.location?await LZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??SZ({...gZ({source:w,storage:D,counts:J2,now:B,authority:()=>C.authority()}),fetchImpl:N,now:B,randomUUID:k4,accountStoragePath:Y().configPath,accountStatePath:Y().statePath,packageVersion:Q,layoutNotice:R0,loadAccounts:q2,store:()=>w.poolStore(),migration:async()=>{if(S2(Y().configPath))return{migrated:!0};let _=await _2();return{migrated:!1,blockers:_.open?[]:_.blockers}},beginAccountLogin:Z.beginLogin??m1,refreshAllQuota:async()=>(await w.pollRows(await q2(Y()))).map((_)=>({..._,account:_.id})),getStickyRouting:async(_)=>M.get(_),cacheKeepManager:A.manager,setCacheKeepEnabled:(_)=>A.configure({enabled:_}),setCacheKeepSubagents:(_)=>A.configure({subagents:_}),setCacheKeepSustain:(_)=>A.configure({sustain:_}),setCacheKeepWindow:(_)=>A.configure({window:_}),afterWrite:()=>w.load(),refreshSidebar:()=>L.publish(),clearStickyRouting:async(_)=>{let b=M.get(_)!==void 0;return M.forget(_),b},vault:C})):void 0;let G2=new AbortController;(async()=>{try{for await(let _ of $.event.subscribe({signal:G2.signal}))if(_.type==="session.deleted")n.forgetSession(_.data.sessionID),A.forget(_.data.sessionID),v.forget(_.data.sessionID)}catch(_){if(!G2.signal.aborted)J.warn("stopped listening for session deletion",{error:_ instanceof Error?_.message:String(_)})}})();d=!0;return async()=>{O=!0,G2.abort();let _=A.release();await x?.(),K?.dispose(),await w.dispose(),await L.release(),await Promise.allSettled([u.dispose(),e.dispose(),p.dispose()]);let b;try{await Promise.race([Promise.all([K?.idle(),w.settled(),R.store?.settled(),_]),new Promise((j2)=>{b=setTimeout(j2,D4),b.unref?.()})])}finally{clearTimeout(b),q.release(),await l?.release()}}}catch(m){var $2=m,X2=1}finally{Q0(g,$2,X2)}}var y4=l1(),j7={id:V1,setup:y4.setup,server:b0.server};export{j7 as default,l1 as createOpenAIAuthPlugin,V1 as OPENAI_AUTH_PLUGIN_ID};
3
+ `)}}function F1($,Z){let J=new TextDecoder,G="",Y=(F)=>{let W=I0(F);if(!W)return;try{$(W)}catch(N){Z(N)}},Q=()=>{for(;;){let F=/\r?\n\r?\n/.exec(G);if(!F)return;let W=G.slice(0,F.index);G=G.slice(F.index+F[0].length),Y(W)}};return new TransformStream({transform(F,W){W.enqueue(F),G+=J.decode(F,{stream:!0}),Q()},flush(){if(G+=J.decode(),Q(),G.trim()!=="")Y(G);G=""}})}var r1=512,t1=1200000,R2="x-common-auth-attempt",O2=($,Z)=>JSON.stringify([$,Z]),N2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function f0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function v0($,Z){let J=$.getReader();return new ReadableStream({async pull(G){let Y;try{Y=await J.read()}catch(Q){Z({reason:"failed",message:Q instanceof Error?Q.message:String(Q)}),G.error(Q);return}if(Y.done)Z(),G.close();else G.enqueue(Y.value)},async cancel(G){Z({reason:"cancelled",...G===void 0?{}:{message:String(G)}}),await J.cancel(G)}})}function u2($,Z){for(let[J,G]of Object.entries(Z)){let Y=J.toLowerCase();for(let Q of Object.keys($))if(Q.toLowerCase()===Y)delete $[Q];if(G!==null)$[J]=G}}function h0($,Z){for(let[J,G]of Object.entries(Z))if(G===null)$.delete(J);else $.set(J,G)}async function K1($,Z,J={}){let{providerID:G}=Z,Y=J.gateOnPlaceholder,Q=(z)=>Y===void 0||Y.credential(z)===K2(G),F=J.logger,W=Math.max(1,J.maxRecords??r1),N=[...J.hostCredentials??[K2(G)],...Y?[K2(G)]:[]].filter((z)=>z!==""),B=new Map,H=new WeakMap,T=new Map,R=0,C=new Set,D=new Map,d=new Map,O=(z)=>{let j=d.get(z);return j?.ownedSeen===!0&&j.foreignSeen},f=(z,j)=>{D.set(z,j);let V=d.get(z)??{ownedSeen:!1,foreignSeen:!1};if(j)V.ownedSeen=!0;else V.foreignSeen=!0;d.set(z,V)},B2=(z,j)=>{let V=Y?.refuseMisplaced,P=V?[...j].filter(([,k])=>k.includes(K2(G))):[],U=Q(j)&&(!V||P.length>0);if(V){if(P.length>0&&(P.length!==1||!U))throw f(z.sessionID,!1),new Y2({kind:"placement-refused",providerID:G,sessionID:z.sessionID,requestKind:z.kind,message:V(P[0]?.[0]??"")})}return f(z.sessionID,U),U},J2=!1,w=!1,l=new Map,L2=0,Z2=!1,i=new Map,X=(z,j)=>{try{F?.warn(z,j)}catch{}},K=(z)=>z instanceof Error?z.message:String(z),M=new Map,_=(z,j)=>{let V=(M.get(z)??Promise.resolve()).then(j),P=V.then(()=>{},()=>{});return M.set(z,P),P.then(()=>{if(M.get(z)===P)M.delete(z)}),V},h=(z,j)=>{let V=M.get(z);return V?V.then(()=>h(z,j)):j()},A=async(z)=>{try{await Z.dropChoice?.({...z.input,accountId:z.accountId})}catch(j){X("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:z.input.sessionID,error:K(j)})}},S=async(z)=>{try{await Z.dropSameAccountRetry?.({...z.input,accountId:z.accountId})}catch(j){X("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:z.input.sessionID,error:K(j)})}},v=async(z)=>{if(z.next)await A(z.next);if(z.sameAccount)await S(z.sameAccount)},x=(z)=>{let j=T.get(z);if(T.delete(z),j)_(j.sessionID,()=>v(j))},I=async(z,j)=>{let V=l.get(z);if(!V||V.size===0)return;await Promise.all([...V].map(async(P)=>{try{await P(j)}catch(U){X("opencode2 auth listener threw; the request is unaffected",{event:z,error:K(U)})}}))},n=async(z,j)=>{try{await Z.onAttemptEnd?.(z,j)}catch(V){X("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:z.attemptId,error:K(V)})}},u=(z,j)=>{if(z.ended||!z.attempt)return;let V={...z.status===void 0?{}:{status:z.status},outputStarted:z.outputStarted,...z.limit?{limit:z.limit.signal}:{},...j?{error:j}:{}};if(j)z.endError=j;z.ended=n(z.attempt,V)},o=(z,j)=>u(z,{reason:"abandoned",message:j}),s=(z)=>[...B.values()].filter((j)=>j.key===z),e=(z)=>s(z).at(-1),p=(z)=>{if(B.delete(z.id),T.get(z.key)?.attemptId===z.id||!s(z.key).length)x(z.key)},q=(z)=>{B.set(z.id,z);while(B.size>W){let j=B.values().next().value;if(j===void 0)break;o(j,"dropped to keep the record bound"),p(j)}},G2=(z)=>z.accountId===void 0?void 0:{...z.scope,accountId:z.accountId},g=(z,j)=>new Y2({kind:"no-account",providerID:G,sessionID:z.sessionID,requestKind:z.kind,...j===void 0?{}:{message:j}}),m=(z)=>{i.get(z)?.clear(),i.delete(z)},$2=async(z,j)=>{let V=()=>g(z,`${G} ${z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(Z2)throw V();let P=i.get(z.sessionID);if(!P)P=new Set,i.set(z.sessionID,P);let U={};P.add(U);let k=()=>{if(!P.has(U))throw V()};try{return await j(k)}finally{if(P.delete(U),P.size===0&&i.get(z.sessionID)===P)i.delete(z.sessionID)}},X2=(z,j)=>{for(let[V,P]of j)if(N.some((U)=>P.includes(U)))throw new Y2({kind:"host-credential-on-wire",providerID:G,sessionID:z.sessionID,requestKind:z.kind,message:`${G} ${z.kind} request still carries the host's placeholder credential in ${V}; the adapter's account headers must replace it`})},L=(z)=>{for(let j of s(z))if(j.ended||!j.attempt)p(j);else if(j.transport==="ws"||j.judged)o(j,"a newer attempt of its session and kind began"),p(j)},b=async(z,j,V,P)=>{let U=O2(z.sessionID,z.kind),{input:k,accountId:E,sameAccountRetry:y}=await h(z.sessionID,async()=>{V();let r=T.get(U);T.delete(U);let z2=r?.accountId??e(U)?.accountId;L(U);let t=r?.next,Q2=r?.sameAccount,a=Q2!==void 0&&Q2.input.modelID===z.modelID&&Q2.input.agent===z.agent,W2=t!==void 0&&t.input.modelID===z.modelID&&t.input.agent===z.agent,U2={...z,phase:"request",...z2===void 0?{}:{previousAccountId:z2},...r?.rerouteFrom?{rerouteFrom:r.rerouteFrom}:{}};if(t&&!W2)await _(z.sessionID,()=>A(t)),V();if(Q2&&!a)await _(z.sessionID,()=>S(Q2)),V();let H2=a?Q2.accountId:W2?t.accountId:await Z.chooseAccount(U2);return{input:U2,accountId:typeof H2==="string"?H2:void 0,sameAccountRetry:a}});V();let c={},V2;if(E!==void 0){let r=await Z.accountHeaders({...z,accountId:E});if(V(),f0(r))c=r.headers,V2=r.attempt;else c=r}let g2=`attempt-${++L2}`,E2={id:g2,key:U,scope:z,accountId:E,headers:c,attempt:E===void 0?void 0:{...z,accountId:E,attemptId:g2,transport:P,data:V2},...P===void 0?{}:{transport:P},outputStarted:!1,sameAccountRetry:y};if(q(E2),E2.attempt)I("select",{...z,accountId:E2.attempt.accountId,hook:j,...k.previousAccountId===void 0?{}:{previousAccountId:k.previousAccountId},...k.rerouteFrom===void 0?{}:{rerouteFrom:k.rerouteFrom},handle:E2.attempt});return E2},j2=async(z,j,V,P,U)=>{let k=O2(z.sessionID,z.kind),E=P===void 0?void 0:B.get(P);if(E?.key!==k)E=void 0;if(!E){if(E=e(k),s(k).filter((c)=>c.transport===void 0&&!c.ended).length>1&&!w)w=!0,X("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:z.sessionID,kind:z.kind})}if(!E||E.transport!==void 0||E.ended)E=await b(z,j,U,V);else if(E.transport=V,E.attempt)E.attempt.transport=V;if(V==="ws"){for(let y of s(k))if(y!==E&&y.transport==="ws")o(y,"a newer attempt of its session and kind went out over WebSocket")}return E},b2=async(z,j)=>{try{return await j()}catch(V){throw u(z,{reason:"failed",message:K(V)}),V}},u1=(z,j)=>{let V=s(O2(z,j)).filter((P)=>P.transport==="ws").at(-1);return V?.attempt!==void 0&&!V.ended?V:void 0},W1=(z,j,V)=>{let P=G2(z);if(!P||!z.attempt||z.limit)return;z.limit={signal:j,delivered:I("limit",{...P,via:V,limit:j,outputStarted:z.outputStarted,handle:z.attempt})}},p1=(z,j,V,P)=>{let U=G2(z);if(!U||!z.attempt)return;I("quota",{...U,transport:j,...P===void 0?{}:{status:P},quota:V,handle:z.attempt})},c1=(z,j,V,P)=>{let U=z.attempt;if(!U)return;let k=Z.inspectEvent?.(P===void 0?{transport:j,data:V,attempt:U}:{transport:j,data:V,event:P,attempt:U});if(!k)return;if(k.quota!==void 0)p1(z,j,k.quota);if(k.outputStarted)z.outputStarted=!0;if(k.limit)W1(z,k.limit,j);if(k.error!==void 0)u(z,{reason:"failed",message:k.error});else if(k.done)u(z)},w0=(z,j)=>{let V=z.attempt;if(!V||j.accountId===z.accountId)return;if(V.reboundFrom??=V.accountId,V.accountId=j.accountId,"data"in j)V.data=j.data;z.accountId=j.accountId},y0=(z)=>!z.attempt||z.endError!==void 0||z.status!==void 0&&z.status>=400,d1=(z)=>{let j=[...B.values()].filter((y)=>y.scope.sessionID===z),V=j.filter((y)=>y.limit&&!y.rerouted).at(-1);if(V)return V;let P=j.filter((y)=>y.scope.kind==="primary"),U=P.length>0?P:j;if(U.length<=1)return U[0];let k=U.filter((y)=>!y.judged&&y0(y)).at(-1);if(k)return k;let E=U.filter((y)=>y.attempt&&!y.ended);if(E.length>1)return"ambiguous";return E[0]??U.at(-1)},C2={providerID:G},P2=[];P2.push(await $.session.hook("model.request",(z)=>{if(Y)return;return $2(N2(z),async(j)=>{let V=await b(N2(z),"model.request",j);if(j(),V.accountId===void 0)throw g(V.scope);u2(z.headers,{...V.headers,[R2]:V.id})})},C2)),P2.push(await $.session.hook("http.request",(z)=>{if(Y){if(!B2(N2(z),z.request.headers))return}return $2(N2(z),async(j)=>{let V=z.request.headers.get(R2)??void 0,P=Y?await b(N2(z),"http.request",j,"http"):await j2(N2(z),"http.request","http",V,j);j();let U=G2(P),k=P.attempt;if(!U||!k)throw g(P.scope);await b2(P,async()=>{let E=z.request;if(Z.rewriteRequest){if(V!==void 0){let V2=new Headers(E.headers);V2.delete(R2),E=new Request(E,{headers:V2})}E=await Z.rewriteRequest({...U,request:E,attempt:k})??E,j()}let y=new Headers(E.headers);y.delete(R2),h0(y,P.headers),X2(P.scope,y.entries());let c=new Request(E,{headers:y});H.set(c,P),z.request=c})})},C2)),P2.push(await $.session.hook("http.response",async(z)=>{let j=H.get(z.request);if(!j){if(Y)return;if(!J2)J2=!0,X("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:z.sessionID,kind:z.kind});return}let V=z.response;if(Z.answeredBy&&j.attempt){let y=j.attempt,c=await b2(j,async()=>Z.answeredBy?.({request:z.request,response:V,attempt:y}));if(c)w0(j,c)}let P=G2(j),U=j.attempt;if(!P||!U)return;j.status=V.status;let k=Z.quotaFromHeaders?.(V.headers,V.status,U);if(k!==void 0)p1(j,"http",k,V.status);if(!V.ok&&Z.limitFromResponse){let y=await Z.limitFromResponse({status:V.status,headers:V.headers,body:()=>V.clone().text(),attempt:U});if(y)W1(j,y,"http")}if(!V.ok||!V.body)u(j);let E=V;if(V.body&&(Z.inspectEvent||Z.onAttemptEnd)){let y=V.body;if(Z.inspectEvent)y=y.pipeThrough(F1((c)=>c1(j,"http",c.data,c.event),(c)=>X("opencode2 auth event inspection threw",{error:K(c)})));E=new Response(v0(y,(c)=>u(j,c)),{status:V.status,statusText:V.statusText,headers:V.headers})}if(Z.rewriteResponse)E=await Z.rewriteResponse({...P,request:z.request,response:E,attempt:U})??E;if(E!==V)z.response=E},C2)),P2.push(await $.session.hook("experimental.ws.handshake",(z)=>{if(Y){let j=O2(z.sessionID,z.kind);if(C.delete(j),!B2(N2(z),new Headers(z.headers)))return}return $2(N2(z),async(j)=>{let V;for(let E of Object.keys(z.headers)){if(E.toLowerCase()!==R2)continue;V??=z.headers[E],delete z.headers[E]}let P=Y?await b(N2(z),"experimental.ws.handshake",j,"ws"):await j2(N2(z),"experimental.ws.handshake","ws",V,j);j();let U=G2(P),k=P.attempt;if(!U||!k)throw g(P.scope);await b2(P,async()=>{if(!Y?.refuseMisplaced)u2(z.headers,P.headers);let E=Z.rewriteHandshakeURL?.({...U,url:z.url,attempt:k});if(E!==void 0)z.url=E;if(Y?.refuseMisplaced)u2(z.headers,P.headers);if(X2(P.scope,Object.entries(z.headers)),Y)C.add(P.key)})})},C2));let i1=Z.rewriteWebSocketFrame?.bind(Z);if(i1)P2.push(await $.session.hook("experimental.ws.send",async(z)=>{let j=N2(z);if(Y&&!C.has(O2(j.sessionID,j.kind)))return;let V=u1(j.sessionID,j.kind),P=await i1({...j,attempt:V?.attempt,frame:z.frame});if(P!==void 0)z.frame=P},C2));P2.push(await $.session.hook("experimental.ws.receive",(z)=>{if(Y&&!C.has(O2(z.sessionID,z.kind)))return;let j=u1(z.sessionID,z.kind);if(!j)return;try{c1(j,"ws",z.frame)}catch(V){X("opencode2 auth frame inspection threw",{error:K(V)})}},C2)),P2.push(await $.session.hook("retry",async(z)=>{if(Y&&D.get(z.sessionID)!==!0)return;let j=z.decision,V=()=>I("retry",{sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:j,decision:j});if(O(z.sessionID)&&!Z.retrySameAccount){await V();return}let P=d1(z.sessionID);if(!P)return;if(P==="ambiguous"){await I("retry",{sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:j,decision:j});return}let U=P;await $2(U.scope,async(k)=>{let E=k,y=Z.retrySameAccount?.bind(Z),c=U.attempt;if(y&&c&&!U.outputStarted&&!U.sameAccountRetry){if(U.ended)await U.ended;if(U.limit)await U.limit.delivered;let r=await _(U.scope.sessionID,async()=>{E();let z2=c.accountId,t=()=>B.has(U.id)&&U.accountId===z2&&d1(z.sessionID)===U&&!U.outputStarted&&(!Y||D.get(z.sessionID)===!0);if(!t()||U.sameAccountRetry)return!1;U.sameAccountRetry=!0;let Q2={...U.scope,accountId:z2,error:z.error,attempt:z.attempt,...U.limit?{limit:U.limit.signal}:{}},a;try{a=await y(Q2)}catch(H2){X("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:z.sessionID,error:K(H2)})}if(!a)return E(),!1;let W2={accountId:a.accountId,input:Q2};try{E()}catch(H2){throw await S(W2),H2}if(!t()||a.accountId!==z2)return await S(W2),!1;let U2=T.get(U.key);if(T.delete(U.key),U2)await v(U2);try{E()}catch(H2){throw await S(W2),H2}if(!t())return await S(W2),!1;return T.set(U.key,{attemptId:U.id,sessionID:U.scope.sessionID,order:++R,accountId:z2,sameAccount:W2}),U.judged=!0,z.decision={retry:!0,delay:0},!0});if(E(),r){await I("retry",{sessionID:z.sessionID,accountId:U.accountId,kind:U.scope.kind,attempt:z.attempt,reason:"same-account",hostDecision:j,decision:z.decision,handle:U.attempt});return}}if(O(z.sessionID)){await V();return}U.judged=!0;let V2=U.attempt;if(V2&&!U.outputStarted){if(!U.limit){let r=Z.limitFromError?.(z.error,V2);if(r)W1(U,r,"error")}if(U.ended)await U.ended;if(U.limit)await U.limit.delivered}E();let{decision:g2,reason:E2}=await _(U.scope.sessionID,async()=>{if(E(),O(z.sessionID))return{decision:j,reason:"host-decides"};let r=T.get(U.key);if(T.delete(U.key),r)await v(r);if(E(),O(z.sessionID))return{decision:j,reason:"host-decides"};let z2=j,t,Q2,a;if(U.accountId===void 0||!V2)z2={retry:!1},t="no-account";else if(U.outputStarted)z2={retry:!1},t="output-started";else if(U.limit){let W2={accountId:U.accountId,limit:U.limit.signal},U2,H2={...U.scope,phase:"retry",previousAccountId:U.accountId,rerouteFrom:W2};try{U2=await Z.chooseAccount(H2)}catch(H1){X("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:U.scope.sessionID,error:K(H1)})}let M2=typeof U2==="object"?U2.hold:void 0,l2=typeof U2==="string"?U2:M2?U.accountId:void 0;if(l2!==void 0)a={accountId:l2,input:H2};try{E()}catch(H1){if(a)await A(a);throw H1}if(O(z.sessionID)){if(a)await A(a);return{decision:j,reason:"host-decides"}}if(M2&&Number.isFinite(M2.delayMs)&&M2.delayMs>=0)z2={retry:!0,delay:Math.min(M2.delayMs,t1)},t="hold";else if(!M2&&l2!==void 0&&l2!==U.accountId)U.rerouted=!0,Q2=W2,z2={retry:!0,delay:0},t="reroute";else{if(M2&&a)await A(a),a=void 0;t="host-decides-last-account"}}else t="host-decides";if(z.decision=z2,z2.retry&&U.accountId!==void 0&&B.has(U.id))T.set(U.key,{attemptId:U.id,sessionID:U.scope.sessionID,order:++R,accountId:U.accountId,...Q2===void 0?{}:{rerouteFrom:Q2},...a===void 0?{}:{next:a}});else if(a)await A(a);return{decision:z2,reason:t}});E(),await I("retry",{sessionID:z.sessionID,...U.accountId===void 0?{}:{accountId:U.accountId},kind:U.scope.kind,attempt:z.attempt,reason:E2,hostDecision:j,decision:g2,...V2===void 0?{}:{handle:V2}})})},C2));let a1=(z)=>{if(m(z),D.delete(z),!d.get(z)?.foreignSeen)d.delete(z);for(let j of C)if(JSON.parse(j)[0]===z)C.delete(j);for(let j of[...B.values()]){if(j.scope.sessionID!==z)continue;o(j,"its session was forgotten"),B.delete(j.id)}for(let[j,V]of T)if(V.sessionID===z)x(j)},U1=new AbortController,n1=$.event;if(n1)(async()=>{try{for await(let z of n1.subscribe({signal:U1.signal}))if(z.type==="session.deleted")a1(z.data.sessionID);else if(z.type==="session.status"&&z.data.status.type==="idle"){let j=z.data.sessionID,V=++R;_(j,async()=>{for(let[P,U]of T)if(U.sessionID===j&&U.order<V)T.delete(P),await v(U)})}}catch(z){if(!U1.signal.aborted)X("opencode2 auth stopped listening for session deletion",{error:K(z)})}})();return{on(z,j){let V=l.get(z);if(!V)V=new Set,l.set(z,V);let P=j;return V.add(P),()=>{V.delete(P)}},accountFor(z,j){return e(O2(z,j))?.accountId},forgetSession:a1,get size(){return B.size},async dispose(){if(Z2)return;Z2=!0;for(let z of i.keys())m(z);U1.abort();for(let z of B.values())o(z,"the installation was disposed");B.clear();for(let z of T.keys())x(z);C.clear(),D.clear(),d.clear(),l.clear(),await Promise.all(M.values()),await Promise.all(P2.map(async(z)=>{try{await z.dispose()}catch(j){X("opencode2 auth hook did not dispose cleanly",{error:K(j)})}}))}}}import{createHash as m0}from"node:crypto";var g0=1024,l0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),e1=($)=>$$($,"user"),u0=($)=>l0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function p0($){return m0("sha256").update(JSON.stringify($)).digest("hex")}class x2{runtime;maxSessions;#$=new Map;constructor($,Z=g0){this.runtime=$;this.maxSessions=Z}advance($,Z,J=this.runtime){let G=this.#$.get($),Y=Array.isArray(Z.input)?Z.input:[],Q=Y.filter(e1),F=Y.findLastIndex(e1),W=F<0?void 0:p0(Y[F]),N=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,B,H,T;if(N)B=Q.length>0,H=W??G?.fingerprint,T=G?.userCount===void 0?void 0:G.userCount+Q.length;else{H=W,T=Q.length;let C=F>=0&&F>Y.findLastIndex(u0),D=G!==void 0&&!G.completed&&G.fingerprint===H&&G.userCount===T;B=C&&!D}let R=B||!G?{turnID:(J?.uuid??A2)(),turnStartedAt:(J?.now??Date.now)()}:{turnID:G.turnID,turnStartedAt:G.turnStartedAt};return this.#Z($,{...R,completed:!1,fingerprint:H,userCount:T}),R}completed($){let Z=this.#$.get($);if(Z)this.#Z($,{...Z,completed:!0})}get($){return this.#$.get($)}forget($){this.#$.delete($)}#Z($,Z){this.#$.delete($),this.#$.set($,Z);while(this.#$.size>this.maxSessions){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function T1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var Z$=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function c0(){let $=globalThis;return $[Z$]??=crypto.randomUUID(),$[Z$]}class D2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,J){this.runtime=$;this.store=J;this.installationID=Z??c0(),this.sessions=J?.sessions??new Map,this.frameTurns=J?.frameTurns??new x2}get($){let Z=this.runtime?.uuid??A2;if(this.store)return this.store.get($,Z);let J=this.sessions.get($);if(!J){let G=Z();J={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,J)}return J}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(p2(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var _1={version:J$,"user-agent":z$,originator:"codex_exec"};var d0=1024,i0=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,d2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),Y$=($)=>d2($)&&($.type==="message"||("role"in $))&&$.role==="user",X$=($)=>d2($)&&$.type==="configuration_update";class L1{http;#$=new Map;constructor($=new D2){this.http=$}apply($,Z,J){if(Z.kind!=="primary")return!1;let G=typeof $.model==="string"?$.model:"";if(!G$.has(G))return!1;if(i0.test(G))return!1;let Y=d2($.reasoning)?$.reasoning:void 0,Q=typeof Y?.effort==="string"?Y.effort:void 0;if(!Q)return!1;let F=this.#$.get(Z.sessionID);if(F===void 0)return this.#Z(Z.sessionID,Q),!1;if(Q===F)return!1;let W=Array.isArray($.input)?$.input:void 0;if(!W||W.length===0)return!1;let N=W.findLastIndex(Y$);if(N<0){if(J==="http")return!1;return $.reasoning={...Y,effort:F},!0}if($.reasoning={...Y,effort:F},!X$(W[N-1]))W.splice(N,0,{type:"configuration_update",reasoning:{effort:Q}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>d0){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function p2($){try{let Z=JSON.parse($);return d2(Z)?Z:void 0}catch{return}}async function j$($,Z,J,G,Y=J.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Q=await $.clone().text(),F=p2(Q);if(F)delete F.max_output_tokens;let W=new Headers($.headers),N=c2({rewriteLite:Q$,init:{body:F?JSON.stringify(F):$.body===null?void 0:Q},headers:W,metadata:Y.get(Z.sessionID),installationID:Y.installationID,runtime:Y.runtime,websocket:!1,responsesLite:G,applyEffort:(B)=>{J.apply(B,Z,"http")}});return new Request($,{headers:W,body:N.init?.body})}function B$($,Z,J,G){let Y=G.sessions.get($.sessionID),Q=G.frameTurns.get($.sessionID);if(!Y||!Q)return;let F=T1(Y,Q),W=new Headers({"content-type":"application/json"});for(let B of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let H=J.get(B);if(H!==null)W.set(B,H)}c2({init:{body:$.bodyText},headers:W,metadata:F,installationID:G.installationID,runtime:G.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let N=new URL(Z);if(N.protocol==="wss:")N.protocol="https:";if(N.protocol==="ws:")N.protocol="http:";return new Request(N,{method:"POST",headers:W,body:$.bodyText})}function a0($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let J=Z.findIndex((G,Y)=>JSON.stringify(G)!==JSON.stringify($[Y]));return J>=0&&X$(Z[J])&&Y$(Z[J+1])&&JSON.stringify(Z.slice(J+1))===JSON.stringify($.slice(J))}function V$($,Z,J){let G=p2($);if(G?.type!=="response.create")return;let Y=J.http.advanceFrame(Z.sessionID,G),Q=J.http.get(Z.sessionID);delete G.max_output_tokens;let F=c2({rewriteLite:()=>{},init:{body:JSON.stringify(G)},headers:new Headers,metadata:T1(Q,Y),installationID:J.http.installationID,runtime:J.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(N)=>{J.apply(N,Z,"ws")}}),W=p2(String(F.init?.body));if(!W)return;if(!a0(G.input,W.input)){if("input"in G)W.input=G.input;else delete W.input;return JSON.stringify(W)}return String(F.init?.body)}function n0($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function P1($,Z){let J=new URL($);if(J.origin!=="https://api.openai.com"&&J.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(J.pathname))return $;let G=new URL(`${n0(Z)}/responses`);if(G.search=J.search,J.protocol==="ws:"||J.protocol==="wss:")G.protocol=G.protocol==="https:"?"wss:":"ws:";return G.href}import{resolve as M1}from"node:path";var W$=Symbol.for("@cortexkit/openai-auth/opencode2-rate-limits/v1"),U$=globalThis,C1=U$[W$]??new Map;U$[W$]=C1;function H$($){let Z=C1.get($);if(!Z)Z=new Map,C1.set($,Z);return Z}function N$($){return H$(JSON.stringify(["pool",M1($.configPath),M1($.statePath)]))}function F$($){return H$(JSON.stringify(["vault",M1($)]))}import{resolve as K$}from"node:path";var o0=1024;class i2{accounts=new Map;limit;constructor($=o0){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let J=this.accounts.keys().next().value;if(J===void 0)break;this.accounts.delete(J)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var T$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),_$=globalThis,E1=_$[T$]??new Map;_$[T$]=E1;function O1($){let Z=JSON.stringify([K$($.configPath),K$($.statePath)]),J=E1.get(Z);if(!J)J=new i2,E1.set(Z,J);return J}var F2="openai",s0=60000,A1=1,r0="request refused: no account with a usable credential",T2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function t0($){let Z=T2($)?$.counters:void 0,J=T2(Z)?Z.resetCredits:void 0,G=T2(J)?J.value:void 0;return typeof G==="number"&&Number.isFinite(G)?G:void 0}function n2($){try{return JSON.parse($)}catch{return}}function L$($){let Z=s2($);return Z?r2(Z):void 0}var e0=new Set(["usage_limit_reached","rate_limit_exceeded"]);function x1($,Z,J){return{reason:$.window,...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function $4($,Z){let J=o2($);if(J){let Q=typeof $.status==="number"?$.status:void 0;return x1(J,Z,Q)}if($.type!=="response.failed"||!T2($.response))return;let G=$.response.failed;if(T2(G)&&typeof G.rate_limit_reached_type==="string")return{reason:G.rate_limit_reached_type};let Y=$.response.error;if(T2(Y)){let Q=typeof Y.code==="string"?Y.code:typeof Y.type==="string"?Y.type:void 0;if(Q&&e0.has(Q))return{reason:Q}}return}function Z4($,Z){let J=n2($);if(!T2(J))return;let G=typeof J.type==="string"?J.type:void 0;if(G==="codex.rate_limits")return{quota:{snapshot:E$(J),complete:!0}};let Y=$4(J,Z);if(Y)return{limit:Y};if(G===void 0||G==="error")return;return l$(G)?void 0:{outputStarted:!0}}function J4($){let Z=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:M$($),complete:C$($)}}function z4($){let Z=$.get("retry-after");if(Z===null)return;let J=Number(Z);return Number.isFinite(J)&&J>=0?J*1000:void 0}function p$($){let Z=new WeakMap,J=new WeakSet,{source:G,pins:Y}=$,Q=$.now??Date.now,F=$.log,W=$.vault,N=new L1($.codex),B=new Map,H=new Map,T=(X)=>`${X.sessionID}\x00${X.kind}\x00${X.accountId}`,R=W?.paths?.rosterPath,C=R?F$(R):new Map,D=$.sessionAccounts??new i2,d=new y$,O=(X,K,M)=>{let _=M?[]:u$(G.peek().rows,X,K,W?.identities()??new Set),h=(W?.routes()??[]).filter((A)=>A.kind==="oauth"&&A$(y2(A.quota),X,K));return[..._.map((A)=>({id:A.id,...A.identity!==void 0?{identity:A.identity}:{},quota:A.quota,row:A})),...h.map((A)=>({id:A.id,...A.identity!==void 0?{identity:A.identity}:{},quota:A.quota}))]},f=(X,K,M)=>{let _=k$(X,K,M),h=X.map((x)=>({id:x.id,kind:"oauth",...P$(x.quota)?{quota:x.quota}:{}})),A=X.flatMap((x)=>x.row?[x.row]:[]),S=new Set(X.filter((x)=>!x.row).map((x)=>x.id)),v=G.rateLimitMarks(A);for(let x of S){let I=C.get(x);if(I===void 0)continue;if(I<=M)C.delete(x);else v.set(x,I)}return{rows:h,now:M,rateLimitMarks:v,refreshBackoff:G.refreshBackoffFor(A),killswitch:_,requestPull:(x)=>S.has(x)?W?.requestReading(x):G.requestReading(x)}},B2=(X,K,M,_,h)=>{let A=I$({...X,placement:D$(K),mainId:h});if(A.kind==="block"){F?.debug("pool admission refused the request",{reason:A.block.reason});return}let S=A.order.filter((v)=>!M.has(v));if(_!==void 0&&S.includes(_))return _;return S[0]},J2=(X,K,M,_,h,A,S,v)=>{let x=new Map(K.map((q)=>[q.id,q.quota])),I={requestBytes:A1,reservePercent:(q)=>R$(M,q===S$?void 0:q),resetCredits:(q)=>t0(x.get(q))},n=R1(X),u=(q,G2)=>t2(S,{sessionId:_,requestBytes:A1,validPinnedAccountIds:X.rows.map((g)=>g.id).filter((g)=>!n.excluded.has(g)),excludeAccountIds:q,quotaCheckedAtByAccount:Object.fromEntries(X.rows.map((g)=>[g.id,n.projections.get(g.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(K.map((g)=>[g.id,g.identity])),select:(g)=>v?{accountId:v,source:"mode-fallback",quotaCheckedAt:n.projections.get(v)?.checkedAt}:f$(X,I,new Set(q),g),persist:G2},(g,m)=>S.set(g,m)),o=[...h],s=u(o,A);if(!s)return;let e=s.accountId,p=v$(X,I,e);if(p.kind==="none")return;if(p.kind==="move"){let q=u([...o,e],A);if(q)return q.accountId;return p.reason==="killswitch"?void 0:e}if(p.kind==="detour")return u([...o,e],!1)?.accountId;return e},L2={providerID:F2,dropChoice(X){let K=T(X);H.get(K)?.drop(),H.delete(K),B.delete(K)},chooseAccount:async(X)=>{let K=await W?.authority(),M=await $.storage(),_=K!==void 0&&K!=="local",h=()=>{throw new Y2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:e2})};if(_)await $.awaitVaultRoster?.();else{if(!(await G.current()).active){if(await $.slotPlaceholderWithoutMain?.())h();F?.warn("the account pool does not serve requests yet; refusing the request",{kind:X.kind});return}await G.prepareTokens(G.peek().rows,M)}let A=Q(),S=O(M,A,_),v=w$(f(S.filter((m)=>m.id!==X.rerouteFrom?.accountId),M,A));if(v)await v,A=Q(),S=O(M,A,_);let x=new Map(S.map((m)=>[m.id,m])),I=f(S,M,A),n=new Set(X.rerouteFrom?[X.rerouteFrom.accountId]:[]),u=M?.routing?.mode??"main-first",o=X.kind==="primary",s=new Set,e,p,q,G2=!1,g=(m)=>{let $2=R1(I).projections.get(m)?.checkedAt,X2=x.get(m)?.identity;return Y.reserve(X.sessionID,{accountId:m,inputBytes:A1,...$2!==void 0?{quotaCheckedAt:$2}:{},...X2!==void 0?{wireIdentity:X2}:{}})};try{for(;;){let m=new Set([...n,...s]);q=void 0,e=void 0;let $2=u!=="sticky-balanced";if(u==="sticky-balanced"){let L=new Map(Y.placementSnapshot(X.sessionID)),b=L.get(X.sessionID);if($2=b===void 0,q=J2(I,S,M,X.sessionID,m,o&&s.size===0,L),q!==void 0&&L.get(X.sessionID)!==b)e=L.get(X.sessionID)}if(q??=B2(I,u,m,o?void 0:D.activeAccount(X.sessionID),_?u==="sticky-balanced"?null:b$(W?.routes()??[]):void 0),q===void 0||s.has(q)){if(n.size>0){let L=new Map(I.rateLimitMarks);for(let b of n)L.delete(b);I={...I,rateLimitMarks:L},n.clear();continue}if(I.rateLimitMarks.size>0){I={...I,rateLimitMarks:new Map};continue}q=void 0;break}if(o&&u==="sticky-balanced")p=g(q);if(!G2){G2=!0;let L=await h$({vaultMode:_,fresh:$2,sessionId:X.sessionID,request:{modelId:X.modelID,kind:X.kind,retry:X.phase==="retry"||X.rerouteFrom!==void 0},routes:W?.routes()??[],routing:I,eligibleIds:S.filter((b)=>!m.has(b.id)).map((b)=>b.id)});if(L&&L!==q){if(p)Y.rollback(p);if(p=void 0,u==="sticky-balanced"){let b=new Map(Y.placementSnapshot(X.sessionID));q=J2(I,S,M,X.sessionID,m,o,b,L)??q,e=b.get(X.sessionID)??e}else q=L;if(o&&u==="sticky-balanced")p=g(q)}}let X2=x.get(q)?.row;if(X2){if(G.usableToken(X2)!==void 0)break;F?.debug("pool row holds no usable token; choosing again",{accountId:q})}else{if(!W)break;let L=await W.authorize(q);if(L){B.set(T({...X,accountId:q}),L);break}F?.debug("the vault refused to serve an account; choosing again",{accountId:q})}if(p)Y.rollback(p);p=void 0,s.add(q)}if(q===void 0&&!_&&S.length===0&&await $.slotPlaceholderWithoutMain?.())h();if(q===void 0&&_&&W&&(S.length===0||s.size>0)){let m=s.size>0?"vault-refused":q$(W);throw F?.warn("vault mode: no vault account can serve; refusing the request",{cause:m}),new Y2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:x$(m,W.name)})}if(q!==void 0){let m=q,$2=p,X2=e,L=()=>{if($2)Y.finish($2,X2);if(o)D.record(X.sessionID,m),$.onRoute?.(X.sessionID,m,u)};if(X.phase==="retry")H.set(T({...X,accountId:q}),{commit:L,drop:()=>{if($2)Y.rollback($2)}}),p=void 0;else L();let b=F?.info;d.served(I,q,F&&b?{info:(j2,b2)=>b.call(F,j2,b2)}:void 0)}return F?.debug("pool account chosen",{kind:X.kind,accountId:q,mode:u,...X.rerouteFrom?{rerouteFrom:X.rerouteFrom.accountId}:{}}),q}finally{if(p)Y.rollback(p)}},accountHeaders:async(X)=>{let{accountId:K}=X,M=T(X),_=H.get(M);H.delete(M);let h=()=>{_?.commit()};try{let A=()=>new Y2({kind:"no-account",providerID:F2,sessionID:X.sessionID,requestKind:X.kind,message:r0}),S=W&&await W.authority()!=="local"?void 0:G.peek().rows.find((I)=>I.id===K);if(!S&&W){let I=T(X),n=B.get(I)??await W.authorize(K);if(B.delete(I),!n)throw F?.warn("the vault refused to serve an account; refusing the request",{accountId:K}),A();return h(),{headers:{..._1,"session-id":X.sessionID,authorization:`Bearer ${n.accessToken}`,"chatgpt-account-id":n.accountIdentity??L$(n.accessToken)??null},attempt:{kind:"vault",routeId:K,receipt:n}}}let v=S?G.usableToken(S):void 0;if(!S||!v)throw F?.warn("pool row holds no usable token; refusing the request",{accountId:K}),A();let x=S.identity??L$(v);return h(),{headers:{..._1,"session-id":X.sessionID,authorization:`Bearer ${v}`,"chatgpt-account-id":x??null},attempt:{kind:"pool",token:v,credentialEpoch:S.credentialEpoch}}}finally{_?.drop()}},async rewriteRequest({request:X,sessionID:K,kind:M}){let _=$.codexEndpoint?P1(X.url,$.codexEndpoint()):X.url,h=_===X.url?X:new Request(_,X);return await j$(h,{sessionID:K,kind:M},N,$.responsesLite?.()??!1)??h},rewriteHandshakeURL:({url:X})=>$.codexEndpoint?P1(X,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:X,sessionID:K,kind:M})=>V$(X,{sessionID:K,kind:M},N),quotaFromHeaders:(X,K,M)=>{if(M.data?.kind==="vault"&&w2()&&K>=200&&K<300)Z.set(M,{status:K,headers:X});return J4(X)},async limitFromResponse({status:X,headers:K,body:M,attempt:_}){if(X<400)return;let h=n2(await M().catch(()=>"")),A=o2({...T2(h)?h:{},status:X});if(_.data?.kind==="vault"&&w2())a2(_.sessionID,_.data.receipt,{status:X,headers:K,body:h,limit:A,quota:W?.routes().find((I)=>I.id===_.accountId)?.quota,now:Q()});if(!A)return;let S=Q(),v=x1(A,S,X);if(v.retryAfterMs!==void 0)return v;let x=z4(K);return x===void 0?v:{...v,retryAfterMs:x}},inspectEvent:({data:X,transport:K,attempt:M})=>{if(M.data?.kind==="vault"&&w2()&&(g$(X)||K==="ws"&&X.includes('"response.completed"'))){let _=n2(X);if(m$(_))J.add(M);if(K==="ws"&&T2(_)&&_.type==="response.completed")a2(M.sessionID,M.data.receipt,{status:200,headers:new Headers,failed:J.has(M)})}return Z4(X,Q())},limitFromError(X){let K=n2(X.message),M=o2({...T2(K)?K:{},...X.status!==void 0?{status:X.status}:{}})??(X.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return M?x1(M,Q(),X.status):void 0},async onAttemptEnd(X,K){let M=X.data,_=M?.kind==="vault"&&w2()?Z.get(X):void 0;if(Z.delete(X),M?.kind==="vault"&&_&&!K.error&&!K.limit)a2(X.sessionID,M.receipt,{..._,failed:J.has(X)});if(M?.kind!=="vault"||K.status!==401)return;F?.warn("a vault account answered 401; reporting it to the vault",{accountId:X.accountId}),await W?.reportFailure(M.receipt,401)}},Z2=(X,K,M)=>{let _=M.data;if(_?.kind==="vault"){W?.recordSnapshot(X,K.snapshot,K.complete,_.receipt);return}if(_?.kind!=="pool")return;if(G.peek().rows.find((A)=>A.id===X)?.credentialEpoch!==_.credentialEpoch){F?.debug("quota reading dropped: the row holds another credential",{accountId:X});return}G.recordSnapshot(X,K.snapshot,_.token,K.complete)},i=(X,K,M)=>{let _=Q(),h=M.data?.kind==="vault",A=h?W?.routes().find((x)=>x.id===X)?.quota:G.peek().rows.find((x)=>x.id===X)?.quota,S=O$(y2(A),K.reason,_,s0,K.retryAfterMs!==void 0?_+K.retryAfterMs:void 0);if(!h){G.markRateLimited(X,S);return}let v=C.get(X);if(v===void 0||v<S)C.set(X,S)};return{adapter:L2,attach(X){X.on("quota",(K)=>Z2(K.accountId,K.quota,K.handle)),X.on("limit",(K)=>{i(K.accountId,K.limit,K.handle),F?.debug("pool row refused the request",{accountId:K.accountId,via:K.via,reason:K.limit.reason,outputStarted:K.outputStarted})})},forgetSession(X){Y.forget(X),D.forget(X),N.forget(X)},activeAccount:(X)=>D.activeAccount(X)}}import{resolve as o$}from"node:path";import{Buffer as G4}from"node:buffer";import{resolve as c$}from"node:path";function I2($){return G4.byteLength(JSON.stringify($))}function Q4($){return $.reduce((Z,J)=>Z+I2(J),0)}function q1($,Z){return 2+$+Math.max(0,Z-1)}function Y4($){let{head:Z,pending:J}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+q1(Z.inputBytes,Z.input.length)+1:0)+(J?20+q1(J.inputBytes,J.input.length)+10+q1(J.outputBytes,J.output.length)+(J.responseID===void 0?0:14+J.responseIDBytes)+1:0)}function d$($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class i${enabled;caps=$1;entries=new Map;bytes=0;constructor($=!1){this.enabled=$}setEnabled($){if(this.enabled=$,!$)this.entries.clear(),this.bytes=0}send($,Z){if(!this.enabled)return;let J=d$(Z);if(J?.type!=="response.create")return;if(!Array.isArray(J.input)){this.forget($);return}let G=J.previous_response_id,Y=this.entries.get($),Q=Y?.head;if(G&&G!==Q?.responseID){this.forget($);return}let{type:F,previous_response_id:W,input:N,...B}=J;this.keep($,{fields:G&&Y?Y.fields:B,fieldsBytes:G&&Y?Y.fieldsBytes:I2(B),...G&&Q?{head:Q}:{},pending:{input:N,inputBytes:Q4(N),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,J){if(!this.enabled||!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed"))return;let G=this.entries.get($);if(!G?.pending)return;let Y=d$(Z);if(!Y)return;let Q=G.pending,F=Y.response;if(Y.type==="response.created"&&typeof F?.id==="string")Q.responseID=F.id,Q.responseIDBytes=I2(F.id),this.keep($,G);else if(Y.type==="response.output_item.done"&&Y.item){if(typeof Y.response_id==="string"&&Q.responseID!==void 0&&Y.response_id!==Q.responseID)return;Q.output.push(Y.item),Q.outputBytes+=I2(Y.item),this.keep($,G)}else if(Y.type==="response.completed"&&typeof F?.id==="string"){if(F.id===G.head?.responseID||Q.responseID!==void 0&&F.id!==Q.responseID)return;let W={responseID:F.id,responseIDBytes:Q.responseID===F.id?Q.responseIDBytes:I2(F.id),input:[...G.head?.input??[],...Q.input,...Q.output],inputBytes:(G.head?.inputBytes??0)+Q.inputBytes+Q.outputBytes},N={...G,head:W,pending:void 0};if(!this.keep($,N))return;J?.({sessionID:$,responseID:W.responseID,bodyText:this.body(G.fields,W)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let J=Y4(Z);if(this.forget($),J>this.caps.maxBytes)return!1;Z.bytes=J,this.entries.set($,Z),this.bytes+=J;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let G=this.entries.keys().next().value;if(G===void 0)break;this.forget(G)}return this.entries.has($)}}var a$=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),n$=globalThis,S1=n$[a$]??new Map;n$[a$]=S1;function Z1($){let Z=JSON.stringify([c$($.configPath),c$($.statePath)]),J=S1.get(Z);if(!J)J=new i$,S1.set(Z,J);return J}var X4=5000,j4=["accept","originator","session-id","thread-id","user-agent","version","x-client-request-id","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-openai-internal-codex-responses-lite","x-opencode-parent-session-id","x-parent-session-id"],B4=["x-opencode-parent-session-id","x-parent-session-id"];function e$($){let Z=s$($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:r$($?{...$,cachekeep:Z}:$)}}var $Z=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),ZZ=globalThis,f2=ZZ[$Z]??new Map;ZZ[$Z]=f2;function V4($,Z){let J=[],G=()=>J.at(-1)?.location,Y=()=>{let N=G();if(!N)throw Error("no location holds keep-warm");return N},Q=(N,B)=>{W.remove(N),G()?.log?.debug(`cachekeep dropped target (${B})`,{sessionKey:N})},F=async(N)=>{if(N.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let B=N.accountId??"main",H=Y(),T=await H.source.accessFor(B,await H.storage());if(!T)throw Error(`pool row ${B} has no usable token`);return{token:T.token,identity:T.row.identity}},W=t$({...$1,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(N,B)=>Y().fetch(N,B),logger:{debug:(N,B)=>G()?.log?.debug(N,B),warn:(N,B)=>G()?.log?.warn(N,B)},getWindow:()=>G()?.settings().window,getSustain:()=>G()?.settings().sustain===!0,resolveLocal:F,vault:{owns:(N)=>G()?.vault.owns(N)===!0,authority:()=>Y().vault.authority(),send:async(N,B,H)=>{let T=Y();if(await T.vault.authority()!=="vault")return;return T.vault.send(N,B,H)}},activeAccount:(N)=>{if(N===void 0)throw Error("target has no session");let B=G(),H=B?.settings();if(!B||!H?.enabled){Q(N,"keep-warm is off");return}if(!H.subagents&&W.status().targets.some((R)=>R.sessionKey===N&&R.isSubagent)){Q(N,"subagent warming is off");return}let T=B.accounts.activeAccount(N);if(T===void 0){Q(N,"no account recorded for the session");return}return T},verifyCredential:({target:N,mode:B,identity:H})=>{if(N.meta.credentialMode!==B)throw Error(`a target captured in ${N.meta.credentialMode??"an unknown"} mode is not warmed with a ${B} credential`);if(H!==N.meta.chatgptAccountId)throw Q(N.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:W,settings:Z,holders:J,joinTimeoutMs:$.joinTimeoutMs??X4}}function W4($){try{let Z=JSON.parse($),J=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(J?.role!=="user")return!1;return(typeof J.content==="string"?J.content:Array.isArray(J.content)?J.content.map((Y)=>typeof Y?.text==="string"?Y.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function U4($){let Z={};for(let J of j4){let G=$.get(J);if(G)Z[J]=G}return Z}function JZ($,Z,J){let G=JSON.stringify([o$($.configPath),o$($.statePath)]),Y=f2.get(G);if(!Y)Y=V4(J,Z.settings()),f2.set(G,Y);let Q=Y,F=Z1($);F.setEnabled(Q.settings.enabled);let W={location:{...Z,settings:()=>Q.settings}};Q.holders.push(W);let N=!1,B=async(H)=>{try{let T=W.location.settings();if(N||!T.enabled)return;if(H.kind!=="primary"){if(H.kind==="generate"&&W4(await H.request.clone().text())){if(N)return;Q.manager.remove(H.sessionID)}return}let R=H.attempt.data,C=R?.kind==="pool"?"local":R?.kind==="vault"?"vault":void 0;if(!C)return;let D=H.request.headers,d=B4.some((B2)=>D.has(B2))||Z.parentOf!==void 0&&await Z.parentOf(H.sessionID)!==void 0;if(d&&!T.subagents)return;let O=await H.request.clone().text();if(N)return;let f=D.get("chatgpt-account-id")??void 0;Q.manager.track({sessionKey:H.sessionID,bodyText:O,accountId:H.attempt.accountId,isSubagent:d,meta:{replayHeaders:U4(D),...f?{chatgptAccountId:f}:{},routingSessionId:H.sessionID,url:H.request.url,credentialMode:C}})}catch(T){Z.log?.warn("cachekeep capture failed",{error:T instanceof Error?T.message:String(T)})}};return{manager:Q.manager,configure:(H)=>{Object.assign(Q.settings,H),F.setEnabled(Q.settings.enabled)},capture:B,forget:(H)=>Q.manager.remove(H),async release(){if(N)return;N=!0;let H=Q.holders.indexOf(W);if(H>=0)Q.holders.splice(H,1);if(Q.holders.length>0)return;if(f2.get(G)===Q)f2.delete(G);Q.manager.stop();let T;try{await Promise.race([Q.manager.tick().catch(()=>{}),new Promise((R)=>{T=setTimeout(R,Q.joinTimeoutMs),T.unref?.()})])}finally{clearTimeout(T)}}}}import{mkdirSync as H4}from"node:fs";import{dirname as N4,resolve as F4}from"node:path";function K4(){return zZ("opencode2")}var T4=2000;class jZ{path;options;sessions;frameTurns=new x2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Q=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=YZ($,Z.uuid??A2)}get($,Z=A2){let J=this.sessions.get($);if(!J){let G=Z();J={threadID:G,turnID:Z(),windowID:`${G}:0`},this.sessions.set($,J),this.#Z.delete($),this.#z.delete($),this.#$.add($),this.#Y()}return J}delete($){let Z=this.sessions.delete($);if(this.frameTurns.forget($),this.#$.delete($),Z)this.#Z.add($);else if(!this.#Z.has($))this.#z.add($);this.#Y()}#Y(){if(this.#J)return;this.#J=setTimeout(()=>{this.#J=void 0,this.save()},this.options.saveDelayMs??T4),this.#J.unref?.()}save(){if(clearTimeout(this.#J),this.#J=void 0,!this.#Q)this.#Q=!0,this.#G=this.#G.then(()=>{return this.#Q=!1,this.#j()});return this.#G}settled(){return this.#J?this.save():this.#G}#X(){if(this.#z.size===0)return;let $;try{$=b1(this.path)}catch{$=new Map}for(let Z of this.#z)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#z.clear()}async#j(){if(this.#X(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((G)=>{let Y=this.sessions.get(G);return Y?[[G,Y]]:[]}),Z=[...this.#Z],J=null;try{if(H4(N4(this.path),{recursive:!0}),J=await this.#B(),!J)return;let G;try{G=b1(this.path)}catch{G=new Map}await this.options.afterRead?.();let Y=!1;for(let Q of Z)if(G.delete(Q))Y=!0;for(let[Q,F]of $){if(G.get(Q)===F.threadID)continue;G.set(Q,F.threadID),Y=!0}if(Y)XZ(this.path,G)}catch{return}finally{await J?.release().catch(()=>{})}for(let[G,Y]of $)if(this.sessions.get(G)===Y)this.#$.delete(G);for(let G of Z)if(!this.sessions.has(G))this.#Z.delete(G)}#B(){return QZ(this.path,this.options.lockWaitMs??GZ)}}var BZ=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),VZ=globalThis,J1=VZ[BZ]??new Map;VZ[BZ]=J1;function _4($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.sessions instanceof Map&&typeof Z.get==="function"&&typeof Z.delete==="function"&&typeof Z.save==="function"&&typeof Z.settled==="function"&&(Z.frameTurns===void 0||Z.frameTurns!==null&&typeof Z.frameTurns.advance==="function"&&typeof Z.frameTurns.get==="function"&&typeof Z.frameTurns.completed==="function"&&typeof Z.frameTurns.forget==="function")}function WZ($=K4()){let Z=F4($),J=J1,G=J1.get(Z),Y=J1;if(G!==void 0&&!_4(G))J.compatible??=new Map,Y=J.compatible;let Q=Y.get(Z);if(!Q)Q=new jZ(Z),Y.set(Z,Q);let F=Q;return F.frameTurns??=new x2,Q}var k1=Symbol.for("cortexkit.openai-auth.v2.commands"),L4=_2("v2-command");function z1($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.closed instanceof AbortController&&typeof Z.menu?.open==="function"&&typeof Z.menu?.apply==="function"&&typeof Z.session?.get==="function"&&(Z.registration===void 0||Z.registration!==null&&typeof Z.registration.dispose==="function")}function D1($){L4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function P4(){let $=globalThis;return $[k1]??={locations:new Map},$[k1].locations??=new Map,$[k1]}async function _Z($,Z){let J=P4(),G=$.location.directory,Y={menu:Z,session:$.session,closed:new AbortController},Q=await HZ(G),F=await UZ(KZ,Q.dir,()=>TZ({...Q,drain:FZ,apply:(T)=>{let R=J.locations.get(G);if(!z1(R))throw Error("The OpenAI menu location was closed");return R.menu.apply(T)}})),W=J.locations.get(G);if(J.locations.set(G,Y),z1(W))W.closed.abort(),await W.registration?.dispose();let N={name:"openai",description:"OpenAI account menu",async execute(T){let R=[...J.locations.values()].find(z1)?.session;if(!R)return D1("no live location");let C=await R.get({sessionID:T.sessionID}),D=J.locations.get(C.location.directory);if(!z1(D))return D1("location closed");let d=await NZ(T.sessionID,D.closed.signal);if(!d||J.locations.get(C.location.directory)!==D){if(!d&&!D.closed.signal.aborted)w1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},T.sessionID);return D1(D.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let O=await D.menu.open(T.sessionID);w1(O,T.sessionID)}};J.command??=N,J.command.execute=N.execute;let B=J.command;try{Y.registration=await $.command.transform((T)=>{T.add(B)})}catch(T){if(Y.closed.abort(),J.locations.get(G)===Y)J.locations.delete(G);throw await F.release(),T}let H=!1;return async()=>{if(H)return;if(H=!0,Y.closed.abort(),J.locations.get(G)===Y)J.locations.delete(G);await F.release(),await Y.registration?.dispose()}}var M4="openai-auth-pool-browser",C4="openai-auth-pool-headless",E4="openai-auth-vault",O4="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Run /openai → Vault → Connect and approve the request before trying again.";async function v2($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function OZ($){return{method:{id:E4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await LZ($.paths,$.name)!=="vault")throw Error(O4)}}}function AZ($){let Z=(J,G,Y)=>({method:{id:J,type:"oauth",label:G},async authorize(){if($.vault)await v2($.vault);let Q=await $.beginLogin({version:$.version,headless:Y});return{url:Q.url,instructions:Q.instructions,mode:"auto",callback:Q.completion}}});return[Z(M4,"ChatGPT (openai-auth pool, browser)",!1),Z(C4,"ChatGPT (openai-auth pool, headless)",!0)]}function y1($){let Z=(J)=>typeof J==="string"?J:"";return k2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===CZ||PZ($)}function A4($){if($.accountId)return $.accountId;let Z=$.access?s2($.access):void 0;return Z?r2(Z):void 0}async function RZ($,Z,J,G={}){if(G.vault)await v2(G.vault);if(y1(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Y=MZ($,{rowLocks:(C)=>EZ(Z,C)}),Q=await Y.read();if(Q.status!=="ready")throw Error(`the account pool cannot be read (${Q.status}); the login was not stored`);let F={type:"oauth",refresh:J.refresh,...J.access!==void 0?{access:J.access}:{},...J.expires!==void 0?{expires:J.expires}:{}},W=A4(J);if(G.vault)await v2(G.vault);let N=W!==void 0?{identity:W}:{};if(G.origin==="import"){let C=Q.rows.find((D)=>W!==void 0&&D.identity===W||D.credential?.type==="oauth"&&D.credential.refresh===J.refresh);if(C)return{id:C.id,operation:"kept"}}let B=Q.rows.filter((C)=>C.type==="oauth"&&!C.invalid),H=W?B.find((C)=>C.identity===W):void 0,T=Q.rows.find((C)=>C.id===G1);if(H)return{id:(await Y.replace(H.id,F,N)).id,operation:"replaced"};if(!T){let C=await Y.add({id:G1,credential:F,...N,...J.label!==void 0?{label:J.label}:{}});return{id:C.id,operation:C.outcome==="added-disabled"?"added-disabled":"added"}}if(!T.invalid&&!T.credential)return{id:(await Y.replace(G1,F,N)).id,operation:"replaced"};let R=await Y.add({id:J.id,credential:F,...N,...J.label!==void 0?{label:J.label}:{}});return{id:R.id,operation:R.outcome==="added-disabled"?"added-disabled":R.outcome==="rotated"?"replaced":"added"}}function R4($){let Z=$.itemId!==void 0;switch($.sectionId){case"accounts":return Z?["enable","disable","remove","move"].includes($.actionId):$.actionId==="add";case"routing":return!Z&&["order","mode"].includes($.actionId);case"quota":return $.actionId==="check";case"limits":return Z?$.actionId==="floors":$.actionId==="killswitch";case"session":return!Z&&$.actionId==="clear-pin";case"vault":return Z?["enable","disable"].includes($.actionId):["connect","disconnect"].includes($.actionId);case"diagnostics":return!Z&&["logging","dump"].includes($.actionId);case"cache":return!Z&&["enabled","subagents","sustain","window"].includes($.actionId);case"reset":return Z&&["preview","spend","retry"].includes($.actionId);default:return!1}}function SZ($){let Z={...$,allowAction:R4,unavailableSections:[]};return{open:(J)=>xZ(Z,J),apply:(J)=>{let G=J!==null&&typeof J==="object"?J:{},Y=G.values&&typeof G.values==="object"&&!Array.isArray(G.values)?Object.fromEntries(Object.entries(G.values).filter(([,Q])=>Q===null||["string","number","boolean"].includes(typeof Q))):void 0;return qZ(Z,{command:"openai",sectionId:typeof G.sectionId==="string"?G.sectionId:"",actionId:typeof G.actionId==="string"?G.actionId:"",...Y?{values:Y}:{},...G.confirmed===!0?{confirmed:!0}:{},...typeof G.itemId==="string"?{itemId:G.itemId}:{},...typeof G.sessionId==="string"?{sessionId:G.sessionId}:{}})}}}function x4($,Z){if(!bZ($.modelID??$.id)){$.enabled=!1;return}let J=kZ($.id);if(J)$.limit={...J};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((G)=>[G.id,G])).values()]}function wZ($){return $.model.transform((Z)=>{let J=Z.list(F2);for(let G of J){let Y=DZ(String(G.id)),Q=Y?J.find((F)=>String(F.id)===Y):void 0;Z.update(F2,String(G.id),(F)=>x4(F,Q?.variants?.map((W)=>({...W,id:String(W.id)}))))}})}class I1{log;pending=new Map;requests=new Map;writing=new Set;constructor($){this.log=$}async safely($){let Z=(async()=>{try{await $()}catch{this.log.warn("request dump failed")}})();this.writing.add(Z);try{await Z}finally{this.writing.delete(Z)}}async captureHttp($,Z){if(!yZ())return;await this.safely(async()=>{let J={sessionID:Z.sessionID,accountId:Z.accountId,transport:"http",phase:"http",url:$.url,method:$.method,headers:new Headers($.headers),bodyText:await $.clone().text()};if(this.pending.set($,{attemptId:Z.attemptId,input:J}),this.requests.set(Z.attemptId,$),this.pending.size>512){let G=this.pending.keys().next().value;if(G)this.take(G)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let J=this.take($);if(J)await this.safely(()=>Q1({...J,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let J=this.requests.get($.attemptId),G=J&&this.take(J);if(!G)return;let{reason:Y,message:Q}=Z.error,F=Q?`${Y}: ${Q}`:Y;await this.safely(()=>Q1({...G,error:Y1(F,J?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>Q1({sessionID:Z.sessionID,accountId:Z.accountId,transport:"websocket",phase:"observed",bodyText:$}))}clear(){this.pending.clear(),this.requests.clear()}async settle(){await Promise.all(this.writing)}}class f1{counts=new Map;record($,Z){let J=Z.resetCreditsApplicable;this.counts.set($.id,{credentialEpoch:$.credentialEpoch,identity:$.identity,applicable:typeof J==="number"&&Number.isFinite(J)?J:void 0})}applicable($){let Z=this.counts.get($.id);if(!Z||Z.credentialEpoch!==$.credentialEpoch||Z.identity!==$.identity)return;return Z.applicable}}function mZ($){return async(Z)=>{let J=Z.credential;if(J.type!=="oauth"||!J.access)throw Error("the row holds no access token to poll with");let G=await IZ({accessToken:J.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,G),fZ(G,$.now(),!0)}}function gZ($){let{source:Z,counts:J,now:G}=$,Y=async(B)=>{let H=await Z.rowAccess(B,await $.storage());if(!H?.row)throw new vZ("unknown_account",`${B==="main"?"Main":"Fallback"} account ${B} was not found.`);return hZ(B,H)},Q=async(B)=>{if($.authority&&await $.authority()!=="local")return{account:B,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[H]=await Z.pollRows(await $.storage(),{ids:[B]});if(!H)return{account:B,ok:!1,error:"targeted quota refresh returned no result"};return{account:H.id,ok:H.ok,...H.error!==void 0?{error:H.error}:{}}},F=(B)=>Z.peek().rows.find((H)=>H.id===B),W=(B)=>{let H=F(B);if(!H)return null;let T=y2(H.quota)??{},R=J.applicable(H),C=Math.max(0,...[T.primary?.checkedAt,T.secondary?.checkedAt].filter((D)=>typeof D==="number"));return{quota:{...T,...R!==void 0?{resetCreditsApplicable:R}:{}},checkedAt:C,refreshAfter:C,...H.identity!==void 0?{accountId:H.identity}:{}}};return{resolveResetTarget:Y,refreshResetTargetQuota:Q,quotaManager:{isRateLimited:(B)=>{let H=F(B);if(!H)return!1;let T=Z.rateLimitMarks([H]).get(H.id);return T!==void 0&&T>G()},getMain:()=>W("main"),getFallback:(B)=>W(B)}}}import{resolve as lZ}from"node:path";var q4=1024;class v1{pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=q4){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.reservations.delete($),this.pins.delete($);for(let Z of this.listeners)Z($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}snapshot(){return new Map(this.pins)}placementSnapshot($){let Z=new Map(this.pins);for(let J of this.reservations.values())if(J.sessionId!==$)Z.set(J.sessionId,J.pin);return Z}reserve($,Z){let J={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,J),J}rollback($){if(this.reservations.get($.sessionId)===$)this.reservations.delete($.sessionId)}finish($,Z){if(this.reservations.get($.sessionId)!==$)return;if(this.rollback($),Z&&this.pins.get($.sessionId)===$.previous)this.set($.sessionId,Z)}get size(){return this.pins.size}set($,Z){this.reservations.delete($),this.pins.delete($),this.pins.set($,Z);for(let J of this.listeners)J($,Z);while(this.pins.size>this.limit){let J=this.pins.keys().next().value;if(J===void 0)break;this.forget(J)}}place($){return t2(this.placementSnapshot($.sessionId),$,(Z,J)=>this.set(Z,J))}}var uZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),pZ=globalThis,X1=pZ[uZ]??new Map;pZ[uZ]=X1;function S4($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.get==="function"&&typeof Z.forget==="function"&&typeof Z.subscribe==="function"&&typeof Z.snapshot==="function"&&typeof Z.place==="function"&&typeof Z.placementSnapshot==="function"&&typeof Z.reserve==="function"&&typeof Z.rollback==="function"&&typeof Z.finish==="function"}function cZ($){let Z=JSON.stringify([lZ($.configPath),lZ($.statePath)]),J=X1,G=X1.get(Z);if(G!==void 0&&!S4(G)){let Q=X1;Q.compatibleV1??=new Map,J=Q.compatibleV1}let Y=J.get(Z);if(!Y)Y=new v1,J.set(Z,Y);return Y}import{statSync as b4}from"node:fs";import{resolve as k4}from"node:path";function eZ($){return $.map((Z)=>{try{let J=b4(Z);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}function h1($){return eZ([$.vault.paths.tokenPath,$.vault.paths.statePath])}function dZ($){return eZ([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+h1($)}class $0{file;observationIntervalMs;producers=new Set;subscriptions=new Map;observations=new Map;protocol=J0;chain=Promise.resolve();timer;constructor($,Z){this.file=$;this.observationIntervalMs=Z}add($){this.producers.add($),this.observations.set($,{stamp:dZ($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),J=this.subscriptions.get($.pins);if(!J){let G=new Set;J={producers:G,stop:$.pins.subscribe((Y,Q)=>{let F=G.values().next().value;if(F)this.publish(F,{sessionId:Y,pin:Q,accountId:Q?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,J)}return J.producers.add($),this.timer??=setInterval(()=>{for(let G of this.producers){let Y={stamp:dZ(G),roster:G.vault.snapshot()},Q=this.observations.get(G);if(Y.stamp!==Q?.stamp||Y.roster!==Q?.roster)this.observations.set(G,Y),this.publish(G)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),J.producers.delete($),!J.producers.size)J.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;await($.write??Z0)(this.file,$,Z,()=>this.producers.has($))}).catch(()=>{_2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var Z0=async($,Z,J,G)=>{let Q=await Z.vault.authority()!=="local",F=h1(Z),W=()=>G()&&Z.vault.enrolled()===Q&&h1(Z)===F,N=await(Q?m2(Z.paths):q2(Z.paths)),B=Q?rZ(Z.vault.snapshot()?.rows,new Set(Z.vault.routes().map((R)=>R.id)),N,Date.now()):tZ((await Z.source.sidebarView()).rows,N,Date.now()),H={canWrite:W,vaultMode:Q};if(await aZ(B,$,H),!W()||!J)return;let T=B.vaultAccounts??B.fallbacks;if(J.accountId===void 0){await oZ(J.sessionId,T,$,H);return}if(J.pin){let R=Date.now();await sZ({sessionId:J.sessionId,assignment:{accountId:J.pin.accountId,wireAccountId:J.pin.wireIdentity,inputBytes:J.pin.inputBytes??0,quotaCheckedAt:J.pin.quotaCheckedAt,assignedAt:R,lastSeenAt:R},validPinnedAccountIds:[...Q?[]:["main"],...T.filter((C)=>C.enabled).map((C)=>C.id)]},$,H)}await nZ({sessionId:J.sessionId,activeId:J.accountId,route:J.route??B.route,updatedAt:Date.now()},T,$,H)},J0=2,z0=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),G0=globalThis,h2=G0[z0]??new Map;G0[z0]=h2;function Q0($,Z=iZ(),J=2000){let G=k4(Z),Y=h2.get(G);if(Y?.protocol!==J0)Y=new $0(G,J),h2.set(G,Y);let Q=Y;$={...$,write:$.write??Z0};let F=Q.add($),W=!1;for(let[N,B]of $.pins.snapshot())Q.publish($,{sessionId:N,pin:B,accountId:B.accountId,route:"sticky-balanced"});return{publish:()=>Q.publish($),route:(N,B,H)=>{Q.publish($,{sessionId:N,accountId:B,route:H})},async release(){if(W)return;if(W=!0,F(),await Q.settled(),Q.empty&&h2.get(G)===Q)h2.delete(G)}}}var V1="cortexkit-openai-auth",y4=5000;async function Y0($,Z,J,G=new D2,Y,Q,F){let W=new I1(J),N=new D4,B=new Map,H=new Map,T=(O)=>{H.delete(O);for(let f of B.keys())if(f.startsWith(`${O}:`))B.delete(f)},R=(O)=>{F?.(O.sessionID),Q?.send(O.sessionID,O.frame)},D=await K1({session:{hook:(O,f,B2)=>$.session.hook(O,async(J2)=>{let w=O==="http.request"?J2:void 0,l=O==="experimental.ws.handshake"?J2:void 0,Z2=(w?w.request.headers:l?new Headers(l.headers):void 0)?.get("authorization")===`Bearer ${K2(Z.providerID)}`,i={};if(l)B.delete(`${l.sessionID}:${l.kind}`);try{await N.run(i,()=>f(J2))}catch(X){if(Z2&&!(X instanceof Y2))throw U0(X);throw X}if(w&&Z2&&i.attempt){let X=w.request.headers.get("thread-id");if(X)w.request.headers.set("session-id",X)}if(w&&Z2&&i.attempt)await W.captureHttp(w.request,i.attempt);if(w&&Z2&&i.attempt)await Y?.({sessionID:w.sessionID,kind:w.kind,request:w.request,attempt:i.attempt});if(l&&Z2&&i.attempt)l.headers["session-id"]=G.get(l.sessionID).threadID;if(O==="experimental.ws.send"){let X=J2,K=B.get(`${X.sessionID}:${X.kind}`);if(K)await W.frame(X.frame,K.attempt);if(K&&X.kind==="primary")R(X)}if(w||l){let X=w??l;if(!X)return;let M=(w?w.request.headers:new Headers(X.headers)).get("authorization")?.replace(/^Bearer /,"");if(Z2&&M)H.set(X.sessionID,M);else H.delete(X.sessionID);if(l){let _=`${l.sessionID}:${l.kind}`;if(Z2&&M&&i.attempt)B.set(_,{bearer:M,attempt:i.attempt,url:l.url,headers:new Headers(Object.entries(l.headers).filter(([h])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(h.toLowerCase())))});else B.delete(_)}if(H.size>512){let _=H.keys().next().value;if(_)H.delete(_)}if(B.size>512){let _=B.keys().next().value;if(_)B.delete(_)}}else if(O==="experimental.ws.receive"){let X=J2,K=B.get(`${X.sessionID}:${X.kind}`);if(K){if(G.frameReceived(X.sessionID,X.frame),X.kind==="primary"){let M;if(Q?.receive(X.sessionID,X.frame,(_)=>{M=_}),M)try{let _=B$(M,K.url,K.headers,G);if(_)await Y?.({sessionID:X.sessionID,kind:"primary",request:_,attempt:K.attempt})}catch(_){J.warn("cachekeep WebSocket capture failed",{error:_ instanceof Error?_.message:String(_)})}}X.frame=H0(X.frame,K.bearer)}}else if(O==="retry"){let X=J2,K=H.get(X.sessionID);if(K)Object.assign(X.error,{message:Y1(X.error.message,K)})}},B2)},event:{subscribe:(O)=>async function*(){for await(let f of $.event.subscribe(O)){if(f.type==="session.deleted")T(f.data.sessionID);yield f}}()}},{...Z,rewriteRequest:async(O)=>{let f=N.getStore();if(f)f.attempt=O.attempt;return Z.rewriteRequest?.(O)},rewriteHandshakeURL:(O)=>{let f=N.getStore();if(f)f.attempt=O.attempt;return Z.rewriteHandshakeURL?.(O)},onAttemptEnd:async(O,f)=>{await W.end(O,f),await Z.onAttemptEnd?.(O,f)},rewriteResponse:async(O)=>{await W.response(O.request,O.response.status);let f=await Z.rewriteResponse?.(O)??O.response;return N0(f,O.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(O)=>{let f=O.get("authorization");return f?.startsWith("Bearer ")?f.slice(7):void 0}},logger:{warn:(O,f)=>J.warn(O,{data:f})}}),d=D.dispose;return{...D,dispose:async()=>{H.clear(),B.clear(),await d(),await W.settle(),W.clear()}}}function l1($={}){return{id:V1,setup:(Z)=>I4(Z,$)}}async function I4($,Z={}){let g=[];try{let J=_2("opencode2");let G=_2("quota");let Y=Z.version??K0;await q0({version:Y,...Z.runtimeLayout});let Q=Z.paths??(()=>_0(F0()));let F=await m2(Q());let W=F?.logging?.level;if(W&&typeof W==="string")j0(W);let N=Z.fetch??fetch;let B=Z.now??Date.now;let H=Z.poolMigration??b0;if(!H&&!S2(Q().configPath)){J.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let L=(j2)=>{throw new Y2({kind:"no-account",providerID:F2,sessionID:j2.sessionID,requestKind:j2.kind,message:e2})},b=await Y0($,{providerID:F2,chooseAccount:L,accountHeaders:L},J);return()=>b.dispose()}let T=Z.vault?.firstRosterWaitMs??E0;let R=S0({host:"opencode",stateDir:Z.vault?.stateDir??W0(Q().statePath),reservedRouteIds:()=>w.peek().rows.map((L)=>L.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>N},Q());let C=R.vault;let D=async()=>await C.authority()==="local"?q2(Q()):m2(Q());let d=!1;let O=!1;const f=j1(g,{[Symbol.dispose](){if(!d)R.release()}},0);await C.authority();let B2=R.firstRoster;let J2=new f1;let w=new O0({paths:Q,rateLimitMarks:N$(Q()),refreshProvider:async(L)=>{let b=await V0({refreshToken:L.refresh,fetchImpl:N,now:B}),j2=B0({id_token:"",access_token:b.access,refresh_token:b.refresh});return{...b,...j2?{identity:j2}:{}}},pullQuota:mZ({fetchImpl:N,now:B,counts:J2,logger:G}),now:B,vaultIdentities:()=>C.identities(),vaultMode:()=>C.enrolled(),vaultAuthority:()=>C.authority(),vaultFirstRoster:B2,vaultFirstRosterBackgroundWaitMs:T,log:_2("pool")});if(await C.authority()==="local")await w.load();let l=Z.heartbeat===!1?void 0:await R0({version:Y,logger:_2("heartbeat")});let L2=Z.fence??(()=>T0({currentVersion:Y}));let Z2=Z.slot??k0();let i=async()=>L0(Q(),await Z2.get({path:{id:"openai"}}));let X=!1;let K=H?A0({paths:Q,slot:Z2,version:Y,fence:L2,runDeps:{vaultServes:()=>C.serves()},paused:async()=>await C.authority()!=="local",migrate:async(L)=>{let b=await P0(L);if(X=b.status==="refused",!O)await w.load();return b},adopt:async(L)=>{if(O)return{status:"retry",reason:"unsettled"};if(!await g1(B2,T))return{status:"retry",reason:"vault-roster-pending"};if(O)return{status:"retry",reason:"unsettled"};let b=await M0(L);if(!O)await w.load();return b}}):void 0;K?.start();R.start();let M=cZ(Q());let _=Q0({paths:Q(),source:w,pins:M,vault:C},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const h=j1(g,{[Symbol.dispose](){if(!d)_.release()}},0);_.publish();let A=Z.codex??new D2(void 0,void 0,WZ());let S=e$(F);let v=Z1(Q());let x=JZ(Q(),{source:w,storage:D,vault:C,accounts:O1(Q()),settings:()=>S,parentOf:async(L)=>(await $.session.get({sessionID:L}))?.parentID??void 0,fetch:N,log:_2("cachekeep")},{now:B,codexResponsesUrl:B1().codexApiEndpoint,...Z.cacheKeep});const I=j1(g,{[Symbol.dispose](){if(!d)x.release()}},0);let n=p$({codex:A,onRoute:_.route,source:w,slotPlaceholderWithoutMain:i,storage:D,pins:M,sessionAccounts:O1(Q()),vault:C,awaitVaultRoster:async()=>{await g1(C.awaitRequestRoster(),C0)},responsesLite:()=>B1().responsesLite,codexEndpoint:()=>B1().codexApiEndpoint,now:B,log:J});let u=await Y0($,n.adapter,J,A,(L)=>x.capture(L),v,(L)=>x.forget(L));n.attach(u);let o=async(L)=>{if(await v2(C),S2(Q().configPath))return;if(await K?.idle(),S2(Q().configPath))return;if(X&&!y1(L)&&(await L2()).open){await w.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let s=async(L)=>{await o(L);let b=await RZ(w.poolStore(),Q(),L,{vault:C});if(!S2(Q().configPath))await K?.requestAdoption();await w.load(),J.info("ChatGPT login stored in the account pool",b)};let e=await N1($,{integrationID:F2,methods:AZ({beginLogin:Z.beginLogin??m1,version:Y,vault:C}),onLogin:(L)=>s(L),label:"ChatGPT (openai-auth account pool)",vault:OZ(C)});let p=await wZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let q=$.command&&$.location?await _Z({session:$.session,command:$.command,location:$.location},Z.controlPlane??SZ({...gZ({source:w,storage:D,counts:J2,now:B,authority:()=>C.authority()}),fetchImpl:N,now:B,randomUUID:w4,accountStoragePath:Q().configPath,accountStatePath:Q().statePath,packageVersion:Y,layoutNotice:x0,loadAccounts:q2,store:()=>w.poolStore(),migration:async()=>{if(S2(Q().configPath))return{migrated:!0};let L=await L2();return{migrated:!1,blockers:L.open?[]:L.blockers}},beginAccountLogin:Z.beginLogin??m1,refreshAllQuota:async()=>(await w.pollRows(await q2(Q()))).map((L)=>({...L,account:L.id})),getStickyRouting:async(L)=>M.get(L),cacheKeepManager:x.manager,setCacheKeepEnabled:(L)=>x.configure({enabled:L}),setCacheKeepSubagents:(L)=>x.configure({subagents:L}),setCacheKeepSustain:(L)=>x.configure({sustain:L}),setCacheKeepWindow:(L)=>x.configure({window:L}),afterWrite:()=>w.load(),refreshSidebar:()=>_.publish(),clearStickyRouting:async(L)=>{let b=M.get(L)!==void 0;return M.forget(L),b},vault:C})):void 0;let G2=new AbortController;(async()=>{try{for await(let L of $.event.subscribe({signal:G2.signal}))if(L.type==="session.deleted")n.forgetSession(L.data.sessionID),x.forget(L.data.sessionID),v.forget(L.data.sessionID)}catch(L){if(!G2.signal.aborted)J.warn("stopped listening for session deletion",{error:L instanceof Error?L.message:String(L)})}})();d=!0;return async()=>{O=!0,G2.abort();let L=x.release();await q?.(),K?.dispose(),await w.dispose(),await _.release(),await Promise.allSettled([u.dispose(),e.dispose(),p.dispose()]);let b;try{await Promise.race([Promise.all([K?.idle(),w.settled(),A.store?.settled(),L]),new Promise((j2)=>{b=setTimeout(j2,y4),b.unref?.()})])}finally{clearTimeout(b),R.release(),await l?.release()}}}catch(m){var $2=m,X2=1}finally{X0(g,$2,X2)}}var f4=l1(),V7={id:V1,setup:f4.setup,server:D0.server};export{V7 as default,l1 as createOpenAIAuthPlugin,V1 as OPENAI_AUTH_PLUGIN_ID};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-openai-auth",
3
- "version": "1.9.2",
3
+ "version": "1.9.4",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- import{b as a}from"./index-96971sba.js";import"./index-2f9w48sc.js";export default a();