@cortexkit/opencode-openai-auth 1.8.5 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +2 -2
- package/dist/index-0vvxnhd3.js +76 -0
- package/dist/{index-byz2j6hz.js → index-2f9w48sc.js} +1 -1
- package/dist/{index-jh90fx7y.js → index-2sb7q9wr.js} +2 -2
- package/dist/{index-zf649dj2.js → index-7bgst9rd.js} +2 -2
- package/dist/{index-kphzmgq6.js → index-96971sba.js} +1 -1
- package/dist/{index-5wgxt362.js → index-bvswyxpt.js} +1 -1
- package/dist/{index-g5hv0tda.js → index-e32hgdk4.js} +2 -2
- package/dist/index-ececstzk.js +91 -0
- package/dist/{index-95s2mw9w.js → index-jenb51ww.js} +2 -2
- package/dist/{index-zah8t2d2.js → index-v0y4hv4r.js} +2 -2
- package/dist/{index-rmc6hwg6.js → index-vkg5pw57.js} +1 -1
- package/dist/{index-n12zjwh9.js → index-wkn4d21h.js} +2 -2
- package/dist/index-yw0wnqjq.js +63 -0
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/token-util-ybe08zph.js +1 -0
- package/dist/{token-j2jmx8k7.js → token-y2zkdr5m.js} +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.js +2 -2
- package/package.json +2 -2
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +25 -0
- package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +20 -1
- package/src/tui-compiled/raw/shared/549daf371622c304-index.tsx +262 -129
- package/src/tui-compiled/raw/shared/d0f0b6be200311af-insula.js +6 -0
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +25 -0
- package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +20 -1
- package/src/tui-compiled/runtime/shared/549daf371622c304-index.js +338 -222
- package/src/tui-compiled/runtime/shared/d0f0b6be200311af-insula.js +6 -0
- package/dist/index-8x42xzxb.js +0 -74
- package/dist/index-a7xv52hy.js +0 -63
- package/dist/index-zne9tzy9.js +0 -91
- package/dist/token-util-7n2nfbyc.js +0 -1
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-
|
|
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-yw0wnqjq.js";import"./index-0vvxnhd3.js";import"./index-v0y4hv4r.js";import{ld as a,md as b}from"./index-ececstzk.js";import"./index-wkn4d21h.js";import"./index-e32hgdk4.js";import"./index-2sb7q9wr.js";import"./index-7bgst9rd.js";import"./index-jenb51ww.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};
|
package/dist/rpc/port-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Xe as b,Ye as c}from"../index-e32hgdk4.js";import{af as a}from"../index-2sb7q9wr.js";import"../index-jenb51ww.js";import"../index-bvswyxpt.js";import"../index-2f9w48sc.js";export{b as writePortFile,c as isOpenaiRpcStateDir,a as discoverPortFile};
|
package/dist/rpc/protocol.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{of as b}from"../index-7bgst9rd.js";import"../index-jenb51ww.js";import"../index-2f9w48sc.js";export{b as isNotifyPayload};
|
package/dist/rpc/rpc-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{bf as F,cf as f}from"../index-2sb7q9wr.js";import"../index-jenb51ww.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};
|
package/dist/rpc/rpc-dir.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
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};
|
package/dist/sidebar-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$b as
|
|
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-v0y4hv4r.js";import"./index-ececstzk.js";import"./index-wkn4d21h.js";import"./index-7bgst9rd.js";import"./index-jenb51ww.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as a}from"./index-96971sba.js";import"./index-2f9w48sc.js";export default a();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as U,b as V}from"./index-
|
|
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();
|
package/dist/tui-preferences.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ie as h,Pe as u,Qe as P}from"./index-wkn4d21h.js";import{qf as M,rf as R,wf as S}from"./index-jenb51ww.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.
|
|
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
|
|
1
|
+
import{c as S0}from"../index-vkg5pw57.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-yw0wnqjq.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-0vvxnhd3.js";import{ac as iZ,pc as aZ,qc as nZ,sc as oZ,wc as sZ}from"../index-v0y4hv4r.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-ececstzk.js";import"../index-wkn4d21h.js";import{Ve as WZ,We as N0}from"../index-e32hgdk4.js";import"../index-2sb7q9wr.js";import{ff as Y0,hf as L2}from"../index-7bgst9rd.js";import"../index-jenb51ww.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(`
|
|
2
2
|
`)}:{event:J,data:Z.join(`
|
|
3
|
-
`)}}function W1($,Z){let J=new TextDecoder,G="",Y=(F)=>{let N=M0(F);if(!N)return;try{$(N)}catch(H){Z(H)}},Q=()=>{for(;;){let F=/\r?\n\r?\n/.exec(G);if(!F)return;let N=G.slice(0,F.index);G=G.slice(F.index+F[0].length),Y(N)}};return new TransformStream({transform(F,N){N.enqueue(F),G+=J.decode(F,{stream:!0}),Q()},flush(){if(G+=J.decode(),Q(),G.trim()!=="")Y(G);G=""}})}var a1=512,n1=1200000,R2="x-common-auth-attempt",C2=($,Z)=>JSON.stringify([$,Z]),V2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function C0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function E0($,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 g2($,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 O0($,Z){for(let[J,G]of Object.entries(Z))if(G===null)$.delete(J);else $.set(J,G)}async function H1($,Z,J={}){let{providerID:G}=Z,Y=J.gateOnPlaceholder,Q=(z)=>Y===void 0||Y.credential(z)===N2(G),F=J.logger,N=Math.max(1,J.maxRecords??a1),H=[...J.hostCredentials??[N2(G)],...Y?[N2(G)]:[]].filter((z)=>z!==""),j=new Map,W=new WeakMap,K=new Map,x=0,M=new Set,y=new Map,d=new Map,q=(z)=>{let X=d.get(z);return X?.ownedSeen===!0&&X.foreignSeen},I=(z,X)=>{y.set(z,X);let B=d.get(z)??{ownedSeen:!1,foreignSeen:!1};if(X)B.ownedSeen=!0;else B.foreignSeen=!0;d.set(z,B)},W2=(z,X)=>{let B=Y?.refuseMisplaced,L=B?[...X].filter(([,k])=>k.includes(N2(G))):[],U=Q(X)&&(!B||L.length>0);if(B){if(L.length>0&&(L.length!==1||!U))throw I(z.sessionID,!1),new G2({kind:"placement-refused",providerID:G,sessionID:z.sessionID,requestKind:z.kind,message:B(L[0]?.[0]??"")})}return I(z.sessionID,U),U},J2=!1,b=!1,l=new Map,V=0,T=!1,E=new Map,P=(z,X)=>{try{F?.warn(z,X)}catch{}},R=(z)=>z instanceof Error?z.message:String(z),C=new Map,_=(z,X)=>{let B=(C.get(z)??Promise.resolve()).then(X),L=B.then(()=>{},()=>{});return C.set(z,L),L.then(()=>{if(C.get(z)===L)C.delete(z)}),B},m=(z,X)=>{let B=C.get(z);return B?B.then(()=>m(z,X)):X()},S=async(z)=>{try{await Z.dropChoice?.({...z.input,accountId:z.accountId})}catch(X){P("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:z.input.sessionID,error:R(X)})}},h=async(z)=>{try{await Z.dropSameAccountRetry?.({...z.input,accountId:z.accountId})}catch(X){P("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:z.input.sessionID,error:R(X)})}},p=async(z)=>{if(z.next)await S(z.next);if(z.sameAccount)await h(z.sameAccount)},g=(z)=>{let X=K.get(z);if(K.delete(z),X)_(X.sessionID,()=>p(X))},e=async(z,X)=>{let B=l.get(z);if(!B||B.size===0)return;await Promise.all([...B].map(async(L)=>{try{await L(X)}catch(U){P("opencode2 auth listener threw; the request is unaffected",{event:z,error:R(U)})}}))},o=async(z,X)=>{try{await Z.onAttemptEnd?.(z,X)}catch(B){P("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:z.attemptId,error:R(B)})}},s=(z,X)=>{if(z.ended||!z.attempt)return;let B={...z.status===void 0?{}:{status:z.status},outputStarted:z.outputStarted,...z.limit?{limit:z.limit.signal}:{},...X?{error:X}:{}};if(X)z.endError=X;z.ended=o(z.attempt,B)},v=(z,X)=>s(z,{reason:"abandoned",message:X}),w=(z)=>[...j.values()].filter((X)=>X.key===z),f=(z)=>w(z).at(-1),$2=(z)=>{if(j.delete(z.id),K.get(z.key)?.attemptId===z.id||!w(z.key).length)g(z.key)},a=(z)=>{j.set(z.id,z);while(j.size>N){let X=j.values().next().value;if(X===void 0)break;v(X,"dropped to keep the record bound"),$2(X)}},n=(z)=>z.accountId===void 0?void 0:{...z.scope,accountId:z.accountId},Q2=(z,X)=>new G2({kind:"no-account",providerID:G,sessionID:z.sessionID,requestKind:z.kind,...X===void 0?{}:{message:X}}),O2=(z)=>{E.get(z)?.clear(),E.delete(z)},P2=async(z,X)=>{let B=()=>Q2(z,`${G} ${z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(T)throw B();let L=E.get(z.sessionID);if(!L)L=new Set,E.set(z.sessionID,L);let U={};L.add(U);let k=()=>{if(!L.has(U))throw B()};try{return await X(k)}finally{if(L.delete(U),L.size===0&&E.get(z.sessionID)===L)E.delete(z.sessionID)}},v2=(z,X)=>{for(let[B,L]of X)if(H.some((U)=>L.includes(U)))throw new G2({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 ${B}; the adapter's account headers must replace it`})},A=(z)=>{for(let X of w(z))if(X.ended||!X.attempt)$2(X);else if(X.transport==="ws"||X.judged)v(X,"a newer attempt of its session and kind began"),$2(X)},u=async(z,X,B,L)=>{let U=C2(z.sessionID,z.kind),{input:k,accountId:O,sameAccountRetry:D}=await m(z.sessionID,async()=>{B();let r=K.get(U);K.delete(U);let Z2=r?.accountId??f(U)?.accountId;A(U);let t=r?.next,z2=r?.sameAccount,i=z2!==void 0&&z2.input.modelID===z.modelID&&z2.input.agent===z.agent,X2=t!==void 0&&t.input.modelID===z.modelID&&t.input.agent===z.agent,j2={...z,phase:"request",...Z2===void 0?{}:{previousAccountId:Z2},...r?.rerouteFrom?{rerouteFrom:r.rerouteFrom}:{}};if(t&&!X2)await _(z.sessionID,()=>S(t)),B();if(z2&&!i)await _(z.sessionID,()=>h(z2)),B();let B2=i?z2.accountId:X2?t.accountId:await Z.chooseAccount(j2);return{input:j2,accountId:typeof B2==="string"?B2:void 0,sameAccountRetry:i}});B();let c={},Y2;if(O!==void 0){let r=await Z.accountHeaders({...z,accountId:O});if(B(),C0(r))c=r.headers,Y2=r.attempt;else c=r}let h2=`attempt-${++V}`,M2={id:h2,key:U,scope:z,accountId:O,headers:c,attempt:O===void 0?void 0:{...z,accountId:O,attemptId:h2,transport:L,data:Y2},...L===void 0?{}:{transport:L},outputStarted:!1,sameAccountRetry:D};if(a(M2),M2.attempt)e("select",{...z,accountId:M2.attempt.accountId,hook:X,...k.previousAccountId===void 0?{}:{previousAccountId:k.previousAccountId},...k.rerouteFrom===void 0?{}:{rerouteFrom:k.rerouteFrom},handle:M2.attempt});return M2},H2=async(z,X,B,L,U)=>{let k=C2(z.sessionID,z.kind),O=L===void 0?void 0:j.get(L);if(O?.key!==k)O=void 0;if(!O){if(O=f(k),w(k).filter((c)=>c.transport===void 0&&!c.ended).length>1&&!b)b=!0,P("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:z.sessionID,kind:z.kind})}if(!O||O.transport!==void 0||O.ended)O=await u(z,X,U,B);else if(O.transport=B,O.attempt)O.attempt.transport=B;if(B==="ws"){for(let D of w(k))if(D!==O&&D.transport==="ws")v(D,"a newer attempt of its session and kind went out over WebSocket")}return O},X1=async(z,X)=>{try{return await X()}catch(B){throw s(z,{reason:"failed",message:R(B)}),B}},h1=(z,X)=>{let B=w(C2(z,X)).filter((L)=>L.transport==="ws").at(-1);return B?.attempt!==void 0&&!B.ended?B:void 0},j1=(z,X,B)=>{let L=n(z);if(!L||!z.attempt||z.limit)return;z.limit={signal:X,delivered:e("limit",{...L,via:B,limit:X,outputStarted:z.outputStarted,handle:z.attempt})}},m1=(z,X,B,L)=>{let U=n(z);if(!U||!z.attempt)return;e("quota",{...U,transport:X,...L===void 0?{}:{status:L},quota:B,handle:z.attempt})},g1=(z,X,B,L)=>{let U=z.attempt;if(!U)return;let k=Z.inspectEvent?.(L===void 0?{transport:X,data:B,attempt:U}:{transport:X,data:B,event:L,attempt:U});if(!k)return;if(k.quota!==void 0)m1(z,X,k.quota);if(k.outputStarted)z.outputStarted=!0;if(k.limit)j1(z,k.limit,X);if(k.error!==void 0)s(z,{reason:"failed",message:k.error});else if(k.done)s(z)},T0=(z,X)=>{let B=z.attempt;if(!B||X.accountId===z.accountId)return;if(B.reboundFrom??=B.accountId,B.accountId=X.accountId,"data"in X)B.data=X.data;z.accountId=X.accountId},_0=(z)=>!z.attempt||z.endError!==void 0||z.status!==void 0&&z.status>=400,l1=(z)=>{let X=[...j.values()].filter((D)=>D.scope.sessionID===z),B=X.filter((D)=>D.limit&&!D.rerouted).at(-1);if(B)return B;let L=X.filter((D)=>D.scope.kind==="primary"),U=L.length>0?L:X;if(U.length<=1)return U[0];let k=U.filter((D)=>!D.judged&&_0(D)).at(-1);if(k)return k;let O=U.filter((D)=>D.attempt&&!D.ended);if(O.length>1)return"ambiguous";return O[0]??U.at(-1)},_2={providerID:G},L2=[];L2.push(await $.session.hook("model.request",(z)=>{if(Y)return;return P2(V2(z),async(X)=>{let B=await u(V2(z),"model.request",X);if(X(),B.accountId===void 0)throw Q2(B.scope);g2(z.headers,{...B.headers,[R2]:B.id})})},_2)),L2.push(await $.session.hook("http.request",(z)=>{if(Y){if(!W2(V2(z),z.request.headers))return}return P2(V2(z),async(X)=>{let B=z.request.headers.get(R2)??void 0,L=Y?await u(V2(z),"http.request",X,"http"):await H2(V2(z),"http.request","http",B,X);X();let U=n(L),k=L.attempt;if(!U||!k)throw Q2(L.scope);await X1(L,async()=>{let O=z.request;if(Z.rewriteRequest){if(B!==void 0){let Y2=new Headers(O.headers);Y2.delete(R2),O=new Request(O,{headers:Y2})}O=await Z.rewriteRequest({...U,request:O,attempt:k})??O,X()}let D=new Headers(O.headers);D.delete(R2),O0(D,L.headers),v2(L.scope,D.entries());let c=new Request(O,{headers:D});W.set(c,L),z.request=c})})},_2)),L2.push(await $.session.hook("http.response",async(z)=>{let X=W.get(z.request);if(!X){if(Y)return;if(!J2)J2=!0,P("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:z.sessionID,kind:z.kind});return}let B=z.response;if(Z.answeredBy&&X.attempt){let D=X.attempt,c=await X1(X,async()=>Z.answeredBy?.({request:z.request,response:B,attempt:D}));if(c)T0(X,c)}let L=n(X),U=X.attempt;if(!L||!U)return;X.status=B.status;let k=Z.quotaFromHeaders?.(B.headers,B.status,U);if(k!==void 0)m1(X,"http",k,B.status);if(!B.ok&&Z.limitFromResponse){let D=await Z.limitFromResponse({status:B.status,headers:B.headers,body:()=>B.clone().text(),attempt:U});if(D)j1(X,D,"http")}if(!B.ok||!B.body)s(X);let O=B;if(B.body&&(Z.inspectEvent||Z.onAttemptEnd)){let D=B.body;if(Z.inspectEvent)D=D.pipeThrough(W1((c)=>g1(X,"http",c.data,c.event),(c)=>P("opencode2 auth event inspection threw",{error:R(c)})));O=new Response(E0(D,(c)=>s(X,c)),{status:B.status,statusText:B.statusText,headers:B.headers})}if(Z.rewriteResponse)O=await Z.rewriteResponse({...L,request:z.request,response:O,attempt:U})??O;if(O!==B)z.response=O},_2)),L2.push(await $.session.hook("experimental.ws.handshake",(z)=>{if(Y){let X=C2(z.sessionID,z.kind);if(M.delete(X),!W2(V2(z),new Headers(z.headers)))return}return P2(V2(z),async(X)=>{let B;for(let O of Object.keys(z.headers)){if(O.toLowerCase()!==R2)continue;B??=z.headers[O],delete z.headers[O]}let L=Y?await u(V2(z),"experimental.ws.handshake",X,"ws"):await H2(V2(z),"experimental.ws.handshake","ws",B,X);X();let U=n(L),k=L.attempt;if(!U||!k)throw Q2(L.scope);await X1(L,async()=>{if(!Y?.refuseMisplaced)g2(z.headers,L.headers);let O=Z.rewriteHandshakeURL?.({...U,url:z.url,attempt:k});if(O!==void 0)z.url=O;if(Y?.refuseMisplaced)g2(z.headers,L.headers);if(v2(L.scope,Object.entries(z.headers)),Y)M.add(L.key)})})},_2));let u1=Z.rewriteWebSocketFrame?.bind(Z);if(u1)L2.push(await $.session.hook("experimental.ws.send",async(z)=>{let X=V2(z);if(Y&&!M.has(C2(X.sessionID,X.kind)))return;let B=h1(X.sessionID,X.kind),L=await u1({...X,attempt:B?.attempt,frame:z.frame});if(L!==void 0)z.frame=L},_2));L2.push(await $.session.hook("experimental.ws.receive",(z)=>{if(Y&&!M.has(C2(z.sessionID,z.kind)))return;let X=h1(z.sessionID,z.kind);if(!X)return;try{g1(X,"ws",z.frame)}catch(B){P("opencode2 auth frame inspection threw",{error:R(B)})}},_2)),L2.push(await $.session.hook("retry",async(z)=>{if(Y&&y.get(z.sessionID)!==!0)return;let X=z.decision,B=()=>e("retry",{sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:X,decision:X});if(q(z.sessionID)&&!Z.retrySameAccount){await B();return}let L=l1(z.sessionID);if(!L)return;if(L==="ambiguous"){await e("retry",{sessionID:z.sessionID,attempt:z.attempt,reason:"host-decides",hostDecision:X,decision:X});return}let U=L;await P2(U.scope,async(k)=>{let O=k,D=Z.retrySameAccount?.bind(Z),c=U.attempt;if(D&&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()=>{O();let Z2=c.accountId,t=()=>j.has(U.id)&&U.accountId===Z2&&l1(z.sessionID)===U&&!U.outputStarted&&(!Y||y.get(z.sessionID)===!0);if(!t()||U.sameAccountRetry)return!1;U.sameAccountRetry=!0;let z2={...U.scope,accountId:Z2,error:z.error,attempt:z.attempt,...U.limit?{limit:U.limit.signal}:{}},i;try{i=await D(z2)}catch(B2){P("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:z.sessionID,error:R(B2)})}if(!i)return O(),!1;let X2={accountId:i.accountId,input:z2};try{O()}catch(B2){throw await h(X2),B2}if(!t()||i.accountId!==Z2)return await h(X2),!1;let j2=K.get(U.key);if(K.delete(U.key),j2)await p(j2);try{O()}catch(B2){throw await h(X2),B2}if(!t())return await h(X2),!1;return K.set(U.key,{attemptId:U.id,sessionID:U.scope.sessionID,order:++x,accountId:Z2,sameAccount:X2}),U.judged=!0,z.decision={retry:!0,delay:0},!0});if(O(),r){await e("retry",{sessionID:z.sessionID,accountId:U.accountId,kind:U.scope.kind,attempt:z.attempt,reason:"same-account",hostDecision:X,decision:z.decision,handle:U.attempt});return}}if(q(z.sessionID)){await B();return}U.judged=!0;let Y2=U.attempt;if(Y2&&!U.outputStarted){if(!U.limit){let r=Z.limitFromError?.(z.error,Y2);if(r)j1(U,r,"error")}if(U.ended)await U.ended;if(U.limit)await U.limit.delivered}O();let{decision:h2,reason:M2}=await _(U.scope.sessionID,async()=>{if(O(),q(z.sessionID))return{decision:X,reason:"host-decides"};let r=K.get(U.key);if(K.delete(U.key),r)await p(r);if(O(),q(z.sessionID))return{decision:X,reason:"host-decides"};let Z2=X,t,z2,i;if(U.accountId===void 0||!Y2)Z2={retry:!1},t="no-account";else if(U.outputStarted)Z2={retry:!1},t="output-started";else if(U.limit){let X2={accountId:U.accountId,limit:U.limit.signal},j2,B2={...U.scope,phase:"retry",previousAccountId:U.accountId,rerouteFrom:X2};try{j2=await Z.chooseAccount(B2)}catch(V1){P("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:U.scope.sessionID,error:R(V1)})}let T2=typeof j2==="object"?j2.hold:void 0,m2=typeof j2==="string"?j2:T2?U.accountId:void 0;if(m2!==void 0)i={accountId:m2,input:B2};try{O()}catch(V1){if(i)await S(i);throw V1}if(q(z.sessionID)){if(i)await S(i);return{decision:X,reason:"host-decides"}}if(T2&&Number.isFinite(T2.delayMs)&&T2.delayMs>=0)Z2={retry:!0,delay:Math.min(T2.delayMs,n1)},t="hold";else if(!T2&&m2!==void 0&&m2!==U.accountId)U.rerouted=!0,z2=X2,Z2={retry:!0,delay:0},t="reroute";else{if(T2&&i)await S(i),i=void 0;t="host-decides-last-account"}}else t="host-decides";if(z.decision=Z2,Z2.retry&&U.accountId!==void 0&&j.has(U.id))K.set(U.key,{attemptId:U.id,sessionID:U.scope.sessionID,order:++x,accountId:U.accountId,...z2===void 0?{}:{rerouteFrom:z2},...i===void 0?{}:{next:i}});else if(i)await S(i);return{decision:Z2,reason:t}});O(),await e("retry",{sessionID:z.sessionID,...U.accountId===void 0?{}:{accountId:U.accountId},kind:U.scope.kind,attempt:z.attempt,reason:M2,hostDecision:X,decision:h2,...Y2===void 0?{}:{handle:Y2}})})},_2));let p1=(z)=>{if(O2(z),y.delete(z),!d.get(z)?.foreignSeen)d.delete(z);for(let X of M)if(JSON.parse(X)[0]===z)M.delete(X);for(let X of[...j.values()]){if(X.scope.sessionID!==z)continue;v(X,"its session was forgotten"),j.delete(X.id)}for(let[X,B]of K)if(B.sessionID===z)g(X)},B1=new AbortController,c1=$.event;if(c1)(async()=>{try{for await(let z of c1.subscribe({signal:B1.signal}))if(z.type==="session.deleted")p1(z.data.sessionID);else if(z.type==="session.status"&&z.data.status.type==="idle"){let X=z.data.sessionID,B=++x;_(X,async()=>{for(let[L,U]of K)if(U.sessionID===X&&U.order<B)K.delete(L),await p(U)})}}catch(z){if(!B1.signal.aborted)P("opencode2 auth stopped listening for session deletion",{error:R(z)})}})();return{on(z,X){let B=l.get(z);if(!B)B=new Set,l.set(z,B);let L=X;return B.add(L),()=>{B.delete(L)}},accountFor(z,X){return f(C2(z,X))?.accountId},forgetSession:p1,get size(){return j.size},async dispose(){if(T)return;T=!0;for(let z of E.keys())O2(z);B1.abort();for(let z of j.values())v(z,"the installation was disposed");j.clear();for(let z of K.keys())g(z);M.clear(),y.clear(),d.clear(),l.clear(),await Promise.all(C.values()),await Promise.all(L2.map(async(z)=>{try{await z.dispose()}catch(X){P("opencode2 auth hook did not dispose cleanly",{error:R(X)})}}))}}}import{createHash as R0}from"node:crypto";var A0=1024,q0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),o1=($)=>s1($,"user"),x0=($)=>q0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function S0($){return R0("sha256").update(JSON.stringify($)).digest("hex")}class A2{runtime;maxSessions;#$=new Map;constructor($,Z=A0){this.runtime=$;this.maxSessions=Z}advance($,Z,J=this.runtime){let G=this.#$.get($),Y=Array.isArray(Z.input)?Z.input:[],Q=Y.filter(o1),F=Y.findLastIndex(o1),N=F<0?void 0:S0(Y[F]),H=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,j,W,K;if(H)j=Q.length>0,W=N??G?.fingerprint,K=G?.userCount===void 0?void 0:G.userCount+Q.length;else{W=N,K=Q.length;let M=F>=0&&F>Y.findLastIndex(x0),y=G!==void 0&&!G.completed&&G.fingerprint===W&&G.userCount===K;j=M&&!y}let x=j||!G?{turnID:(J?.uuid??E2)(),turnStartedAt:(J?.now??Date.now)()}:{turnID:G.turnID,turnStartedAt:G.turnStartedAt};return this.#Z($,{...x,completed:!1,fingerprint:W,userCount:K}),x}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 N1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var r1=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function b0(){let $=globalThis;return $[r1]??=crypto.randomUUID(),$[r1]}class b2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,J){this.runtime=$;this.store=J;this.installationID=Z??b0(),this.sessions=J?.sessions??new Map,this.frameTurns=J?.frameTurns??new A2}get($){let Z=this.runtime?.uuid??E2;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(l2(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var F1={version:t1,"user-agent":e1,originator:"codex_exec"};var k0=1024,D0=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,p2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),J$=($)=>p2($)&&($.type==="message"||("role"in $))&&$.role==="user",z$=($)=>p2($)&&$.type==="configuration_update";class K1{http;#$=new Map;constructor($=new b2){this.http=$}apply($,Z,J){if(Z.kind!=="primary")return!1;let G=typeof $.model==="string"?$.model:"";if(!$$.has(G))return!1;if(D0.test(G))return!1;let Y=p2($.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 N=Array.isArray($.input)?$.input:void 0;if(!N||N.length===0)return!1;let H=N.findLastIndex(J$);if(H<0){if(J==="http")return!1;return $.reasoning={...Y,effort:F},!0}if($.reasoning={...Y,effort:F},!z$(N[H-1]))N.splice(H,0,{type:"configuration_update",reasoning:{effort:Q}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>k0){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function l2($){try{let Z=JSON.parse($);return p2(Z)?Z:void 0}catch{return}}async function G$($,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=l2(Q);if(F)delete F.max_output_tokens;let N=new Headers($.headers),H=u2({rewriteLite:Z$,init:{body:F?JSON.stringify(F):$.body===null?void 0:Q},headers:N,metadata:Y.get(Z.sessionID),installationID:Y.installationID,runtime:Y.runtime,websocket:!1,responsesLite:G,applyEffort:(j)=>{J.apply(j,Z,"http")}});return new Request($,{headers:N,body:H.init?.body})}function Q$($,Z,J,G){let Y=G.sessions.get($.sessionID),Q=G.frameTurns.get($.sessionID);if(!Y||!Q)return;let F=N1(Y,Q),N=new Headers({"content-type":"application/json"});for(let j of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let W=J.get(j);if(W!==null)N.set(j,W)}u2({init:{body:$.bodyText},headers:N,metadata:F,installationID:G.installationID,runtime:G.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let H=new URL(Z);if(H.protocol==="wss:")H.protocol="https:";if(H.protocol==="ws:")H.protocol="http:";return new Request(H,{method:"POST",headers:N,body:$.bodyText})}function w0($,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&&z$(Z[J])&&J$(Z[J+1])&&JSON.stringify(Z.slice(J+1))===JSON.stringify($.slice(J))}function Y$($,Z,J){let G=l2($);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=u2({rewriteLite:()=>{},init:{body:JSON.stringify(G)},headers:new Headers,metadata:N1(Q,Y),installationID:J.http.installationID,runtime:J.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(H)=>{J.apply(H,Z,"ws")}}),N=l2(String(F.init?.body));if(!N)return;if(!w0(G.input,N.input)){if("input"in G)N.input=G.input;else delete N.input;return JSON.stringify(N)}return String(F.init?.body)}function y0($){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(`${y0(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 X$}from"node:path";var f0=1024;class c2{accounts=new Map;limit;constructor($=f0){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 j$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),B$=globalThis,L1=B$[j$]??new Map;B$[j$]=L1;function T1($){let Z=JSON.stringify([X$($.configPath),X$($.statePath)]),J=L1.get(Z);if(!J)J=new c2,L1.set(Z,J);return J}var U2="openai",I0=60000,_1=1,v0="request refused: no account with a usable credential",K2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function h0($){let Z=K2($)?$.counters:void 0,J=K2(Z)?Z.resetCredits:void 0,G=K2(J)?J.value:void 0;return typeof G==="number"&&Number.isFinite(G)?G:void 0}function C1($){try{return JSON.parse($)}catch{return}}function V$($){let Z=i2($);return Z?a2(Z):void 0}var m0=new Set(["usage_limit_reached","rate_limit_exceeded"]);function E1($,Z,J){return{reason:$.window,...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function g0($,Z){let J=d2($);if(J){let Q=typeof $.status==="number"?$.status:void 0;return E1(J,Z,Q)}if($.type!=="response.failed"||!K2($.response))return;let G=$.response.failed;if(K2(G)&&typeof G.rate_limit_reached_type==="string")return{reason:G.rate_limit_reached_type};let Y=$.response.error;if(K2(Y)){let Q=typeof Y.code==="string"?Y.code:typeof Y.type==="string"?Y.type:void 0;if(Q&&m0.has(Q))return{reason:Q}}return}function l0($,Z){let J=C1($);if(!K2(J))return;let G=typeof J.type==="string"?J.type:void 0;if(G==="codex.rate_limits")return{quota:{snapshot:N$(J),complete:!0}};let Y=g0(J,Z);if(Y)return{limit:Y};if(G===void 0||G==="error")return;return b$(G)?void 0:{outputStarted:!0}}function u0($){let Z=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:W$($),complete:H$($)}}function p0($){let Z=$.get("retry-after");if(Z===null)return;let J=Number(Z);return Number.isFinite(J)&&J>=0?J*1000:void 0}function k$($){let{source:Z,pins:J}=$,G=$.now??Date.now,Y=$.log,Q=$.vault,F=new K1($.codex),N=new Map,H=new Map,j=(V)=>`${V.sessionID}\x00${V.kind}\x00${V.accountId}`,W=new Map,K=$.sessionAccounts??new c2,x=new R$,M=(V,T,E)=>{let P=E?[]:S$(Z.peek().rows,V,T,Q?.identities()??new Set),R=(Q?.routes()??[]).filter((C)=>C.kind==="oauth"&&K$(k2(C.quota),V,T));return[...P.map((C)=>({id:C.id,...C.identity!==void 0?{identity:C.identity}:{},quota:C.quota,row:C})),...R.map((C)=>({id:C.id,...C.identity!==void 0?{identity:C.identity}:{},quota:C.quota}))]},y=(V,T,E)=>{let P=C$(V,T,E),R=V.map((S)=>({id:S.id,kind:"oauth",...U$(S.quota)?{quota:S.quota}:{}})),C=V.flatMap((S)=>S.row?[S.row]:[]),_=new Set(V.filter((S)=>!S.row).map((S)=>S.id)),m=Z.rateLimitMarks(C);for(let S of _){let h=W.get(S);if(h===void 0)continue;if(h<=E)W.delete(S);else m.set(S,h)}return{rows:R,now:E,rateLimitMarks:m,refreshBackoff:Z.refreshBackoffFor(C),killswitch:P,requestPull:(S)=>_.has(S)?Q?.requestReading(S):Z.requestReading(S)}},d=(V,T,E,P,R)=>{let C=A$({...V,placement:E$(T),mainId:R});if(C.kind==="block"){Y?.debug("pool admission refused the request",{reason:C.block.reason});return}let _=C.order.filter((m)=>!E.has(m));if(P!==void 0&&_.includes(P))return P;return _[0]},q=(V,T,E,P,R,C,_)=>{let m=new Map(T.map((v)=>[v.id,v.quota])),S={requestBytes:_1,reservePercent:(v)=>P$(E,v===_$?void 0:v),resetCredits:(v)=>h0(m.get(v))},h=M1(V),p=(v,w)=>n2(_,{sessionId:P,requestBytes:_1,validPinnedAccountIds:V.rows.map((f)=>f.id).filter((f)=>!h.excluded.has(f)),excludeAccountIds:v,quotaCheckedAtByAccount:Object.fromEntries(V.rows.map((f)=>[f.id,h.projections.get(f.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(T.map((f)=>[f.id,f.identity])),select:(f)=>q$(V,S,new Set(v),f),persist:w},(f,$2)=>_.set(f,$2)),g=[...R],e=p(g,C);if(!e)return;let o=e.accountId,s=x$(V,S,o);if(s.kind==="none")return;if(s.kind==="move"){let v=p([...g,o],C);if(v)return v.accountId;return s.reason==="killswitch"?void 0:o}if(s.kind==="detour")return p([...g,o],!1)?.accountId;return o},J2={providerID:U2,dropChoice(V){let T=j(V);H.get(T)?.drop(),H.delete(T),N.delete(T)},chooseAccount:async(V)=>{let T=await Q?.authority(),E=await $.storage(),P=T!==void 0&&T!=="local",R=()=>{throw new G2({kind:"no-account",providerID:U2,sessionID:V.sessionID,requestKind:V.kind,message:o2})};if(P)await $.awaitVaultRoster?.();else{if(!(await Z.current()).active){if(await $.slotPlaceholderWithoutMain?.())R();Y?.warn("the account pool does not serve requests yet; refusing the request",{kind:V.kind});return}await Z.prepareTokens(Z.peek().rows,E)}let C=G(),_=M(E,C,P),m=O$(y(_.filter((f)=>f.id!==V.rerouteFrom?.accountId),E,C));if(m)await m,C=G(),_=M(E,C,P);let S=new Map(_.map((f)=>[f.id,f])),h=y(_,E,C),p=new Set(V.rerouteFrom?[V.rerouteFrom.accountId]:[]),g=E?.routing?.mode??"main-first",e=V.kind==="primary",o=new Set,s,v,w;try{for(;;){let f=new Set([...p,...o]);if(w=void 0,s=void 0,g==="sticky-balanced"){let a=new Map(J.placementSnapshot(V.sessionID)),n=a.get(V.sessionID);if(w=q(h,_,E,V.sessionID,f,e&&o.size===0,a),w!==void 0&&a.get(V.sessionID)!==n)s=a.get(V.sessionID)}if(w??=d(h,g,f,e?void 0:K.activeAccount(V.sessionID),P?g==="sticky-balanced"?null:M$(Q?.routes()??[]):void 0),w===void 0||o.has(w)){if(p.size>0){let a=new Map(h.rateLimitMarks);for(let n of p)a.delete(n);h={...h,rateLimitMarks:a},p.clear();continue}w=void 0;break}if(e&&g==="sticky-balanced"){let a=M1(h).projections.get(w)?.checkedAt,n=S.get(w)?.identity;v=J.reserve(V.sessionID,{accountId:w,inputBytes:_1,...a!==void 0?{quotaCheckedAt:a}:{},...n!==void 0?{wireIdentity:n}:{}})}let $2=S.get(w)?.row;if($2){if(Z.usableToken($2)!==void 0)break;Y?.debug("pool row holds no usable token; choosing again",{accountId:w})}else{if(!Q)break;let a=await Q.authorize(w);if(a){N.set(j({...V,accountId:w}),a);break}Y?.debug("the vault refused to serve an account; choosing again",{accountId:w})}if(v)J.rollback(v);v=void 0,o.add(w)}if(w===void 0&&!P&&_.length===0&&await $.slotPlaceholderWithoutMain?.())R();if(w===void 0&&P&&Q&&(_.length===0||o.size>0)){let f=o.size>0?"vault-refused":T$(Q);throw Y?.warn("vault mode: no vault account can serve; refusing the request",{cause:f}),new G2({kind:"no-account",providerID:U2,sessionID:V.sessionID,requestKind:V.kind,message:L$(f,Q.name)})}if(w!==void 0){let f=w,$2=v,a=s,n=()=>{if($2)J.finish($2,a);if(e)K.record(V.sessionID,f),$.onRoute?.(V.sessionID,f,g)};if(V.phase==="retry")H.set(j({...V,accountId:w}),{commit:n,drop:()=>{if($2)J.rollback($2)}}),v=void 0;else n();let Q2=Y?.info;x.served(h,w,Y&&Q2?{info:(O2,P2)=>Q2.call(Y,O2,P2)}:void 0)}return Y?.debug("pool account chosen",{kind:V.kind,accountId:w,mode:g,...V.rerouteFrom?{rerouteFrom:V.rerouteFrom.accountId}:{}}),w}finally{if(v)J.rollback(v)}},accountHeaders:async(V)=>{let{accountId:T}=V,E=j(V),P=H.get(E);H.delete(E);let R=()=>{P?.commit()};try{let C=()=>new G2({kind:"no-account",providerID:U2,sessionID:V.sessionID,requestKind:V.kind,message:v0}),_=Q&&await Q.authority()!=="local"?void 0:Z.peek().rows.find((h)=>h.id===T);if(!_&&Q){let h=j(V),p=N.get(h)??await Q.authorize(T);if(N.delete(h),!p)throw Y?.warn("the vault refused to serve an account; refusing the request",{accountId:T}),C();return R(),{headers:{...F1,"session-id":V.sessionID,authorization:`Bearer ${p.accessToken}`,"chatgpt-account-id":p.accountIdentity??V$(p.accessToken)??null},attempt:{kind:"vault",routeId:T,receipt:p}}}let m=_?Z.usableToken(_):void 0;if(!_||!m)throw Y?.warn("pool row holds no usable token; refusing the request",{accountId:T}),C();let S=_.identity??V$(m);return R(),{headers:{...F1,"session-id":V.sessionID,authorization:`Bearer ${m}`,"chatgpt-account-id":S??null},attempt:{kind:"pool",token:m,credentialEpoch:_.credentialEpoch}}}finally{P?.drop()}},async rewriteRequest({request:V,sessionID:T,kind:E}){let P=$.codexEndpoint?P1(V.url,$.codexEndpoint()):V.url,R=P===V.url?V:new Request(P,V);return await G$(R,{sessionID:T,kind:E},F,$.responsesLite?.()??!1)??R},rewriteHandshakeURL:({url:V})=>$.codexEndpoint?P1(V,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:V,sessionID:T,kind:E})=>Y$(V,{sessionID:T,kind:E},F),quotaFromHeaders:(V)=>u0(V),async limitFromResponse({status:V,headers:T,body:E}){if(V<400)return;let P=C1(await E().catch(()=>"")),R=d2({...K2(P)?P:{},status:V});if(!R)return;let C=G(),_=E1(R,C,V);if(_.retryAfterMs!==void 0)return _;let m=p0(T);return m===void 0?_:{..._,retryAfterMs:m}},inspectEvent:({data:V})=>l0(V,G()),limitFromError(V){let T=C1(V.message),E=d2({...K2(T)?T:{},...V.status!==void 0?{status:V.status}:{}})??(V.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return E?E1(E,G(),V.status):void 0},async onAttemptEnd(V,T){let E=V.data;if(E?.kind!=="vault"||T.status!==401)return;Y?.warn("a vault account answered 401; reporting it to the vault",{accountId:V.accountId}),await Q?.reportFailure(E.receipt,401)}},b=(V,T,E)=>{let P=E.data;if(P?.kind==="vault"){Q?.recordSnapshot(V,T.snapshot,T.complete,P.receipt);return}if(P?.kind!=="pool")return;if(Z.peek().rows.find((C)=>C.id===V)?.credentialEpoch!==P.credentialEpoch){Y?.debug("quota reading dropped: the row holds another credential",{accountId:V});return}Z.recordSnapshot(V,T.snapshot,P.token,T.complete)},l=(V,T,E)=>{let P=G(),R=E.data?.kind==="vault",C=R?Q?.routes().find((S)=>S.id===V)?.quota:Z.peek().rows.find((S)=>S.id===V)?.quota,_=F$(k2(C),T.reason,P,I0,T.retryAfterMs!==void 0?P+T.retryAfterMs:void 0);if(!R){Z.markRateLimited(V,_);return}let m=W.get(V);if(m===void 0||m<_)W.set(V,_)};return{adapter:J2,attach(V){V.on("quota",(T)=>b(T.accountId,T.quota,T.handle)),V.on("limit",(T)=>{l(T.accountId,T.limit,T.handle),Y?.debug("pool row refused the request",{accountId:T.accountId,via:T.via,reason:T.limit.reason,outputStarted:T.outputStarted})})},forgetSession(V){J.forget(V),K.forget(V),F.forget(V)},activeAccount:(V)=>K.activeAccount(V)}}import{resolve as v$}from"node:path";import{Buffer as c0}from"node:buffer";import{resolve as D$}from"node:path";function D2($){return c0.byteLength(JSON.stringify($))}function d0($){return $.reduce((Z,J)=>Z+D2(J),0)}function O1($,Z){return 2+$+Math.max(0,Z-1)}function i0($){let{head:Z,pending:J}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+O1(Z.inputBytes,Z.input.length)+1:0)+(J?20+O1(J.inputBytes,J.input.length)+10+O1(J.outputBytes,J.output.length)+(J.responseID===void 0?0:14+J.responseIDBytes)+1:0)}function w$($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class y${enabled;caps=s2;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=w$(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:N,input:H,...j}=J;this.keep($,{fields:G&&Y?Y.fields:j,fieldsBytes:G&&Y?Y.fieldsBytes:D2(j),...G&&Q?{head:Q}:{},pending:{input:H,inputBytes:d0(H),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=w$(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=D2(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+=D2(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 N={responseID:F.id,responseIDBytes:Q.responseID===F.id?Q.responseIDBytes:D2(F.id),input:[...G.head?.input??[],...Q.input,...Q.output],inputBytes:(G.head?.inputBytes??0)+Q.inputBytes+Q.outputBytes},H={...G,head:N,pending:void 0};if(!this.keep($,H))return;J?.({sessionID:$,responseID:N.responseID,bodyText:this.body(G.fields,N)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let J=i0(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 f$=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),I$=globalThis,R1=I$[f$]??new Map;I$[f$]=R1;function r2($){let Z=JSON.stringify([D$($.configPath),D$($.statePath)]),J=R1.get(Z);if(!J)J=new y$,R1.set(Z,J);return J}var a0=5000,n0=["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"],o0=["x-opencode-parent-session-id","x-parent-session-id"];function l$($){let Z=h$($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:m$($?{...$,cachekeep:Z}:$)}}var u$=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),p$=globalThis,w2=p$[u$]??new Map;p$[u$]=w2;function s0($,Z){let J=[],G=()=>J.at(-1)?.location,Y=()=>{let H=G();if(!H)throw Error("no location holds keep-warm");return H},Q=(H,j)=>{N.remove(H),G()?.log?.debug(`cachekeep dropped target (${j})`,{sessionKey:H})},F=async(H)=>{if(H.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let j=H.accountId??"main",W=Y(),K=await W.source.accessFor(j,await W.storage());if(!K)throw Error(`pool row ${j} has no usable token`);return{token:K.token,identity:K.row.identity}},N=g$({...s2,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(H,j)=>Y().fetch(H,j),logger:{debug:(H,j)=>G()?.log?.debug(H,j),warn:(H,j)=>G()?.log?.warn(H,j)},getWindow:()=>G()?.settings().window,getSustain:()=>G()?.settings().sustain===!0,resolveLocal:F,vault:{owns:(H)=>G()?.vault.owns(H)===!0,authority:()=>Y().vault.authority(),send:async(H,j,W)=>{let K=Y();if(await K.vault.authority()!=="vault")return;return K.vault.send(H,j,W)}},activeAccount:(H)=>{if(H===void 0)throw Error("target has no session");let j=G(),W=j?.settings();if(!j||!W?.enabled){Q(H,"keep-warm is off");return}if(!W.subagents&&N.status().targets.some((x)=>x.sessionKey===H&&x.isSubagent)){Q(H,"subagent warming is off");return}let K=j.accounts.activeAccount(H);if(K===void 0){Q(H,"no account recorded for the session");return}return K},verifyCredential:({target:H,mode:j,identity:W})=>{if(H.meta.credentialMode!==j)throw Error(`a target captured in ${H.meta.credentialMode??"an unknown"} mode is not warmed with a ${j} credential`);if(W!==H.meta.chatgptAccountId)throw Q(H.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:N,settings:Z,holders:J,joinTimeoutMs:$.joinTimeoutMs??a0}}function r0($){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 t0($){let Z={};for(let J of n0){let G=$.get(J);if(G)Z[J]=G}return Z}function c$($,Z,J){let G=JSON.stringify([v$($.configPath),v$($.statePath)]),Y=w2.get(G);if(!Y)Y=s0(J,Z.settings()),w2.set(G,Y);let Q=Y,F=r2($);F.setEnabled(Q.settings.enabled);let N={location:{...Z,settings:()=>Q.settings}};Q.holders.push(N);let H=!1,j=async(W)=>{try{let K=N.location.settings();if(H||!K.enabled)return;if(W.kind!=="primary"){if(W.kind==="generate"&&r0(await W.request.clone().text())){if(H)return;Q.manager.remove(W.sessionID)}return}let x=W.attempt.data,M=x?.kind==="pool"?"local":x?.kind==="vault"?"vault":void 0;if(!M)return;let y=W.request.headers,d=o0.some((W2)=>y.has(W2))||Z.parentOf!==void 0&&await Z.parentOf(W.sessionID)!==void 0;if(d&&!K.subagents)return;let q=await W.request.clone().text();if(H)return;let I=y.get("chatgpt-account-id")??void 0;Q.manager.track({sessionKey:W.sessionID,bodyText:q,accountId:W.attempt.accountId,isSubagent:d,meta:{replayHeaders:t0(y),...I?{chatgptAccountId:I}:{},routingSessionId:W.sessionID,url:W.request.url,credentialMode:M}})}catch(K){Z.log?.warn("cachekeep capture failed",{error:K instanceof Error?K.message:String(K)})}};return{manager:Q.manager,configure:(W)=>{Object.assign(Q.settings,W),F.setEnabled(Q.settings.enabled)},capture:j,forget:(W)=>Q.manager.remove(W),async release(){if(H)return;H=!0;let W=Q.holders.indexOf(N);if(W>=0)Q.holders.splice(W,1);if(Q.holders.length>0)return;if(w2.get(G)===Q)w2.delete(G);Q.manager.stop();let K;try{await Promise.race([Q.manager.tick().catch(()=>{}),new Promise((x)=>{K=setTimeout(x,Q.joinTimeoutMs),K.unref?.()})])}finally{clearTimeout(K)}}}}import{mkdirSync as e0}from"node:fs";import{dirname as $4,resolve as Z4}from"node:path";function J4(){return d$("opencode2")}var z4=2000;class s${path;options;sessions;frameTurns=new A2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Q=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=n$($,Z.uuid??E2)}get($,Z=E2){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??z4),this.#J.unref?.()}save(){if(clearTimeout(this.#J),this.#J=void 0,!this.#Q)this.#Q=!0,this.#G=this.#G.then(()=>{return this.#Q=!1,this.#j()});return this.#G}settled(){return this.#J?this.save():this.#G}#X(){if(this.#z.size===0)return;let $;try{$=A1(this.path)}catch{$=new Map}for(let Z of this.#z)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#z.clear()}async#j(){if(this.#X(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((G)=>{let Y=this.sessions.get(G);return Y?[[G,Y]]:[]}),Z=[...this.#Z],J=null;try{if(e0($4(this.path),{recursive:!0}),J=await this.#B(),!J)return;let G;try{G=A1(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)o$(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 a$(this.path,this.options.lockWaitMs??i$)}}var r$=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),t$=globalThis,t2=t$[r$]??new Map;t$[r$]=t2;function G4($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.sessions instanceof Map&&typeof Z.get==="function"&&typeof Z.delete==="function"&&typeof Z.save==="function"&&typeof Z.settled==="function"&&(Z.frameTurns===void 0||Z.frameTurns!==null&&typeof Z.frameTurns.advance==="function"&&typeof Z.frameTurns.get==="function"&&typeof Z.frameTurns.completed==="function"&&typeof Z.frameTurns.forget==="function")}function e$($=J4()){let Z=Z4($),J=t2,G=t2.get(Z),Y=t2;if(G!==void 0&&!G4(G))J.compatible??=new Map,Y=J.compatible;let Q=Y.get(Z);if(!Q)Q=new s$(Z),Y.set(Z,Q);let F=Q;return F.frameTurns??=new A2,Q}var q1=Symbol.for("cortexkit.openai-auth.v2.commands"),Q4=F2("v2-command");function e2($){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 x1($){Q4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function Y4(){let $=globalThis;return $[q1]??={locations:new Map},$[q1].locations??=new Map,$[q1]}async function YZ($,Z){let J=Y4(),G=$.location.directory,Y={menu:Z,session:$.session,closed:new AbortController},Q=await ZZ(G),F=await $Z(GZ,Q.dir,()=>QZ({...Q,drain:zZ,apply:(K)=>{let x=J.locations.get(G);if(!e2(x))throw Error("The OpenAI menu location was closed");return x.menu.apply(K)}})),N=J.locations.get(G);if(J.locations.set(G,Y),e2(N))N.closed.abort(),await N.registration?.dispose();let H={name:"openai",description:"OpenAI account menu",async execute(K){let x=[...J.locations.values()].find(e2)?.session;if(!x)return x1("no live location");let M=await x.get({sessionID:K.sessionID}),y=J.locations.get(M.location.directory);if(!e2(y))return x1("location closed");let d=await JZ(K.sessionID,y.closed.signal);if(!d||J.locations.get(M.location.directory)!==y){if(!d&&!y.closed.signal.aborted)S1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},K.sessionID);return x1(y.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let q=await y.menu.open(K.sessionID);S1(q,K.sessionID)}};J.command??=H,J.command.execute=H.execute;let j=J.command;try{Y.registration=await $.command.transform((K)=>{K.add(j)})}catch(K){if(Y.closed.abort(),J.locations.get(G)===Y)J.locations.delete(G);throw await F.release(),K}let W=!1;return async()=>{if(W)return;if(W=!0,Y.closed.abort(),J.locations.get(G)===Y)J.locations.delete(G);await F.release(),await Y.registration?.dispose()}}var X4="openai-auth-pool-browser",j4="openai-auth-pool-headless",B4="openai-auth-vault",V4="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 y2($){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 WZ($){return{method:{id:B4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await XZ($.paths,$.name)!=="vault")throw Error(V4)}}}function HZ($){let Z=(J,G,Y)=>({method:{id:J,type:"oauth",label:G},async authorize(){if($.vault)await y2($.vault);let Q=await $.beginLogin({version:$.version,headless:Y});return{url:Q.url,instructions:Q.instructions,mode:"auto",callback:Q.completion}}});return[Z(X4,"ChatGPT (openai-auth pool, browser)",!1),Z(j4,"ChatGPT (openai-auth pool, headless)",!0)]}function b1($){let Z=(J)=>typeof J==="string"?J:"";return S2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===VZ||jZ($)}function U4($){if($.accountId)return $.accountId;let Z=$.access?i2($.access):void 0;return Z?a2(Z):void 0}async function NZ($,Z,J,G={}){if(G.vault)await y2(G.vault);if(b1(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Y=BZ($,{rowLocks:(M)=>UZ(Z,M)}),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}:{}},N=U4(J);if(G.vault)await y2(G.vault);let H=N!==void 0?{identity:N}:{};if(G.origin==="import"){let M=Q.rows.find((y)=>N!==void 0&&y.identity===N||y.credential?.type==="oauth"&&y.credential.refresh===J.refresh);if(M)return{id:M.id,operation:"kept"}}let j=Q.rows.filter((M)=>M.type==="oauth"&&!M.invalid),W=N?j.find((M)=>M.identity===N):void 0,K=Q.rows.find((M)=>M.id===$1);if(W)return{id:(await Y.replace(W.id,F,H)).id,operation:"replaced"};if(!K){let M=await Y.add({id:$1,credential:F,...H,...J.label!==void 0?{label:J.label}:{}});return{id:M.id,operation:M.outcome==="added-disabled"?"added-disabled":"added"}}if(!K.invalid&&!K.credential)return{id:(await Y.replace($1,F,H)).id,operation:"replaced"};let x=await Y.add({id:J.id,credential:F,...H,...J.label!==void 0?{label:J.label}:{}});return{id:x.id,operation:x.outcome==="added-disabled"?"added-disabled":x.outcome==="rotated"?"replaced":"added"}}function W4($){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 PZ($){let Z={...$,allowAction:W4,unavailableSections:[]};return{open:(J)=>FZ(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 KZ(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 H4($,Z){if(!LZ($.modelID??$.id)){$.enabled=!1;return}let J=TZ($.id);if(J)$.limit={...J};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((G)=>[G.id,G])).values()]}function MZ($){return $.model.transform((Z)=>{let J=Z.list(U2);for(let G of J){let Y=_Z(String(G.id)),Q=Y?J.find((F)=>String(F.id)===Y):void 0;Z.update(U2,String(G.id),(F)=>H4(F,Q?.variants?.map((N)=>({...N,id:String(N.id)}))))}})}class k1{log;pending=new Map;requests=new Map;writing=new Set;constructor($){this.log=$}async safely($){let Z=(async()=>{try{await $()}catch{this.log.warn("request dump failed")}})();this.writing.add(Z);try{await Z}finally{this.writing.delete(Z)}}async captureHttp($,Z){if(!CZ())return;await this.safely(async()=>{let 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(()=>Z1({...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(()=>Z1({...G,error:J1(F,J?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>Z1({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 D1{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 qZ($){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 EZ({accessToken:J.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,G),OZ(G,$.now(),!0)}}function xZ($){let{source:Z,counts:J,now:G}=$,Y=async(j)=>{let W=await Z.rowAccess(j,await $.storage());if(!W?.row)throw new RZ("unknown_account",`${j==="main"?"Main":"Fallback"} account ${j} was not found.`);return AZ(j,W)},Q=async(j)=>{if($.authority&&await $.authority()!=="local")return{account:j,ok:!1,error:"local accounts are not polled while this host is connected to the vault"};let[W]=await Z.pollRows(await $.storage(),{ids:[j]});if(!W)return{account:j,ok:!1,error:"targeted quota refresh returned no result"};return{account:W.id,ok:W.ok,...W.error!==void 0?{error:W.error}:{}}},F=(j)=>Z.peek().rows.find((W)=>W.id===j),N=(j)=>{let W=F(j);if(!W)return null;let K=k2(W.quota)??{},x=J.applicable(W),M=Math.max(0,...[K.primary?.checkedAt,K.secondary?.checkedAt].filter((y)=>typeof y==="number"));return{quota:{...K,...x!==void 0?{resetCreditsApplicable:x}:{}},checkedAt:M,refreshAfter:M,...W.identity!==void 0?{accountId:W.identity}:{}}};return{resolveResetTarget:Y,refreshResetTargetQuota:Q,quotaManager:{isRateLimited:(j)=>{let W=F(j);if(!W)return!1;let K=Z.rateLimitMarks([W]).get(W.id);return K!==void 0&&K>G()},getMain:()=>N("main"),getFallback:(j)=>N(j)}}}import{resolve as SZ}from"node:path";var N4=1024;class w1{pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=N4){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 n2(this.placementSnapshot($.sessionId),$,(Z,J)=>this.set(Z,J))}}var bZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),kZ=globalThis,z1=kZ[bZ]??new Map;kZ[bZ]=z1;function F4($){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 DZ($){let Z=JSON.stringify([SZ($.configPath),SZ($.statePath)]),J=z1,G=z1.get(Z);if(G!==void 0&&!F4(G)){let Q=z1;Q.compatibleV1??=new Map,J=Q.compatibleV1}let Y=J.get(Z);if(!Y)Y=new w1,J.set(Z,Y);return Y}import{statSync as K4}from"node:fs";import{resolve as P4}from"node:path";function lZ($){return $.map((Z)=>{try{let J=K4(Z);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}function y1($){return lZ([$.vault.paths.tokenPath,$.vault.paths.statePath])}function wZ($){return lZ([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+y1($)}class uZ{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:wZ($),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:wZ(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;let G=await $.vault.authority()!=="local",Y=y1($),Q=()=>this.producers.has($)&&$.vault.enrolled()===G&&y1($)===Y,F=await(G?I2($.paths):q2($.paths)),N=G?mZ($.vault.snapshot()?.rows,new Set($.vault.routes().map((W)=>W.id)),F,Date.now()):gZ((await $.source.sidebarView()).rows,F,Date.now()),H={canWrite:Q,vaultMode:G};if(await fZ(N,this.file,H),!Q()||!Z)return;let j=N.vaultAccounts??N.fallbacks;if(Z.accountId===void 0){await vZ(Z.sessionId,j,this.file,H);return}if(Z.pin){let W=Date.now();await hZ({sessionId:Z.sessionId,assignment:{accountId:Z.pin.accountId,wireAccountId:Z.pin.wireIdentity,inputBytes:Z.pin.inputBytes??0,quotaCheckedAt:Z.pin.quotaCheckedAt,assignedAt:W,lastSeenAt:W},validPinnedAccountIds:[...G?[]:["main"],...j.filter((K)=>K.enabled).map((K)=>K.id)]},this.file,H)}await IZ({sessionId:Z.sessionId,activeId:Z.accountId,route:Z.route??N.route,updatedAt:Date.now()},j,this.file,H)}).catch(()=>{F2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var pZ=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),cZ=globalThis,f2=cZ[pZ]??new Map;cZ[pZ]=f2;function dZ($,Z=yZ(),J=2000){let G=P4(Z),Y=f2.get(G);if(!Y)Y=new uZ(G,J),f2.set(G,Y);let Q=Y,F=Q.add($),N=!1;for(let[H,j]of $.pins.snapshot())Q.publish($,{sessionId:H,pin:j,accountId:j.accountId,route:"sticky-balanced"});return{publish:()=>Q.publish($),route:(H,j,W)=>{Q.publish($,{sessionId:H,accountId:j,route:W})},async release(){if(N)return;if(N=!0,F(),await Q.settled(),Q.empty&&f2.get(G)===Q)f2.delete(G)}}}var Y1="cortexkit-openai-auth",_4=5000;async function iZ($,Z,J,G=new b2,Y,Q,F){let N=new k1(J),H=new L4,j=new Map,W=new Map,K=(q)=>{W.delete(q);for(let I of j.keys())if(I.startsWith(`${q}:`))j.delete(I)},x=(q)=>{F?.(q.sessionID),Q?.send(q.sessionID,q.frame)},y=await H1({session:{hook:(q,I,W2)=>$.session.hook(q,async(J2)=>{let b=q==="http.request"?J2:void 0,l=q==="experimental.ws.handshake"?J2:void 0,T=(b?b.request.headers:l?new Headers(l.headers):void 0)?.get("authorization")===`Bearer ${N2(Z.providerID)}`,E={};if(l)j.delete(`${l.sessionID}:${l.kind}`);try{await H.run(E,()=>I(J2))}catch(P){if(T&&!(P instanceof G2))throw tZ(P);throw P}if(b&&T&&E.attempt){let P=b.request.headers.get("thread-id");if(P)b.request.headers.set("session-id",P)}if(b&&T&&E.attempt)await N.captureHttp(b.request,E.attempt);if(b&&T&&E.attempt)await Y?.({sessionID:b.sessionID,kind:b.kind,request:b.request,attempt:E.attempt});if(l&&T&&E.attempt)l.headers["session-id"]=G.get(l.sessionID).threadID;if(q==="experimental.ws.send"){let P=J2,R=j.get(`${P.sessionID}:${P.kind}`);if(R)await N.frame(P.frame,R.attempt);if(R&&P.kind==="primary")x(P)}if(b||l){let P=b??l;if(!P)return;let C=(b?b.request.headers:new Headers(P.headers)).get("authorization")?.replace(/^Bearer /,"");if(T&&C)W.set(P.sessionID,C);else W.delete(P.sessionID);if(l){let _=`${l.sessionID}:${l.kind}`;if(T&&C&&E.attempt)j.set(_,{bearer:C,attempt:E.attempt,url:l.url,headers:new Headers(Object.entries(l.headers).filter(([m])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(m.toLowerCase())))});else j.delete(_)}if(W.size>512){let _=W.keys().next().value;if(_)W.delete(_)}if(j.size>512){let _=j.keys().next().value;if(_)j.delete(_)}}else if(q==="experimental.ws.receive"){let P=J2,R=j.get(`${P.sessionID}:${P.kind}`);if(R){if(G.frameReceived(P.sessionID,P.frame),P.kind==="primary"){let C;if(Q?.receive(P.sessionID,P.frame,(_)=>{C=_}),C)try{let _=Q$(C,R.url,R.headers,G);if(_)await Y?.({sessionID:P.sessionID,kind:"primary",request:_,attempt:R.attempt})}catch(_){J.warn("cachekeep WebSocket capture failed",{error:_ instanceof Error?_.message:String(_)})}}P.frame=eZ(P.frame,R.bearer)}}else if(q==="retry"){let P=J2,R=W.get(P.sessionID);if(R)Object.assign(P.error,{message:J1(P.error.message,R)})}},W2)},event:{subscribe:(q)=>async function*(){for await(let I of $.event.subscribe(q)){if(I.type==="session.deleted")K(I.data.sessionID);yield I}}()}},{...Z,rewriteRequest:async(q)=>{let I=H.getStore();if(I)I.attempt=q.attempt;return Z.rewriteRequest?.(q)},rewriteHandshakeURL:(q)=>{let I=H.getStore();if(I)I.attempt=q.attempt;return Z.rewriteHandshakeURL?.(q)},onAttemptEnd:async(q,I)=>{await N.end(q,I),await Z.onAttemptEnd?.(q,I)},rewriteResponse:async(q)=>{await N.response(q.request,q.response.status);let I=await Z.rewriteResponse?.(q)??q.response;return $0(I,q.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(q)=>{let I=q.get("authorization");return I?.startsWith("Bearer ")?I.slice(7):void 0}},logger:{warn:(q,I)=>J.warn(q,{data:I})}}),d=y.dispose;return{...y,dispose:async()=>{W.clear(),j.clear(),await d(),await N.settle(),N.clear()}}}function v1($={}){return{id:Y1,setup:(Z)=>M4(Z,$)}}async function M4($,Z={}){let Q2=[];try{let J=F2("opencode2");let G=F2("quota");let Y=Z.version??J0;await N0({version:Y,...Z.runtimeLayout});let Q=Z.paths??(()=>G0(Z0()));let F=await I2(Q());let N=F?.logging?.level;if(N&&typeof N==="string")nZ(N);let H=Z.fetch??fetch;let j=Z.now??Date.now;let W=Z.poolMigration??K0;if(!W&&!x2(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 A=(H2)=>{throw new G2({kind:"no-account",providerID:U2,sessionID:H2.sessionID,requestKind:H2.kind,message:o2})},u=await iZ($,{providerID:U2,chooseAccount:A,accountHeaders:A},J);return()=>u.dispose()}let K=Z.vault?.firstRosterWaitMs??B0;let x=F0({host:"opencode",stateDir:Z.vault?.stateDir??rZ(Q().statePath),reservedRouteIds:()=>b.peek().rows.map((A)=>A.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>H},Q());let M=x.vault;let y=async()=>await M.authority()==="local"?q2(Q()):I2(Q());let d=!1;let q=!1;const I=G1(Q2,{[Symbol.dispose](){if(!d)x.release()}},0);await M.authority();let W2=x.firstRoster;let J2=new D1;let b=new V0({paths:Q,refreshProvider:async(A)=>{let u=await sZ({refreshToken:A.refresh,fetchImpl:H,now:j}),H2=oZ({id_token:"",access_token:u.access,refresh_token:u.refresh});return{...u,...H2?{identity:H2}:{}}},pullQuota:qZ({fetchImpl:H,now:j,counts:J2,logger:G}),now:j,vaultIdentities:()=>M.identities(),vaultMode:()=>M.enrolled(),vaultAuthority:()=>M.authority(),vaultFirstRoster:W2,vaultFirstRosterBackgroundWaitMs:K,log:F2("pool")});if(await M.authority()==="local")await b.load();let l=Z.heartbeat===!1?void 0:await W0({version:Y,logger:F2("heartbeat")});let V=Z.fence??(()=>z0({currentVersion:Y}));let T=Z.slot??P0();let E=async()=>Q0(Q(),await T.get({path:{id:"openai"}}));let P=!1;let R=W?U0({paths:Q,slot:T,version:Y,fence:V,runDeps:{vaultServes:()=>M.serves()},paused:async()=>await M.authority()!=="local",migrate:async(A)=>{let u=await Y0(A);if(P=u.status==="refused",!q)await b.load();return u},adopt:async(A)=>{if(q)return{status:"retry",reason:"unsettled"};if(!await I1(W2,K))return{status:"retry",reason:"vault-roster-pending"};if(q)return{status:"retry",reason:"unsettled"};let u=await X0(A);if(!q)await b.load();return u}}):void 0;R?.start();x.start();let C=DZ(Q());let _=dZ({paths:Q(),source:b,pins:C,vault:M},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const m=G1(Q2,{[Symbol.dispose](){if(!d)_.release()}},0);_.publish();let S=Z.codex??new b2(void 0,void 0,e$());let h=l$(F);let p=r2(Q());let g=c$(Q(),{source:b,storage:y,vault:M,accounts:T1(Q()),settings:()=>h,parentOf:async(A)=>(await $.session.get({sessionID:A}))?.parentID??void 0,fetch:H,log:F2("cachekeep")},{now:j,codexResponsesUrl:Q1().codexApiEndpoint,...Z.cacheKeep});const e=G1(Q2,{[Symbol.dispose](){if(!d)g.release()}},0);let o=k$({codex:S,onRoute:_.route,source:b,slotPlaceholderWithoutMain:E,storage:y,pins:C,sessionAccounts:T1(Q()),vault:M,awaitVaultRoster:async()=>{await I1(M.awaitRequestRoster(),j0)},responsesLite:()=>Q1().responsesLite,codexEndpoint:()=>Q1().codexApiEndpoint,now:j,log:J});let s=await iZ($,o.adapter,J,S,(A)=>g.capture(A),p,(A)=>g.forget(A));o.attach(s);let v=async(A)=>{if(await y2(M),x2(Q().configPath))return;if(await R?.idle(),x2(Q().configPath))return;if(P&&!b1(A)&&(await V()).open){await b.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 w=async(A)=>{await v(A);let u=await NZ(b.poolStore(),Q(),A,{vault:M});if(!x2(Q().configPath))await R?.requestAdoption();await b.load(),J.info("ChatGPT login stored in the account pool",u)};let f=await U1($,{integrationID:U2,methods:HZ({beginLogin:Z.beginLogin??f1,version:Y,vault:M}),onLogin:(A)=>w(A),label:"ChatGPT (openai-auth account pool)",vault:WZ(M)});let $2=await MZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let a=$.command&&$.location?await YZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??PZ({...xZ({source:b,storage:y,counts:J2,now:j,authority:()=>M.authority()}),fetchImpl:H,now:j,randomUUID:T4,accountStoragePath:Q().configPath,accountStatePath:Q().statePath,packageVersion:Y,layoutNotice:H0,loadAccounts:q2,store:()=>b.poolStore(),migration:async()=>{if(x2(Q().configPath))return{migrated:!0};let A=await V();return{migrated:!1,blockers:A.open?[]:A.blockers}},beginAccountLogin:Z.beginLogin??f1,refreshAllQuota:async()=>(await b.pollRows(await q2(Q()))).map((A)=>({...A,account:A.id})),getStickyRouting:async(A)=>C.get(A),cacheKeepManager:g.manager,setCacheKeepEnabled:(A)=>g.configure({enabled:A}),setCacheKeepSubagents:(A)=>g.configure({subagents:A}),setCacheKeepSustain:(A)=>g.configure({sustain:A}),setCacheKeepWindow:(A)=>g.configure({window:A}),afterWrite:()=>b.load(),refreshSidebar:()=>_.publish(),clearStickyRouting:async(A)=>{let u=C.get(A)!==void 0;return C.forget(A),u},vault:M})):void 0;let n=new AbortController;(async()=>{try{for await(let A of $.event.subscribe({signal:n.signal}))if(A.type==="session.deleted")o.forgetSession(A.data.sessionID),g.forget(A.data.sessionID),p.forget(A.data.sessionID)}catch(A){if(!n.signal.aborted)J.warn("stopped listening for session deletion",{error:A instanceof Error?A.message:String(A)})}})();d=!0;return async()=>{q=!0,n.abort();let A=g.release();await a?.(),R?.dispose(),await b.dispose(),await _.release(),await Promise.allSettled([s.dispose(),f.dispose(),$2.dispose()]);let u;try{await Promise.race([Promise.all([R?.idle(),b.settled(),S.store?.settled(),A]),new Promise((H2)=>{u=setTimeout(H2,_4),u.unref?.()})])}finally{clearTimeout(u),x.release(),await l?.release()}}}catch(O2){var P2=O2,v2=1}finally{aZ(Q2,P2,v2)}}var C4=v1(),i6={id:Y1,setup:C4.setup,server:L0.server};export{i6 as default,v1 as createOpenAIAuthPlugin,Y1 as OPENAI_AUTH_PLUGIN_ID};
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-openai-auth",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.9.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -66,7 +66,7 @@
|
|
|
66
66
|
},
|
|
67
67
|
"devDependencies": {
|
|
68
68
|
"@ai-sdk/openai": "3.0.88",
|
|
69
|
-
"@cortexkit/common-auth": "^0.
|
|
69
|
+
"@cortexkit/common-auth": "^0.32.1",
|
|
70
70
|
"@cortexkit/openai-auth-core": "workspace:*",
|
|
71
71
|
"@opencode/plugin": "2.2.0"
|
|
72
72
|
},
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { channel } from "node:diagnostics_channel";
|
|
1
2
|
import { ClaustrumCredentialError, } from "@cortexkit/claustrum-client";
|
|
2
3
|
import { createLogger } from "./cc9e0702a752cea7-index.js";
|
|
3
4
|
import { ClaustrumUnreachableError, classifyVaultFailure, } from "./94f53cfd572ba4bb-availability.js";
|
|
@@ -27,6 +28,8 @@ function scopedRetryReason(served, current) {
|
|
|
27
28
|
return 'rotated';
|
|
28
29
|
}
|
|
29
30
|
const defaultLogger = createLogger('claustrum');
|
|
31
|
+
// Opt-in diagnostics let tests retain wait phases without logging each vault read.
|
|
32
|
+
const phaseDiagnostics = channel('common-auth.claustrum.phases');
|
|
30
33
|
/**
|
|
31
34
|
* Decide whether a request that got a 401 should retry with the freshly
|
|
32
35
|
* re-authorized receipt, and log the decision. The vault can refresh a
|
|
@@ -280,6 +283,11 @@ export class ClaustrumScopedCustody {
|
|
|
280
283
|
}
|
|
281
284
|
async #token(signal) {
|
|
282
285
|
this.#check(signal);
|
|
286
|
+
if (phaseDiagnostics.hasSubscribers)
|
|
287
|
+
phaseDiagnostics.publish({
|
|
288
|
+
logger: this.#logger,
|
|
289
|
+
phase: 'token read begin',
|
|
290
|
+
});
|
|
283
291
|
const pending = this.#readToken();
|
|
284
292
|
this.#tokenReads.add(pending);
|
|
285
293
|
let value;
|
|
@@ -288,6 +296,11 @@ export class ClaustrumScopedCustody {
|
|
|
288
296
|
}
|
|
289
297
|
finally {
|
|
290
298
|
this.#tokenReads.delete(pending);
|
|
299
|
+
if (phaseDiagnostics.hasSubscribers)
|
|
300
|
+
phaseDiagnostics.publish({
|
|
301
|
+
logger: this.#logger,
|
|
302
|
+
phase: 'token read end',
|
|
303
|
+
});
|
|
291
304
|
}
|
|
292
305
|
this.#check(signal);
|
|
293
306
|
if (!/^[0-9a-f]{64}$/.test(value.token) ||
|
|
@@ -359,6 +372,11 @@ export class ClaustrumScopedCustody {
|
|
|
359
372
|
this.#kept.clear();
|
|
360
373
|
throw error;
|
|
361
374
|
}
|
|
375
|
+
if (phaseDiagnostics.hasSubscribers)
|
|
376
|
+
phaseDiagnostics.publish({
|
|
377
|
+
logger: this.#logger,
|
|
378
|
+
phase: 'list scoped begin',
|
|
379
|
+
});
|
|
362
380
|
try {
|
|
363
381
|
inventory = await this.#call(() => this.#client.listScoped(token), signal);
|
|
364
382
|
}
|
|
@@ -366,6 +384,13 @@ export class ClaustrumScopedCustody {
|
|
|
366
384
|
this.listFailed(error);
|
|
367
385
|
throw error;
|
|
368
386
|
}
|
|
387
|
+
finally {
|
|
388
|
+
if (phaseDiagnostics.hasSubscribers)
|
|
389
|
+
phaseDiagnostics.publish({
|
|
390
|
+
logger: this.#logger,
|
|
391
|
+
phase: 'list scoped end',
|
|
392
|
+
});
|
|
393
|
+
}
|
|
369
394
|
const skipped = [];
|
|
370
395
|
const refused = [];
|
|
371
396
|
let notMine = 0;
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
// different processes already share, plus the base-view rule, so a commit
|
|
12
12
|
// never replaces a view another process committed after this hub listed.
|
|
13
13
|
import { createHash } from "node:crypto";
|
|
14
|
+
import { channel } from "node:diagnostics_channel";
|
|
14
15
|
import { readdir, stat } from "node:fs/promises";
|
|
15
16
|
import { dirname, join, resolve } from "node:path";
|
|
16
17
|
import { createLogger } from "./cc9e0702a752cea7-index.js";
|
|
@@ -766,7 +767,25 @@ export class ClaustrumDiscoveryHub {
|
|
|
766
767
|
throw base;
|
|
767
768
|
// A member's first roster under this key carries the declines and
|
|
768
769
|
// order of its newest roster under an older key.
|
|
769
|
-
|
|
770
|
+
let seed;
|
|
771
|
+
if (!base.file) {
|
|
772
|
+
const phaseDiagnostics = channel('common-auth.claustrum.phases');
|
|
773
|
+
if (phaseDiagnostics.hasSubscribers)
|
|
774
|
+
phaseDiagnostics.publish({
|
|
775
|
+
logger: this.#logger,
|
|
776
|
+
phase: `seed read ${entry.provider} begin`,
|
|
777
|
+
});
|
|
778
|
+
try {
|
|
779
|
+
seed = await this.#seed(entry);
|
|
780
|
+
}
|
|
781
|
+
finally {
|
|
782
|
+
if (phaseDiagnostics.hasSubscribers)
|
|
783
|
+
phaseDiagnostics.publish({
|
|
784
|
+
logger: this.#logger,
|
|
785
|
+
phase: `seed read ${entry.provider} end`,
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
}
|
|
770
789
|
const roster = await refreshVaultRoster({
|
|
771
790
|
path: entry.path,
|
|
772
791
|
custody: { discover: async () => share },
|