@cortexkit/opencode-openai-auth 1.8.3 → 1.8.5
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 +8 -8
- package/dist/{codex-request-GJkvxv4S.d.ts → codex-request-By530v1D.d.ts} +3 -2
- package/dist/{index-c50p5mem.js → index-5wgxt362.js} +1 -1
- package/dist/{index-rw932qm9.js → index-8x42xzxb.js} +20 -20
- package/dist/{index-g556s1mz.js → index-95s2mw9w.js} +2 -2
- package/dist/{index-bej7x30p.js → index-a7xv52hy.js} +7 -7
- package/dist/{index-hpnj460b.js → index-byz2j6hz.js} +1 -1
- package/dist/{index-z81cged1.js → index-g5hv0tda.js} +2 -2
- package/dist/{index-yt52fztj.js → index-jh90fx7y.js} +2 -2
- package/dist/{index-p8m4yh73.js → index-kphzmgq6.js} +1 -1
- package/dist/index-n12zjwh9.js +8 -0
- package/dist/{index-0v7ar02e.js → index-rmc6hwg6.js} +1 -1
- package/dist/index-zah8t2d2.js +2 -0
- package/dist/{index-dw6yd976.js → index-zf649dj2.js} +2 -2
- package/dist/index-zne9tzy9.js +91 -0
- package/dist/index.d.ts +2 -2
- 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-DkNebAiC.d.ts → sidebar-state-CrRiE9hw.d.ts} +3 -1
- package/dist/sidebar-state.d.ts +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-3vtr29vt.js → token-j2jmx8k7.js} +1 -1
- package/dist/token-util-7n2nfbyc.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +2 -21
- package/dist/v2/server.d.ts +1 -1
- package/dist/v2/server.js +2 -2
- package/package.json +2 -2
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +20 -6
- package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +25 -0
- package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +1 -1
- package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +55 -5
- package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +1 -1
- package/src/tui-compiled/raw/shared/549daf371622c304-index.tsx +497 -0
- package/src/tui-compiled/raw/shared/7c97ac0cec074ae7-format.js +208 -0
- package/src/tui-compiled/raw/shared/b4ad0d49429f0096-map.js +98 -0
- package/src/tui-compiled/raw/shared/b717cdcce3966455-projection.js +90 -0
- package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +3 -1
- package/src/tui-compiled/raw/sidebar-state.js +10 -6
- package/src/tui-compiled/raw/tui.tsx +232 -623
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +20 -6
- package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +25 -0
- package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +1 -1
- package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +55 -5
- package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +1 -1
- package/src/tui-compiled/runtime/shared/549daf371622c304-index.js +550 -0
- package/src/tui-compiled/runtime/shared/7c97ac0cec074ae7-format.js +208 -0
- package/src/tui-compiled/runtime/shared/b4ad0d49429f0096-map.js +98 -0
- package/src/tui-compiled/runtime/shared/b717cdcce3966455-projection.js +90 -0
- package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +3 -1
- package/src/tui-compiled/runtime/sidebar-state.js +10 -6
- package/src/tui-compiled/runtime/tui.js +256 -893
- package/dist/index-03hs0rq7.js +0 -2
- package/dist/index-b0s5cty6.js +0 -91
- package/dist/index-fyrgwfx3.js +0 -8
- package/dist/token-util-erhrf24m.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as a}from"./index-kphzmgq6.js";import"./index-byz2j6hz.js";export default a();
|
package/dist/tui-preferences.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Be as h,Ie as u,Je as P}from"./index-n12zjwh9.js";import{jf as M,kf as R,pf as S}from"./index-95s2mw9w.js";import"./index-byz2j6hz.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/tui.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as OpenDialogPayload, n as ApplyResult, t as ApplyRequest } from "./protocol-BZZtDn5h.js";
|
|
2
|
-
import { S as SidebarState, d as QuotaPacing, f as QuotaWindow, i as AccountQuota, w as SpendControlReading } from "./sidebar-state-
|
|
2
|
+
import { S as SidebarState, d as QuotaPacing, f as QuotaWindow, i as AccountQuota, w as SpendControlReading } from "./sidebar-state-CrRiE9hw.js";
|
|
3
3
|
import { t as RpcClient } from "./rpc-client-CmaZW1by.js";
|
|
4
4
|
import { Plugin } from "@opencode/plugin/tui";
|
|
5
5
|
import { TuiPluginApi, TuiPluginModule } from "@opencode-ai/plugin/tui";
|
|
@@ -96,26 +96,7 @@ export declare function getAccountMetadataRows(resetCredits: number | undefined,
|
|
|
96
96
|
label: string;
|
|
97
97
|
value: string;
|
|
98
98
|
}>;
|
|
99
|
-
|
|
100
|
-
/** Cells of usage bar to draw; 0 draws no bar. */
|
|
101
|
-
barCells: number;
|
|
102
|
-
showReset: boolean;
|
|
103
|
-
}
|
|
104
|
-
/**
|
|
105
|
-
* How an expanded quota row fits on one line `columns` cells wide. The row is
|
|
106
|
-
* the padded label, the bar, the " N% left" figure and, at the right edge, the
|
|
107
|
-
* reset time. When it does not fit, the reset time goes first, then the bar
|
|
108
|
-
* shrinks (to no fewer than MIN_QUOTA_BAR_CELLS cells, else it is dropped).
|
|
109
|
-
* The label and the figure are never cut. `columns` of 0 means the row has not
|
|
110
|
-
* been measured yet, and everything is drawn.
|
|
111
|
-
*/
|
|
112
|
-
export declare function fitQuotaRow(input: {
|
|
113
|
-
columns: number;
|
|
114
|
-
label: string;
|
|
115
|
-
barWidth: number;
|
|
116
|
-
figure: string;
|
|
117
|
-
resetText?: string;
|
|
118
|
-
}): QuotaRowFit;
|
|
99
|
+
/** The fewest cells a shortened quota bar keeps; below this it is dropped. */
|
|
119
100
|
export declare function readStateFromFile(): Promise<SidebarState>;
|
|
120
101
|
export declare function resolveQuotaDialogActiveId(state: SidebarState, sessionId: string | undefined, now?: number): string | undefined;
|
|
121
102
|
export interface RoutingDisplayRow {
|
package/dist/v2/server.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as HostSlotAdapter, d as OpenAiVaultOptions, f as BeginAccountLoginOptions, i as CodexSessionMetadata, o as RuntimeLayoutOptions, p as BeginAccountLoginResult, r as CodexRequestRuntime, s as PoolLifecycleDeps, v as AccountPaths } from "../codex-request-
|
|
1
|
+
import { c as HostSlotAdapter, d as OpenAiVaultOptions, f as BeginAccountLoginOptions, i as CodexSessionMetadata, o as RuntimeLayoutOptions, p as BeginAccountLoginResult, r as CodexRequestRuntime, s as PoolLifecycleDeps, v as AccountPaths } from "../codex-request-By530v1D.js";
|
|
2
2
|
import { i as OpenDialogPayload, n as ApplyResult } from "../protocol-BZZtDn5h.js";
|
|
3
3
|
import { Plugin } from "@opencode/plugin";
|
|
4
4
|
import "@opencode/plugin/promise/session";
|
package/dist/v2/server.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{c as
|
|
1
|
+
import{c as P0}from"../index-rmc6hwg6.js";import{A as U0,B as S$,C as mZ,D as gZ,E as F0,F as GZ,G as QZ,H as d2,I as b$,L as LZ,M as TZ,N as _Z,V as RZ,W as AZ,_ as K0,d as Z0,e as CZ,ea as $$,f as Q1,fa as Z$,g as x2,h as o2,i as Z1,ia as L0,k as t1,l as e1,m as s1,n as u2,o as JZ,p as S1,q as zZ,r as FZ,s as KZ,t as s2,u as m$,v as g$,w as j0,x as B0,y as I1,z as V0}from"../index-a7xv52hy.js";import{Cb as E2,Db as i$,Eb as a$,Fb as A1,Gb as n$,Hb as o$,Jb as W0,Kb as H0,La as BZ,Lb as N0,Sa as n2,ab as J1,bb as tZ,cb as eZ,db as $0,eb as z0,fb as d$,hb as G0,ib as VZ,pa as rZ,rb as Q0,sb as Y0,ta as L$,tb as X0,ua as T$,ub as UZ}from"../index-8x42xzxb.js";import{Vb as yZ,ic as fZ,jc as IZ,lc as vZ,pc as hZ}from"../index-zah8t2d2.js";import{Ed as jZ,Fc as U$,Gd as sZ,Hd as EZ,Id as F$,Rd as q2,Sd as I2,Xd as K$,Zd as h$,_d as P$,ed as i2,ee as $1,fd as a2,gd as oZ,le as OZ,me as k2,nd as f1,ne as _$,od as W$,oe as M$,pd as H$,pe as C$,qd as N$,re as E$,se as O$,ue as R$,ve as A$,we as M1,xe as q$,yd as XZ,ye as x$}from"../index-zne9tzy9.js";import"../index-n12zjwh9.js";import{Oe as $Z,Pe as J0}from"../index-g5hv0tda.js";import"../index-jh90fx7y.js";import{_e as nZ,af as F2}from"../index-zf649dj2.js";import"../index-95s2mw9w.js";import{xf as ZZ}from"../index-5wgxt362.js";import{Bf as G1,Cf as aZ}from"../index-byz2j6hz.js";import{AsyncLocalStorage as L4}from"node:async_hooks";import{randomUUID as T4}from"node:crypto";class G2 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 N2($){return`common-auth-placeholder.${$}`}function d1($){let Z=N2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function S2($,Z){if($?.type!=="oauth")return!1;let J=Z===void 0?void 0:N2(Z),G=(Y)=>J===void 0?Y.startsWith("common-auth-placeholder."):Y===J;return G($.access)&&G($.refresh)}var i1="No browser sign-in: this connects the plugin to the accounts in its vault.";async function U1($,Z){let J=Z.now??Date.now,{integrationID:G}=Z,Y=(N)=>d1({integrationID:G,methodID:N,now:J()}),Q=async(N,H)=>{return await Z.onLogin(N,{integrationID:G,methodID:H}),Y(H)},F=(N)=>async(H)=>{let j=N.method.id,W=await N.authorize(H),K={url:W.url,instructions:W.instructions,...W.expiresAt===void 0?{}:{expiresAt:W.expiresAt}};if(W.mode==="auto")return{...K,mode:"auto",callback:W.callback.then((M)=>Q(M,j))};let x=W.callback;return{...K,mode:"code",callback:async(M)=>Q(await x(M),j)}};return $.integration.transform((N)=>{let H=Z.label===void 0?{}:{label:()=>Z.label};for(let K of Z.methods)N.method.update({integrationID:G,method:K.method,authorize:F(K),refresh:async(x)=>{if(!S2(x,G))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return Y(x.methodID)},...H});let j=Z.vault;if(j===void 0)return;let W=j.method.id;N.method.update({integrationID:G,method:j.method,authorize:async()=>({url:"",instructions:j.instructions??i1,mode:"auto",callback:Promise.resolve().then(()=>j.activate({integrationID:G,methodID:W})).then(()=>Y(W))}),refresh:async(K)=>{if(!S2(K,G)||K.methodID!==W)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return Y(W)},...H})})}function M0($){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 B1($,Z){let J=new TextDecoder,z="",Y=(N)=>{let H=P0(N);if(!H)return;try{$(H)}catch(W){Z(W)}},Q=()=>{for(;;){let N=/\r?\n\r?\n/.exec(z);if(!N)return;let H=z.slice(0,N.index);z=z.slice(N.index+N[0].length),Y(H)}};return new TransformStream({transform(N,H){H.enqueue(N),z+=J.decode(N,{stream:!0}),Q()},flush(){if(z+=J.decode(),Q(),z.trim()!=="")Y(z);z=""}})}var u1=512,p1=1200000,C2="x-common-auth-attempt",T2=($,Z)=>JSON.stringify([$,Z]),G2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function T0($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function L0($,Z){let J=$.getReader();return new ReadableStream({async pull(z){let Y;try{Y=await J.read()}catch(Q){Z({reason:"failed",message:Q instanceof Error?Q.message:String(Q)}),z.error(Q);return}if(Y.done)Z(),z.close();else z.enqueue(Y.value)},async cancel(z){Z({reason:"cancelled",...z===void 0?{}:{message:String(z)}}),await J.cancel(z)}})}function v2($,Z){for(let[J,z]of Object.entries(Z)){let Y=J.toLowerCase();for(let Q of Object.keys($))if(Q.toLowerCase()===Y)delete $[Q];if(z!==null)$[J]=z}}function _0($,Z){for(let[J,z]of Object.entries(Z))if(z===null)$.delete(J);else $.set(J,z)}async function V1($,Z,J={}){let{providerID:z}=Z,Y=J.gateOnPlaceholder,Q=(G)=>Y===void 0||Y.credential(G)===V2(z),N=J.logger,H=Math.max(1,J.maxRecords??u1),W=[...J.hostCredentials??[V2(z)],...Y?[V2(z)]:[]].filter((G)=>G!==""),j=new Map,U=new WeakMap,P=new Map,S=0,_=new Set,w=new Map,i=new Map,R=(G)=>{let X=i.get(G);return X?.ownedSeen===!0&&X.foreignSeen},y=(G,X)=>{w.set(G,X);let B=i.get(G)??{ownedSeen:!1,foreignSeen:!1};if(X)B.ownedSeen=!0;else B.foreignSeen=!0;i.set(G,B)},Y2=(G,X)=>{let B=Y?.refuseMisplaced,T=B?[...X].filter(([,D])=>D.includes(V2(z))):[],F=Q(X)&&(!B||T.length>0);if(B){if(T.length>0&&(T.length!==1||!F))throw y(G.sessionID,!1),new Z2({kind:"placement-refused",providerID:z,sessionID:G.sessionID,requestKind:G.kind,message:B(T[0]?.[0]??"")})}return y(G.sessionID,F),F},$2=!1,k=!1,g=new Map,V=0,L=!1,E=new Map,K=(G,X)=>{try{N?.warn(G,X)}catch{}},A=(G)=>G instanceof Error?G.message:String(G),C=new Map,M=(G,X)=>{let B=(C.get(G)??Promise.resolve()).then(X),T=B.then(()=>{},()=>{});return C.set(G,T),T.then(()=>{if(C.get(G)===T)C.delete(G)}),B},h=(G,X)=>{let B=C.get(G);return B?B.then(()=>h(G,X)):X()},q=async(G)=>{try{await Z.dropChoice?.({...G.input,accountId:G.accountId})}catch(X){K("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:G.input.sessionID,error:A(X)})}},m=(G)=>{let X=P.get(G);if(P.delete(G),X?.next){let B=X.next;M(X.sessionID,()=>q(B))}},l=async(G,X)=>{let B=g.get(G);if(!B||B.size===0)return;await Promise.all([...B].map(async(T)=>{try{await T(X)}catch(F){K("opencode2 auth listener threw; the request is unaffected",{event:G,error:A(F)})}}))},u=async(G,X)=>{try{await Z.onAttemptEnd?.(G,X)}catch(B){K("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:G.attemptId,error:A(B)})}},t=(G,X)=>{if(G.ended||!G.attempt)return;let B={...G.status===void 0?{}:{status:G.status},outputStarted:G.outputStarted,...G.limit?{limit:G.limit.signal}:{},...X?{error:X}:{}};if(X)G.endError=X;G.ended=u(G.attempt,B)},p=(G,X)=>t(G,{reason:"abandoned",message:X}),n=(G)=>[...j.values()].filter((X)=>X.key===G),v=(G)=>n(G).at(-1),f=(G)=>{if(j.delete(G.id),P.get(G.key)?.attemptId===G.id||!n(G.key).length)m(G.key)},I=(G)=>{j.set(G.id,G);while(j.size>H){let X=j.values().next().value;if(X===void 0)break;p(X,"dropped to keep the record bound"),f(X)}},o=(G)=>G.accountId===void 0?void 0:{...G.scope,accountId:G.accountId},c=(G,X)=>new Z2({kind:"no-account",providerID:z,sessionID:G.sessionID,requestKind:G.kind,...X===void 0?{}:{message:X}}),s=(G)=>{E.get(G)?.clear(),E.delete(G)},J2=async(G,X)=>{let B=()=>c(G,`${z} ${G.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(L)throw B();let T=E.get(G.sessionID);if(!T)T=new Set,E.set(G.sessionID,T);let F={};T.add(F);let D=()=>{if(!T.has(F))throw B()};try{return await X(D)}finally{if(T.delete(F),T.size===0&&E.get(G.sessionID)===T)E.delete(G.sessionID)}},_2=(G,X)=>{for(let[B,T]of X)if(W.some((F)=>T.includes(F)))throw new Z2({kind:"host-credential-on-wire",providerID:z,sessionID:G.sessionID,requestKind:G.kind,message:`${z} ${G.kind} request still carries the host's placeholder credential in ${B}; the adapter's account headers must replace it`})},R2=(G)=>{for(let X of n(G))if(X.ended||!X.attempt)f(X);else if(X.transport==="ws"||X.judged)p(X,"a newer attempt of its session and kind began"),f(X)},M2=async(G,X,B,T)=>{let F=T2(G.sessionID,G.kind),{input:D,accountId:x}=await h(G.sessionID,async()=>{B();let r=P.get(F);P.delete(F);let j2=r?.accountId??v(F)?.accountId;R2(F);let B2=r?.next,e=B2!==void 0&&B2.input.modelID===G.modelID&&B2.input.agent===G.agent,x2={...G,phase:"request",...j2===void 0?{}:{previousAccountId:j2},...r?.rerouteFrom?{rerouteFrom:r.rerouteFrom}:{}};if(B2&&!e)await M(G.sessionID,()=>q(B2)),B();let N2=e?B2.accountId:await Z.chooseAccount(x2);return{input:x2,accountId:typeof N2==="string"?N2:void 0}});B();let b={},a;if(x!==void 0){let r=await Z.accountHeaders({...G,accountId:x});if(B(),T0(r))b=r.headers,a=r.attempt;else b=r}let K2=`attempt-${++V}`,z2={id:K2,key:F,scope:G,accountId:x,headers:b,attempt:x===void 0?void 0:{...G,accountId:x,attemptId:K2,transport:T,data:a},...T===void 0?{}:{transport:T},outputStarted:!1};if(I(z2),z2.attempt)l("select",{...G,accountId:z2.attempt.accountId,hook:X,...D.previousAccountId===void 0?{}:{previousAccountId:D.previousAccountId},...D.rerouteFrom===void 0?{}:{rerouteFrom:D.rerouteFrom},handle:z2.attempt});return z2},O=async(G,X,B,T,F)=>{let D=T2(G.sessionID,G.kind),x=T===void 0?void 0:j.get(T);if(x?.key!==D)x=void 0;if(!x){if(x=v(D),n(D).filter((a)=>a.transport===void 0&&!a.ended).length>1&&!k)k=!0,K("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:G.sessionID,kind:G.kind})}if(!x||x.transport!==void 0||x.ended)x=await M2(G,X,F,B);else if(x.transport=B,x.attempt)x.attempt.transport=B;if(B==="ws"){for(let b of n(D))if(b!==x&&b.transport==="ws")p(b,"a newer attempt of its session and kind went out over WebSocket")}return x},d=async(G,X)=>{try{return await X()}catch(B){throw t(G,{reason:"failed",message:A(B)}),B}},X2=(G,X)=>{let B=n(T2(G,X)).filter((T)=>T.transport==="ws").at(-1);return B?.attempt!==void 0&&!B.ended?B:void 0},G1=(G,X,B)=>{let T=o(G);if(!T||!G.attempt||G.limit)return;G.limit={signal:X,delivered:l("limit",{...T,via:B,limit:X,outputStarted:G.outputStarted,handle:G.attempt})}},f1=(G,X,B,T)=>{let F=o(G);if(!F||!G.attempt)return;l("quota",{...F,transport:X,...T===void 0?{}:{status:T},quota:B,handle:G.attempt})},I1=(G,X,B,T)=>{let F=G.attempt;if(!F)return;let D=Z.inspectEvent?.(T===void 0?{transport:X,data:B,attempt:F}:{transport:X,data:B,event:T,attempt:F});if(!D)return;if(D.quota!==void 0)f1(G,X,D.quota);if(D.outputStarted)G.outputStarted=!0;if(D.limit)G1(G,D.limit,X);if(D.error!==void 0)t(G,{reason:"failed",message:D.error});else if(D.done)t(G)},N0=(G,X)=>{let B=G.attempt;if(!B||X.accountId===G.accountId)return;if(B.reboundFrom??=B.accountId,B.accountId=X.accountId,"data"in X)B.data=X.data;G.accountId=X.accountId},F0=(G)=>!G.attempt||G.endError!==void 0||G.status!==void 0&&G.status>=400,K0=(G)=>{let X=[...j.values()].filter((b)=>b.scope.sessionID===G),B=X.filter((b)=>b.limit&&!b.rerouted).at(-1);if(B)return B;let T=X.filter((b)=>b.scope.kind==="primary"),F=T.length>0?T:X;if(F.length<=1)return F[0];let D=F.filter((b)=>!b.judged&&F0(b)).at(-1);if(D)return D;let x=F.filter((b)=>b.attempt&&!b.ended);if(x.length>1)return"ambiguous";return x[0]??F.at(-1)},F2={providerID:z},H2=[];H2.push(await $.session.hook("model.request",(G)=>{if(Y)return;return J2(G2(G),async(X)=>{let B=await M2(G2(G),"model.request",X);if(X(),B.accountId===void 0)throw c(B.scope);v2(G.headers,{...B.headers,[C2]:B.id})})},F2)),H2.push(await $.session.hook("http.request",(G)=>{if(Y){if(!Y2(G2(G),G.request.headers))return}return J2(G2(G),async(X)=>{let B=G.request.headers.get(C2)??void 0,T=Y?await M2(G2(G),"http.request",X,"http"):await O(G2(G),"http.request","http",B,X);X();let F=o(T),D=T.attempt;if(!F||!D)throw c(T.scope);await d(T,async()=>{let x=G.request;if(Z.rewriteRequest){if(B!==void 0){let K2=new Headers(x.headers);K2.delete(C2),x=new Request(x,{headers:K2})}x=await Z.rewriteRequest({...F,request:x,attempt:D})??x,X()}let b=new Headers(x.headers);b.delete(C2),_0(b,T.headers),_2(T.scope,b.entries());let a=new Request(x,{headers:b});U.set(a,T),G.request=a})})},F2)),H2.push(await $.session.hook("http.response",async(G)=>{let X=U.get(G.request);if(!X){if(Y)return;if(!$2)$2=!0,K("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:G.sessionID,kind:G.kind});return}let B=G.response;if(Z.answeredBy&&X.attempt){let b=X.attempt,a=await d(X,async()=>Z.answeredBy?.({request:G.request,response:B,attempt:b}));if(a)N0(X,a)}let T=o(X),F=X.attempt;if(!T||!F)return;X.status=B.status;let D=Z.quotaFromHeaders?.(B.headers,B.status,F);if(D!==void 0)f1(X,"http",D,B.status);if(!B.ok&&Z.limitFromResponse){let b=await Z.limitFromResponse({status:B.status,headers:B.headers,body:()=>B.clone().text(),attempt:F});if(b)G1(X,b,"http")}if(!B.ok||!B.body)t(X);let x=B;if(B.body&&(Z.inspectEvent||Z.onAttemptEnd)){let b=B.body;if(Z.inspectEvent)b=b.pipeThrough(B1((a)=>I1(X,"http",a.data,a.event),(a)=>K("opencode2 auth event inspection threw",{error:A(a)})));x=new Response(L0(b,(a)=>t(X,a)),{status:B.status,statusText:B.statusText,headers:B.headers})}if(Z.rewriteResponse)x=await Z.rewriteResponse({...T,request:G.request,response:x,attempt:F})??x;if(x!==B)G.response=x},F2)),H2.push(await $.session.hook("experimental.ws.handshake",(G)=>{if(Y){let X=T2(G.sessionID,G.kind);if(_.delete(X),!Y2(G2(G),new Headers(G.headers)))return}return J2(G2(G),async(X)=>{let B;for(let x of Object.keys(G.headers)){if(x.toLowerCase()!==C2)continue;B??=G.headers[x],delete G.headers[x]}let T=Y?await M2(G2(G),"experimental.ws.handshake",X,"ws"):await O(G2(G),"experimental.ws.handshake","ws",B,X);X();let F=o(T),D=T.attempt;if(!F||!D)throw c(T.scope);await d(T,async()=>{if(!Y?.refuseMisplaced)v2(G.headers,T.headers);let x=Z.rewriteHandshakeURL?.({...F,url:G.url,attempt:D});if(x!==void 0)G.url=x;if(Y?.refuseMisplaced)v2(G.headers,T.headers);if(_2(T.scope,Object.entries(G.headers)),Y)_.add(T.key)})})},F2));let v1=Z.rewriteWebSocketFrame?.bind(Z);if(v1)H2.push(await $.session.hook("experimental.ws.send",async(G)=>{let X=G2(G);if(Y&&!_.has(T2(X.sessionID,X.kind)))return;let B=X2(X.sessionID,X.kind),T=await v1({...X,attempt:B?.attempt,frame:G.frame});if(T!==void 0)G.frame=T},F2));H2.push(await $.session.hook("experimental.ws.receive",(G)=>{if(Y&&!_.has(T2(G.sessionID,G.kind)))return;let X=X2(G.sessionID,G.kind);if(!X)return;try{I1(X,"ws",G.frame)}catch(B){K("opencode2 auth frame inspection threw",{error:A(B)})}},F2)),H2.push(await $.session.hook("retry",async(G)=>{if(Y&&w.get(G.sessionID)!==!0)return;let X=G.decision,B=()=>l("retry",{sessionID:G.sessionID,attempt:G.attempt,reason:"host-decides",hostDecision:X,decision:X});if(R(G.sessionID)){await B();return}let T=K0(G.sessionID);if(!T)return;if(T==="ambiguous"){await l("retry",{sessionID:G.sessionID,attempt:G.attempt,reason:"host-decides",hostDecision:X,decision:X});return}let F=T;await J2(F.scope,async(D)=>{let x=D;if(R(G.sessionID)){await B();return}F.judged=!0;let b=F.attempt;if(b&&!F.outputStarted){if(!F.limit){let z2=Z.limitFromError?.(G.error,b);if(z2)G1(F,z2,"error")}if(F.ended)await F.ended;if(F.limit)await F.limit.delivered}x();let{decision:a,reason:K2}=await M(F.scope.sessionID,async()=>{if(x(),R(G.sessionID))return{decision:X,reason:"host-decides"};let z2=P.get(F.key);if(P.delete(F.key),z2?.next)await q(z2.next);if(x(),R(G.sessionID))return{decision:X,reason:"host-decides"};let r=X,j2,B2,e;if(F.accountId===void 0||!b)r={retry:!1},j2="no-account";else if(F.outputStarted)r={retry:!1},j2="output-started";else if(F.limit){let x2={accountId:F.accountId,limit:F.limit.signal},N2,Y1={...F.scope,phase:"retry",previousAccountId:F.accountId,rerouteFrom:x2};try{N2=await Z.chooseAccount(Y1)}catch(X1){K("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:F.scope.sessionID,error:A(X1)})}let P2=typeof N2==="object"?N2.hold:void 0,I2=typeof N2==="string"?N2:P2?F.accountId:void 0;if(I2!==void 0)e={accountId:I2,input:Y1};try{x()}catch(X1){if(e)await q(e);throw X1}if(R(G.sessionID)){if(e)await q(e);return{decision:X,reason:"host-decides"}}if(P2&&Number.isFinite(P2.delayMs)&&P2.delayMs>=0)r={retry:!0,delay:Math.min(P2.delayMs,p1)},j2="hold";else if(!P2&&I2!==void 0&&I2!==F.accountId)F.rerouted=!0,B2=x2,r={retry:!0,delay:0},j2="reroute";else{if(P2&&e)await q(e),e=void 0;j2="host-decides-last-account"}}else j2="host-decides";if(G.decision=r,r.retry&&F.accountId!==void 0&&j.has(F.id))P.set(F.key,{attemptId:F.id,sessionID:F.scope.sessionID,order:++S,accountId:F.accountId,...B2===void 0?{}:{rerouteFrom:B2},...e===void 0?{}:{next:e}});else if(e)await q(e);return{decision:r,reason:j2}});x(),await l("retry",{sessionID:G.sessionID,...F.accountId===void 0?{}:{accountId:F.accountId},kind:F.scope.kind,attempt:G.attempt,reason:K2,hostDecision:X,decision:a,...b===void 0?{}:{handle:b}})})},F2));let h1=(G)=>{if(s(G),w.delete(G),!i.get(G)?.foreignSeen)i.delete(G);for(let X of _)if(JSON.parse(X)[0]===G)_.delete(X);for(let X of[...j.values()]){if(X.scope.sessionID!==G)continue;p(X,"its session was forgotten"),j.delete(X.id)}for(let[X,B]of P)if(B.sessionID===G)m(X)},Q1=new AbortController,m1=$.event;if(m1)(async()=>{try{for await(let G of m1.subscribe({signal:Q1.signal}))if(G.type==="session.deleted")h1(G.data.sessionID);else if(G.type==="session.status"&&G.data.status.type==="idle"){let X=G.data.sessionID,B=++S;M(X,async()=>{for(let[T,F]of P)if(F.sessionID===X&&F.order<B){if(P.delete(T),F.next)await q(F.next)}})}}catch(G){if(!Q1.signal.aborted)K("opencode2 auth stopped listening for session deletion",{error:A(G)})}})();return{on(G,X){let B=g.get(G);if(!B)B=new Set,g.set(G,B);let T=X;return B.add(T),()=>{B.delete(T)}},accountFor(G,X){return v(T2(G,X))?.accountId},forgetSession:h1,get size(){return j.size},async dispose(){if(L)return;L=!0;for(let G of E.keys())s(G);Q1.abort();for(let G of j.values())p(G,"the installation was disposed");j.clear();for(let G of P.keys())m(G);_.clear(),w.clear(),i.clear(),g.clear(),await Promise.all(C.values()),await Promise.all(H2.map(async(G)=>{try{await G.dispose()}catch(X){K("opencode2 auth hook did not dispose cleanly",{error:A(X)})}}))}}}import{createHash as M0}from"node:crypto";var C0=1024,E0=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),c1=($)=>d1($,"user"),O0=($)=>E0($)&&($.role==="assistant"||typeof $.type==="string"&&$.type!=="message"&&$.type!=="configuration_update");function A0($){return M0("sha256").update(JSON.stringify($)).digest("hex")}class E2{runtime;maxSessions;#$=new Map;constructor($,Z=C0){this.runtime=$;this.maxSessions=Z}advance($,Z,J=this.runtime){let z=this.#$.get($),Y=Array.isArray(Z.input)?Z.input:[],Q=Y.filter(c1),N=Y.findLastIndex(c1),H=N<0?void 0:A0(Y[N]),W=typeof Z.previous_response_id==="string"&&Z.previous_response_id.length>0,j,U,P;if(W)j=Q.length>0,U=H??z?.fingerprint,P=z?.userCount===void 0?void 0:z.userCount+Q.length;else{U=H,P=Q.length;let _=N>=0&&N>Y.findLastIndex(O0),w=z!==void 0&&!z.completed&&z.fingerprint===U&&z.userCount===P;j=_&&!w}let S=j||!z?{turnID:(J?.uuid??L2)(),turnStartedAt:(J?.now??Date.now)()}:{turnID:z.turnID,turnStartedAt:z.turnStartedAt};return this.#Z($,{...S,completed:!1,fingerprint:U,userCount:P}),S}completed($){let Z=this.#$.get($);if(Z)this.#Z($,{...Z,completed:!0})}get($){return this.#$.get($)}forget($){this.#$.delete($)}#Z($,Z){this.#$.delete($),this.#$.set($,Z);while(this.#$.size>this.maxSessions){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function U1($,Z){return{threadID:$.threadID,windowID:$.windowID,turnID:Z.turnID,turnStartedAt:Z.turnStartedAt}}var i1=Symbol.for("@cortexkit/openai-auth/opencode2/codex-installation");function R0(){let $=globalThis;return $[i1]??=crypto.randomUUID(),$[i1]}class S2{runtime;store;sessions;frameTurns;installationID;constructor($,Z,J){this.runtime=$;this.store=J;this.installationID=Z??R0(),this.sessions=J?.sessions??new Map,this.frameTurns=J?.frameTurns??new E2}get($){let Z=this.runtime?.uuid??L2;if(this.store)return this.store.get($,Z);let J=this.sessions.get($);if(!J){let z=Z();J={threadID:z,turnID:Z(),windowID:`${z}:0`},this.sessions.set($,J)}return J}advanceFrame($,Z){return this.frameTurns.advance($,Z,this.runtime)}frameReceived($,Z){if(!Z.includes("response.completed"))return;if(h2(Z)?.type==="response.completed")this.frameTurns.completed($)}forget($){if(this.store)this.store.delete($);else this.sessions.delete($);this.frameTurns.forget($)}}var W1={version:a1,"user-agent":n1,originator:"codex_exec"};var x0=1024,q0=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,g2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),s1=($)=>g2($)&&($.type==="message"||("role"in $))&&$.role==="user",t1=($)=>g2($)&&$.type==="configuration_update";class H1{http;#$=new Map;constructor($=new S2){this.http=$}apply($,Z,J){if(Z.kind!=="primary")return!1;let z=typeof $.model==="string"?$.model:"";if(!o1.has(z))return!1;if(q0.test(z))return!1;let Y=g2($.reasoning)?$.reasoning:void 0,Q=typeof Y?.effort==="string"?Y.effort:void 0;if(!Q)return!1;let N=this.#$.get(Z.sessionID);if(N===void 0)return this.#Z(Z.sessionID,Q),!1;if(Q===N)return!1;let H=Array.isArray($.input)?$.input:void 0;if(!H||H.length===0)return!1;let W=H.findLastIndex(s1);if(W<0){if(J==="http")return!1;return $.reasoning={...Y,effort:N},!0}if($.reasoning={...Y,effort:N},!t1(H[W-1]))H.splice(W,0,{type:"configuration_update",reasoning:{effort:Q}});return!0}forget($){this.#$.delete($),this.http.forget($)}#Z($,Z){this.#$.set($,Z);while(this.#$.size>x0){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function h2($){try{let Z=JSON.parse($);return g2(Z)?Z:void 0}catch{return}}async function e1($,Z,J,z,Y=J.http){if($.method.toUpperCase()!=="POST")return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let Q=await $.clone().text(),N=h2(Q);if(N)delete N.max_output_tokens;let H=new Headers($.headers),W=m2({rewriteLite:r1,init:{body:N?JSON.stringify(N):$.body===null?void 0:Q},headers:H,metadata:Y.get(Z.sessionID),installationID:Y.installationID,runtime:Y.runtime,websocket:!1,responsesLite:z,applyEffort:(j)=>{J.apply(j,Z,"http")}});return new Request($,{headers:H,body:W.init?.body})}function $$($,Z,J,z){let Y=z.sessions.get($.sessionID),Q=z.frameTurns.get($.sessionID);if(!Y||!Q)return;let N=U1(Y,Q),H=new Headers({"content-type":"application/json"});for(let j of["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"]){let U=J.get(j);if(U!==null)H.set(j,U)}m2({init:{body:$.bodyText},headers:H,metadata:N,installationID:z.installationID,runtime:z.runtime,websocket:!1,skipTurnUpdate:!0,responsesLite:!1,rewriteLite:()=>{}});let W=new URL(Z);if(W.protocol==="wss:")W.protocol="https:";if(W.protocol==="ws:")W.protocol="http:";return new Request(W,{method:"POST",headers:H,body:$.bodyText})}function S0($,Z){if(JSON.stringify($)===JSON.stringify(Z))return!0;if(!Array.isArray($)||!Array.isArray(Z)||Z.length!==$.length+1)return!1;let J=Z.findIndex((z,Y)=>JSON.stringify(z)!==JSON.stringify($[Y]));return J>=0&&t1(Z[J])&&s1(Z[J+1])&&JSON.stringify(Z.slice(J+1))===JSON.stringify($.slice(J))}function Z$($,Z,J){let z=h2($);if(z?.type!=="response.create")return;let Y=J.http.advanceFrame(Z.sessionID,z),Q=J.http.get(Z.sessionID);delete z.max_output_tokens;let N=m2({rewriteLite:()=>{},init:{body:JSON.stringify(z)},headers:new Headers,metadata:U1(Q,Y),installationID:J.http.installationID,runtime:J.http.runtime,websocket:!0,responsesLite:!1,applyEffort:(W)=>{J.apply(W,Z,"ws")}}),H=h2(String(N.init?.body));if(!H)return;if(!S0(z.input,H.input)){if("input"in z)H.input=z.input;else delete H.input;return JSON.stringify(H)}return String(N.init?.body)}function b0($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function N1($,Z){let J=new URL($);if(J.origin!=="https://api.openai.com"&&J.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(J.pathname))return $;let z=new URL(`${b0(Z)}/responses`);if(z.search=J.search,J.protocol==="ws:"||J.protocol==="wss:")z.protocol=z.protocol==="https:"?"wss:":"ws:";return z.href}import{resolve as J$}from"node:path";var k0=1024;class l2{accounts=new Map;limit;constructor($=k0){this.limit=Math.max(1,$)}record($,Z){this.accounts.delete($),this.accounts.set($,Z);while(this.accounts.size>this.limit){let J=this.accounts.keys().next().value;if(J===void 0)break;this.accounts.delete(J)}}activeAccount($){return this.accounts.get($)}forget($){this.accounts.delete($)}get size(){return this.accounts.size}}var z$=Symbol.for("@cortexkit/openai-auth/opencode2-session-accounts"),G$=globalThis,F1=G$[z$]??new Map;G$[z$]=F1;function K1($){let Z=JSON.stringify([J$($.configPath),J$($.statePath)]),J=F1.get(Z);if(!J)J=new l2,F1.set(Z,J);return J}var Q2="openai",D0=60000,P1=1,w0="request refused: no account with a usable credential",W2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function y0($){let Z=W2($)?$.counters:void 0,J=W2(Z)?Z.resetCredits:void 0,z=W2(J)?J.value:void 0;return typeof z==="number"&&Number.isFinite(z)?z:void 0}function L1($){try{return JSON.parse($)}catch{return}}function Q$($){let Z=p2($);return Z?c2(Z):void 0}var f0=new Set(["usage_limit_reached","rate_limit_exceeded"]);function _1($,Z,J){return{reason:$.window,...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function I0($,Z){let J=u2($);if(J){let Q=typeof $.status==="number"?$.status:void 0;return _1(J,Z,Q)}if($.type!=="response.failed"||!W2($.response))return;let z=$.response.failed;if(W2(z)&&typeof z.rate_limit_reached_type==="string")return{reason:z.rate_limit_reached_type};let Y=$.response.error;if(W2(Y)){let Q=typeof Y.code==="string"?Y.code:typeof Y.type==="string"?Y.type:void 0;if(Q&&f0.has(Q))return{reason:Q}}return}function v0($,Z){let J=L1($);if(!W2(J))return;let z=typeof J.type==="string"?J.type:void 0;if(z==="codex.rate_limits")return{quota:{snapshot:B$(J),complete:!0}};let Y=I0(J,Z);if(Y)return{limit:Y};if(z===void 0||z==="error")return;return A$(z)?void 0:{outputStarted:!0}}function h0($){let Z=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:X$($),complete:j$($)}}function m0($){let Z=$.get("retry-after");if(Z===null)return;let J=Number(Z);return Number.isFinite(J)&&J>=0?J*1000:void 0}function R$($){let{source:Z,pins:J}=$,z=$.now??Date.now,Y=$.log,Q=$.vault,N=new H1($.codex),H=new Map,W=new Map,j=(V)=>`${V.sessionID}\x00${V.kind}\x00${V.accountId}`,U=new Map,P=$.sessionAccounts??new l2,S=new _$,_=(V,L,E)=>{let K=E?[]:O$(Z.peek().rows,V,L,Q?.identities()??new Set),A=(Q?.routes()??[]).filter((C)=>C.kind==="oauth"&&U$(b2(C.quota),V,L));return[...K.map((C)=>({id:C.id,...C.identity!==void 0?{identity:C.identity}:{},quota:C.quota,row:C})),...A.map((C)=>({id:C.id,...C.identity!==void 0?{identity:C.identity}:{},quota:C.quota}))]},w=(V,L,E)=>{let K=P$(V,L,E),A=V.map((q)=>({id:q.id,kind:"oauth",...Y$(q.quota)?{quota:q.quota}:{}})),C=V.flatMap((q)=>q.row?[q.row]:[]),M=new Set(V.filter((q)=>!q.row).map((q)=>q.id)),h=Z.rateLimitMarks(C);for(let q of M){let m=U.get(q);if(m===void 0)continue;if(m<=E)U.delete(q);else h.set(q,m)}return{rows:A,now:E,rateLimitMarks:h,refreshBackoff:Z.refreshBackoffFor(C),killswitch:K,requestPull:(q)=>M.has(q)?Q?.requestReading(q):Z.requestReading(q)}},i=(V,L,E,K,A)=>{let C=M$({...V,placement:T$(L),mainId:A});if(C.kind==="block"){Y?.debug("pool admission refused the request",{reason:C.block.reason});return}let M=C.order.filter((h)=>!E.has(h));if(K!==void 0&&M.includes(K))return K;return M[0]},R=(V,L,E,K,A,C,M)=>{let h=new Map(L.map((v)=>[v.id,v.quota])),q={requestBytes:P1,reservePercent:(v)=>W$(E,v===F$?void 0:v),resetCredits:(v)=>y0(h.get(v))},m=T1(V),l=(v,f)=>d2(M,{sessionId:K,requestBytes:P1,validPinnedAccountIds:V.rows.map((I)=>I.id).filter((I)=>!m.excluded.has(I)),excludeAccountIds:v,quotaCheckedAtByAccount:Object.fromEntries(V.rows.map((I)=>[I.id,m.projections.get(I.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(L.map((I)=>[I.id,I.identity])),select:(I)=>C$(V,q,new Set(v),I),persist:f},(I,o)=>M.set(I,o)),u=[...A],t=l(u,C);if(!t)return;let p=t.accountId,n=E$(V,q,p);if(n.kind==="none")return;if(n.kind==="move"){let v=l([...u,p],C);if(v)return v.accountId;return n.reason==="killswitch"?void 0:p}if(n.kind==="detour")return l([...u,p],!1)?.accountId;return p},$2={providerID:Q2,dropChoice(V){let L=j(V);W.get(L)?.drop(),W.delete(L),H.delete(L)},chooseAccount:async(V)=>{let L=await Q?.authority(),E=await $.storage(),K=L!==void 0&&L!=="local",A=()=>{throw new Z2({kind:"no-account",providerID:Q2,sessionID:V.sessionID,requestKind:V.kind,message:i2})};if(K)await $.awaitVaultRoster?.();else{if(!(await Z.current()).active){if(await $.slotPlaceholderWithoutMain?.())A();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=z(),M=_(E,C,K),h=L$(w(M.filter((I)=>I.id!==V.rerouteFrom?.accountId),E,C));if(h)await h,C=z(),M=_(E,C,K);let q=new Map(M.map((I)=>[I.id,I])),m=w(M,E,C),l=new Set(V.rerouteFrom?[V.rerouteFrom.accountId]:[]),u=E?.routing?.mode??"main-first",t=V.kind==="primary",p=new Set,n,v,f;try{for(;;){let I=new Set([...l,...p]);if(f=void 0,n=void 0,u==="sticky-balanced"){let c=new Map(J.placementSnapshot(V.sessionID)),s=c.get(V.sessionID);if(f=R(m,M,E,V.sessionID,I,t&&p.size===0,c),f!==void 0&&c.get(V.sessionID)!==s)n=c.get(V.sessionID)}if(f??=i(m,u,I,t?void 0:P.activeAccount(V.sessionID),K?u==="sticky-balanced"?null:K$(Q?.routes()??[]):void 0),f===void 0||p.has(f)){if(l.size>0){let c=new Map(m.rateLimitMarks);for(let s of l)c.delete(s);m={...m,rateLimitMarks:c},l.clear();continue}f=void 0;break}if(t&&u==="sticky-balanced"){let c=T1(m).projections.get(f)?.checkedAt,s=q.get(f)?.identity;v=J.reserve(V.sessionID,{accountId:f,inputBytes:P1,...c!==void 0?{quotaCheckedAt:c}:{},...s!==void 0?{wireIdentity:s}:{}})}let o=q.get(f)?.row;if(o){if(Z.usableToken(o)!==void 0)break;Y?.debug("pool row holds no usable token; choosing again",{accountId:f})}else{if(!Q)break;let c=await Q.authorize(f);if(c){H.set(j({...V,accountId:f}),c);break}Y?.debug("the vault refused to serve an account; choosing again",{accountId:f})}if(v)J.rollback(v);v=void 0,p.add(f)}if(f===void 0&&!K&&M.length===0&&await $.slotPlaceholderWithoutMain?.())A();if(f===void 0&&K&&Q&&(M.length===0||p.size>0)){let I=p.size>0?"vault-refused":N$(Q);throw Y?.warn("vault mode: no vault account can serve; refusing the request",{cause:I}),new Z2({kind:"no-account",providerID:Q2,sessionID:V.sessionID,requestKind:V.kind,message:H$(I,Q.name)})}if(f!==void 0){let I=f,o=v,c=n,s=()=>{if(o)J.finish(o,c);if(t)P.record(V.sessionID,I),$.onRoute?.(V.sessionID,I,u)};if(V.phase==="retry")W.set(j({...V,accountId:f}),{commit:s,drop:()=>{if(o)J.rollback(o)}}),v=void 0;else s();let J2=Y?.info;S.served(m,f,Y&&J2?{info:(_2,R2)=>J2.call(Y,_2,R2)}:void 0)}return Y?.debug("pool account chosen",{kind:V.kind,accountId:f,mode:u,...V.rerouteFrom?{rerouteFrom:V.rerouteFrom.accountId}:{}}),f}finally{if(v)J.rollback(v)}},accountHeaders:async(V)=>{let{accountId:L}=V,E=j(V),K=W.get(E);W.delete(E);let A=()=>{K?.commit()};try{let C=()=>new Z2({kind:"no-account",providerID:Q2,sessionID:V.sessionID,requestKind:V.kind,message:w0}),M=Q&&await Q.authority()!=="local"?void 0:Z.peek().rows.find((m)=>m.id===L);if(!M&&Q){let m=j(V),l=H.get(m)??await Q.authorize(L);if(H.delete(m),!l)throw Y?.warn("the vault refused to serve an account; refusing the request",{accountId:L}),C();return A(),{headers:{...W1,"session-id":V.sessionID,authorization:`Bearer ${l.accessToken}`,"chatgpt-account-id":l.accountIdentity??Q$(l.accessToken)??null},attempt:{kind:"vault",routeId:L,receipt:l}}}let h=M?Z.usableToken(M):void 0;if(!M||!h)throw Y?.warn("pool row holds no usable token; refusing the request",{accountId:L}),C();let q=M.identity??Q$(h);return A(),{headers:{...W1,"session-id":V.sessionID,authorization:`Bearer ${h}`,"chatgpt-account-id":q??null},attempt:{kind:"pool",token:h,credentialEpoch:M.credentialEpoch}}}finally{K?.drop()}},async rewriteRequest({request:V,sessionID:L,kind:E}){let K=$.codexEndpoint?N1(V.url,$.codexEndpoint()):V.url,A=K===V.url?V:new Request(K,V);return await e1(A,{sessionID:L,kind:E},N,$.responsesLite?.()??!1)??A},rewriteHandshakeURL:({url:V})=>$.codexEndpoint?N1(V,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:V,sessionID:L,kind:E})=>Z$(V,{sessionID:L,kind:E},N),quotaFromHeaders:(V)=>h0(V),async limitFromResponse({status:V,headers:L,body:E}){if(V<400)return;let K=L1(await E().catch(()=>"")),A=u2({...W2(K)?K:{},status:V});if(!A)return;let C=z(),M=_1(A,C,V);if(M.retryAfterMs!==void 0)return M;let h=m0(L);return h===void 0?M:{...M,retryAfterMs:h}},inspectEvent:({data:V})=>v0(V,z()),limitFromError(V){let L=L1(V.message),E=u2({...W2(L)?L:{},...V.status!==void 0?{status:V.status}:{}})??(V.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return E?_1(E,z(),V.status):void 0},async onAttemptEnd(V,L){let E=V.data;if(E?.kind!=="vault"||L.status!==401)return;Y?.warn("a vault account answered 401; reporting it to the vault",{accountId:V.accountId}),await Q?.reportFailure(E.receipt,401)}},k=(V,L,E)=>{let K=E.data;if(K?.kind==="vault"){Q?.recordSnapshot(V,L.snapshot,L.complete,K.receipt);return}if(K?.kind!=="pool")return;if(Z.peek().rows.find((C)=>C.id===V)?.credentialEpoch!==K.credentialEpoch){Y?.debug("quota reading dropped: the row holds another credential",{accountId:V});return}Z.recordSnapshot(V,L.snapshot,K.token,L.complete)},g=(V,L,E)=>{let K=z(),A=E.data?.kind==="vault",C=A?Q?.routes().find((q)=>q.id===V)?.quota:Z.peek().rows.find((q)=>q.id===V)?.quota,M=V$(b2(C),L.reason,K,D0,L.retryAfterMs!==void 0?K+L.retryAfterMs:void 0);if(!A){Z.markRateLimited(V,M);return}let h=U.get(V);if(h===void 0||h<M)U.set(V,M)};return{adapter:$2,attach(V){V.on("quota",(L)=>k(L.accountId,L.quota,L.handle)),V.on("limit",(L)=>{g(L.accountId,L.limit,L.handle),Y?.debug("pool row refused the request",{accountId:L.accountId,via:L.via,reason:L.limit.reason,outputStarted:L.outputStarted})})},forgetSession(V){J.forget(V),P.forget(V),N.forget(V)},activeAccount:(V)=>P.activeAccount(V)}}import{resolve as D$}from"node:path";import{Buffer as g0}from"node:buffer";import{resolve as x$}from"node:path";function k2($){return g0.byteLength(JSON.stringify($))}function l0($){return $.reduce((Z,J)=>Z+k2(J),0)}function M1($,Z){return 2+$+Math.max(0,Z-1)}function u0($){let{head:Z,pending:J}=$;return 10+$.fieldsBytes+1+(Z?22+Z.responseIDBytes+9+M1(Z.inputBytes,Z.input.length)+1:0)+(J?20+M1(J.inputBytes,J.input.length)+10+M1(J.outputBytes,J.output.length)+(J.responseID===void 0?0:14+J.responseIDBytes)+1:0)}function q$($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}class S${enabled;caps=a2;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=q$(Z);if(J?.type!=="response.create")return;if(!Array.isArray(J.input)){this.forget($);return}let z=J.previous_response_id,Y=this.entries.get($),Q=Y?.head;if(z&&z!==Q?.responseID){this.forget($);return}let{type:N,previous_response_id:H,input:W,...j}=J;this.keep($,{fields:z&&Y?Y.fields:j,fieldsBytes:z&&Y?Y.fieldsBytes:k2(j),...z&&Q?{head:Q}:{},pending:{input:W,inputBytes:l0(W),output:[],outputBytes:0,responseIDBytes:0},bytes:0})}receive($,Z,J){if(!this.enabled||!Z.includes("response.created")&&!Z.includes("response.output_item.done")&&!Z.includes("response.completed"))return;let z=this.entries.get($);if(!z?.pending)return;let Y=q$(Z);if(!Y)return;let Q=z.pending,N=Y.response;if(Y.type==="response.created"&&typeof N?.id==="string")Q.responseID=N.id,Q.responseIDBytes=k2(N.id),this.keep($,z);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+=k2(Y.item),this.keep($,z)}else if(Y.type==="response.completed"&&typeof N?.id==="string"){if(N.id===z.head?.responseID||Q.responseID!==void 0&&N.id!==Q.responseID)return;let H={responseID:N.id,responseIDBytes:Q.responseID===N.id?Q.responseIDBytes:k2(N.id),input:[...z.head?.input??[],...Q.input,...Q.output],inputBytes:(z.head?.inputBytes??0)+Q.inputBytes+Q.outputBytes},W={...z,head:H,pending:void 0};if(!this.keep($,W))return;J?.({sessionID:$,responseID:H.responseID,bodyText:this.body(z.fields,H)})}}replay($){let Z=this.entries.get($);if(!Z?.head)return;return this.entries.delete($),this.entries.set($,Z),this.body(Z.fields,Z.head)}forget($){let Z=this.entries.get($);if(Z)this.bytes-=Z.bytes;this.entries.delete($)}status(){return{bytes:this.bytes,sessions:[...this.entries].map(([$,Z])=>({sessionID:$,bytes:Z.bytes,responseID:Z.head?.responseID,pending:Z.pending!==void 0}))}}body($,Z){return JSON.stringify({...$,input:Z.input,stream:!0})}keep($,Z){let J=u0(Z);if(this.forget($),J>this.caps.maxBytes)return!1;Z.bytes=J,this.entries.set($,Z),this.bytes+=J;while(this.entries.size>this.caps.maxTargets||this.bytes>this.caps.maxBytes){let z=this.entries.keys().next().value;if(z===void 0)break;this.forget(z)}return this.entries.has($)}}var b$=Symbol.for("@cortexkit/openai-auth/opencode2-frame-mirror"),k$=globalThis,C1=k$[b$]??new Map;k$[b$]=C1;function n2($){let Z=JSON.stringify([x$($.configPath),x$($.statePath)]),J=C1.get(Z);if(!J)J=new S$,C1.set(Z,J);return J}var p0=5000,c0=["accept","originator","session-id","thread-id","user-agent","version","x-client-request-id","x-codex-beta-features","x-codex-turn-metadata","x-codex-window-id","x-openai-internal-codex-responses-lite","x-opencode-parent-session-id","x-parent-session-id"],d0=["x-opencode-parent-session-id","x-parent-session-id"];function I$($){let Z=w$($);return{enabled:Z?.enabled===!0,subagents:Z?.subagents===!0,sustain:Z?.sustain===!0,window:y$($?{...$,cachekeep:Z}:$)}}var v$=Symbol.for("@cortexkit/openai-auth/opencode2-cache-keep"),h$=globalThis,D2=h$[v$]??new Map;h$[v$]=D2;function i0($,Z){let J=[],z=()=>J.at(-1)?.location,Y=()=>{let W=z();if(!W)throw Error("no location holds keep-warm");return W},Q=(W,j)=>{H.remove(W),z()?.log?.debug(`cachekeep dropped target (${j})`,{sessionKey:W})},N=async(W)=>{if(W.meta.credentialMode!=="local")throw Error("a target captured in vault mode is not warmed with a local credential");let j=W.accountId??"main",U=Y(),P=await U.source.accessFor(j,await U.storage());if(!P)throw Error(`pool row ${j} has no usable token`);return{token:P.token,identity:P.row.identity}},H=f$({...a2,now:$.now,...$.setIntervalImpl?{setIntervalImpl:$.setIntervalImpl}:{},...$.clearIntervalImpl?{clearIntervalImpl:$.clearIntervalImpl}:{},codexResponsesUrl:$.codexResponsesUrl,fetchImpl:(W,j)=>Y().fetch(W,j),logger:{debug:(W,j)=>z()?.log?.debug(W,j),warn:(W,j)=>z()?.log?.warn(W,j)},getWindow:()=>z()?.settings().window,getSustain:()=>z()?.settings().sustain===!0,resolveLocal:N,vault:{owns:(W)=>z()?.vault.owns(W)===!0,authority:()=>Y().vault.authority(),send:async(W,j,U)=>{let P=Y();if(await P.vault.authority()!=="vault")return;return P.vault.send(W,j,U)}},activeAccount:(W)=>{if(W===void 0)throw Error("target has no session");let j=z(),U=j?.settings();if(!j||!U?.enabled){Q(W,"keep-warm is off");return}if(!U.subagents&&H.status().targets.some((S)=>S.sessionKey===W&&S.isSubagent)){Q(W,"subagent warming is off");return}let P=j.accounts.activeAccount(W);if(P===void 0){Q(W,"no account recorded for the session");return}return P},verifyCredential:({target:W,mode:j,identity:U})=>{if(W.meta.credentialMode!==j)throw Error(`a target captured in ${W.meta.credentialMode??"an unknown"} mode is not warmed with a ${j} credential`);if(U!==W.meta.chatgptAccountId)throw Q(W.sessionKey,"the account signs in as another login now"),Error("the account signs in as another login now")}});return{manager:H,settings:Z,holders:J,joinTimeoutMs:$.joinTimeoutMs??p0}}function a0($){try{let Z=JSON.parse($),J=Array.isArray(Z.input)?Z.input.at(-1):void 0;if(J?.role!=="user")return!1;return(typeof J.content==="string"?J.content:Array.isArray(J.content)?J.content.map((Y)=>typeof Y?.text==="string"?Y.text:"").join(""):"").startsWith("This is a keep-alive request.")}catch{return!1}}function n0($){let Z={};for(let J of c0){let z=$.get(J);if(z)Z[J]=z}return Z}function m$($,Z,J){let z=JSON.stringify([D$($.configPath),D$($.statePath)]),Y=D2.get(z);if(!Y)Y=i0(J,Z.settings()),D2.set(z,Y);let Q=Y,N=n2($);N.setEnabled(Q.settings.enabled);let H={location:{...Z,settings:()=>Q.settings}};Q.holders.push(H);let W=!1,j=async(U)=>{try{let P=H.location.settings();if(W||!P.enabled)return;if(U.kind!=="primary"){if(U.kind==="generate"&&a0(await U.request.clone().text())){if(W)return;Q.manager.remove(U.sessionID)}return}let S=U.attempt.data,_=S?.kind==="pool"?"local":S?.kind==="vault"?"vault":void 0;if(!_)return;let w=U.request.headers,i=d0.some((Y2)=>w.has(Y2))||Z.parentOf!==void 0&&await Z.parentOf(U.sessionID)!==void 0;if(i&&!P.subagents)return;let R=await U.request.clone().text();if(W)return;let y=w.get("chatgpt-account-id")??void 0;Q.manager.track({sessionKey:U.sessionID,bodyText:R,accountId:U.attempt.accountId,isSubagent:i,meta:{replayHeaders:n0(w),...y?{chatgptAccountId:y}:{},routingSessionId:U.sessionID,url:U.request.url,credentialMode:_}})}catch(P){Z.log?.warn("cachekeep capture failed",{error:P instanceof Error?P.message:String(P)})}};return{manager:Q.manager,configure:(U)=>{Object.assign(Q.settings,U),N.setEnabled(Q.settings.enabled)},capture:j,forget:(U)=>Q.manager.remove(U),async release(){if(W)return;W=!0;let U=Q.holders.indexOf(H);if(U>=0)Q.holders.splice(U,1);if(Q.holders.length>0)return;if(D2.get(z)===Q)D2.delete(z);Q.manager.stop();let P;try{await Promise.race([Q.manager.tick().catch(()=>{}),new Promise((S)=>{P=setTimeout(S,Q.joinTimeoutMs),P.unref?.()})])}finally{clearTimeout(P)}}}}import{mkdirSync as o0}from"node:fs";import{dirname as r0,resolve as s0}from"node:path";function t0(){return g$("opencode2")}var e0=2000;class d${path;options;sessions;frameTurns=new E2;#$=new Set;#Z=new Set;#z=new Set;#G=Promise.resolve();#Q=!1;#J;constructor($,Z={}){this.path=$;this.options=Z;this.sessions=p$($,Z.uuid??L2)}get($,Z=L2){let J=this.sessions.get($);if(!J){let z=Z();J={threadID:z,turnID:Z(),windowID:`${z}:0`},this.sessions.set($,J),this.#Z.delete($),this.#z.delete($),this.#$.add($),this.#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??e0),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{$=E1(this.path)}catch{$=new Map}for(let Z of this.#z)if($.has(Z)&&!this.sessions.has(Z))this.#Z.add(Z);this.#z.clear()}async#j(){if(this.#X(),this.#$.size===0&&this.#Z.size===0)return;let $=[...this.#$].flatMap((z)=>{let Y=this.sessions.get(z);return Y?[[z,Y]]:[]}),Z=[...this.#Z],J=null;try{if(o0(r0(this.path),{recursive:!0}),J=await this.#B(),!J)return;let z;try{z=E1(this.path)}catch{z=new Map}await this.options.afterRead?.();let Y=!1;for(let Q of Z)if(z.delete(Q))Y=!0;for(let[Q,N]of $){if(z.get(Q)===N.threadID)continue;z.set(Q,N.threadID),Y=!0}if(Y)c$(this.path,z)}catch{return}finally{await J?.release().catch(()=>{})}for(let[z,Y]of $)if(this.sessions.get(z)===Y)this.#$.delete(z);for(let z of Z)if(!this.sessions.has(z))this.#Z.delete(z)}#B(){return u$(this.path,this.options.lockWaitMs??l$)}}var i$=Symbol.for("@cortexkit/openai-auth/opencode2-codex-sessions"),a$=globalThis,o2=a$[i$]??new Map;a$[i$]=o2;function $4($){if(!$||typeof $!=="object")return!1;let Z=$;return Z.sessions instanceof Map&&typeof Z.get==="function"&&typeof Z.delete==="function"&&typeof Z.save==="function"&&typeof Z.settled==="function"&&(Z.frameTurns===void 0||Z.frameTurns!==null&&typeof Z.frameTurns.advance==="function"&&typeof Z.frameTurns.get==="function"&&typeof Z.frameTurns.completed==="function"&&typeof Z.frameTurns.forget==="function")}function n$($=t0()){let Z=s0($),J=o2,z=o2.get(Z),Y=o2;if(z!==void 0&&!$4(z))J.compatible??=new Map,Y=J.compatible;let Q=Y.get(Z);if(!Q)Q=new d$(Z),Y.set(Z,Q);let N=Q;return N.frameTurns??=new E2,Q}var O1=Symbol.for("cortexkit.openai-auth.v2.commands"),Z4=U2("v2-command");function r2($){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 A1($){Z4.warn(`/openai needs the terminal UI (session state: ${$}).`)}function J4(){let $=globalThis;return $[O1]??={locations:new Map},$[O1].locations??=new Map,$[O1]}async function ZZ($,Z){let J=J4(),z=$.location.directory,Y={menu:Z,session:$.session,closed:new AbortController},Q=await r$(z),N=await o$(e$,Q.dir,()=>$Z({...Q,drain:t$,apply:(P)=>{let S=J.locations.get(z);if(!r2(S))throw Error("The OpenAI menu location was closed");return S.menu.apply(P)}})),H=J.locations.get(z);if(J.locations.set(z,Y),r2(H))H.closed.abort(),await H.registration?.dispose();let W={name:"openai",description:"OpenAI account menu",async execute(P){let S=[...J.locations.values()].find(r2)?.session;if(!S)return A1("no live location");let _=await S.get({sessionID:P.sessionID}),w=J.locations.get(_.location.directory);if(!r2(w))return A1("location closed");let i=await s$(P.sessionID,w.closed.signal);if(!i||J.locations.get(_.location.directory)!==w){if(!i&&!w.closed.signal.aborted)R1({command:"openai",notify:{message:"/openai timed out waiting for the terminal UI. Run it again.",kind:"warning"}},P.sessionID);return A1(w.closed.signal.aborted?"location closed":"no TUI poll within 2 s")}let R=await w.menu.open(P.sessionID);R1(R,P.sessionID)}};J.command??=W,J.command.execute=W.execute;let j=J.command;try{Y.registration=await $.command.transform((P)=>{P.add(j)})}catch(P){if(Y.closed.abort(),J.locations.get(z)===Y)J.locations.delete(z);throw await N.release(),P}let U=!1;return async()=>{if(U)return;if(U=!0,Y.closed.abort(),J.locations.get(z)===Y)J.locations.delete(z);await N.release(),await Y.registration?.dispose()}}var z4="openai-auth-pool-browser",G4="openai-auth-pool-headless",Q4="openai-auth-vault",Y4="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Run /openai → Vault → Connect and approve the request before trying again.";async function w2($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function XZ($){return{method:{id:Q4,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await JZ($.paths,$.name)!=="vault")throw Error(Y4)}}}function jZ($){let Z=(J,z,Y)=>({method:{id:J,type:"oauth",label:z},async authorize(){if($.vault)await w2($.vault);let Q=await $.beginLogin({version:$.version,headless:Y});return{url:Q.url,instructions:Q.instructions,mode:"auto",callback:Q.completion}}});return[Z(z4,"ChatGPT (openai-auth pool, browser)",!1),Z(G4,"ChatGPT (openai-auth pool, headless)",!0)]}function x1($){let Z=(J)=>typeof J==="string"?J:"";return q2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===QZ||zZ($)}function X4($){if($.accountId)return $.accountId;let Z=$.access?p2($.access):void 0;return Z?c2(Z):void 0}async function BZ($,Z,J,z={}){if(z.vault)await w2(z.vault);if(x1(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let Y=GZ($,{rowLocks:(_)=>YZ(Z,_)}),Q=await Y.read();if(Q.status!=="ready")throw Error(`the account pool cannot be read (${Q.status}); the login was not stored`);let N={type:"oauth",refresh:J.refresh,...J.access!==void 0?{access:J.access}:{},...J.expires!==void 0?{expires:J.expires}:{}},H=X4(J);if(z.vault)await w2(z.vault);let W=H!==void 0?{identity:H}:{};if(z.origin==="import"){let _=Q.rows.find((w)=>H!==void 0&&w.identity===H||w.credential?.type==="oauth"&&w.credential.refresh===J.refresh);if(_)return{id:_.id,operation:"kept"}}let j=Q.rows.filter((_)=>_.type==="oauth"&&!_.invalid),U=H?j.find((_)=>_.identity===H):void 0,P=Q.rows.find((_)=>_.id===s2);if(U)return{id:(await Y.replace(U.id,N,W)).id,operation:"replaced"};if(!P){let _=await Y.add({id:s2,credential:N,...W,...J.label!==void 0?{label:J.label}:{}});return{id:_.id,operation:_.outcome==="added-disabled"?"added-disabled":"added"}}if(!P.invalid&&!P.credential)return{id:(await Y.replace(s2,N,W)).id,operation:"replaced"};let S=await Y.add({id:J.id,credential:N,...W,...J.label!==void 0?{label:J.label}:{}});return{id:S.id,operation:S.outcome==="added-disabled"?"added-disabled":S.outcome==="rotated"?"replaced":"added"}}function j4($){let Z=$.itemId!==void 0;switch($.sectionId){case"accounts":return Z?["enable","disable","remove","move"].includes($.actionId):$.actionId==="add";case"routing":return!Z&&["order","mode"].includes($.actionId);case"quota":return $.actionId==="check";case"limits":return Z?$.actionId==="floors":$.actionId==="killswitch";case"session":return!Z&&$.actionId==="clear-pin";case"vault":return Z?["enable","disable"].includes($.actionId):["connect","disconnect"].includes($.actionId);case"diagnostics":return!Z&&["logging","dump"].includes($.actionId);case"cache":return!Z&&["enabled","subagents","sustain","window"].includes($.actionId);case"reset":return Z&&["preview","spend","retry"].includes($.actionId);default:return!1}}function WZ($){let Z={...$,allowAction:j4,unavailableSections:[]};return{open:(J)=>VZ(Z,J),apply:(J)=>{let z=J!==null&&typeof J==="object"?J:{},Y=z.values&&typeof z.values==="object"&&!Array.isArray(z.values)?Object.fromEntries(Object.entries(z.values).filter(([,Q])=>Q===null||["string","number","boolean"].includes(typeof Q))):void 0;return UZ(Z,{command:"openai",sectionId:typeof z.sectionId==="string"?z.sectionId:"",actionId:typeof z.actionId==="string"?z.actionId:"",...Y?{values:Y}:{},...z.confirmed===!0?{confirmed:!0}:{},...typeof z.itemId==="string"?{itemId:z.itemId}:{},...typeof z.sessionId==="string"?{sessionId:z.sessionId}:{}})}}}function B4($,Z){if(!HZ($.modelID??$.id)){$.enabled=!1;return}let J=NZ($.id);if(J)$.limit={...J};if(Z)$.variants=[...new Map([...Z,...$.variants??[]].map((z)=>[z.id,z])).values()]}function KZ($){return $.model.transform((Z)=>{let J=Z.list(Q2);for(let z of J){let Y=FZ(String(z.id)),Q=Y?J.find((N)=>String(N.id)===Y):void 0;Z.update(Q2,String(z.id),(N)=>B4(N,Q?.variants?.map((H)=>({...H,id:String(H.id)}))))}})}class q1{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(!PZ())return;await this.safely(async()=>{let J={sessionID:Z.sessionID,accountId:Z.accountId,transport:"http",phase:"http",url:$.url,method:$.method,headers:new Headers($.headers),bodyText:await $.clone().text()};if(this.pending.set($,{attemptId:Z.attemptId,input:J}),this.requests.set(Z.attemptId,$),this.pending.size>512){let z=this.pending.keys().next().value;if(z)this.take(z)}})}take($){let Z=this.pending.get($);if(Z)this.pending.delete($),this.requests.delete(Z.attemptId);return Z?.input}async response($,Z){let J=this.take($);if(J)await this.safely(()=>t2({...J,status:Z}))}async end($,Z){if(Z.status!==void 0||!Z.error)return;let J=this.requests.get($.attemptId),z=J&&this.take(J);if(!z)return;let{reason:Y,message:Q}=Z.error,N=Q?`${Y}: ${Q}`:Y;await this.safely(()=>t2({...z,error:e2(N,J?.headers.get("authorization")?.replace(/^Bearer /,""))}))}async frame($,Z){await this.safely(()=>t2({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 S1{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 CZ($){return async(Z)=>{let J=Z.credential;if(J.type!=="oauth"||!J.access)throw Error("the row holds no access token to poll with");let z=await TZ({accessToken:J.access,fetchImpl:$.fetchImpl,now:$.now,...Z.identity?{accountId:Z.identity}:{},accountKey:Z.id,...$.logger?{logger:$.logger}:{}});return $.counts.record(Z,z),LZ(z,$.now(),!0)}}function EZ($){let{source:Z,counts:J,now:z}=$,Y=async(j)=>{let U=await Z.rowAccess(j,await $.storage());if(!U?.row)throw new _Z("unknown_account",`${j==="main"?"Main":"Fallback"} account ${j} was not found.`);return MZ(j,U)},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[U]=await Z.pollRows(await $.storage(),{ids:[j]});if(!U)return{account:j,ok:!1,error:"targeted quota refresh returned no result"};return{account:U.id,ok:U.ok,...U.error!==void 0?{error:U.error}:{}}},N=(j)=>Z.peek().rows.find((U)=>U.id===j),H=(j)=>{let U=N(j);if(!U)return null;let P=b2(U.quota)??{},S=J.applicable(U),_=Math.max(0,...[P.primary?.checkedAt,P.secondary?.checkedAt].filter((w)=>typeof w==="number"));return{quota:{...P,...S!==void 0?{resetCreditsApplicable:S}:{}},checkedAt:_,refreshAfter:_,...U.identity!==void 0?{accountId:U.identity}:{}}};return{resolveResetTarget:Y,refreshResetTargetQuota:Q,quotaManager:{isRateLimited:(j)=>{let U=N(j);if(!U)return!1;let P=Z.rateLimitMarks([U]).get(U.id);return P!==void 0&&P>z()},getMain:()=>H("main"),getFallback:(j)=>H(j)}}}import{resolve as OZ}from"node:path";var V4=1024;class b1{pins=new Map;reservations=new Map;listeners=new Set;limit;constructor($=V4){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.reservations.delete($),this.pins.delete($);for(let Z of this.listeners)Z($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}snapshot(){return new Map(this.pins)}placementSnapshot($){let Z=new Map(this.pins);for(let J of this.reservations.values())if(J.sessionId!==$)Z.set(J.sessionId,J.pin);return Z}reserve($,Z){let J={sessionId:$,previous:this.pins.get($),pin:Z};return this.reservations.set($,J),J}rollback($){if(this.reservations.get($.sessionId)===$)this.reservations.delete($.sessionId)}finish($,Z){if(this.reservations.get($.sessionId)!==$)return;if(this.rollback($),Z&&this.pins.get($.sessionId)===$.previous)this.set($.sessionId,Z)}get size(){return this.pins.size}set($,Z){this.reservations.delete($),this.pins.delete($),this.pins.set($,Z);for(let J of this.listeners)J($,Z);while(this.pins.size>this.limit){let J=this.pins.keys().next().value;if(J===void 0)break;this.forget(J)}}place($){return d2(this.placementSnapshot($.sessionId),$,(Z,J)=>this.set(Z,J))}}var AZ=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),RZ=globalThis,$1=RZ[AZ]??new Map;RZ[AZ]=$1;function U4($){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 xZ($){let Z=JSON.stringify([OZ($.configPath),OZ($.statePath)]),J=$1,z=$1.get(Z);if(z!==void 0&&!U4(z)){let Q=$1;Q.compatibleV1??=new Map,J=Q.compatibleV1}let Y=J.get(Z);if(!Y)Y=new b1,J.set(Z,Y);return Y}import{statSync as W4}from"node:fs";import{resolve as H4}from"node:path";function IZ($){return $.map((Z)=>{try{let J=W4(Z);return`${J.ino}:${J.size}:${J.mtimeMs}:${J.ctimeMs}`}catch{return"?"}}).join("|")}function k1($){return IZ([$.vault.paths.tokenPath,$.vault.paths.statePath])}function qZ($){return IZ([$.paths.configPath,$.paths.statePath,$.vault.paths.rosterPath])+k1($)}class vZ{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:qZ($),roster:$.vault.snapshot()});let Z=$.source.subscribe(()=>{this.publish($)}),J=this.subscriptions.get($.pins);if(!J){let z=new Set;J={producers:z,stop:$.pins.subscribe((Y,Q)=>{let N=z.values().next().value;if(N)this.publish(N,{sessionId:Y,pin:Q,accountId:Q?.accountId,route:"sticky-balanced"})})},this.subscriptions.set($.pins,J)}return J.producers.add($),this.timer??=setInterval(()=>{for(let z of this.producers){let Y={stamp:qZ(z),roster:z.vault.snapshot()},Q=this.observations.get(z);if(Y.stamp!==Q?.stamp||Y.roster!==Q?.roster)this.observations.set(z,Y),this.publish(z)}},this.observationIntervalMs),this.timer.unref?.(),()=>{if(Z(),this.producers.delete($),this.observations.delete($),J.producers.delete($),!J.producers.size)J.stop(),this.subscriptions.delete($.pins);if(!this.producers.size)clearInterval(this.timer),this.timer=void 0}}publish($,Z){return this.chain=this.chain.then(async()=>{if(!this.producers.has($))return;let z=await $.vault.authority()!=="local",Y=k1($),Q=()=>this.producers.has($)&&$.vault.enrolled()===z&&k1($)===Y,N=await(z?f2($.paths):O2($.paths)),H=z?yZ($.vault.snapshot()?.rows,new Set($.vault.routes().map((j)=>j.id)),N,Date.now()):fZ((await $.source.sidebarView()).rows,N,Date.now());if(await bZ(H,this.file,{canWrite:Q}),!Q()||!Z)return;let W=H.vaultAccounts??H.fallbacks;if(Z.accountId===void 0){await DZ(Z.sessionId,W,this.file,{canWrite:Q});return}if(Z.pin){let j=Date.now();await wZ({sessionId:Z.sessionId,assignment:{accountId:Z.pin.accountId,wireAccountId:Z.pin.wireIdentity,inputBytes:Z.pin.inputBytes??0,quotaCheckedAt:Z.pin.quotaCheckedAt,assignedAt:j,lastSeenAt:j},validPinnedAccountIds:[...z?[]:["main"],...W.filter((U)=>U.enabled).map((U)=>U.id)]},this.file)}await kZ({sessionId:Z.sessionId,activeId:Z.accountId,route:Z.route??H.route,updatedAt:Date.now()},W,this.file,{canWrite:Q})}).catch(()=>{U2("opencode2").warn("sidebar publication failed")}),this.chain}settled(){return this.chain}get empty(){return this.producers.size===0}}var hZ=Symbol.for("@cortexkit/openai-auth/opencode2-sidebar-publishers"),mZ=globalThis,y2=mZ[hZ]??new Map;mZ[hZ]=y2;function gZ($,Z=SZ(),J=2000){let z=H4(Z),Y=y2.get(z);if(!Y)Y=new vZ(z,J),y2.set(z,Y);let Q=Y,N=Q.add($),H=!1;for(let[W,j]of $.pins.snapshot())Q.publish($,{sessionId:W,pin:j,accountId:j.accountId,route:"sticky-balanced"});return{publish:()=>Q.publish($),route:(W,j,U)=>{Q.publish($,{sessionId:W,accountId:j,route:U})},async release(){if(H)return;if(H=!0,N(),await Q.settled(),Q.empty&&y2.get(z)===Q)y2.delete(z)}}}var z1="cortexkit-openai-auth",K4=5000;async function lZ($,Z,J,z=new S2,Y,Q,N){let H=new q1(J),W=new N4,j=new Map,U=new Map,P=(R)=>{U.delete(R);for(let y of j.keys())if(y.startsWith(`${R}:`))j.delete(y)},S=(R)=>{N?.(R.sessionID),Q?.send(R.sessionID,R.frame)},w=await V1({session:{hook:(R,y,Y2)=>$.session.hook(R,async($2)=>{let k=R==="http.request"?$2:void 0,g=R==="experimental.ws.handshake"?$2:void 0,L=(k?k.request.headers:g?new Headers(g.headers):void 0)?.get("authorization")===`Bearer ${V2(Z.providerID)}`,E={};if(g)j.delete(`${g.sessionID}:${g.kind}`);try{await W.run(E,()=>y($2))}catch(K){if(L&&!(K instanceof Z2))throw aZ(K);throw K}if(k&&L&&E.attempt){let K=k.request.headers.get("thread-id");if(K)k.request.headers.set("session-id",K)}if(k&&L&&E.attempt)await H.captureHttp(k.request,E.attempt);if(k&&L&&E.attempt)await Y?.({sessionID:k.sessionID,kind:k.kind,request:k.request,attempt:E.attempt});if(g&&L&&E.attempt)g.headers["session-id"]=z.get(g.sessionID).threadID;if(R==="experimental.ws.send"){let K=$2,A=j.get(`${K.sessionID}:${K.kind}`);if(A)await H.frame(K.frame,A.attempt);if(A&&K.kind==="primary")S(K)}if(k||g){let K=k??g;if(!K)return;let C=(k?k.request.headers:new Headers(K.headers)).get("authorization")?.replace(/^Bearer /,"");if(L&&C)U.set(K.sessionID,C);else U.delete(K.sessionID);if(g){let M=`${g.sessionID}:${g.kind}`;if(L&&C&&E.attempt)j.set(M,{bearer:C,attempt:E.attempt,url:g.url,headers:new Headers(Object.entries(g.headers).filter(([h])=>["chatgpt-account-id","x-opencode-parent-session-id","x-parent-session-id"].includes(h.toLowerCase())))});else j.delete(M)}if(U.size>512){let M=U.keys().next().value;if(M)U.delete(M)}if(j.size>512){let M=j.keys().next().value;if(M)j.delete(M)}}else if(R==="experimental.ws.receive"){let K=$2,A=j.get(`${K.sessionID}:${K.kind}`);if(A){if(z.frameReceived(K.sessionID,K.frame),K.kind==="primary"){let C;if(Q?.receive(K.sessionID,K.frame,(M)=>{C=M}),C)try{let M=$$(C,A.url,A.headers,z);if(M)await Y?.({sessionID:K.sessionID,kind:"primary",request:M,attempt:A.attempt})}catch(M){J.warn("cachekeep WebSocket capture failed",{error:M instanceof Error?M.message:String(M)})}}K.frame=nZ(K.frame,A.bearer)}}else if(R==="retry"){let K=$2,A=U.get(K.sessionID);if(A)Object.assign(K.error,{message:e2(K.error.message,A)})}},Y2)},event:{subscribe:(R)=>async function*(){for await(let y of $.event.subscribe(R)){if(y.type==="session.deleted")P(y.data.sessionID);yield y}}()}},{...Z,rewriteRequest:async(R)=>{let y=W.getStore();if(y)y.attempt=R.attempt;return Z.rewriteRequest?.(R)},rewriteHandshakeURL:(R)=>{let y=W.getStore();if(y)y.attempt=R.attempt;return Z.rewriteHandshakeURL?.(R)},onAttemptEnd:async(R,y)=>{await H.end(R,y),await Z.onAttemptEnd?.(R,y)},rewriteResponse:async(R)=>{await H.response(R.request,R.response.status);let y=await Z.rewriteResponse?.(R)??R.response;return oZ(y,R.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(R)=>{let y=R.get("authorization");return y?.startsWith("Bearer ")?y.slice(7):void 0}},logger:{warn:(R,y)=>J.warn(R,{data:y})}}),i=w.dispose;return{...w,dispose:async()=>{U.clear(),j.clear(),await i(),await H.settle(),H.clear()}}}function y1($={}){return{id:z1,setup:(Z)=>P4(Z,$)}}async function P4($,Z={}){let J2=[];try{let J=U2("opencode2");let z=U2("quota");let Y=Z.version??sZ;await B0({version:Y,...Z.runtimeLayout});let Q=Z.paths??(()=>eZ(rZ()));let N=await f2(Q());let H=N?.logging?.level;if(H&&typeof H==="string")pZ(H);let W=Z.fetch??fetch;let j=Z.now??Date.now;let U=Z.poolMigration??U0;if(!U&&!A2(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 O=(X2)=>{throw new Z2({kind:"no-account",providerID:Q2,sessionID:X2.sessionID,requestKind:X2.kind,message:i2})},d=await lZ($,{providerID:Q2,chooseAccount:O,accountHeaders:O},J);return()=>d.dispose()}let P=Z.vault?.firstRosterWaitMs??G0;let S=V0({host:"opencode",stateDir:Z.vault?.stateDir??iZ(Q().statePath),reservedRouteIds:()=>k.peek().rows.map((O)=>O.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>W},Q());let _=S.vault;let w=async()=>await _.authority()==="local"?O2(Q()):f2(Q());let i=!1;let R=!1;const y=Z1(J2,{[Symbol.dispose](){if(!i)S.release()}},0);await _.authority();let Y2=S.firstRoster;let $2=new S1;let k=new Q0({paths:Q,refreshProvider:async(O)=>{let d=await dZ({refreshToken:O.refresh,fetchImpl:W,now:j}),X2=cZ({id_token:"",access_token:d.access,refresh_token:d.refresh});return{...d,...X2?{identity:X2}:{}}},pullQuota:CZ({fetchImpl:W,now:j,counts:$2,logger:z}),now:j,vaultIdentities:()=>_.identities(),vaultMode:()=>_.enrolled(),vaultAuthority:()=>_.authority(),vaultFirstRoster:Y2,vaultFirstRosterBackgroundWaitMs:P,log:U2("pool")});if(await _.authority()==="local")await k.load();let g=Z.heartbeat===!1?void 0:await X0({version:Y,logger:U2("heartbeat")});let V=Z.fence??(()=>tZ({currentVersion:Y}));let L=Z.slot??W0();let E=async()=>$0(Q(),await L.get({path:{id:"openai"}}));let K=!1;let A=U?Y0({paths:Q,slot:L,version:Y,fence:V,runDeps:{vaultServes:()=>_.serves()},paused:async()=>await _.authority()!=="local",migrate:async(O)=>{let d=await Z0(O);if(K=d.status==="refused",!R)await k.load();return d},adopt:async(O)=>{if(R)return{status:"retry",reason:"unsettled"};if(!await w1(Y2,P))return{status:"retry",reason:"vault-roster-pending"};if(R)return{status:"retry",reason:"unsettled"};let d=await J0(O);if(!R)await k.load();return d}}):void 0;A?.start();S.start();let C=xZ(Q());let M=gZ({paths:Q(),source:k,pins:C,vault:_},Z.sidebarStateFile,Z.sidebarObservationIntervalMs);const h=Z1(J2,{[Symbol.dispose](){if(!i)M.release()}},0);M.publish();let q=Z.codex??new S2(void 0,void 0,n$());let m=I$(N);let l=n2(Q());let u=m$(Q(),{source:k,storage:w,vault:_,accounts:K1(Q()),settings:()=>m,parentOf:async(O)=>(await $.session.get({sessionID:O}))?.parentID??void 0,fetch:W,log:U2("cachekeep")},{now:j,codexResponsesUrl:J1().codexApiEndpoint,...Z.cacheKeep});const t=Z1(J2,{[Symbol.dispose](){if(!i)u.release()}},0);let p=R$({codex:q,onRoute:M.route,source:k,slotPlaceholderWithoutMain:E,storage:w,pins:C,sessionAccounts:K1(Q()),vault:_,awaitVaultRoster:async()=>{await w1(_.awaitRequestRoster(),z0)},responsesLite:()=>J1().responsesLite,codexEndpoint:()=>J1().codexApiEndpoint,now:j,log:J});let n=await lZ($,p.adapter,J,q,(O)=>u.capture(O),l,(O)=>u.forget(O));p.attach(n);let v=async(O)=>{if(await w2(_),A2(Q().configPath))return;if(await A?.idle(),A2(Q().configPath))return;if(K&&!x1(O)&&(await V()).open){await k.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let f=async(O)=>{await v(O);let d=await BZ(k.poolStore(),Q(),O,{vault:_});if(!A2(Q().configPath))await A?.requestAdoption();await k.load(),J.info("ChatGPT login stored in the account pool",d)};let I=await j1($,{integrationID:Q2,methods:jZ({beginLogin:Z.beginLogin??D1,version:Y,vault:_}),onLogin:(O)=>f(O),label:"ChatGPT (openai-auth account pool)",vault:XZ(_)});let o=await KZ($);if(Z.controlPlane&&(!$.command||!$.location))throw Error("OpenCode 2 control plane requires command and location APIs");let c=$.command&&$.location?await ZZ({session:$.session,command:$.command,location:$.location},Z.controlPlane??WZ({...EZ({source:k,storage:w,counts:$2,now:j,authority:()=>_.authority()}),fetchImpl:W,now:j,randomUUID:F4,accountStoragePath:Q().configPath,accountStatePath:Q().statePath,packageVersion:Y,layoutNotice:j0,loadAccounts:O2,store:()=>k.poolStore(),migration:async()=>{if(A2(Q().configPath))return{migrated:!0};let O=await V();return{migrated:!1,blockers:O.open?[]:O.blockers}},beginAccountLogin:Z.beginLogin??D1,refreshAllQuota:async()=>(await k.pollRows(await O2(Q()))).map((O)=>({...O,account:O.id})),getStickyRouting:async(O)=>C.get(O),cacheKeepManager:u.manager,setCacheKeepEnabled:(O)=>u.configure({enabled:O}),setCacheKeepSubagents:(O)=>u.configure({subagents:O}),setCacheKeepSustain:(O)=>u.configure({sustain:O}),setCacheKeepWindow:(O)=>u.configure({window:O}),afterWrite:()=>k.load(),refreshSidebar:()=>M.publish(),clearStickyRouting:async(O)=>{let d=C.get(O)!==void 0;return C.forget(O),d},vault:_})):void 0;let s=new AbortController;(async()=>{try{for await(let O of $.event.subscribe({signal:s.signal}))if(O.type==="session.deleted")p.forgetSession(O.data.sessionID),u.forget(O.data.sessionID),l.forget(O.data.sessionID)}catch(O){if(!s.signal.aborted)J.warn("stopped listening for session deletion",{error:O instanceof Error?O.message:String(O)})}})();i=!0;return async()=>{R=!0,s.abort();let O=u.release();await c?.(),A?.dispose(),await k.dispose(),await M.release(),await Promise.allSettled([n.dispose(),I.dispose(),o.dispose()]);let d;try{await Promise.race([Promise.all([A?.idle(),k.settled(),q.store?.settled(),O]),new Promise((X2)=>{d=setTimeout(X2,K4),d.unref?.()})])}finally{clearTimeout(d),S.release(),await g?.release()}}}catch(_2){var R2=_2,M2=1}finally{uZ(J2,R2,M2)}}var T4=y1(),u6={id:z1,setup:T4.setup,server:H0.server};export{u6 as default,y1 as createOpenAIAuthPlugin,z1 as OPENAI_AUTH_PLUGIN_ID};
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-openai-auth",
|
|
3
|
-
"version": "1.8.
|
|
3
|
+
"version": "1.8.5",
|
|
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.31.0",
|
|
70
70
|
"@cortexkit/openai-auth-core": "workspace:*",
|
|
71
71
|
"@opencode/plugin": "2.2.0"
|
|
72
72
|
},
|
|
@@ -85,16 +85,28 @@ function credentialTypeOf(row, family) {
|
|
|
85
85
|
return notMine;
|
|
86
86
|
if (!row.categories.includes(family.category))
|
|
87
87
|
return notMine;
|
|
88
|
-
if (row.credentialType !== 'oauth' && row.credentialType !== 'api_key')
|
|
89
|
-
return notMine;
|
|
90
88
|
if ('classify' in family) {
|
|
91
|
-
|
|
89
|
+
const metadata = rowFactsOf(row);
|
|
90
|
+
let type;
|
|
91
|
+
// The id's type is only a hint; the vault's auth method determines serving.
|
|
92
|
+
switch (metadata.authMethod) {
|
|
93
|
+
case 'apikey':
|
|
94
|
+
type = 'api_key';
|
|
95
|
+
break;
|
|
96
|
+
case 'chatgpt':
|
|
97
|
+
case 'antigravity':
|
|
98
|
+
case 'oauth':
|
|
99
|
+
type = 'oauth';
|
|
100
|
+
break;
|
|
101
|
+
default:
|
|
102
|
+
return { kind: 'refused', code: 'unknown-auth-method' };
|
|
103
|
+
}
|
|
92
104
|
const facts = {
|
|
93
105
|
credentialId: row.id,
|
|
94
|
-
credentialType:
|
|
106
|
+
credentialType: type,
|
|
95
107
|
categories: row.categories,
|
|
96
108
|
refreshAdapter: row.refreshAdapter,
|
|
97
|
-
...
|
|
109
|
+
...metadata,
|
|
98
110
|
};
|
|
99
111
|
if (facts.providerIds === undefined)
|
|
100
112
|
return { kind: 'refused', code: 'unmapped' };
|
|
@@ -103,7 +115,7 @@ function credentialTypeOf(row, family) {
|
|
|
103
115
|
if (result.kind === 'not-mine')
|
|
104
116
|
return notMine;
|
|
105
117
|
if (result.kind === 'mine' && typeof result.member === 'string')
|
|
106
|
-
return { kind: 'mine', type
|
|
118
|
+
return { kind: 'mine', type, member: result.member };
|
|
107
119
|
if (result.kind === 'refused' &&
|
|
108
120
|
typeof result.code === 'string' &&
|
|
109
121
|
/^[a-z][a-z0-9-]{0,31}$/.test(result.code) &&
|
|
@@ -116,6 +128,8 @@ function credentialTypeOf(row, family) {
|
|
|
116
128
|
}
|
|
117
129
|
return { kind: 'refused', code: 'unclassified' };
|
|
118
130
|
}
|
|
131
|
+
if (row.credentialType !== 'oauth' && row.credentialType !== 'api_key')
|
|
132
|
+
return notMine;
|
|
119
133
|
if (row.credentialType === 'oauth')
|
|
120
134
|
return row.refreshAdapter === family.refreshAdapter
|
|
121
135
|
? { kind: 'mine', type: 'oauth' }
|
|
@@ -314,8 +314,17 @@ export class ClaustrumConsumer {
|
|
|
314
314
|
this.#refreshing = undefined;
|
|
315
315
|
});
|
|
316
316
|
this.#track(this.#refreshing);
|
|
317
|
+
this.#notifyDiscovery(this.#refreshing);
|
|
317
318
|
return this.#refreshing;
|
|
318
319
|
}
|
|
320
|
+
#notifyDiscovery(promise) {
|
|
321
|
+
try {
|
|
322
|
+
this.#options.onDiscovery?.(promise);
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
this.#options.onError?.(error);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
319
328
|
/**
|
|
320
329
|
* Poll in the background and open the vault and insula watches. Until the
|
|
321
330
|
* vault watch is accepted, and whenever it is unavailable, every tick lists
|
|
@@ -571,6 +580,13 @@ export class ClaustrumConsumer {
|
|
|
571
580
|
/** The hub's handle on this member's memory. */
|
|
572
581
|
#hubHooks() {
|
|
573
582
|
return {
|
|
583
|
+
discovery: (promise) => {
|
|
584
|
+
const hub = this.#hub;
|
|
585
|
+
if (!hub || !this.#options.onDiscovery || this.#shutdown.signal.aborted)
|
|
586
|
+
return;
|
|
587
|
+
const discovery = this.#track(promise.then((outcome) => this.#hubOutcome(hub, outcome)));
|
|
588
|
+
this.#notifyDiscovery(discovery);
|
|
589
|
+
},
|
|
574
590
|
install: (roster) => {
|
|
575
591
|
if (this.#shutdown.signal.aborted)
|
|
576
592
|
return;
|
|
@@ -607,6 +623,9 @@ export class ClaustrumConsumer {
|
|
|
607
623
|
*/
|
|
608
624
|
async #hubRefresh(hub) {
|
|
609
625
|
const outcome = await hub.refresh();
|
|
626
|
+
return this.#hubOutcome(hub, outcome);
|
|
627
|
+
}
|
|
628
|
+
#hubOutcome(hub, outcome) {
|
|
610
629
|
this.#assertOpen();
|
|
611
630
|
if (!outcome)
|
|
612
631
|
return undefined;
|
|
@@ -788,6 +807,8 @@ export class ClaustrumConsumer {
|
|
|
788
807
|
this.#assertOpen();
|
|
789
808
|
await declineVaultRoute(this.#options.rosterPath, routeId);
|
|
790
809
|
this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
|
|
810
|
+
if (this.#roster)
|
|
811
|
+
this.#hub?.publishRoster(this.#roster);
|
|
791
812
|
// A hub member shares kept receipts with every other member, so they are
|
|
792
813
|
// retained against all members' rosters, never against this one alone.
|
|
793
814
|
if (this.#hub)
|
|
@@ -799,6 +820,8 @@ export class ClaustrumConsumer {
|
|
|
799
820
|
this.#assertOpen();
|
|
800
821
|
await acceptVaultRoute(this.#options.rosterPath, routeId);
|
|
801
822
|
this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
|
|
823
|
+
if (this.#roster)
|
|
824
|
+
this.#hub?.publishRoster(this.#roster);
|
|
802
825
|
}
|
|
803
826
|
/**
|
|
804
827
|
* Set the order vault accounts are tried in (`reorderVaultRoster`), then
|
|
@@ -809,6 +832,8 @@ export class ClaustrumConsumer {
|
|
|
809
832
|
this.#assertOpen();
|
|
810
833
|
const result = await reorderVaultRoster(this.#options.rosterPath, routeIds);
|
|
811
834
|
this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
|
|
835
|
+
if (this.#roster)
|
|
836
|
+
this.#hub?.publishRoster(this.#roster);
|
|
812
837
|
return result;
|
|
813
838
|
}
|
|
814
839
|
/**
|