@cortexkit/opencode-openai-auth 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ChatGPT Plus/Pro OAuth support for [OpenCode](https://opencode.ai).
4
4
 
5
- This OpenCode plugin lets OpenCode talk to the OpenAI Codex backend using a ChatGPT Plus/Pro subscription instead of a pay-as-you-go API key. It rewrites OpenCode's outbound OpenAI requests into Codex's request shape, filters the model list to OAuth-eligible models, zeroes provider costs for those models, and adds a prompt-cache stabilizer.
5
+ This OpenCode plugin lets OpenCode talk to the OpenAI Codex backend using a ChatGPT Plus/Pro subscription instead of a pay-as-you-go API key. It rewrites OpenCode's outbound OpenAI requests into Codex's request shape, filters the model list to OAuth-eligible models, and zeroes provider costs for those models.
6
6
 
7
7
  The plugin registers the built-in `openai` provider id. OpenCode loads external plugins after its built-ins, so this package supersedes OpenCode's internal OpenAI auth hook without any change to your model configuration.
8
8
 
@@ -10,7 +10,7 @@ The plugin registers the built-in `openai` provider id. OpenCode loads external
10
10
 
11
11
  ```json
12
12
  {
13
- "plugin": ["@cortexkit/opencode-openai-auth@0.1.0"]
13
+ "plugin": ["@cortexkit/opencode-openai-auth@0.10.0"]
14
14
  }
15
15
  ```
16
16
 
@@ -25,7 +25,6 @@ Restart OpenCode after changing plugin config, then authenticate:
25
25
  - ChatGPT Plus/Pro OAuth login (browser and headless device flows), plus a manual API-key fallback.
26
26
  - Codex request rewriting for OAuth requests, with Codex identity parity.
27
27
  - OAuth model filtering and zero-cost display.
28
- - Prompt-cache stabilizer (`web_search`) that keeps tool-continuation requests on the backend's cached path (on by default).
29
28
  - Multiple ChatGPT accounts with automatic reactive fallback on rate limits, `main-first`, `fallback-first`, or sticky-balanced routing, and a per-account quota killswitch.
30
29
  - Per-turn quota tracking (5-hour + weekly windows) on both transports, with a sidebar readout and an explicit all-accounts refresh.
31
30
  - Idle prompt-cache keep-warm, with an optional subagent mode and main-only sustain mode.
@@ -66,15 +65,14 @@ Settings resolve as environment variable → config file (`~/.config/opencode/op
66
65
 
67
66
  | Config field | Environment variable | Default | Purpose |
68
67
  | --- | --- | --- | --- |
69
- | `webSearch` | `CORTEXKIT_OPENAI_AUTH_NO_WEB_SEARCH` (set to disable) | `true` | Inject the `web_search` prompt-cache stabilizer. |
70
68
  | `webSockets` | `CORTEXKIT_OPENAI_AUTH_WEBSOCKETS` | `false` | Use the Codex Responses WebSocket transport instead of HTTP. |
71
69
  | `rawWebSocket` | `CORTEXKIT_OPENAI_AUTH_RAW_WS` | `false` | Use the hand-rolled raw TCP/TLS client with Codex-style incremental streaming. Bun uses `Bun.connect`; Node/OpenCode Desktop uses `node:net`/`node:tls`. |
72
- | `responsesLite` | `CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE` | `false` | Send `gpt-5.6-sol`/`-terra`/`-luna` requests in Codex's Responses Lite shape, matching the Codex CLI. Bypasses the `web_search` stabilizer for these models. |
70
+ | `responsesLite` | `CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE` | `false` | Send `gpt-5.6-sol`/`-terra`/`-luna` requests in Codex's Responses Lite shape, matching the Codex CLI. |
73
71
  | `dump` | `CORTEXKIT_OPENAI_AUTH_DUMP` | `false` | Dump final Codex request bodies for cache debugging. |
74
72
  | `dumpDir` | `OPENCODE_OPENAI_AUTH_DUMP_DIR` | OS temp dir: `opencode-openai-auth-dumps` | Directory for request dump files. |
75
73
  | `codexApiEndpoint` | `CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT` | `https://chatgpt.com/backend-api/codex/responses` | Send rewritten Codex requests to a compatible proxy/relay instead of ChatGPT's backend endpoint. |
76
74
 
77
- See the [repository README](https://github.com/cortexkit/openai-auth#readme) for transport differences and why `web_search` is needed.
75
+ See the [repository README](https://github.com/cortexkit/openai-auth#readme) for transport differences.
78
76
 
79
77
  `sticky-balanced` places a cold session by least projected quota pressure, then keeps its SHA-256-keyed sidebar-state pin for up to seven days. It does not rebalance mid-session or use a Retry-After hold; it migrates only after confirmed exhaustion or permanent auth failure. Stale or unknown quota is excluded from weighted placement; when the killswitch is enabled, accounts below their per-account threshold are also excluded from both weighted placement AND the mode-fallback fail-open branch — that branch otherwise orders by `resetCreditsApplicable` first, then configured order, then account id. Subagents have separate pins and reuse them when resumed.
80
78
 
@@ -1,2 +1,2 @@
1
- import{Z as _}from"./index-338z7171.js";import{chmod as L,mkdir as M,readdir as W,readFile as $,rename as R,rmdir as S,unlink as X,writeFile as U}from"node:fs/promises";import{join as N,resolve as Y}from"node:path";var A=_("rpc");function E(q){try{return process.kill(q,0),!0}catch(H){return H.code==="EPERM"}}function C(q){return/^(?:openai-auth-)?[0-9a-f]{16}$/.test(q)}function O(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)&&typeof q.pid==="number"&&Number.isFinite(q.pid)&&typeof q.port==="number"&&Number.isFinite(q.port)}async function Z(q){A.debug("rpc corrupt port file",{pid:process.pid,portFile:q}),await X(q).catch(()=>{})}async function w(q,H,I={}){let J=async()=>{if(await M(q,{recursive:!0,mode:I.secureDir?448:void 0}),I.secureDir)await L(q,448);await I.beforeWrite?.();let z={...H,startedAt:Date.now()},K=N(q,`port-${H.pid}.json`),B=`${K}.${process.pid}.tmp`;return await U(B,JSON.stringify(z),{encoding:"utf8",mode:384}),await R(B,K),K};try{return await J()}catch(z){if(z.code==="ENOENT")return await J();throw z}}async function x(q,H){let I;try{I=await W(q,{withFileTypes:!0})}catch(z){if(z.code==="ENOENT")return;throw z}let J=Y(H);for(let z of I){if(!z.isDirectory()||!C(z.name))continue;let K=N(q,z.name),B;try{B=await W(K)}catch(G){if(G.code==="ENOENT")continue;throw G}for(let G of B){if(!G.startsWith("port-")||!G.endsWith(".json"))continue;let Q=N(K,G),T;try{T=await $(Q,"utf8")}catch{continue}if(T===void 0)continue;let V;try{V=JSON.parse(T)}catch{await Z(Q);continue}if(!O(V)){await Z(Q);continue}if(!E(V.pid))await X(Q).catch(()=>{})}if(Y(K)!==J)await S(K).catch(()=>{})}}async function y(q,H){let I;try{I=await W(q)}catch{return null}let J=[];for(let B of I){if(!B.startsWith("port-")||!B.endsWith(".json"))continue;try{let G=JSON.parse(await $(N(q,B),"utf8"));if(Number.isFinite(G.port))if(E(G.pid))J.push(G);else X(N(q,B)).catch(()=>{})}catch{}}if(J.length===0)return null;let z=H!==void 0&&H>=1?J.filter((B)=>B.pid===H):[];return(z.length>0?z:J).sort((B,G)=>G.startedAt-B.startedAt)[0]??null}
1
+ import{Z as _}from"./index-sq36b120.js";import{chmod as L,mkdir as M,readdir as W,readFile as $,rename as R,rmdir as S,unlink as X,writeFile as U}from"node:fs/promises";import{join as N,resolve as Y}from"node:path";var A=_("rpc");function E(q){try{return process.kill(q,0),!0}catch(H){return H.code==="EPERM"}}function C(q){return/^(?:openai-auth-)?[0-9a-f]{16}$/.test(q)}function O(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)&&typeof q.pid==="number"&&Number.isFinite(q.pid)&&typeof q.port==="number"&&Number.isFinite(q.port)}async function Z(q){A.debug("rpc corrupt port file",{pid:process.pid,portFile:q}),await X(q).catch(()=>{})}async function w(q,H,I={}){let J=async()=>{if(await M(q,{recursive:!0,mode:I.secureDir?448:void 0}),I.secureDir)await L(q,448);await I.beforeWrite?.();let z={...H,startedAt:Date.now()},K=N(q,`port-${H.pid}.json`),B=`${K}.${process.pid}.tmp`;return await U(B,JSON.stringify(z),{encoding:"utf8",mode:384}),await R(B,K),K};try{return await J()}catch(z){if(z.code==="ENOENT")return await J();throw z}}async function x(q,H){let I;try{I=await W(q,{withFileTypes:!0})}catch(z){if(z.code==="ENOENT")return;throw z}let J=Y(H);for(let z of I){if(!z.isDirectory()||!C(z.name))continue;let K=N(q,z.name),B;try{B=await W(K)}catch(G){if(G.code==="ENOENT")continue;throw G}for(let G of B){if(!G.startsWith("port-")||!G.endsWith(".json"))continue;let Q=N(K,G),T;try{T=await $(Q,"utf8")}catch{continue}if(T===void 0)continue;let V;try{V=JSON.parse(T)}catch{await Z(Q);continue}if(!O(V)){await Z(Q);continue}if(!E(V.pid))await X(Q).catch(()=>{})}if(Y(K)!==J)await S(K).catch(()=>{})}}async function y(q,H){let I;try{I=await W(q)}catch{return null}let J=[];for(let B of I){if(!B.startsWith("port-")||!B.endsWith(".json"))continue;try{let G=JSON.parse(await $(N(q,B),"utf8"));if(Number.isFinite(G.port))if(E(G.pid))J.push(G);else X(N(q,B)).catch(()=>{})}catch{}}if(J.length===0)return null;let z=H!==void 0&&H>=1?J.filter((B)=>B.pid===H):[];return(z.length>0?z:J).sort((B,G)=>G.startedAt-B.startedAt)[0]??null}
2
2
  export{w as I,x as J,y as K};
@@ -0,0 +1,2 @@
1
+ import{Ea as a,Z as c}from"./index-sq36b120.js";import{createHash as zT,randomUUID as DT}from"node:crypto";import{chmod as KT,mkdir as UT,readFile as i,rename as BT,rm as QT,writeFile as bT}from"node:fs/promises";import{tmpdir as PT}from"node:os";import{dirname as FT,join as t}from"node:path";var x=["needs-login","mode-mismatch","corrupt-under-binding","manifest-unreadable","unbound-under-claustrum","orphan-tombstone","vault-cold","vault-reauth","identity-mismatch","no-handle","takeover-incomplete","new-local-family-under-claustrum","takeover-incomplete/vault-unavailable","takeover-incomplete/slot-absent"];function O(T){return T}function B(T,V){return T==="empty"?{...V,canonicalize:!0}:V}function CT(T){switch(T){case"real":return{kind:"LOCAL"};case"tombstone":case"empty":case"slot-absent":return{kind:"NEEDS_LOGIN"};case"gone":return{kind:"NEEDS_LOGIN",reason:"corrupt"}}return O(T)}function RT(T,V){switch(T){case"real":return V?{kind:"LOCAL"}:{kind:"INERT",reason:"needs-login"};case"tombstone":case"empty":case"slot-absent":return{kind:"INERT",reason:"mode-mismatch"};case"gone":return{kind:"INERT",reason:"corrupt-under-binding"}}return O(T)}function jT(T){switch(T){case"tombstone":case"empty":return{kind:"INERT",reason:"orphan-tombstone"};case"real":case"gone":case"slot-absent":return{kind:"INERT",reason:"unbound-under-claustrum"}}return O(T)}function JT(T,V){switch(V){case"serves":return B(T,{kind:"VAULT"});case"cold":return B(T,{kind:"INERT",reason:"vault-cold"});case"needs_reauth":return B(T,{kind:"INERT",reason:"vault-reauth"});case"identity_mismatch":return B(T,{kind:"INERT",reason:"identity-mismatch"});case"no_handle":return B(T,{kind:"INERT",reason:"no-handle"})}return O(V)}function ZT(T,V){switch(T){case"serves":return V===!1?{kind:"INERT",reason:"new-local-family-under-claustrum"}:{kind:"INERT",reason:"takeover-incomplete"};case"cold":case"needs_reauth":return{kind:"INERT",reason:"takeover-incomplete/vault-unavailable"};case"identity_mismatch":return{kind:"INERT",reason:"identity-mismatch"};case"no_handle":return{kind:"INERT",reason:"no-handle"}}return O(T)}function $T(T){switch(T){case"serves":return{kind:"VAULT",installTombstone:!0};case"cold":return{kind:"INERT",reason:"vault-cold",installTombstone:!0};case"needs_reauth":return{kind:"INERT",reason:"vault-reauth",installTombstone:!0};case"identity_mismatch":return{kind:"INERT",reason:"identity-mismatch"};case"no_handle":return{kind:"INERT",reason:"no-handle"}}return O(T)}function GT(T){switch(T){case"serves":case"cold":case"needs_reauth":return{kind:"INERT",reason:"takeover-incomplete/slot-absent"};case"identity_mismatch":return{kind:"INERT",reason:"identity-mismatch"};case"no_handle":return{kind:"INERT",reason:"no-handle"}}return O(T)}function XT(T,V,L){switch(T){case"tombstone":case"empty":return JT(T,V);case"real":return ZT(V,L);case"gone":return $T(V);case"slot-absent":return GT(V)}return O(T)}function nT(T){if(T.manifest==="unreadable")return{kind:"INERT",reason:"manifest-unreadable"};switch(T.mode){case"local":return T.manifest==="present"?RT(T.local,T.verifiedInProcessLogin):CT(T.local);case"claustrum":if(T.manifest==="absent")return jT(T.local);if(T.manifest==="present")return XT(T.local,T.vault(),T.fingerprintMatch);return O(T.manifest)}return O(T.mode)}var n=["primary","secondary"],s={primary:300,secondary:10080};function y(T){return Number.isInteger(T)?String(T):String(Math.round(T*10)/10)}function OT(T,V){let L=T!==void 0&&Number.isFinite(T)&&T>0?T:s[V];if(L<60)return`${y(L)}m`;if(L<1440)return`${y(L/60)}h`;return`${y(L/1440)}d`}function YT(T){if(!T)return[];let V=[];for(let L of n){let N=T[L];if(!N)continue;let E=N.windowMinutes,_=E!==void 0&&Number.isFinite(E)&&E>0?E:s[L];V.push({key:L,label:OT(_,L),window:N,windowMs:_*60000})}return V}var I=c("sidebar"),WT="OPENCODE_OPENAI_AUTH_SIDEBAR_STATE_FILE",yT=t(PT(),"opencode-openai-auth"),e=t(yT,"sidebar-state.json"),HT=/^[a-f0-9]{64}$/,S=604800000,MT=256,TT=3600000;function F(T){return zT("sha256").update(T).digest("hex")}function qT(T){return typeof T==="number"&&Number.isFinite(T)&&T>=0?T:void 0}function A(T){let V=qT(T);return V!==void 0?{resetCredits:V}:{}}var IT=new Set(["vault","needsLogin","local","inert"]),ST=new Set([...x,"corrupt"]);function h(T){if(T===null||typeof T!=="object"||Array.isArray(T))return;let V=T;if(typeof V.state!=="string"||!IT.has(V.state))return;let N={state:V.state};if(typeof V.reason==="string"&&ST.has(V.reason))N.reason=V.reason;return N}function vT(T){if(T===null||typeof T!=="object"||Array.isArray(T))return;let V={};for(let[L,N]of Object.entries(T)){if(N===null||typeof N!=="object"||Array.isArray(N))continue;let E=N;if(typeof E.activeId!=="string"||typeof E.route!=="string"||typeof E.updatedAt!=="number"||!Number.isFinite(E.updatedAt))continue;V[L]={activeId:E.activeId,route:E.route,updatedAt:E.updatedAt}}return Object.keys(V).length>0?V:void 0}function fT(T){if(T===null||typeof T!=="object"||Array.isArray(T))return;let V={};for(let[L,N]of Object.entries(T)){if(!HT.test(L)||N===null||typeof N!=="object"||Array.isArray(N))continue;let E=N;if(typeof E.accountId!=="string"||E.accountId.length===0||typeof E.assignedAt!=="number"||!Number.isFinite(E.assignedAt)||E.assignedAt<0||typeof E.lastSeenAt!=="number"||!Number.isFinite(E.lastSeenAt)||E.lastSeenAt<0||typeof E.inputBytes!=="number"||!Number.isFinite(E.inputBytes)||E.inputBytes<0)continue;let _=E.quotaCheckedAt;if(_!==void 0&&(typeof _!=="number"||!Number.isFinite(_)||_<0))continue;let C=E.wireAccountId;V[L]={accountId:E.accountId,assignedAt:E.assignedAt,lastSeenAt:E.lastSeenAt,inputBytes:E.inputBytes,..._===void 0?{}:{quotaCheckedAt:_},...typeof C==="string"?{wireAccountId:C}:{}}}return Object.keys(V).length>0?V:void 0}function z(){return process.env[WT]||e}function EV(T){switch(T.kind){case"LOCAL":return{state:"local"};case"VAULT":return{state:"vault"};case"INERT":return{state:"inert",reason:T.reason};case"NEEDS_LOGIN":return T.reason==="corrupt"?{state:"needsLogin",reason:"corrupt"}:{state:"needsLogin"}}}var K={main:{quota:null,killed:!1},fallbacks:[],activeId:void 0,route:"main",lastUpdated:0};function v(T){if(T===null||typeof T!=="object"||Array.isArray(T))return K;let V=T,L=V.main,N;if(L!==null&&typeof L==="object"&&!Array.isArray(L)){let R=L;N={quota:"quota"in R?R.quota:null,killed:typeof R.killed==="boolean"?R.killed:!1,...typeof R.mainAccountId==="string"?{mainAccountId:R.mainAccountId}:{},...(()=>{let Y=h(R.custody);return Y?{custody:Y}:{}})(),...typeof R.quotaBackedOff==="boolean"?{quotaBackedOff:R.quotaBackedOff}:{},...typeof R.quotaBackoffUntil==="number"?{quotaBackoffUntil:R.quotaBackoffUntil}:{},...typeof R.refreshBackedOff==="boolean"?{refreshBackedOff:R.refreshBackedOff}:{},...typeof R.refreshBackoffUntil==="number"?{refreshBackoffUntil:R.refreshBackoffUntil}:{},...A(R.resetCredits)}}else N={quota:null,killed:!1};let E=V.fallbacks,_=Array.isArray(E)?E.filter((R)=>R!==null&&typeof R==="object"&&!Array.isArray(R)&&typeof R.id==="string").map((R)=>{let Y=h(R.custody);return{id:R.id,label:typeof R.label==="string"?R.label:void 0,...typeof R.accountId==="string"?{accountId:R.accountId}:{},quota:"quota"in R?R.quota:null,killed:typeof R.killed==="boolean"?R.killed:!1,enabled:typeof R.enabled==="boolean"?R.enabled:!0,...A(R.resetCredits),...Y?{custody:Y}:{}}}):[],C=typeof V.activeId==="string"?V.activeId:void 0,j=typeof V.route==="string"?V.route:K.route,Z=typeof V.lastUpdated==="number"?V.lastUpdated:0,J=typeof V.planType==="string"?V.planType:void 0,G=typeof V.credits==="number"?V.credits:void 0,$=vT(V.activeRouting),X=fT(V.stickyAssignments);return{main:N,fallbacks:_,activeId:C,route:j,lastUpdated:Z,...$!==void 0?{activeRouting:$}:{},...X!==void 0?{stickyAssignments:X}:{},...J!==void 0?{planType:J}:{},...G!==void 0?{credits:G}:{}}}async function _V(T=z()){try{let V=await i(T,"utf8");return v(JSON.parse(V))}catch{return K}}var kT=3600000,p=128;function VT(T,V,L=Date.now()){if(!(T.updatedAt>=L-kT&&T.updatedAt<=L))return!1;if(V===void 0)return!0;return T.activeId==="main"||V.some((E)=>E.enabled!==!1&&E.killed!==!0&&E.id===T.activeId)}function xT(T,V=Date.now()){let L=T?.spendControl;if(L?.reached!==!0||typeof L.resetsAt!=="string")return;let N=Date.parse(L.resetsAt);if(!Number.isFinite(N)||N<=V)return;return{resetsAt:L.resetsAt,resetAtMs:N}}function AT(T,V=Date.now()){let L;for(let E of n){let _=T?.[E];if(typeof _?.resetsAt!=="string"||!Number.isFinite(_.usedPercent)||_.usedPercent<100)continue;let C=Date.parse(_.resetsAt);if(!Number.isFinite(C)||C<=V)continue;if(!L||C<L.resetAtMs)L={resetsAt:_.resetsAt,resetAtMs:C}}let N=xT(T,V);if(N&&(!L||N.resetAtMs<L.resetAtMs))L=N;return L}function Q(T,V=Date.now()){return AT(T,V)!==void 0}function hT(T,V,L=Date.now()){if(!V||T.route!=="sticky-balanced")return;let N=T.stickyAssignments?.[F(V)];if(!N||N.lastSeenAt<L-S)return;if(N.accountId==="main")return T.main?.killed||Q(T.main?.quota,L)?void 0:"main";let E=T.fallbacks?.find((_)=>_.id===N.accountId);if(!E||E.enabled===!1||E.killed===!0||Q(E.quota,L))return;return E.id}function CV(T,V,L=Date.now()){if(!V)return{activeId:T.activeId??"main",route:T.route};let N=V?T.activeRouting?.[V]:void 0,E=N?.activeId==="main"?T.main.quota:T.fallbacks.find((Z)=>Z.id===N?.activeId)?.quota;if(N&&VT(N,T.fallbacks,L)&&!Q(E,L))return{activeId:N.activeId,route:N.route};let _=hT(T,V,L);if(_)return{activeId:_,route:T.route};let C=T.fallbacks.filter((Z)=>Z.enabled&&!Z.killed),j=C.find((Z)=>!Q(Z.quota,L))??C[0];return{activeId:T.route==="fallback-first"&&j?j.id:"main",route:T.route}}function LT(T,V,L=Date.now(),N){if(!T)return;let E=Object.entries(T).filter(([C,j])=>C!==N&&VT(j,V,L)),_=E.length<=p?E:E.sort((C,j)=>j[1].updatedAt-C[1].updatedAt).slice(0,p);return _.length>0?Object.fromEntries(_):void 0}function W(T,V,L=Date.now(),N){if(!T)return;let E=0,_=0,C=0,j=[];for(let[J,G]of Object.entries(T)){if(J===N){C+=1;continue}if(G.lastSeenAt<L-S){_+=1;continue}if(V!==void 0&&!V.has(G.accountId)){E+=1;continue}j.push([J,G])}let Z=E+_+C;if(Z>0)I.debug("pruned sticky assignments",{pid:process.pid,removed:Z,reasons:{"account-not-in-roster":E,expired:_,"explicit-removal":C}});return j.length>0?Object.fromEntries(j):void 0}function pT(T,V){let L=Object.keys(T).length-MT;if(L<=0)return T;let N=new Set(Object.entries(T).filter(([E])=>E!==V).sort(([E,_],[C,j])=>_.lastSeenAt-j.lastSeenAt||E.localeCompare(C)).slice(0,L).map(([E])=>E));return Object.fromEntries(Object.entries(T).filter(([E])=>!N.has(E)))}function rT(T,V){if(T===V)return!0;if(!T||!V)return!1;let L=Object.entries(T);if(L.length!==Object.keys(V).length)return!1;return L.every(([N,E])=>Object.is(V[N],E))}function r(T,V,L,N){return T!==void 0&&V.has(T.accountId)&&!L.has(T.accountId)&&T.lastSeenAt>=N-S}function w(T,V,L,N){return V>T.inputBytes||L-T.lastSeenAt>=TT||T.wireAccountId===void 0&&N!==void 0}function m(T,V){return typeof T.wireAccountId==="string"&&typeof V==="string"&&T.wireAccountId!==V}function wT(T){let V=new Map(T),L={get size(){return V.size},has:(N)=>V.has(N),get:(N)=>V.get(N),entries:()=>V.entries(),keys:()=>V.keys(),values:()=>V.values(),forEach:(N,E)=>{V.forEach((_,C)=>{N.call(E,_,C,L)})},[Symbol.iterator]:()=>V[Symbol.iterator]()};return Object.freeze(L)}function mT(T,V,L){let N=new Map;for(let[E,_]of Object.entries(T??{})){if(E===L)continue;if(_.quotaCheckedAt!==V[_.accountId])continue;N.set(_.accountId,(N.get(_.accountId)??0)+_.inputBytes)}return wT(N)}function f(T){if(T===void 0)return;return new Set(["main",...T.filter((V)=>V.enabled!==!1&&V.killed!==!0).map((V)=>V.id)])}var H=Promise.resolve(),dT=3,uT=1e4,lT=15000;function D(T){let V=H.then(T);return H=V.catch(()=>{}),V}function RV(T,V=z()){return D(()=>q(T,V))}async function NT(T){try{return ET(await M(T))}catch{return K}}async function M(T){try{return await i(T,"utf8")}catch(V){if(V.code==="ENOENT")return"";throw V}}function ET(T){if(T==="")return K;try{return v(JSON.parse(T))}catch{return K}}async function gT(T){await _T(T);let V=Date.now()+lT;while(Date.now()<=V){let L=await a({name:"sidebar-write",path:T,ttlMs:uT,renew:!0});if(L)return L;await new Promise((N)=>setTimeout(N,10))}throw Error("Timed out waiting for the sidebar state write lock")}async function _T(T){let V=FT(T);if(await UT(V,{recursive:!0,mode:448}),T!==e)return;await KT(V,448).catch((L)=>{I.warn("sidebar directory permission remediation failed",{pid:process.pid,error:L instanceof Error?L.message:String(L)})})}async function U(T,V,L){let N=await gT(T);try{for(let C=0;C<dT;C+=1){let j=await M(T),Z=V(ET(j));if(!Z)return;if(C===0)await L?.beforeRecheck?.();if(await M(T)!==j)continue;await q(Z,T);return}let E=await NT(T),_=V(E);if(_)await q(_,T)}finally{await N.release()}}function b(T){let V;for(let L of[T?.primary?.checkedAt,T?.secondary?.checkedAt,T?.checkedAt])if(typeof L==="number"&&Number.isFinite(L))V=V===void 0?L:Math.max(V,L);return V}function d(T,V){let L=b(T),N=b(V);if(N!==void 0&&(L===void 0||N>L))return V;return T}function u(T,V){return T!==void 0&&V!==void 0&&T===V}function P(T,V){let L=T?.checkedAt;if(typeof L==="number"&&Number.isFinite(L))return L;if(typeof V==="number"&&Number.isFinite(V))return V;return}function l(T,V,L,N,E){if(T&&V){let _=P(T,N),C=P(V,E);if(C!==void 0&&(_===void 0||C>_))return V;return T}return L?V:T}function g(T,V){if(T.spendControl!==void 0)return T.spendControl;if(T.spendControlCleared===!0)return;return V.spendControl}function o(T,V){if(!T)return V;if(!V)return T;let L=b(T),N=b(V),E=N!==void 0&&(L===void 0||N>L),_=l(T.primary,V.primary,E,T.checkedAt,V.checkedAt),C=l(T.secondary,V.secondary,E,T.checkedAt,V.checkedAt),j=E?g(V,T):g(T,V),Z=j===void 0&&(T.spendControlCleared===!0||V.spendControlCleared===!0),J;for(let R of[P(_),P(C)])if(R!==void 0)J=J===void 0?R:Math.max(J,R);let{spendControl:G,spendControlCleared:$,...X}=T;return{...X,primary:_,secondary:C,...j!==void 0?{spendControl:j}:{},...Z?{spendControlCleared:!0}:{},checkedAt:J??T.checkedAt}}function jV(T,V=z(),L){return D(async()=>{await U(V,(N)=>{let E=new Map(N.fallbacks.map((J)=>[J.id,J])),_=u(T.main.mainAccountId,N.main.mainAccountId),C=_?o(T.main.quota,N.main.quota):d(T.main.quota,N.main.quota),j=Date.now(),Z=W(N.stickyAssignments,f(T.fallbacks),j);return{...N,...T,main:{...T.main,quota:C,mainAccountId:_?T.main.mainAccountId:C===N.main.quota&&C!==T.main.quota?N.main.mainAccountId:T.main.mainAccountId},fallbacks:T.fallbacks.map((J)=>{let G=E.get(J.id),$=u(J.accountId,G?.accountId),X=$?o(J.quota,G?.quota??null):d(J.quota,G?.quota??null);return{...J,quota:X,accountId:$?J.accountId:X===G?.quota&&X!==J.quota?G?.accountId:J.accountId}}),activeId:N.activeId,activeRouting:N.activeRouting,stickyAssignments:Z,lastUpdated:Math.max(j,N.lastUpdated+1)}},L)})}function JV(T,V,L=z(),N){return D(async()=>{await U(L,(E)=>{let _=LT({...E.activeRouting,[T.sessionId]:{activeId:T.activeId,route:T.route,updatedAt:T.updatedAt}},V,Date.now()),C=W(E.stickyAssignments,f(V),Date.now());return{...E,activeId:T.activeId,route:T.route,activeRouting:_,stickyAssignments:C,lastUpdated:Math.max(Date.now(),E.lastUpdated+1)}},N)})}function ZV(T,V=z()){return D(async()=>{await U(V,(L)=>({...L,activeId:T.activeId,route:T.route,lastUpdated:Math.max(Date.now(),L.lastUpdated+1)}))})}function $V(T,V,L=z(),N){return D(async()=>{await U(L,(E)=>{let _=Date.now(),C=LT(E.activeRouting,V,_,T),j=W(E.stickyAssignments,f(V),_,F(T));return{...E,activeRouting:C,stickyAssignments:j,lastUpdated:Math.max(Date.now(),E.lastUpdated+1)}},N)})}async function GV(T,V=z(),L){let N=F(T.sessionId),E=new Set(T.validPinnedAccountIds),_=new Set(T.excludeAccountIds),C=(await NT(V)).stickyAssignments?.[N];if(r(C,E,_,T.now)&&!m(C,T.wireAccountIdByAccount?.[C.accountId])&&!w(C,T.requestBytes,T.now,T.wireAccountIdByAccount?.[C.accountId]))return C;let j;return await D(async()=>{await U(V,(Z)=>{let J=W(Z.stickyAssignments,E,T.now),G=!rT(Z.stickyAssignments,J),$=J?.[N],X=$!==void 0&&m($,T.wireAccountIdByAccount?.[$.accountId]);if(r($,E,_,T.now)&&!X){let Y=w($,T.requestBytes,T.now,T.wireAccountIdByAccount?.[$.accountId]),k=Y?{...$,inputBytes:Math.max($.inputBytes,T.requestBytes),...$.wireAccountId===void 0&&T.wireAccountIdByAccount?.[$.accountId]!==void 0?{wireAccountId:T.wireAccountIdByAccount?.[$.accountId]}:{},...T.now-$.lastSeenAt>=TT?{lastSeenAt:T.now}:{}}:$;if(j=k,!G&&!Y)return;return{...Z,stickyAssignments:{...J,[N]:k},lastUpdated:Math.max(T.now,Z.lastUpdated+1)}}let R=T.choose(mT(J,T.quotaCheckedAtByAccount,X?N:void 0));if(!R){if(j=void 0,!G)return;return{...Z,stickyAssignments:J,lastUpdated:Math.max(T.now,Z.lastUpdated+1)}}return j={accountId:R.accountId,assignedAt:T.now,lastSeenAt:T.now,inputBytes:T.requestBytes,...R.quotaCheckedAt===void 0?{}:{quotaCheckedAt:R.quotaCheckedAt},...T.wireAccountIdByAccount?.[R.accountId]===void 0?{}:{wireAccountId:T.wireAccountIdByAccount?.[R.accountId]}},{...Z,stickyAssignments:pT({...J,[N]:j},N),lastUpdated:Math.max(T.now,Z.lastUpdated+1)}},L)}),j}async function XV(T,V=z()){let L=F(T),N=!1;return await D(async()=>{await U(V,(E)=>{let _=E.stickyAssignments;if(_?.[L]===void 0){N=!1;return}N=!0;let{[L]:C,...j}=_;return{...E,...Object.keys(j).length>0?{stickyAssignments:j}:{stickyAssignments:void 0},lastUpdated:Math.max(Date.now(),E.lastUpdated+1)}})}),N}async function q(T,V){let L=`${V}.${DT()}.tmp`;try{await _T(V),await bT(L,JSON.stringify(v(T)),{encoding:"utf8",mode:384}),await BT(L,V)}catch(N){throw await QT(L,{force:!0}).catch(()=>{}),I.warn("sidebar write failed",{pid:process.pid,error:N instanceof Error?N.message:String(N)}),N}}function OV(){return H}function YV(T){let V=T.activeId;if(V&&V!=="main"){let L=T.fallbacks.find((N)=>N.enabled&&N.id===V);if(L)return{id:L.id,name:L.label??L.id,quota:L.quota,killed:L.killed}}return{id:"main",name:"main",quota:T.main.quota,killed:T.main.killed}}function zV(T){let V=T?.primary?.usedPercent??null,L=T?.secondary?.usedPercent??null,N=YT(T);return{primaryUsedPercent:V,secondaryUsedPercent:L,text:N.length===0?null:N.map(({label:E,window:_})=>`${E}: ${Math.round(_.usedPercent)}%`).join(" ")}}var oT=300000,cT=0.01,aT=1;function DV(T,V,L){if(!T.resetsAt)return null;let N=new Date(T.resetsAt).getTime();if(!Number.isFinite(N))return null;let E=N-V,_=L-E;if(_<oT)return null;if(_<V*cT)return null;if(_>=V)return null;let C=T.usedPercent,j=Math.min(Math.max(_/V*100,0),100),Z=C-j,J=Math.abs(Z)<aT?"on-pace":Z>0?"deficit":"reserve",G=null;if(C>0){let $=_*100/C,X=E+$;if(X<N)G=new Date(X).toISOString()}return{pacePercent:j,deltaPercent:Z,state:J,runsOutAt:G}}
2
+ export{nT as c,OT as d,YT as e,S as f,MT as g,F as h,z as i,EV as j,K as k,v as l,_V as m,kT as n,p as o,VT as p,xT as q,AT as r,Q as s,hT as t,CV as u,LT as v,W as w,RV as x,jV as y,JV as z,ZV as A,$V as B,GV as C,XV as D,OV as E,YV as F,zV as G,DV as H};
@@ -0,0 +1,2 @@
1
+ function $(q){if(q==null||q==="")return;let z=typeof q==="number"?q:Number(q);if(Number.isFinite(z)){let G=z<100000000000?z*1000:z,K=new Date(G);return Number.isNaN(K.getTime())?void 0:K.toISOString()}let B=new Date(q);return Number.isNaN(B.getTime())?void 0:B.toISOString()}function k(q){let z=Number(q);return Number.isFinite(z)&&z>0?z:void 0}function I(q){return typeof q==="number"&&Number.isFinite(q)&&q>=0?q:void 0}function T(q,z){let B=q.get(z);if(B===null||B.trim()==="")return;let G=Number(B);if(!Number.isFinite(G)||G<0||G>100)return;let K=z.slice(0,-13),Y=k(q.get(`${K}-window-minutes`)),J=$(q.get(`${K}-reset-at`)??void 0);if(G===0&&q.get(`${K}-window-minutes`)==="0"&&!J)return;return{usedPercent:G,remainingPercent:100-G,resetsAt:J,checkedAt:Date.now(),...Y!==void 0?{windowMinutes:Y}:{}}}var f=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function M(q,z){let B=q.get(z);if(B===null)return"absent";if(B.trim()==="")return"invalid";let G=Number(B);return Number.isFinite(G)&&G>=0&&G<=100?"valid":"invalid"}function C(q){if(f.some((K)=>M(q,K)==="invalid"))return{};let z={},B=T(q,"x-codex-primary-used-percent");if(B)z.primary=B;let G=T(q,"x-codex-secondary-used-percent");if(G)z.secondary=G;return z}function H(q){let z=f.map((B)=>M(q,B));return z.includes("valid")&&!z.includes("invalid")}function U(q){if(!q)return;if(!Number.isFinite(q.used_percent)||q.used_percent<0||q.used_percent>100)return;let z=k(q.window_minutes),B=$(q.reset_at);if(q.used_percent===0&&z===void 0&&!B)return;return{usedPercent:q.used_percent,remainingPercent:100-q.used_percent,resetsAt:B,checkedAt:Date.now(),...z!==void 0?{windowMinutes:z}:{}}}function _(q){let z={},B=U(q.rate_limits?.primary);if(B)z.primary=B;let G=U(q.rate_limits?.secondary);if(G)z.secondary=G;return z}function X(q){if(q==null||q==="")return;let z=Number(q);return Number.isFinite(z)&&z>=0?z:void 0}function W(q){if(!q)return;if(!Number.isFinite(q.used_percent)||q.used_percent<0||q.used_percent>100)return;let z=k(q.limit_window_seconds),B=$(q.reset_at);if(q.used_percent===0&&z===void 0&&!B)return;return{usedPercent:q.used_percent,remainingPercent:100-q.used_percent,resetsAt:B,checkedAt:Date.now(),...z!==void 0?{windowMinutes:z/60}:{}}}function R(q){let z={},B=W(q.rate_limit?.primary_window);if(B)z.primary=B;let G=W(q.rate_limit?.secondary_window);if(G)z.secondary=G;let K=I(q.rate_limit_reset_credits?.available_count);if(K!==void 0)z.resetCreditsAvailable=K;let Y=I(q.rate_limit_reset_credits?.applicable_available_count);if(Y!==void 0)z.resetCreditsApplicable=Y;let J=q.spend_control?.individual_limit;if(q.spend_control===null||J===null)z.spendControlCleared=!0;if(J&&typeof q.spend_control?.reached==="boolean"){let Z=X(J.limit),O=X(J.used),Q=X(J.remaining),x=X(J.used_percent),D=X(J.remaining_percent);if(Z!==void 0&&O!==void 0&&Q!==void 0&&x!==void 0&&D!==void 0)z.spendControl={limit:Z,used:O,remaining:Q,usedPercent:x,remainingPercent:D,resetsAt:$(J.reset_at),unit:J.unit,source:J.source,reached:q.spend_control.reached}}let V=q.credits;if(V&&typeof V.has_credits==="boolean"&&typeof V.unlimited==="boolean"&&typeof V.overage_limit_reached==="boolean"){let Z=X(V.balance);z.credits={hasCredits:V.has_credits,unlimited:V.unlimited,overageLimitReached:V.overage_limit_reached,...Z!==void 0?{balance:Z}:{}}}return z}
2
+ export{$ as lb,C as mb,H as nb,_ as ob,R as pb};