@simonesiega/codex-limits 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/copilot.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import{joinSession as A1}from"@github/copilot-sdk/extension";function PQ(Q){let Z=[];if(Q.windows.fiveHour)Z.push(AQ("5-hour",Q.windows.fiveHour));if(Q.windows.weekly)Z.push(AQ("Weekly",Q.windows.weekly));if(Z.length===0)Z.push(["Usage limits Unavailable"]);if(Z.push(kZ(Q)),Q.warnings.length>0)Z.push(["Warnings",...Q.warnings.map(($)=>`- ${$}`)]);return Z.map(($)=>$.join(`
1
+ import{joinSession as A1}from"@github/copilot-sdk/extension";function bQ(Q){let Z=[];if(Q.windows.fiveHour)Z.push(PQ("5-hour",Q.windows.fiveHour));if(Q.windows.weekly)Z.push(PQ("Weekly",Q.windows.weekly));if(Z.length===0)Z.push(["Usage limits Unavailable"]);if(Z.push(kZ(Q)),Q.warnings.length>0)Z.push(["Warnings",...Q.warnings.map(($)=>`- ${$}`)]);return Z.map(($)=>$.join(`
2
2
  `)).join(`
3
3
 
4
- `)}function AQ(Q,Z){let $=Z.remainingPercent;return[`${Q} ${LZ($)}`,`Remaining ${$===null?"Unknown":`${Math.round($)}% remaining`}`,bZ($),`Reset ${Z.resetsIn?`in ${Z.resetsIn}`:"unknown"}`]}function bZ(Q){if(Q===null)return`[${" ".repeat(22)}] Unknown`;let Z=Math.min(Math.max(Q,0),100),$=Math.round(Z/100*22);return`[${"=".repeat($)}${" ".repeat(22-$)}] ${Math.round(Z)}%`}function kZ(Q){let Z=Q.coupons?.available,G=[`Reset credits ${Z===null||Z===void 0?"Unknown":`${Z} ${Z===1?"credit":"credits"} available`}`],J=Q.coupons?.nextExpirationIn,z=Q.coupons?.nextExpirationDate,K=J&&z?`${J} (${z})`:J??z;if(K!==null&&K!==void 0)G.push(`Next expires ${K}`);return G}function LZ(Q){if(Q===null)return"Unknown";if(Q>=50)return"Healthy";if(Q>=15)return"Low";return"Critical"}function IQ(Q){return PQ(Q)}import{constants as _Z}from"node:fs";import{access as RZ,stat as yZ}from"node:fs/promises";import{homedir as fZ}from"node:os";import{join as b,normalize as s}from"node:path";function N(Q,Z){let $=Q[Z]?.trim();return $?$:null}function P(Q){return Q??process.env}var bQ="CODEX_LIMITS_HOME";function SZ(Q={}){let Z=P(Q.env),$=Q.homeDirectory??N(Z,"HOME")??N(Z,"USERPROFILE")??fZ(),G=Q.appData??N(Z,"APPDATA"),J=Q.localAppData??N(Z,"LOCALAPPDATA"),z=[];if(D(z,N(Z,bQ),"env"),D(z,N(Z,"CODEX_HOME"),"env"),$)D(z,b($,".codex"),"default"),D(z,b($,".config","codex"),"default"),D(z,b($,"Library","Application Support","Codex"),"default"),D(z,b($,"Library","Application Support","Parall","Codex",".codex"),"default");return D(z,G?b(G,"Codex"):null,"default"),D(z,J?b(J,"Codex"):null,"default"),wZ(z)}async function g(Q={}){let Z=P(Q.env),$=N(Z,bQ),G=await Promise.all(SZ(Q).map(async(J)=>({...J,exists:await EZ(J.path)})));return{overrideHome:$?s($):null,candidates:G,foundHome:G.find((J)=>J.exists)?.path??null}}function D(Q,Z,$){if(Z)Q.push({path:s(Z),source:$})}async function EZ(Q){try{if(!(await yZ(Q)).isDirectory())return!1;return await RZ(Q,_Z.R_OK),!0}catch{return!1}}function wZ(Q){let Z=new Set,$=[];for(let G of Q){let J=s(G.path),z=process.platform==="win32"?J.toLowerCase():J;if(!Z.has(z))Z.add(z),$.push({path:J,source:G.source})}return $}import{constants as t}from"node:fs";import{lstat as h,open as rZ,opendir as oZ,realpath as yQ}from"node:fs/promises";import{join as fQ}from"node:path";var gZ=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],vZ=["January","February","March","April","May","June","July","August","September","October","November","December"];function L(Q,Z={}){let $=Z.includeSeconds??!1,G=Math.max(Math.floor(Q/1000),0),J=Math.floor(G/86400);G%=86400;let z=Math.floor(G/3600);G%=3600;let K=Math.floor(G/60),j=G%60,X=[];if(J>0)X.push(`${J}d`);if(z>0)X.push(`${z}h`);if(K>0)X.push(`${K}m`);if($&&j>0)X.push(`${j}s`);return X.length>0?X.join(" "):$?`${j}s`:"0m"}function T(Q){if(typeof Q==="number"&&Number.isFinite(Q)){let Z=Q<10000000000?Q*1000:Q,$=new Date(Z);return Number.isNaN($.getTime())?null:$}if(typeof Q==="string"&&Q.trim().length>0){let Z=Q.trim(),$=Number(Z);if(Number.isFinite($))return T($);let G=new Date(Z);return Number.isNaN(G.getTime())?null:G}return null}function kQ(Q){return`${gZ[Q.getDay()]} ${Q.getDate()} ${vZ[Q.getMonth()]} ${Q.getFullYear()}`}import{isAbsolute as uZ,relative as _Q,resolve as LQ,sep as lZ}from"node:path";var mZ=/(?:chatgpt[-_]?account[-_]?id|access[-_]?token|refresh[-_]?token|id[-_]?token|session[-_]?token|api[-_]?key|account[-_]?id|authorization|cookie|client[-_]?secret|password|credential|secret|token)/,hZ=/[\u0000-\u001f\u007f-\u009f]/g,cZ=new RegExp(`["']?${mZ.source}["']?\\s*[:=]\\s*(?:"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|[^,\\r\\n}\\]&]+)`,"gi"),pZ=[cZ,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}(?:\.[A-Za-z0-9_-]{5,})?\b/g,/sk-[A-Za-z0-9_-]{10,}/g,/\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b/gi,/[A-Za-z0-9_-]{32,}/g];function _(Q){let Z=Q;for(let $ of pZ)Z=Z.replace($,"[redacted]");return Z.replace(hZ,"?")}function a(Q){return Q.map(_)}function v(Q,Z){let $=_Q(LQ(Q),LQ(Z));return $===""||!RQ($)}function R(Q,Z){let $=_Q(Q,Z);return $&&!RQ($)?dZ($):"."}function dZ(Q){let Z=_(Q);return Z.length<=240?Z:`${Z.slice(0,239)}…`}function RQ(Q){return Q===".."||Q.startsWith(`..${lZ}`)||uZ(Q)}function H(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function x(Q,Z){let $=Q[Z];return typeof $==="string"&&$.trim()?$.trim():null}var iZ=8,e=20,m=1000,nZ=512,sZ=1000,GQ=25000000,aZ=1e6,tZ=/^rollout-.*\.jsonl$/i;async function SQ(Q){let Z=fQ(Q,"sessions"),$=[];if(await Y0(Z))return $.push("Skipped the symbolic-link Codex sessions directory."),{homePath:Q,sessionsRoot:Z,files:[],latestSnapshot:null,warnings:$};let G=await eZ(Z,$),J=[],z=null;for(let K of G.slice(0,e)){let j=R(Q,K.path);if(K.size>GQ){$.push("Skipped a local Codex session file because it is too large to inspect safely."),J.push(ZQ(K.path,j,K.modifiedAtMs,!1,"too-large"));continue}try{let X=await $0(Q,K);if(J.push(ZQ(K.path,j,K.modifiedAtMs,X.snapshot!==null,null)),X.skippedOversizedLine)$.push("Skipped an oversized JSONL line in a local Codex session file.");if(X.snapshot&&(!z||J0(X.snapshot,z)))z=X.snapshot}catch(X){let Y=X instanceof c;$.push(Y?"Skipped a local Codex session file because it grew too large to inspect safely.":"Could not inspect a local Codex session file safely."),J.push(ZQ(K.path,j,K.modifiedAtMs,!1,Y?"too-large":"read-error"))}}if(G.length>e)$.push(`Skipped ${G.length-e} older session files to keep inspection small.`);if(G.length>0&&!z)$.push("No token-count rate-limit snapshot was found in local Codex session logs.");return{homePath:Q,sessionsRoot:Z,files:J,latestSnapshot:z,warnings:$}}async function eZ(Q,Z){let $={directories:0,files:[],hitLimit:!1,skippedSymlink:!1};if(await EQ(Q,0,$,Z),$.hitLimit)Z.push("Stopped session discovery after reaching a safe inspection limit.");if($.skippedSymlink)Z.push("Skipped symbolic links while inspecting Codex sessions.");let G;try{G=await yQ(Q)}catch{return[]}let J=[];for(let z of $.files){let K=await Q0(G,z,Z);if(K)J.push(K)}return J.sort((z,K)=>K.modifiedAtMs-z.modifiedAtMs||z.path.localeCompare(K.path))}async function Q0(Q,Z,$){try{let[G,J]=await Promise.all([h(Z),yQ(Z)]);if(!G.isFile()||!v(Q,J))return $.push("Could not inspect a local Codex session file safely."),null;return{path:Z,modifiedAtMs:G.mtimeMs,size:G.size,dev:G.dev,ino:G.ino}}catch{return $.push("Could not inspect a local Codex session file safely."),null}}async function EQ(Q,Z,$,G){if(Z>iZ||$.files.length>=m){$.hitLimit||=$.files.length>=m;return}if($.directories>=nZ){$.hitLimit=!0;return}$.directories+=1;let J;try{J=await Z0(Q,$)}catch{if(Z>0)G.push("Could not inspect part of the local Codex sessions directory safely.");return}for(let z of J){if($.files.length>=m){$.hitLimit=!0;return}let K=fQ(Q,z.name);if(z.isSymbolicLink()){$.skippedSymlink=!0;continue}if(z.isDirectory()){await EQ(K,Z+1,$,G);continue}if(z.isFile()&&tZ.test(z.name)){if($.files.push(K),$.files.length>=m){$.hitLimit=!0;return}}}}async function Z0(Q,Z){let $=await oZ(Q),G=[];for await(let J of $){if(G.length>=sZ){Z.hitLimit=!0;break}G.push(J)}return G.sort((J,z)=>z.name.localeCompare(J.name))}async function $0(Q,Z){let $=Z.path,G=R(Q,$),J=await G0(Z),z=null,K=null,j="",X=0,Y=0,W=!1,V=!1,O=(C)=>{let q=z0(C.endsWith("\r")?C.slice(0,-1):C);if(q.threadId)z=q.threadId;if(q.rateLimits)K={sessionFile:$,relativePath:G,threadId:z,eventTimestamp:q.timestamp,rateLimits:q.rateLimits}};for await(let C of J){let q=String(C);if(Y+=Buffer.byteLength(q,"utf8"),Y>GQ)throw new c;let F=0;while(F<q.length){let A=q.indexOf(`
5
- `,F),IZ=A===-1?q.length:A,TQ=q.slice(F,IZ);if(!W){let FQ=Buffer.byteLength(TQ,"utf8");if(X+FQ>aZ)j="",X=0,W=!0,V=!0;else j+=TQ,X+=FQ}if(A===-1)break;if(!W)O(j);j="",X=0,W=!1,F=A+1}}if(!W&&j.length>0)O(j);return{snapshot:K,skippedOversizedLine:V}}async function G0(Q){let Z;try{let $=await h(Q.path);if(!$.isFile()||!QQ($,Q))throw new $Q;let G=t.O_NOFOLLOW,J=typeof G==="number"?t.O_RDONLY|G:t.O_RDONLY;Z=await rZ(Q.path,J);let[z,K]=await Promise.all([Z.stat(),h(Q.path)]);if(!z.isFile()||!K.isFile()||!QQ(z,Q)||!QQ(z,K))throw new $Q;if(z.size>GQ)throw new c;return Z.createReadStream({encoding:"utf8",highWaterMark:65536})}catch($){throw await Z?.close().catch(()=>{return}),$}}function QQ(Q,Z){return Q.dev===Z.dev&&Q.ino===Z.ino}function J0(Q,Z){let $=T(Q.eventTimestamp)?.getTime()??null,G=T(Z.eventTimestamp)?.getTime()??null;if($===null)return!1;return G===null||$>G}function z0(Q){let Z=K0(Q);if(!Z)return{threadId:null,timestamp:null,rateLimits:null};return{threadId:j0(Z),timestamp:x(Z,"timestamp"),rateLimits:X0(Z)}}function K0(Q){let Z=Q.trim();if(!Z)return null;try{let $=JSON.parse(Z);return H($)?$:null}catch{return null}}function j0(Q){if(Q.type!=="session_meta"||!H(Q.payload))return null;return x(Q.payload,"id")}function X0(Q){if(Q.type!=="event_msg"||!H(Q.payload))return null;if(Q.payload.type!=="token_count"||!H(Q.payload.rate_limits))return null;return Q.payload.rate_limits}function ZQ(Q,Z,$,G,J){return{path:Q,relativePath:Z,modifiedAtMs:$,hasSnapshot:G,error:J}}async function Y0(Q){try{return(await h(Q)).isSymbolicLink()}catch{return!1}}class c extends Error{}class $Q extends Error{}import{opendir as W0,realpath as mQ}from"node:fs/promises";import{extname as V0,join as M0}from"node:path";import{constants as JQ}from"node:fs";import{lstat as wQ,open as H0}from"node:fs/promises";class U extends Error{code;constructor(Q){super(Q);this.name="BoundedFileError",this.code=Q}}async function p(Q,Z){let $;try{let G=await wQ(Q);if(!G.isFile())throw new U("not-file");let J=JQ.O_NOFOLLOW,z=typeof J==="number"?JQ.O_RDONLY|J:JQ.O_RDONLY;$=await H0(Q,z);let K=await $.stat(),j=await wQ(Q);if(!K.isFile()||!j.isFile()||!gQ(G,K)||!gQ(K,j))throw new U("not-file");if(K.size>Z)throw new U("too-large");let X=Buffer.allocUnsafe(Z+1),Y=0;while(Y<=Z){let W=await $.read(X,Y,Z+1-Y,null);if(W.bytesRead===0)break;Y+=W.bytesRead}if(Y>Z)throw new U("too-large");return X.subarray(0,Y).toString("utf8")}catch(G){if(G instanceof U)throw G;if(vQ(G)&&G.code==="ENOENT")throw new U("not-found");if(vQ(G)&&G.code==="ELOOP")throw new U("not-file");throw new U("read-error")}finally{await $?.close().catch(()=>{return})}}function gQ(Q,Z){return Q.dev===Z.dev&&Q.ino===Z.ino}function vQ(Q){return Q instanceof Error&&"code"in Q}var U0=2,zQ=25,KQ=100,q0=64,N0=500,x0=1e6,B0=/(?:auth|token|cookie|session|secret|credential|api[-_]?key|keychain)/i;async function hQ(Q){let Z={directories:0,files:[],hitDirectoryLimit:!1,hitEntryLimit:!1,hitFileLimit:!1,skippedSensitive:!1,skippedSymlink:!1,warnings:[]},$;try{$=await mQ(Q)}catch{return{homePath:Q,files:[],warnings:["Could not inspect the local Codex state directory safely."]}}if(await cQ(Q,0,Z),Z.hitDirectoryLimit||Z.hitEntryLimit||Z.hitFileLimit)Z.warnings.push("Stopped local state discovery after reaching a safe inspection limit.");if(Z.skippedSensitive)Z.warnings.push("Skipped a sensitive-looking local file.");if(Z.skippedSymlink)Z.warnings.push("Skipped symbolic links while inspecting local Codex state.");let G=Z.files.sort((z,K)=>z.localeCompare(K)),J=[];for(let z of G.slice(0,zQ)){let K=R(Q,z);try{let j=await mQ(z);if(!v($,j))throw new U("not-file");let X=await p(z,x0),Y=C0(X,Z.warnings);J.push({path:z,relativePath:K,json:Y.value,error:Y.error})}catch(j){Z.warnings.push(j instanceof U&&j.code==="too-large"?"Skipped a local Codex state file because it is too large to inspect safely.":"Could not read a local Codex state file safely.")}}if(G.length>zQ)Z.warnings.push(`Skipped ${G.length-zQ} extra files to keep inspection small.`);return{homePath:Q,files:J,warnings:Z.warnings}}async function cQ(Q,Z,$){if(Z>U0||$.files.length>=KQ){$.hitFileLimit||=$.files.length>=KQ;return}if($.directories>=q0){$.hitDirectoryLimit=!0;return}$.directories+=1;let G=await O0(Q,$);for(let J of G){if($.files.length>=KQ){$.hitFileLimit=!0;return}if(B0.test(J.name)){$.skippedSensitive=!0;continue}let z=M0(Q,J.name);if(J.isSymbolicLink())$.skippedSymlink=!0;else if(J.isDirectory())await cQ(z,Z+1,$);else if(J.isFile()&&V0(J.name).toLowerCase()===".json")$.files.push(z)}}async function O0(Q,Z){try{let $=await W0(Q),G=[];for await(let J of $){if(G.length>=N0){Z.hitEntryLimit=!0;break}G.push(J)}return G.sort((J,z)=>J.name.localeCompare(z.name))}catch{return Z.warnings.push("Could not inspect part of the local Codex state directory safely."),[]}}function C0(Q,Z){try{return{value:JSON.parse(Q),error:null}}catch{return Z.push("Could not parse JSON in a local Codex state file."),{value:null,error:"invalid-json"}}}import{join as D0,normalize as T0}from"node:path";function B(Q,Z,$){return{code:Q,source:Z,severity:"warning",message:$}}function k(Q){return Q.map((Z)=>_(Z.message))}var F0=1e6;async function u(Q={}){let Z=P(Q.env),$=N(Z,"CODEX_LIMITS_ACCESS_TOKEN"),G=N(Z,"CODEX_LIMITS_ACCOUNT_ID");if($&&G)return{credentials:{accessToken:$,accountId:G},status:"configured",diagnostics:[]};if($||G)return{credentials:null,status:"partial",diagnostics:[B("auth.environment.partial","authentication","Codex authentication environment variables are incomplete.")]};let J=await A0(Q);return J?P0(J):{credentials:null,status:"missing",diagnostics:[]}}async function A0(Q){if(Q.authFile)return T0(Q.authFile);let Z=await g(Q);return Z.foundHome?D0(Z.foundHome,"auth.json"):null}async function P0(Q){let Z;try{Z=await p(Q,F0)}catch($){if($ instanceof U&&$.code==="not-found")return{credentials:null,status:"missing",diagnostics:[]};let G=$ instanceof U&&$.code==="too-large";return{credentials:null,status:"unreadable",diagnostics:[B(G?"auth.file.too-large":"auth.file.unreadable","authentication",G?"Codex auth.json is too large to inspect safely.":"Codex auth.json could not be read safely.")]}}try{let $=JSON.parse(Z);if(!H($))return jQ();let G=H($.tokens)?$.tokens:$,J=x(G,"access_token"),z=x(G,"account_id");return J&&z?{credentials:{accessToken:J,accountId:z},status:"configured",diagnostics:[]}:jQ()}catch{return jQ()}}function jQ(){return{credentials:null,status:"malformed",diagnostics:[B("auth.file.malformed","authentication","Codex auth.json is malformed or does not contain required credentials.")]}}var I0=/[\u0000-\u0020\u007f-\u009f]/;function XQ(Q){return Q.length>0&&Q.length<=512&&!I0.test(Q)}import{request as b0}from"node:http";import{request as k0}from"node:https";var L0=new Set(["127.0.0.1","::1","[::1]","localhost"]);function f(Q){try{let Z=new URL(Q);return Z.username="",Z.password="",Z.search="",Z.hash="",Z.href}catch{return"[invalid endpoint]"}}async function uQ(Q){let Z=_0(Q.endpoint);if(!Z.ok)return Z;if(Q.signal?.aborted)return M("aborted");let $=Q.fetch??globalThis.fetch;if(!$)return pQ(Z.url,Q);let G=await R0(Z.url,Q,$);if(G.ok||G.code==="aborted"||!S0(G,Q.fallbackOnHttpError??!1))return G;let J=await pQ(Z.url,Q);if(J.ok||J.code==="http-error"||J.code==="invalid-json"||J.code==="response-too-large")return J;return G}function l(Q){let Z={...Q,method:"GET"};return delete Z.body,uQ(Z)}function _0(Q){let Z;try{Z=new URL(Q)}catch{return M("invalid-url")}if(Z.username||Z.password)return M("invalid-url");if(Z.protocol==="https:")return{ok:!0,url:Z};if(Z.protocol==="http:"&&L0.has(Z.hostname.toLowerCase()))return{ok:!0,url:Z};return M("unsupported-protocol")}async function R0(Q,Z,$){let G=dQ(Z.timeoutMs,Z.signal);try{let J=await $(Q.href,{method:Z.method??"GET",headers:Z.headers,redirect:"error",signal:G.signal,...Z.body===void 0?{}:{body:Z.body}});if(!J.ok)return await lQ(J),M("http-error",WQ(J.status));let z=await y0(J,Z.maxResponseBytes);return{ok:!0,status:WQ(J.status)??200,payload:z,transport:"fetch"}}catch(J){if(J instanceof y)return M("response-too-large");if(J instanceof d)return M("invalid-json");if(Z.signal?.aborted)return M("aborted");if(G.didTimeout())return M("timeout");return M("network-error")}finally{G.dispose()}}async function y0(Q,Z){let $=Number(Q.headers?.get("content-length"));if(Number.isFinite($)&&$>Z)throw await lQ(Q),new y;if(Q.body){let G=Q.body.getReader(),J=[],z=0;while(!0){let j=await G.read();if(j.done)break;if(!j.value)continue;if(z+=j.value.byteLength,z>Z)throw await G.cancel?.(),new y;J.push(j.value)}let K=Buffer.concat(J.map((j)=>Buffer.from(j)),z).toString("utf8");return HQ(K)}if(Q.text){let G=await Q.text();if(Buffer.byteLength(G,"utf8")>Z)throw new y;return HQ(G)}throw new d}async function lQ(Q){if(!Q.body)return;try{await Q.body.getReader().cancel?.()}catch{}}function pQ(Q,Z){return new Promise(($)=>{let G=dQ(Z.timeoutMs,Z.signal),J=!1,z=null,K=(X)=>{if(J)return;J=!0,G.dispose(),$(X)},j=()=>{z?.destroy(),K(M(Z.signal?.aborted?"aborted":"timeout"))};G.signal.addEventListener("abort",j,{once:!0});try{z=(Q.protocol==="http:"?b0:k0)(Q,{method:Z.method??"GET",headers:Z.headers,signal:G.signal},(Y)=>f0(Y,Z.maxResponseBytes,K)),z.on("error",()=>{if(Z.signal?.aborted)K(M("aborted"));else if(G.didTimeout())K(M("timeout"));else K(M("network-error"))}),z.end(Z.body)}catch{K(M("network-error"))}})}function f0(Q,Z,$){let G=WQ(Q.statusCode);if(G===null||G<200||G>=300){$(M("http-error",G)),YQ(Q);return}let J=Number(Q.headers["content-length"]);if(Number.isFinite(J)&&J>Z){$(M("response-too-large")),YQ(Q);return}let z=[],K=0;Q.on("data",(j)=>{let X=Buffer.isBuffer(j)?j:Buffer.from(j);if(K+=X.length,K>Z){$(M("response-too-large")),YQ(Q);return}z.push(X)}),Q.on("end",()=>{try{let j=HQ(Buffer.concat(z,K).toString("utf8"));$({ok:!0,status:G,payload:j,transport:"node"})}catch{$(M("invalid-json"))}}),Q.on("error",()=>$(M("network-error")))}function YQ(Q){Q.destroy(),Q.socket.destroy()}function dQ(Q,Z){let $=new AbortController,G=!1,J=Number.isFinite(Q)&&Q>0?Math.min(Math.floor(Q),2147483647):1,z=setTimeout(()=>{G=!0,$.abort()},J),K=()=>$.abort();if(Z?.addEventListener("abort",K,{once:!0}),Z?.aborted)K();return{signal:$.signal,didTimeout:()=>G,dispose:()=>{clearTimeout(z),Z?.removeEventListener("abort",K)}}}function S0(Q,Z){return Q.code==="network-error"||Q.code==="timeout"||Q.code==="invalid-json"||Z&&Q.code==="http-error"}function HQ(Q){try{return JSON.parse(Q)}catch{throw new d}}function WQ(Q){return typeof Q==="number"&&Number.isInteger(Q)&&Q>=0?Q:null}function M(Q,Z=null){return{ok:!1,code:Q,status:Z}}class y extends Error{}class d extends Error{}function r(Q,Z){switch(Q.code){case"aborted":return B("network.request.aborted","network",`${Z} lookup was cancelled.`);case"http-error":return B("network.response.http","network",Q.status===null?`${Z} endpoint returned an invalid HTTP status.`:`${Z} endpoint returned HTTP ${Q.status}.`);case"invalid-json":return B("network.response.invalid-json","network",`${Z} endpoint returned malformed JSON.`);case"invalid-url":return B("network.endpoint.invalid","network",`${Z} endpoint URL is invalid.`);case"response-too-large":return B("network.response.too-large","network",`${Z} endpoint response was too large.`);case"timeout":return B("network.request.timeout","network",`${Z} lookup timed out.`);case"unsupported-protocol":return B("network.endpoint.protocol","network",`${Z} endpoint must use HTTPS or loopback HTTP.`);case"network-error":return B("network.request.failed","network",`${Z} lookup failed.`)}}var nQ=["credits","reset_credits","items"],sQ=["available_count","availableCount","available"],aQ=["total_earned_count","earned_this_period","earnedThisPeriod","totalEarnedCount"],E0=64,w0=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(?:Z|[+-](\d{2}):(\d{2}))$/i;function tQ(Q,Z,$){if(!H(Q)||!g0(Q))return S(Z,["Live reset coupon endpoint returned an unexpected payload."]);let G=c0(Q,nQ);if(G.malformed)return S(Z,["Live reset coupon endpoint returned an unexpected payload."]);let J=G.value,z=J.map((V,O)=>v0(V,O+1,$)).filter((V)=>V!==null).sort(h0).map((V,O)=>({...V,index:O+1})),K=z.filter((V)=>V.status?.toLowerCase()==="available"),j=K[0]??z[0]??null,X=iQ(Q,sQ),Y=iQ(Q,aQ),W=[];if(J.length!==z.length)W.push("Live reset coupon endpoint ignored malformed coupon entries.");if(X.malformed||Y.malformed)W.push("Live reset coupon endpoint ignored malformed summary fields.");if(X.value!==null&&X.value!==K.length)W.push("Live reset coupon endpoint returned inconsistent availability data.");return{status:W.length>0?"partial":"available",available:X.value,earnedThisPeriod:Y.value,nextExpirationDate:j?.expirationDate??null,nextExpirationIn:j?.expiresIn??null,items:z,warnings:W,source:{live:!0,label:"live Codex reset-credit endpoint",endpoint:Z}}}function S(Q,Z=[]){return{status:"unavailable",available:null,earnedThisPeriod:null,nextExpirationDate:null,nextExpirationIn:null,items:[],warnings:Z,source:{live:!1,label:"live Codex reset-credit endpoint",endpoint:Q}}}function g0(Q){return[...nQ,...sQ,...aQ].some((Z)=>(Z in Q))}function v0(Q,Z,$){if(!H(Q))return null;let G=Q.id,J=typeof G==="string"&&XQ(G)?G:null,z=Q.reset_type??Q.resetType,K=typeof z==="string"&&/^[a-z][a-z0-9_-]{0,63}$/i.test(z)?z:null,j="expires_at"in Q||"expiresAt"in Q,X="granted_at"in Q||"grantedAt"in Q,Y=x(Q,"expires_at")??x(Q,"expiresAt"),W=x(Q,"granted_at")??x(Q,"grantedAt"),V=rQ(Y),O=rQ(W),C=x(Q,"status"),q=C&&/^[a-z][a-z0-9_-]{0,63}$/i.test(C)?C:null,F=O?W:null,A=V?Y:null;if("id"in Q&&!J||X&&!O||j&&!V||!q&&!F&&!A)return null;return{id:J,resetType:K,index:Z,status:q,grantedAt:F,expiresAt:A,expirationDate:V?kQ(V):null,expiresIn:V?L(V.getTime()-$.getTime()):null}}function rQ(Q){if(!Q||Q.length>E0)return null;let Z=w0.exec(Q);if(!Z)return null;let $=Number(Z[1]),G=Number(Z[2]),J=Number(Z[3]),z=Number(Z[4]),K=Number(Z[5]),j=Number(Z[6]),X=Z[8]===void 0?0:Number(Z[8]),Y=Z[9]===void 0?0:Number(Z[9]);if(G<1||G>12||J<1||J>m0($,G)||z>23||K>59||j>59||X>23||Y>59)return null;let W=new Date(Q);return Number.isNaN(W.getTime())?null:W}function m0(Q,Z){if(Z===2)return Q%4===0&&(Q%100!==0||Q%400===0)?29:28;return Z===4||Z===6||Z===9||Z===11?30:31}function h0(Q,Z){return oQ(Q.expiresAt)-oQ(Z.expiresAt)}function oQ(Q){return T(Q)?.getTime()??Number.POSITIVE_INFINITY}function c0(Q,Z){let $=!1;for(let G of Z){if(!(G in Q))continue;$=!0;let J=Q[G];if(Array.isArray(J))return{value:J,malformed:!1}}return{value:[],malformed:$}}function iQ(Q,Z){let $=!1;for(let G of Z){if(!(G in Q))continue;$=!0;let J=Q[G];if(typeof J==="number"&&Number.isInteger(J)&&J>=0)return{value:J,malformed:!1}}return{value:null,malformed:$}}var VQ="https://chatgpt.com/backend-api/wham/rate-limit-reset-credits",L2=`${VQ}/consume`,p0=1e4,u0=1e6;async function QZ(Q={}){let Z=Q.endpoint??VQ,$=f(Z),G=await u(Q);if(!G.credentials){let z=k(G.diagnostics);return l0($,z.length>0?z:["Live reset coupons require a readable Codex auth.json file or CODEX_LIMITS_ACCESS_TOKEN and CODEX_LIMITS_ACCOUNT_ID."])}let J=d0(Z,G.credentials,Q);try{let z=await(Q.transport??l)(J);return z.ok?tQ(z.payload,$,Q.now??new Date):eQ($,z)}catch{return eQ($,{ok:!1,code:"network-error",status:null})}}function l0(Q=VQ,Z=[]){return S(f(Q),Z)}function eQ(Q,Z){return S(Q,k([r(Z,"Live reset coupon")]))}function d0(Q,Z,$){return{endpoint:Q,headers:r0(Z),timeoutMs:$.timeoutMs??p0,maxResponseBytes:u0,...$.fetch?{fetch:$.fetch}:{},...$.signal?{signal:$.signal}:{}}}function r0(Q){return{Authorization:`Bearer ${Q.accessToken}`,"ChatGPT-Account-ID":Q.accountId,"OpenAI-Beta":"codex-1",originator:"Codex Desktop",Accept:"application/json"}}var zZ=5,qQ="5-hour usage limit",NQ="Weekly usage limit",xQ=["fiveHour","five_hour","fiveHourWindow","five_hour_window","primary","primaryWindow","primary_window","main","mainWindow"],BQ=["weekly","week","weeklyWindow","weekly_window","secondary","secondaryWindow","secondary_window","backup","backupWindow"],o0=["used_percent","usedPercent","used","usage","percentUsed","usagePercent","usagePercentage","percent"],i0=["remaining_percent","remainingPercent","remaining","percentRemaining","availablePercent","available_percentage"],n0=["resets_at","resetsAt","resetAt","resetTime","reset_at","reset","ends_at","endsAt","windowEnd"],s0=["resetsIn","resetIn","resets_in","reset_in","timeUntilReset"],a0=["limit_window_seconds","limitWindowSeconds","window_seconds","windowSeconds","window_length_seconds","windowLengthSeconds"],t0=["window_minutes","windowMinutes","window_length_minutes","windowLengthMinutes"],e0=18000,Q1=604800,Z1=/^(?:(\d+)d)?(?:\s*(\d+)h)?(?:\s*(\d+)m)?(?:\s*(\d+)s)?$/i;function KZ(Q,Z=new Date){let $=Q.latestSnapshot;if(!$)return DQ(Q.warnings);return n(OQ($.rateLimits,Z),Q.warnings)}function OQ(Q,Z=new Date){return WZ(o(Q,xQ),o(Q,BQ),Z)}function jZ(Q){return o(Q,xQ)!==null||o(Q,BQ)!==null}function E(Q){let Z=JZ(I(Q,a0,!1)),$=JZ(I(Q,t0,!1)),G=Z??($===null?null:$*60);if(G===e0)return"fiveHour";if(G===Q1)return"weekly";return null}function XZ(Q,Z){return{...Q,source:Z}}function CQ(Q,Z,$=[]){return{...n(Q,$),source:Z}}function YZ(Q,Z=new Date){let $={fiveHour:null,weekly:null};for(let G of Q.files){if(!G.json)continue;let J=$1(G.json,Z);$=VZ($,J.windows)}return n($,Q.warnings)}function DQ(Q=[]){return{status:"unavailable",windows:{fiveHour:null,weekly:null},warnings:Q}}function HZ(Q,Z){let $=VZ(Q.windows,Z.windows);return n($,[...Q.warnings,...Z.warnings])}function $1(Q,Z){if(!H(Q))return{windows:{fiveHour:null,weekly:null}};let $=UQ(Q,xQ),G=UQ(Q,BQ);if($||G)return{windows:WZ($,G,Z)};let J=E(Q)??"fiveHour",z=MQ(Q,J==="weekly"?NQ:qQ,Z);return{windows:{fiveHour:J==="fiveHour"?z:null,weekly:J==="weekly"?z:null}}}function WZ(Q,Z,$){let G=[];if(Q)G.push({fallbackKind:"fiveHour",value:Q});if(Z)G.push({fallbackKind:"weekly",value:Z});return{fiveHour:MQ(ZZ(G,"fiveHour"),qQ,$),weekly:MQ(ZZ(G,"weekly"),NQ,$)}}function MQ(Q,Z,$){if(!Q)return null;let G=GZ(I(Q,o0,!0)),J=GZ(I(Q,i0,!0)),z=G??(J===null?null:i(100-J)),K=J??(G===null?null:i(100-G)),j=I(Q,n0,!0),X=T(j),Y=X?X.toISOString():null,W=X?L(X.getTime()-$.getTime()):z1(I(Q,s0,!0)),V={label:Z,remainingPercent:K,usedPercent:z,resetsAt:Y,resetsIn:W};return MZ(V)?V:null}function n(Q,Z){return{status:G1(Q),windows:Q,warnings:Z}}function G1(Q){let Z=[Q.fiveHour,Q.weekly].filter(($)=>MZ($));if(Z.length===0)return"unavailable";return Z.every(J1)?"available":"partial"}function ZZ(Q,Z){let $=Q.find((G)=>E(G.value)===Z);if($)return $.value;return Q.find((G)=>G.fallbackKind===Z&&E(G.value)===null)?.value??null}function VZ(Q,Z){return{fiveHour:$Z(Q.fiveHour,Z.fiveHour,qQ),weekly:$Z(Q.weekly,Z.weekly,NQ)}}function $Z(Q,Z,$){if(!Q&&!Z)return null;return{label:$,remainingPercent:Q?.remainingPercent??Z?.remainingPercent??null,usedPercent:Q?.usedPercent??Z?.usedPercent??null,resetsAt:Q?.resetsAt??Z?.resetsAt??null,resetsIn:Q?.resetsIn??Z?.resetsIn??null}}function MZ(Q){return Q!==null&&(Q.remainingPercent!==null||Q.usedPercent!==null||Q.resetsAt!==null||Q.resetsIn!==null)}function J1(Q){return Q!==null&&Q.remainingPercent!==null&&Q.usedPercent!==null&&(Q.resetsAt!==null||Q.resetsIn!==null)}function UQ(Q,Z,$=0){if($>zZ)return null;for(let G of Z){let J=Q[G];if(H(J))return J}for(let G of Object.values(Q)){if(!H(G))continue;let J=UQ(G,Z,$+1);if(J)return J}return null}function o(Q,Z){for(let $ of Z){let G=Q[$];if(H(G))return G}return null}function I(Q,Z,$,G=0){if(G>zZ)return;for(let J of Z)if(J in Q)return Q[J];if(!$)return;for(let J of Object.values(Q)){if(!H(J))continue;let z=I(J,Z,$,G+1);if(z!==void 0)return z}return}function GZ(Q){if(typeof Q==="number"&&Number.isFinite(Q))return i(Q);if(typeof Q==="string"&&Q.trim().length>0){let Z=Q.trim(),$=Z.endsWith("%")?Z.slice(0,-1):Z,G=Number($);return Number.isFinite(G)?i(G):null}return null}function i(Q){return Math.round(Math.min(Math.max(Q,0),100)*10)/10}function JZ(Q){if(typeof Q==="number"&&Number.isFinite(Q))return Q;if(typeof Q==="string"&&Q.trim().length>0){let Z=Number(Q);return Number.isFinite(Z)?Z:null}return null}function z1(Q){let Z=K1(Q);if(!Z||Z.length>100)return null;let G=Z1.exec(Z)?.slice(1);if(!G||G.every((K)=>K===void 0))return null;let J=[86400,3600,60,1],z=0;for(let[K,j]of G.entries()){if(j===void 0)continue;let X=Number(j),Y=X*J[K];if(!Number.isSafeInteger(X)||!Number.isSafeInteger(Y))return null;if(z+=Y,!Number.isSafeInteger(z))return null}return z<=Math.floor(Number.MAX_SAFE_INTEGER/1000)?L(z*1000):null}function K1(Q){if(typeof Q==="string"&&Q.trim().length>0)return Q.trim();return null}var j1=5,X1=1000,Y1={kind:"unavailable",label:"Unavailable"};function qZ(Q,Z,$){let G=H1(Q)??W1(Q);if(!G)return w(["Live usage endpoint returned an unexpected payload."]);let J=CQ(OQ(G,$),{kind:"api",label:"API",endpoint:Z});if(J.status==="unavailable")return w(["Live usage endpoint returned an unexpected payload."]);if(J.status==="partial")return{...J,warnings:["Live usage endpoint returned incomplete usage data."]};return J}function w(Q){return CQ({fiveHour:null,weekly:null},Y1,Q)}function H1(Q){return NZ(Q,(Z)=>{if(!H(Z))return null;let $=Z.rate_limits??Z.rateLimits??Z.rate_limit??Z.rateLimit;if(H($))return $;return jZ(Z)?Z:null})}function W1(Q){return NZ(Q,(Z)=>{if(!Array.isArray(Z))return null;let $=Z.find((J)=>UZ(J,"fiveHour")),G=Z.find((J)=>UZ(J,"weekly"));return $||G?{fiveHour:$,weekly:G}:null})}function NZ(Q,Z){let $=[{value:Q,depth:0}],G=new WeakSet;for(let J=0;J<$.length;J+=1){let z=$[J];if(!z)break;let K=Z(z.value);if(K)return K;if(z.depth>=j1||typeof z.value!=="object"||!z.value)continue;if(G.has(z.value))continue;G.add(z.value);let j=Array.isArray(z.value)?z.value:H(z.value)?Object.values(z.value):[];for(let X of j){if($.length>=X1)break;$.push({value:X,depth:z.depth+1})}}return null}function UZ(Q,Z){if(!H(Q))return!1;let $=E(Q);if($)return $===Z;let G=String(Q.type??Q.kind??Q.name??Q.label??Q.window??"").toLowerCase();return Z==="fiveHour"?G.includes("primary")||G.includes("5-hour")||G.includes("five"):G.includes("secondary")||G.includes("weekly")||G.includes("week")}var V1="https://chatgpt.com/backend-api/codex/usage",M1=1e4,U1=1e6;async function xZ(Q={}){return(await q1(Q)).usage}async function q1(Q={}){let Z=x1(Q),$=f(Z),G=await u(Q);if(!G.credentials){let K=k(G.diagnostics);return{usage:w(K.length>0?K:["Live usage requires Codex authentication."]),authenticationFound:!1,endpointStatus:"not-checked"}}let J={endpoint:Z,headers:N1(G.credentials),timeoutMs:Q.timeoutMs??M1,maxResponseBytes:U1,fallbackOnHttpError:!0,...Q.fetch?{fetch:Q.fetch}:{},...Q.signal?{signal:Q.signal}:{}},z;try{z=await(Q.transport??l)(J)}catch{z={ok:!1,code:"network-error",status:null}}return{usage:z.ok?qZ(z.payload,$,Q.now??new Date):O1(z),authenticationFound:!0,endpointStatus:B1(z)}}function N1(Q){return{Authorization:`Bearer ${Q.accessToken}`,"ChatGPT-Account-ID":Q.accountId,"OpenAI-Beta":"codex-1",originator:"Codex Desktop",Accept:"application/json","User-Agent":"Codex Desktop",Referer:"https://chatgpt.com/codex/cloud/settings/analytics",Origin:"https://chatgpt.com"}}function x1(Q){let Z=P(Q.env);return Q.usageEndpoint??N(Z,"CODEX_LIMITS_USAGE_ENDPOINT")??V1}function B1(Q){if(Q.ok)return"reachable";switch(Q.code){case"http-error":case"invalid-json":case"response-too-large":return"reachable";case"aborted":return"not-checked";case"invalid-url":case"network-error":case"timeout":case"unsupported-protocol":return"unreachable"}}function O1(Q){return w(k([r(Q,"Live usage")]))}var C1={kind:"local",label:"Local"};async function BZ(Q={}){let Z=Q.includeCoupons===!1?Promise.resolve(null):QZ(Q),[$,G]=await Promise.all([D1(Q),Z]),J=G?T1(G):null;return{windows:$.windows,coupons:J,warnings:a([...$.warnings,...J?.warnings??[]])}}async function D1(Q={}){let Z=await xZ(Q);if(Z.status!=="unavailable")return Z;let $=XZ(await F1(Q),C1);return $.status!=="unavailable"?$:{...$,warnings:[...Z.warnings,...$.warnings]}}function T1(Q){return{status:Q.status,available:Q.available,earnedThisPeriod:Q.earnedThisPeriod,nextExpirationDate:Q.nextExpirationDate,nextExpirationIn:Q.nextExpirationIn,items:Q.items.map((Z)=>({index:Z.index,status:Z.status,grantedAt:Z.grantedAt,expiresAt:Z.expiresAt,expirationDate:Z.expirationDate,expiresIn:Z.expiresIn})),warnings:a(Q.warnings)}}async function F1(Q={}){let Z=Q.now??new Date,$=await g(Q);if(!$.foundHome)return DQ(["No readable local Codex home directory was found."]);let[G,J]=await Promise.all([SQ($.foundHome),hQ($.foundHome)]);return HZ(KZ(G,Z),YZ(J,Z))}var P1="Could not load Codex limits.",OZ="Could not display Codex limits.",DZ="codex-limits-copilot-extension-v1";async function TZ(Q={}){let Z=Q.getLimits??BZ,$=Q.joinSession??((J)=>A1(J)),G;G=await $({commands:[{name:"codex-limits",description:"Check Codex limits, resets, and credits",handler:async()=>{let J;try{J=IQ(await Z())}catch{await CZ(G,P1,{level:"error"});return}await CZ(G,J)}}]})}async function CZ(Q,Z,$){if(!Q)throw Error(OZ);try{await Q.log(Z,$)}catch{throw Error(OZ)}}try{await TZ()}catch{process.exitCode=1}var FZ=TZ;function AZ(Q){return Q}var PZ=AZ(FZ),z3=DZ,K3=PZ,X3=PZ;export{K3 as startCopilotExtension,X3 as default,z3 as COPILOT_EXTENSION_MARKER};
4
+ `)}function PQ(Q,Z){let $=Z.remainingPercent;return[`${Q} ${LZ($)}`,`Remaining ${$===null?"Unknown":`${Math.round($)}% remaining`}`,IZ($),`Reset ${Z.resetsIn?`in ${Z.resetsIn}`:"unknown"}`]}function IZ(Q){if(Q===null)return`[${" ".repeat(22)}] Unknown`;let Z=Math.min(Math.max(Q,0),100),$=Math.round(Z/100*22);return`[${"=".repeat($)}${" ".repeat(22-$)}] ${Math.round(Z)}%`}function kZ(Q){let Z=Q.coupons?.available,G=[`Reset credits ${Z===null||Z===void 0?"Unknown":`${Z} ${Z===1?"credit":"credits"} available`}`],J=Q.coupons?.nextExpirationIn,z=Q.coupons?.nextExpirationDate,K=J&&z?`${J} (${z})`:J??z;if(K!==null&&K!==void 0)G.push(`Next expires ${K}`);return G}function LZ(Q){if(Q===null)return"Unknown";if(Q>=50)return"Healthy";if(Q>=15)return"Low";return"Critical"}function IQ(Q){return bQ(Q)}import{constants as _Z}from"node:fs";import{access as RZ,stat as yZ}from"node:fs/promises";import{homedir as fZ}from"node:os";import{join as I,normalize as a}from"node:path";function N(Q,Z){let $=Q[Z]?.trim();return $?$:null}function P(Q){return Q??process.env}var kQ="CODEX_LIMITS_HOME";function SZ(Q={}){let Z=P(Q.env),$=Q.homeDirectory??N(Z,"HOME")??N(Z,"USERPROFILE")??fZ(),G=Q.appData??N(Z,"APPDATA"),J=Q.localAppData??N(Z,"LOCALAPPDATA"),z=[];if(T(z,N(Z,kQ),"env"),T(z,N(Z,"CODEX_HOME"),"env"),$)T(z,I($,".codex"),"default"),T(z,I($,".config","codex"),"default"),T(z,I($,"Library","Application Support","Codex"),"default"),T(z,I($,"Library","Application Support","Parall","Codex",".codex"),"default");return T(z,G?I(G,"Codex"):null,"default"),T(z,J?I(J,"Codex"):null,"default"),wZ(z)}async function m(Q={}){let Z=P(Q.env),$=N(Z,kQ),G=await Promise.all(SZ(Q).map(async(J)=>({...J,exists:await EZ(J.path)})));return{overrideHome:$?a($):null,candidates:G,foundHome:G.find((J)=>J.exists)?.path??null}}function T(Q,Z,$){if(Z)Q.push({path:a(Z),source:$})}async function EZ(Q){try{if(!(await yZ(Q)).isDirectory())return!1;return await RZ(Q,_Z.R_OK),!0}catch{return!1}}function wZ(Q){let Z=new Set,$=[];for(let G of Q){let J=a(G.path),z=process.platform==="win32"?J.toLowerCase():J;if(!Z.has(z))Z.add(z),$.push({path:J,source:G.source})}return $}import{constants as e}from"node:fs";import{lstat as f,open as rZ,opendir as oZ,realpath as $Q}from"node:fs/promises";import{join as fQ}from"node:path";var gZ=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],vZ=["January","February","March","April","May","June","July","August","September","October","November","December"];function L(Q,Z={}){let $=Z.includeSeconds??!1,G=Math.max(Math.floor(Q/1000),0),J=Math.floor(G/86400);G%=86400;let z=Math.floor(G/3600);G%=3600;let K=Math.floor(G/60),j=G%60,X=[];if(J>0)X.push(`${J}d`);if(z>0)X.push(`${z}h`);if(K>0)X.push(`${K}m`);if($&&j>0)X.push(`${j}s`);return X.length>0?X.join(" "):$?`${j}s`:"0m"}function D(Q){if(typeof Q==="number"&&Number.isFinite(Q)){let Z=Q<10000000000?Q*1000:Q,$=new Date(Z);return Number.isNaN($.getTime())?null:$}if(typeof Q==="string"&&Q.trim().length>0){let Z=Q.trim(),$=Number(Z);if(Number.isFinite($))return D($);let G=new Date(Z);return Number.isNaN(G.getTime())?null:G}return null}function LQ(Q){return`${gZ[Q.getDay()]} ${Q.getDate()} ${vZ[Q.getMonth()]} ${Q.getFullYear()}`}import{isAbsolute as uZ,relative as RQ,resolve as _Q,sep as dZ}from"node:path";var mZ=/(?:chatgpt[-_]?account[-_]?id|access[-_]?token|refresh[-_]?token|id[-_]?token|session[-_]?token|api[-_]?key|account[-_]?id|authorization|cookie|client[-_]?secret|password|credential|secret|token)/,hZ=/[\u0000-\u001f\u007f-\u009f]/g,cZ=new RegExp(`["']?${mZ.source}["']?\\s*[:=]\\s*(?:"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|[^,\\r\\n}\\]&]+)`,"gi"),pZ=[cZ,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}(?:\.[A-Za-z0-9_-]{5,})?\b/g,/sk-[A-Za-z0-9_-]{10,}/g,/\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b/gi,/[A-Za-z0-9_-]{32,}/g];function _(Q){let Z=Q;for(let $ of pZ)Z=Z.replace($,"[redacted]");return Z.replace(hZ,"?")}function t(Q){return Q.map(_)}function R(Q,Z){let $=RQ(_Q(Q),_Q(Z));return $===""||!yQ($)}function y(Q,Z){let $=RQ(Q,Z);return $&&!yQ($)?lZ($):"."}function lZ(Q){let Z=_(Q);return Z.length<=240?Z:`${Z.slice(0,239)}…`}function yQ(Q){return Q===".."||Q.startsWith(`..${dZ}`)||uZ(Q)}function W(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function x(Q,Z){let $=Q[Z];return typeof $==="string"&&$.trim()?$.trim():null}var iZ=8,QQ=20,h=1000,nZ=512,sZ=1000,JQ=25000000,aZ=1e6,tZ=/^rollout-.*\.jsonl$/i;async function SQ(Q){let Z=fQ(Q,"sessions"),$=[],G=await eZ(Q,Z,$);if(!G)return{homePath:Q,sessionsRoot:Z,files:[],latestSnapshot:null,warnings:$};let J=await Q0(Z,G,$),z=[],K=null;for(let j of J.slice(0,QQ)){let X=y(Q,j.path);if(j.size>JQ){$.push("Skipped a local Codex session file because it is too large to inspect safely."),z.push(ZQ(j.path,X,j.modifiedAtMs,!1,"too-large"));continue}try{let Y=await G0(Q,j);if(z.push(ZQ(j.path,X,j.modifiedAtMs,Y.snapshot!==null,null)),Y.skippedOversizedLine)$.push("Skipped an oversized JSONL line in a local Codex session file.");if(Y.snapshot&&(!K||z0(Y.snapshot,K)))K=Y.snapshot}catch(Y){let H=Y instanceof p;$.push(H?"Skipped a local Codex session file because it grew too large to inspect safely.":"Could not inspect a local Codex session file safely."),z.push(ZQ(j.path,X,j.modifiedAtMs,!1,H?"too-large":"read-error"))}}if(J.length>QQ)$.push(`Skipped ${J.length-QQ} older session files to keep inspection small.`);if(J.length>0&&!K)$.push("No token-count rate-limit snapshot was found in local Codex session logs.");return{homePath:Q,sessionsRoot:Z,files:z,latestSnapshot:K,warnings:$}}async function eZ(Q,Z,$){try{let G=await f(Z);if(G.isSymbolicLink())return $.push("Skipped the symbolic-link Codex sessions directory."),null;if(!G.isDirectory())return null;let[J,z]=await Promise.all([$Q(Q),$Q(Z)]),K=await f(Z);if(!R(J,z)||!K.isDirectory()||K.isSymbolicLink()||!c(G,K))return $.push("Could not inspect the local Codex sessions directory safely."),null;return z}catch{return null}}async function Q0(Q,Z,$){let G={directories:0,files:[],hitLimit:!1,skippedSymlink:!1};if(await EQ(Q,0,G,$),G.hitLimit)$.push("Stopped session discovery after reaching a safe inspection limit.");if(G.skippedSymlink)$.push("Skipped symbolic links while inspecting Codex sessions.");let J=[];for(let z of G.files){let K=await Z0(Z,z,$);if(K)J.push(K)}return J.sort((z,K)=>K.modifiedAtMs-z.modifiedAtMs||z.path.localeCompare(K.path))}async function Z0(Q,Z,$){try{let[G,J]=await Promise.all([f(Z),$Q(Z)]);if(!G.isFile()||!R(Q,J))return $.push("Could not inspect a local Codex session file safely."),null;return{path:Z,modifiedAtMs:G.mtimeMs,size:G.size,dev:G.dev,ino:G.ino}}catch{return $.push("Could not inspect a local Codex session file safely."),null}}async function EQ(Q,Z,$,G){if(Z>iZ||$.files.length>=h){$.hitLimit||=$.files.length>=h;return}if($.directories>=nZ){$.hitLimit=!0;return}$.directories+=1;let J;try{J=await $0(Q,$)}catch{if(Z>0)G.push("Could not inspect part of the local Codex sessions directory safely.");return}for(let z of J){if($.files.length>=h){$.hitLimit=!0;return}let K=fQ(Q,z.name);if(z.isSymbolicLink()){$.skippedSymlink=!0;continue}if(z.isDirectory()){await EQ(K,Z+1,$,G);continue}if(z.isFile()&&tZ.test(z.name)){if($.files.push(K),$.files.length>=h){$.hitLimit=!0;return}}}}async function $0(Q,Z){let $=await oZ(Q),G=[];for await(let J of $){if(G.length>=sZ){Z.hitLimit=!0;break}G.push(J)}return G.sort((J,z)=>z.name.localeCompare(J.name))}async function G0(Q,Z){let $=Z.path,G=y(Q,$),J=await J0(Z),z=null,K=null,j="",X=0,Y=0,H=!1,V=!1,O=(C)=>{let q=K0(C.endsWith("\r")?C.slice(0,-1):C);if(q.threadId)z=q.threadId;if(q.rateLimits)K={sessionFile:$,relativePath:G,threadId:z,eventTimestamp:q.timestamp,rateLimits:q.rateLimits}};for await(let C of J){let q=String(C);if(Y+=Buffer.byteLength(q,"utf8"),Y>JQ)throw new p;let F=0;while(F<q.length){let A=q.indexOf(`
5
+ `,F),bZ=A===-1?q.length:A,FQ=q.slice(F,bZ);if(!H){let AQ=Buffer.byteLength(FQ,"utf8");if(X+AQ>aZ)j="",X=0,H=!0,V=!0;else j+=FQ,X+=AQ}if(A===-1)break;if(!H)O(j);j="",X=0,H=!1,F=A+1}}if(!H&&j.length>0)O(j);return{snapshot:K,skippedOversizedLine:V}}async function J0(Q){let Z;try{let $=await f(Q.path);if(!$.isFile()||!c($,Q))throw new GQ;let G=e.O_NOFOLLOW,J=typeof G==="number"?e.O_RDONLY|G:e.O_RDONLY;Z=await rZ(Q.path,J);let[z,K]=await Promise.all([Z.stat(),f(Q.path)]);if(!z.isFile()||!K.isFile()||!c(z,Q)||!c(z,K))throw new GQ;if(z.size>JQ)throw new p;return Z.createReadStream({encoding:"utf8",highWaterMark:65536})}catch($){throw await Z?.close().catch(()=>{return}),$}}function c(Q,Z){return Q.dev===Z.dev&&Q.ino===Z.ino}function z0(Q,Z){let $=D(Q.eventTimestamp)?.getTime()??null,G=D(Z.eventTimestamp)?.getTime()??null;if($===null)return!1;return G===null||$>G}function K0(Q){let Z=j0(Q);if(!Z)return{threadId:null,timestamp:null,rateLimits:null};return{threadId:X0(Z),timestamp:x(Z,"timestamp"),rateLimits:Y0(Z)}}function j0(Q){let Z=Q.trim();if(!Z)return null;try{let $=JSON.parse(Z);return W($)?$:null}catch{return null}}function X0(Q){if(Q.type!=="session_meta"||!W(Q.payload))return null;return x(Q.payload,"id")}function Y0(Q){if(Q.type!=="event_msg"||!W(Q.payload))return null;if(Q.payload.type!=="token_count"||!W(Q.payload.rate_limits))return null;return Q.payload.rate_limits}function ZQ(Q,Z,$,G,J){return{path:Q,relativePath:Z,modifiedAtMs:$,hasSnapshot:G,error:J}}class p extends Error{}class GQ extends Error{}import{opendir as W0,realpath as mQ}from"node:fs/promises";import{extname as V0,join as M0}from"node:path";import{constants as zQ}from"node:fs";import{lstat as wQ,open as H0}from"node:fs/promises";class U extends Error{code;constructor(Q){super(Q);this.name="BoundedFileError",this.code=Q}}async function u(Q,Z){let $;try{let G=await wQ(Q);if(!G.isFile())throw new U("not-file");let J=zQ.O_NOFOLLOW,z=typeof J==="number"?zQ.O_RDONLY|J:zQ.O_RDONLY;$=await H0(Q,z);let K=await $.stat(),j=await wQ(Q);if(!K.isFile()||!j.isFile()||!gQ(G,K)||!gQ(K,j))throw new U("not-file");if(K.size>Z)throw new U("too-large");let X=Buffer.allocUnsafe(Z+1),Y=0;while(Y<=Z){let H=await $.read(X,Y,Z+1-Y,null);if(H.bytesRead===0)break;Y+=H.bytesRead}if(Y>Z)throw new U("too-large");return X.subarray(0,Y).toString("utf8")}catch(G){if(G instanceof U)throw G;if(vQ(G)&&G.code==="ENOENT")throw new U("not-found");if(vQ(G)&&G.code==="ELOOP")throw new U("not-file");throw new U("read-error")}finally{await $?.close().catch(()=>{return})}}function gQ(Q,Z){return Q.dev===Z.dev&&Q.ino===Z.ino}function vQ(Q){return Q instanceof Error&&"code"in Q}var U0=2,KQ=25,jQ=100,q0=64,N0=500,x0=1e6,B0=/(?:auth|token|cookie|session|secret|credential|api[-_]?key|keychain)/i;async function hQ(Q){let Z={directories:0,files:[],hitDirectoryLimit:!1,hitEntryLimit:!1,hitFileLimit:!1,skippedSensitive:!1,skippedSymlink:!1,warnings:[]},$;try{$=await mQ(Q)}catch{return{homePath:Q,files:[],warnings:["Could not inspect the local Codex state directory safely."]}}if(await cQ(Q,0,Z),Z.hitDirectoryLimit||Z.hitEntryLimit||Z.hitFileLimit)Z.warnings.push("Stopped local state discovery after reaching a safe inspection limit.");if(Z.skippedSensitive)Z.warnings.push("Skipped a sensitive-looking local file.");if(Z.skippedSymlink)Z.warnings.push("Skipped symbolic links while inspecting local Codex state.");let G=Z.files.sort((z,K)=>z.localeCompare(K)),J=[];for(let z of G.slice(0,KQ)){let K=y(Q,z);try{let j=await mQ(z);if(!R($,j))throw new U("not-file");let X=await u(z,x0),Y=C0(X,Z.warnings);J.push({path:z,relativePath:K,json:Y.value,error:Y.error})}catch(j){Z.warnings.push(j instanceof U&&j.code==="too-large"?"Skipped a local Codex state file because it is too large to inspect safely.":"Could not read a local Codex state file safely.")}}if(G.length>KQ)Z.warnings.push(`Skipped ${G.length-KQ} extra files to keep inspection small.`);return{homePath:Q,files:J,warnings:Z.warnings}}async function cQ(Q,Z,$){if(Z>U0||$.files.length>=jQ){$.hitFileLimit||=$.files.length>=jQ;return}if($.directories>=q0){$.hitDirectoryLimit=!0;return}$.directories+=1;let G=await O0(Q,$);for(let J of G){if($.files.length>=jQ){$.hitFileLimit=!0;return}if(B0.test(J.name)){$.skippedSensitive=!0;continue}let z=M0(Q,J.name);if(J.isSymbolicLink())$.skippedSymlink=!0;else if(J.isDirectory())await cQ(z,Z+1,$);else if(J.isFile()&&V0(J.name).toLowerCase()===".json")$.files.push(z)}}async function O0(Q,Z){try{let $=await W0(Q),G=[];for await(let J of $){if(G.length>=N0){Z.hitEntryLimit=!0;break}G.push(J)}return G.sort((J,z)=>J.name.localeCompare(z.name))}catch{return Z.warnings.push("Could not inspect part of the local Codex state directory safely."),[]}}function C0(Q,Z){try{return{value:JSON.parse(Q),error:null}}catch{return Z.push("Could not parse JSON in a local Codex state file."),{value:null,error:"invalid-json"}}}import{join as T0,normalize as D0}from"node:path";function B(Q,Z,$){return{code:Q,source:Z,severity:"warning",message:$}}function k(Q){return Q.map((Z)=>_(Z.message))}var F0=1e6;async function d(Q={}){let Z=P(Q.env),$=N(Z,"CODEX_LIMITS_ACCESS_TOKEN"),G=N(Z,"CODEX_LIMITS_ACCOUNT_ID");if($&&G)return{credentials:{accessToken:$,accountId:G},status:"configured",diagnostics:[]};if($||G)return{credentials:null,status:"partial",diagnostics:[B("auth.environment.partial","authentication","Codex authentication environment variables are incomplete.")]};let J=await A0(Q);return J?P0(J):{credentials:null,status:"missing",diagnostics:[]}}async function A0(Q){if(Q.authFile)return D0(Q.authFile);let Z=await m(Q);return Z.foundHome?T0(Z.foundHome,"auth.json"):null}async function P0(Q){let Z;try{Z=await u(Q,F0)}catch($){if($ instanceof U&&$.code==="not-found")return{credentials:null,status:"missing",diagnostics:[]};let G=$ instanceof U&&$.code==="too-large";return{credentials:null,status:"unreadable",diagnostics:[B(G?"auth.file.too-large":"auth.file.unreadable","authentication",G?"Codex auth.json is too large to inspect safely.":"Codex auth.json could not be read safely.")]}}try{let $=JSON.parse(Z);if(!W($))return XQ();let G=W($.tokens)?$.tokens:$,J=x(G,"access_token"),z=x(G,"account_id");return J&&z?{credentials:{accessToken:J,accountId:z},status:"configured",diagnostics:[]}:XQ()}catch{return XQ()}}function XQ(){return{credentials:null,status:"malformed",diagnostics:[B("auth.file.malformed","authentication","Codex auth.json is malformed or does not contain required credentials.")]}}var b0=/[\u0000-\u0020\u007f-\u009f]/;function YQ(Q){return Q.length>0&&Q.length<=512&&!b0.test(Q)}import{request as I0}from"node:http";import{request as k0}from"node:https";var L0=new Set(["127.0.0.1","::1","[::1]","localhost"]);function E(Q){try{let Z=new URL(Q);return Z.username="",Z.password="",Z.search="",Z.hash="",Z.href}catch{return"[invalid endpoint]"}}async function uQ(Q){let Z=_0(Q.endpoint);if(!Z.ok)return Z;if(Q.signal?.aborted)return M("aborted");let $=Q.fetch??globalThis.fetch;if(!$)return pQ(Z.url,Q);let G=await R0(Z.url,Q,$);if(G.ok||G.code==="aborted"||!S0(G,Q.fallbackOnHttpError??!1))return G;let J=await pQ(Z.url,Q);if(J.ok||J.code==="http-error"||J.code==="invalid-json"||J.code==="response-too-large")return J;return G}function l(Q){let Z={...Q,method:"GET"};return delete Z.body,uQ(Z)}function _0(Q){let Z;try{Z=new URL(Q)}catch{return M("invalid-url")}if(Z.username||Z.password)return M("invalid-url");if(Z.protocol==="https:")return{ok:!0,url:Z};if(Z.protocol==="http:"&&L0.has(Z.hostname.toLowerCase()))return{ok:!0,url:Z};return M("unsupported-protocol")}async function R0(Q,Z,$){let G=lQ(Z.timeoutMs,Z.signal);try{let J=await $(Q.href,{method:Z.method??"GET",headers:Z.headers,redirect:"error",signal:G.signal,...Z.body===void 0?{}:{body:Z.body}});if(!J.ok)return await dQ(J),M("http-error",VQ(J.status));let z=await y0(J,Z.maxResponseBytes);return{ok:!0,status:VQ(J.status)??200,payload:z,transport:"fetch"}}catch(J){if(J instanceof S)return M("response-too-large");if(J instanceof r)return M("invalid-json");if(Z.signal?.aborted)return M("aborted");if(G.didTimeout())return M("timeout");return M("network-error")}finally{G.dispose()}}async function y0(Q,Z){let $=Number(Q.headers?.get("content-length"));if(Number.isFinite($)&&$>Z)throw await dQ(Q),new S;if(Q.body){let G=Q.body.getReader(),J=[],z=0;while(!0){let j=await G.read();if(j.done)break;if(!j.value)continue;if(z+=j.value.byteLength,z>Z)throw await G.cancel?.(),new S;J.push(j.value)}let K=Buffer.concat(J.map((j)=>Buffer.from(j)),z).toString("utf8");return WQ(K)}if(Q.text){let G=await Q.text();if(Buffer.byteLength(G,"utf8")>Z)throw new S;return WQ(G)}throw new r}async function dQ(Q){if(!Q.body)return;try{await Q.body.getReader().cancel?.()}catch{}}function pQ(Q,Z){return new Promise(($)=>{let G=lQ(Z.timeoutMs,Z.signal),J=!1,z=null,K=(X)=>{if(J)return;J=!0,G.dispose(),$(X)},j=()=>{z?.destroy(),K(M(Z.signal?.aborted?"aborted":"timeout"))};G.signal.addEventListener("abort",j,{once:!0});try{z=(Q.protocol==="http:"?I0:k0)(Q,{method:Z.method??"GET",headers:Z.headers,signal:G.signal},(Y)=>f0(Y,Z.maxResponseBytes,K)),z.on("error",()=>{if(Z.signal?.aborted)K(M("aborted"));else if(G.didTimeout())K(M("timeout"));else K(M("network-error"))}),z.end(Z.body)}catch{K(M("network-error"))}})}function f0(Q,Z,$){let G=VQ(Q.statusCode);if(G===null||G<200||G>=300){$(M("http-error",G)),HQ(Q);return}let J=Number(Q.headers["content-length"]);if(Number.isFinite(J)&&J>Z){$(M("response-too-large")),HQ(Q);return}let z=[],K=0;Q.on("data",(j)=>{let X=Buffer.isBuffer(j)?j:Buffer.from(j);if(K+=X.length,K>Z){$(M("response-too-large")),HQ(Q);return}z.push(X)}),Q.on("end",()=>{try{let j=WQ(Buffer.concat(z,K).toString("utf8"));$({ok:!0,status:G,payload:j,transport:"node"})}catch{$(M("invalid-json"))}}),Q.on("error",()=>$(M("network-error")))}function HQ(Q){Q.destroy(),Q.socket.destroy()}function lQ(Q,Z){let $=new AbortController,G=!1,J=Number.isFinite(Q)&&Q>0?Math.min(Math.floor(Q),2147483647):1,z=setTimeout(()=>{G=!0,$.abort()},J),K=()=>$.abort();if(Z?.addEventListener("abort",K,{once:!0}),Z?.aborted)K();return{signal:$.signal,didTimeout:()=>G,dispose:()=>{clearTimeout(z),Z?.removeEventListener("abort",K)}}}function S0(Q,Z){return Q.code==="network-error"||Q.code==="timeout"||Q.code==="invalid-json"||Z&&Q.code==="http-error"}function WQ(Q){try{return JSON.parse(Q)}catch{throw new r}}function VQ(Q){return typeof Q==="number"&&Number.isInteger(Q)&&Q>=0?Q:null}function M(Q,Z=null){return{ok:!1,code:Q,status:Z}}class S extends Error{}class r extends Error{}function o(Q,Z){switch(Q.code){case"aborted":return B("network.request.aborted","network",`${Z} lookup was cancelled.`);case"http-error":return B("network.response.http","network",Q.status===null?`${Z} endpoint returned an invalid HTTP status.`:`${Z} endpoint returned HTTP ${Q.status}.`);case"invalid-json":return B("network.response.invalid-json","network",`${Z} endpoint returned malformed JSON.`);case"invalid-url":return B("network.endpoint.invalid","network",`${Z} endpoint URL is invalid.`);case"response-too-large":return B("network.response.too-large","network",`${Z} endpoint response was too large.`);case"timeout":return B("network.request.timeout","network",`${Z} lookup timed out.`);case"unsupported-protocol":return B("network.endpoint.protocol","network",`${Z} endpoint must use HTTPS or loopback HTTP.`);case"network-error":return B("network.request.failed","network",`${Z} lookup failed.`)}}var nQ=["credits","reset_credits","items"],sQ=["available_count","availableCount","available"],aQ=["total_earned_count","earned_this_period","earnedThisPeriod","totalEarnedCount"],E0=64,w0=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(?:Z|[+-](\d{2}):(\d{2}))$/i;function tQ(Q,Z,$){if(!W(Q)||!g0(Q))return w(Z,["Live reset coupon endpoint returned an unexpected payload."]);let G=c0(Q,nQ);if(G.malformed)return w(Z,["Live reset coupon endpoint returned an unexpected payload."]);let J=G.value,z=J.map((V,O)=>v0(V,O+1,$)).filter((V)=>V!==null).sort(h0).map((V,O)=>({...V,index:O+1})),K=z.filter((V)=>V.status?.toLowerCase()==="available"),j=K[0]??z[0]??null,X=iQ(Q,sQ),Y=iQ(Q,aQ),H=[];if(J.length!==z.length)H.push("Live reset coupon endpoint ignored malformed coupon entries.");if(X.malformed||Y.malformed)H.push("Live reset coupon endpoint ignored malformed summary fields.");if(X.value!==null&&X.value!==K.length)H.push("Live reset coupon endpoint returned inconsistent availability data.");return{status:H.length>0?"partial":"available",available:X.value,earnedThisPeriod:Y.value,nextExpirationDate:j?.expirationDate??null,nextExpirationIn:j?.expiresIn??null,items:z,warnings:H,source:{live:!0,label:"live Codex reset-credit endpoint",endpoint:Z}}}function w(Q,Z=[]){return{status:"unavailable",available:null,earnedThisPeriod:null,nextExpirationDate:null,nextExpirationIn:null,items:[],warnings:Z,source:{live:!1,label:"live Codex reset-credit endpoint",endpoint:Q}}}function g0(Q){return[...nQ,...sQ,...aQ].some((Z)=>(Z in Q))}function v0(Q,Z,$){if(!W(Q))return null;let G=Q.id,J=typeof G==="string"&&YQ(G)?G:null,z=Q.reset_type??Q.resetType,K=typeof z==="string"&&/^[a-z][a-z0-9_-]{0,63}$/i.test(z)?z:null,j="expires_at"in Q||"expiresAt"in Q,X="granted_at"in Q||"grantedAt"in Q,Y=x(Q,"expires_at")??x(Q,"expiresAt"),H=x(Q,"granted_at")??x(Q,"grantedAt"),V=rQ(Y),O=rQ(H),C=x(Q,"status"),q=C&&/^[a-z][a-z0-9_-]{0,63}$/i.test(C)?C:null,F=O?H:null,A=V?Y:null;if("id"in Q&&!J||X&&!O||j&&!V||!q&&!F&&!A)return null;return{id:J,resetType:K,index:Z,status:q,grantedAt:F,expiresAt:A,expirationDate:V?LQ(V):null,expiresIn:V?L(V.getTime()-$.getTime()):null}}function rQ(Q){if(!Q||Q.length>E0)return null;let Z=w0.exec(Q);if(!Z)return null;let $=Number(Z[1]),G=Number(Z[2]),J=Number(Z[3]),z=Number(Z[4]),K=Number(Z[5]),j=Number(Z[6]),X=Z[8]===void 0?0:Number(Z[8]),Y=Z[9]===void 0?0:Number(Z[9]);if(G<1||G>12||J<1||J>m0($,G)||z>23||K>59||j>59||X>23||Y>59)return null;let H=new Date(Q);return Number.isNaN(H.getTime())?null:H}function m0(Q,Z){if(Z===2)return Q%4===0&&(Q%100!==0||Q%400===0)?29:28;return Z===4||Z===6||Z===9||Z===11?30:31}function h0(Q,Z){return oQ(Q.expiresAt)-oQ(Z.expiresAt)}function oQ(Q){return D(Q)?.getTime()??Number.POSITIVE_INFINITY}function c0(Q,Z){let $=!1;for(let G of Z){if(!(G in Q))continue;$=!0;let J=Q[G];if(Array.isArray(J))return{value:J,malformed:!1}}return{value:[],malformed:$}}function iQ(Q,Z){let $=!1;for(let G of Z){if(!(G in Q))continue;$=!0;let J=Q[G];if(typeof J==="number"&&Number.isSafeInteger(J)&&J>=0)return{value:J,malformed:!1}}return{value:null,malformed:$}}var MQ="https://chatgpt.com/backend-api/wham/rate-limit-reset-credits",L2=`${MQ}/consume`,p0=1e4,u0=1e6;async function QZ(Q={}){let Z=Q.endpoint??MQ,$=E(Z),G=await d(Q);if(!G.credentials){let z=k(G.diagnostics);return d0($,z.length>0?z:["Live reset coupons require a readable Codex auth.json file or CODEX_LIMITS_ACCESS_TOKEN and CODEX_LIMITS_ACCOUNT_ID."])}let J=l0(Z,G.credentials,Q);try{let z=await(Q.transport??l)(J);return z.ok?tQ(z.payload,$,Q.now??new Date):eQ($,z)}catch{return eQ($,{ok:!1,code:"network-error",status:null})}}function d0(Q=MQ,Z=[]){return w(E(Q),Z)}function eQ(Q,Z){return w(Q,k([o(Z,"Live reset coupon")]))}function l0(Q,Z,$){return{endpoint:Q,headers:r0(Z),timeoutMs:$.timeoutMs??p0,maxResponseBytes:u0,...$.fetch?{fetch:$.fetch}:{},...$.signal?{signal:$.signal}:{}}}function r0(Q){return{Authorization:`Bearer ${Q.accessToken}`,"ChatGPT-Account-ID":Q.accountId,"OpenAI-Beta":"codex-1",originator:"Codex Desktop",Accept:"application/json"}}var zZ=5,NQ="5-hour usage limit",xQ="Weekly usage limit",BQ=["fiveHour","five_hour","fiveHourWindow","five_hour_window","primary","primaryWindow","primary_window","main","mainWindow"],OQ=["weekly","week","weeklyWindow","weekly_window","secondary","secondaryWindow","secondary_window","backup","backupWindow"],o0=["used_percent","usedPercent","used","usage","percentUsed","usagePercent","usagePercentage","percent"],i0=["remaining_percent","remainingPercent","remaining","percentRemaining","availablePercent","available_percentage"],n0=["resets_at","resetsAt","resetAt","resetTime","reset_at","reset","ends_at","endsAt","windowEnd"],s0=["resetsIn","resetIn","resets_in","reset_in","timeUntilReset"],a0=["limit_window_seconds","limitWindowSeconds","window_seconds","windowSeconds","window_length_seconds","windowLengthSeconds"],t0=["window_minutes","windowMinutes","window_length_minutes","windowLengthMinutes"],e0=18000,Q1=604800,Z1=/^(?:(\d+)d)?(?:\s*(\d+)h)?(?:\s*(\d+)m)?(?:\s*(\d+)s)?$/i;function KZ(Q,Z=new Date){let $=Q.latestSnapshot;if(!$)return DQ(Q.warnings);return s(CQ($.rateLimits,Z),Q.warnings)}function CQ(Q,Z=new Date){return WZ(i(Q,BQ),i(Q,OQ),Z)}function jZ(Q){return i(Q,BQ)!==null||i(Q,OQ)!==null}function g(Q){let Z=JZ(b(Q,a0,!1)),$=JZ(b(Q,t0,!1)),G=Z??($===null?null:$*60);if(G===e0)return"fiveHour";if(G===Q1)return"weekly";return null}function XZ(Q,Z){return{...Q,source:Z}}function TQ(Q,Z,$=[]){return{...s(Q,$),source:Z}}function YZ(Q,Z=new Date){let $={fiveHour:null,weekly:null};for(let G of Q.files){if(!G.json)continue;let J=$1(G.json,Z);$=VZ($,J.windows)}return s($,Q.warnings)}function DQ(Q=[]){return{status:"unavailable",windows:{fiveHour:null,weekly:null},warnings:Q}}function HZ(Q,Z){let $=VZ(Q.windows,Z.windows);return s($,[...Q.warnings,...Z.warnings])}function $1(Q,Z){if(!W(Q))return{windows:{fiveHour:null,weekly:null}};let $=qQ(Q,BQ),G=qQ(Q,OQ);if($||G)return{windows:WZ($,G,Z)};let J=g(Q)??"fiveHour",z=UQ(Q,J==="weekly"?xQ:NQ,Z);return{windows:{fiveHour:J==="fiveHour"?z:null,weekly:J==="weekly"?z:null}}}function WZ(Q,Z,$){let G=[];if(Q)G.push({fallbackKind:"fiveHour",value:Q});if(Z)G.push({fallbackKind:"weekly",value:Z});return{fiveHour:UQ(ZZ(G,"fiveHour"),NQ,$),weekly:UQ(ZZ(G,"weekly"),xQ,$)}}function UQ(Q,Z,$){if(!Q)return null;let G=GZ(b(Q,o0,!0)),J=GZ(b(Q,i0,!0)),z=G??(J===null?null:n(100-J)),K=J??(G===null?null:n(100-G)),j=b(Q,n0,!0),X=D(j),Y=X?X.toISOString():null,H=X?L(X.getTime()-$.getTime()):z1(b(Q,s0,!0)),V={label:Z,remainingPercent:K,usedPercent:z,resetsAt:Y,resetsIn:H};return MZ(V)?V:null}function s(Q,Z){return{status:G1(Q),windows:Q,warnings:Z}}function G1(Q){let Z=[Q.fiveHour,Q.weekly].filter(($)=>MZ($));if(Z.length===0)return"unavailable";return Z.every(J1)?"available":"partial"}function ZZ(Q,Z){let $=Q.find((G)=>g(G.value)===Z);if($)return $.value;return Q.find((G)=>G.fallbackKind===Z&&g(G.value)===null)?.value??null}function VZ(Q,Z){return{fiveHour:$Z(Q.fiveHour,Z.fiveHour,NQ),weekly:$Z(Q.weekly,Z.weekly,xQ)}}function $Z(Q,Z,$){if(!Q&&!Z)return null;return{label:$,remainingPercent:Q?.remainingPercent??Z?.remainingPercent??null,usedPercent:Q?.usedPercent??Z?.usedPercent??null,resetsAt:Q?.resetsAt??Z?.resetsAt??null,resetsIn:Q?.resetsIn??Z?.resetsIn??null}}function MZ(Q){return Q!==null&&(Q.remainingPercent!==null||Q.usedPercent!==null||Q.resetsAt!==null||Q.resetsIn!==null)}function J1(Q){return Q!==null&&Q.remainingPercent!==null&&Q.usedPercent!==null&&(Q.resetsAt!==null||Q.resetsIn!==null)}function qQ(Q,Z,$=0){if($>zZ)return null;for(let G of Z){let J=Q[G];if(W(J))return J}for(let G of Object.values(Q)){if(!W(G))continue;let J=qQ(G,Z,$+1);if(J)return J}return null}function i(Q,Z){for(let $ of Z){let G=Q[$];if(W(G))return G}return null}function b(Q,Z,$,G=0){if(G>zZ)return;for(let J of Z)if(J in Q)return Q[J];if(!$)return;for(let J of Object.values(Q)){if(!W(J))continue;let z=b(J,Z,$,G+1);if(z!==void 0)return z}return}function GZ(Q){if(typeof Q==="number"&&Number.isFinite(Q))return n(Q);if(typeof Q==="string"&&Q.trim().length>0){let Z=Q.trim(),$=Z.endsWith("%")?Z.slice(0,-1):Z,G=Number($);return Number.isFinite(G)?n(G):null}return null}function n(Q){return Math.round(Math.min(Math.max(Q,0),100)*10)/10}function JZ(Q){if(typeof Q==="number"&&Number.isFinite(Q))return Q;if(typeof Q==="string"&&Q.trim().length>0){let Z=Number(Q);return Number.isFinite(Z)?Z:null}return null}function z1(Q){let Z=K1(Q);if(!Z||Z.length>100)return null;let G=Z1.exec(Z)?.slice(1);if(!G||G.every((K)=>K===void 0))return null;let J=[86400,3600,60,1],z=0;for(let[K,j]of G.entries()){if(j===void 0)continue;let X=Number(j),Y=X*J[K];if(!Number.isSafeInteger(X)||!Number.isSafeInteger(Y))return null;if(z+=Y,!Number.isSafeInteger(z))return null}return z<=Math.floor(Number.MAX_SAFE_INTEGER/1000)?L(z*1000):null}function K1(Q){if(typeof Q==="string"&&Q.trim().length>0)return Q.trim();return null}var j1=5,X1=1000,Y1={kind:"unavailable",label:"Unavailable"};function qZ(Q,Z,$){let G=H1(Q)??W1(Q);if(!G)return v(["Live usage endpoint returned an unexpected payload."]);let J=TQ(CQ(G,$),{kind:"api",label:"API",endpoint:Z});if(J.status==="unavailable")return v(["Live usage endpoint returned an unexpected payload."]);if(J.status==="partial")return{...J,warnings:["Live usage endpoint returned incomplete usage data."]};return J}function v(Q){return TQ({fiveHour:null,weekly:null},Y1,Q)}function H1(Q){return NZ(Q,(Z)=>{if(!W(Z))return null;let $=Z.rate_limits??Z.rateLimits??Z.rate_limit??Z.rateLimit;if(W($))return $;return jZ(Z)?Z:null})}function W1(Q){return NZ(Q,(Z)=>{if(!Array.isArray(Z))return null;let $=Z.find((J)=>UZ(J,"fiveHour")),G=Z.find((J)=>UZ(J,"weekly"));return $||G?{fiveHour:$,weekly:G}:null})}function NZ(Q,Z){let $=[{value:Q,depth:0}],G=new WeakSet;for(let J=0;J<$.length;J+=1){let z=$[J];if(!z)break;let K=Z(z.value);if(K)return K;if(z.depth>=j1||typeof z.value!=="object"||!z.value)continue;if(G.has(z.value))continue;G.add(z.value);let j=Array.isArray(z.value)?z.value:W(z.value)?Object.values(z.value):[];for(let X of j){if($.length>=X1)break;$.push({value:X,depth:z.depth+1})}}return null}function UZ(Q,Z){if(!W(Q))return!1;let $=g(Q);if($)return $===Z;let G=String(Q.type??Q.kind??Q.name??Q.label??Q.window??"").toLowerCase();return Z==="fiveHour"?G.includes("primary")||G.includes("5-hour")||G.includes("five"):G.includes("secondary")||G.includes("weekly")||G.includes("week")}var V1="https://chatgpt.com/backend-api/codex/usage",M1=1e4,U1=1e6;async function xZ(Q={}){return(await q1(Q)).usage}async function q1(Q={}){let Z=x1(Q),$=E(Z),G=await d(Q);if(!G.credentials){let K=k(G.diagnostics);return{usage:v(K.length>0?K:["Live usage requires Codex authentication."]),authenticationFound:!1,endpointStatus:"not-checked"}}let J={endpoint:Z,headers:N1(G.credentials),timeoutMs:Q.timeoutMs??M1,maxResponseBytes:U1,fallbackOnHttpError:!0,...Q.fetch?{fetch:Q.fetch}:{},...Q.signal?{signal:Q.signal}:{}},z;try{z=await(Q.transport??l)(J)}catch{z={ok:!1,code:"network-error",status:null}}return{usage:z.ok?qZ(z.payload,$,Q.now??new Date):O1(z),authenticationFound:!0,endpointStatus:B1(z)}}function N1(Q){return{Authorization:`Bearer ${Q.accessToken}`,"ChatGPT-Account-ID":Q.accountId,"OpenAI-Beta":"codex-1",originator:"Codex Desktop",Accept:"application/json","User-Agent":"Codex Desktop",Referer:"https://chatgpt.com/codex/cloud/settings/analytics",Origin:"https://chatgpt.com"}}function x1(Q){let Z=P(Q.env);return Q.usageEndpoint??N(Z,"CODEX_LIMITS_USAGE_ENDPOINT")??V1}function B1(Q){if(Q.ok)return"reachable";switch(Q.code){case"http-error":case"invalid-json":case"response-too-large":return"reachable";case"aborted":return"not-checked";case"invalid-url":case"network-error":case"timeout":case"unsupported-protocol":return"unreachable"}}function O1(Q){return v(k([o(Q,"Live usage")]))}var C1={kind:"local",label:"Local"};async function BZ(Q={}){let Z=Q.includeCoupons===!1?Promise.resolve(null):QZ(Q),[$,G]=await Promise.all([T1(Q),Z]),J=G?D1(G):null;return{windows:$.windows,coupons:J,warnings:t([...$.warnings,...J?.warnings??[]])}}async function T1(Q={}){let Z=await xZ(Q);if(Z.status!=="unavailable")return Z;let $=XZ(await F1(Q),C1);return $.status!=="unavailable"?$:{...$,warnings:[...Z.warnings,...$.warnings]}}function D1(Q){return{status:Q.status,available:Q.available,earnedThisPeriod:Q.earnedThisPeriod,nextExpirationDate:Q.nextExpirationDate,nextExpirationIn:Q.nextExpirationIn,items:Q.items.map((Z)=>({index:Z.index,status:Z.status,grantedAt:Z.grantedAt,expiresAt:Z.expiresAt,expirationDate:Z.expirationDate,expiresIn:Z.expiresIn})),warnings:t(Q.warnings)}}async function F1(Q={}){let Z=Q.now??new Date,$=await m(Q);if(!$.foundHome)return DQ(["No readable local Codex home directory was found."]);let[G,J]=await Promise.all([SQ($.foundHome),hQ($.foundHome)]);return HZ(KZ(G,Z),YZ(J,Z))}var P1="Could not load Codex limits.",OZ="Could not display Codex limits.",TZ="codex-limits-copilot-extension-v1";async function DZ(Q={}){let Z=Q.getLimits??BZ,$=Q.joinSession??((J)=>A1(J)),G;G=await $({commands:[{name:"codex-limits",description:"Check Codex limits, resets, and credits",handler:async()=>{let J;try{J=IQ(await Z())}catch{await CZ(G,P1,{level:"error"});return}await CZ(G,J)}}]})}async function CZ(Q,Z,$){if(!Q)throw Error(OZ);try{await Q.log(Z,$)}catch{throw Error(OZ)}}try{await DZ()}catch{process.exitCode=1}var FZ=DZ;function AZ(Q){return Q}var PZ=AZ(FZ),z3=TZ,K3=PZ,X3=PZ;export{K3 as startCopilotExtension,X3 as default,z3 as COPILOT_EXTENSION_MARKER};
package/dist/opencode.js CHANGED
@@ -1,5 +1,5 @@
1
- function bQ(Q){let Z=[];if(Q.windows.fiveHour)Z.push(AQ("5-hour",Q.windows.fiveHour));if(Q.windows.weekly)Z.push(AQ("Weekly",Q.windows.weekly));if(Z.length===0)Z.push(["Usage limits Unavailable"]);if(Z.push(bZ(Q)),Q.warnings.length>0)Z.push(["Warnings",...Q.warnings.map(($)=>`- ${$}`)]);return Z.map(($)=>$.join(`
1
+ function kQ(Q){let Z=[];if(Q.windows.fiveHour)Z.push(bQ("5-hour",Q.windows.fiveHour));if(Q.windows.weekly)Z.push(bQ("Weekly",Q.windows.weekly));if(Z.length===0)Z.push(["Usage limits Unavailable"]);if(Z.push(bZ(Q)),Q.warnings.length>0)Z.push(["Warnings",...Q.warnings.map(($)=>`- ${$}`)]);return Z.map(($)=>$.join(`
2
2
  `)).join(`
3
3
 
4
- `)}function AQ(Q,Z){let $=Z.remainingPercent;return[`${Q} ${kZ($)}`,`Remaining ${$===null?"Unknown":`${Math.round($)}% remaining`}`,AZ($),`Reset ${Z.resetsIn?`in ${Z.resetsIn}`:"unknown"}`]}function AZ(Q){if(Q===null)return`[${" ".repeat(22)}] Unknown`;let Z=Math.min(Math.max(Q,0),100),$=Math.round(Z/100*22);return`[${"=".repeat($)}${" ".repeat(22-$)}] ${Math.round(Z)}%`}function bZ(Q){let Z=Q.coupons?.available,G=[`Reset credits ${Z===null||Z===void 0?"Unknown":`${Z} ${Z===1?"credit":"credits"} available`}`],J=Q.coupons?.nextExpirationIn,z=Q.coupons?.nextExpirationDate,j=J&&z?`${J} (${z})`:J??z;if(j!==null&&j!==void 0)G.push(`Next expires ${j}`);return G}function kZ(Q){if(Q===null)return"Unknown";if(Q>=50)return"Healthy";if(Q>=15)return"Low";return"Critical"}function kQ(Q){return bQ(Q)}import{constants as IZ}from"node:fs";import{access as LZ,stat as _Z}from"node:fs/promises";import{homedir as RZ}from"node:os";import{join as k,normalize as s}from"node:path";function x(Q,Z){let $=Q[Z]?.trim();return $?$:null}function A(Q){return Q??process.env}var IQ="CODEX_LIMITS_HOME";function yZ(Q={}){let Z=A(Q.env),$=Q.homeDirectory??x(Z,"HOME")??x(Z,"USERPROFILE")??RZ(),G=Q.appData??x(Z,"APPDATA"),J=Q.localAppData??x(Z,"LOCALAPPDATA"),z=[];if(D(z,x(Z,IQ),"env"),D(z,x(Z,"CODEX_HOME"),"env"),$)D(z,k($,".codex"),"default"),D(z,k($,".config","codex"),"default"),D(z,k($,"Library","Application Support","Codex"),"default"),D(z,k($,"Library","Application Support","Parall","Codex",".codex"),"default");return D(z,G?k(G,"Codex"):null,"default"),D(z,J?k(J,"Codex"):null,"default"),SZ(z)}async function g(Q={}){let Z=A(Q.env),$=x(Z,IQ),G=await Promise.all(yZ(Q).map(async(J)=>({...J,exists:await fZ(J.path)})));return{overrideHome:$?s($):null,candidates:G,foundHome:G.find((J)=>J.exists)?.path??null}}function D(Q,Z,$){if(Z)Q.push({path:s(Z),source:$})}async function fZ(Q){try{if(!(await _Z(Q)).isDirectory())return!1;return await LZ(Q,IZ.R_OK),!0}catch{return!1}}function SZ(Q){let Z=new Set,$=[];for(let G of Q){let J=s(G.path),z=process.platform==="win32"?J.toLowerCase():J;if(!Z.has(z))Z.add(z),$.push({path:J,source:G.source})}return $}import{constants as a}from"node:fs";import{lstat as m,open as lZ,opendir as dZ,realpath as fQ}from"node:fs/promises";import{join as SQ}from"node:path";var EZ=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],wZ=["January","February","March","April","May","June","July","August","September","October","November","December"];function L(Q,Z={}){let $=Z.includeSeconds??!1,G=Math.max(Math.floor(Q/1000),0),J=Math.floor(G/86400);G%=86400;let z=Math.floor(G/3600);G%=3600;let j=Math.floor(G/60),K=G%60,X=[];if(J>0)X.push(`${J}d`);if(z>0)X.push(`${z}h`);if(j>0)X.push(`${j}m`);if($&&K>0)X.push(`${K}s`);return X.length>0?X.join(" "):$?`${K}s`:"0m"}function T(Q){if(typeof Q==="number"&&Number.isFinite(Q)){let Z=Q<10000000000?Q*1000:Q,$=new Date(Z);return Number.isNaN($.getTime())?null:$}if(typeof Q==="string"&&Q.trim().length>0){let Z=Q.trim(),$=Number(Z);if(Number.isFinite($))return T($);let G=new Date(Z);return Number.isNaN(G.getTime())?null:G}return null}function LQ(Q){return`${EZ[Q.getDay()]} ${Q.getDate()} ${wZ[Q.getMonth()]} ${Q.getFullYear()}`}import{isAbsolute as cZ,relative as RQ,resolve as _Q,sep as pZ}from"node:path";var gZ=/(?:chatgpt[-_]?account[-_]?id|access[-_]?token|refresh[-_]?token|id[-_]?token|session[-_]?token|api[-_]?key|account[-_]?id|authorization|cookie|client[-_]?secret|password|credential|secret|token)/,vZ=/[\u0000-\u001f\u007f-\u009f]/g,hZ=new RegExp(`["']?${gZ.source}["']?\\s*[:=]\\s*(?:"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|[^,\\r\\n}\\]&]+)`,"gi"),mZ=[hZ,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}(?:\.[A-Za-z0-9_-]{5,})?\b/g,/sk-[A-Za-z0-9_-]{10,}/g,/\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b/gi,/[A-Za-z0-9_-]{32,}/g];function _(Q){let Z=Q;for(let $ of mZ)Z=Z.replace($,"[redacted]");return Z.replace(vZ,"?")}function t(Q){return Q.map(_)}function v(Q,Z){let $=RQ(_Q(Q),_Q(Z));return $===""||!yQ($)}function R(Q,Z){let $=RQ(Q,Z);return $&&!yQ($)?uZ($):"."}function uZ(Q){let Z=_(Q);return Z.length<=240?Z:`${Z.slice(0,239)}…`}function yQ(Q){return Q===".."||Q.startsWith(`..${pZ}`)||cZ(Q)}function H(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function N(Q,Z){let $=Q[Z];return typeof $==="string"&&$.trim()?$.trim():null}var rZ=8,e=20,h=1000,oZ=512,iZ=1000,GQ=25000000,nZ=1e6,sZ=/^rollout-.*\.jsonl$/i;async function EQ(Q){let Z=SQ(Q,"sessions"),$=[];if(await K0(Z))return $.push("Skipped the symbolic-link Codex sessions directory."),{homePath:Q,sessionsRoot:Z,files:[],latestSnapshot:null,warnings:$};let G=await tZ(Z,$),J=[],z=null;for(let j of G.slice(0,e)){let K=R(Q,j.path);if(j.size>GQ){$.push("Skipped a local Codex session file because it is too large to inspect safely."),J.push(ZQ(j.path,K,j.modifiedAtMs,!1,"too-large"));continue}try{let X=await Q0(Q,j);if(J.push(ZQ(j.path,K,j.modifiedAtMs,X.snapshot!==null,null)),X.skippedOversizedLine)$.push("Skipped an oversized JSONL line in a local Codex session file.");if(X.snapshot&&(!z||$0(X.snapshot,z)))z=X.snapshot}catch(X){let Y=X instanceof c;$.push(Y?"Skipped a local Codex session file because it grew too large to inspect safely.":"Could not inspect a local Codex session file safely."),J.push(ZQ(j.path,K,j.modifiedAtMs,!1,Y?"too-large":"read-error"))}}if(G.length>e)$.push(`Skipped ${G.length-e} older session files to keep inspection small.`);if(G.length>0&&!z)$.push("No token-count rate-limit snapshot was found in local Codex session logs.");return{homePath:Q,sessionsRoot:Z,files:J,latestSnapshot:z,warnings:$}}async function tZ(Q,Z){let $={directories:0,files:[],hitLimit:!1,skippedSymlink:!1};if(await wQ(Q,0,$,Z),$.hitLimit)Z.push("Stopped session discovery after reaching a safe inspection limit.");if($.skippedSymlink)Z.push("Skipped symbolic links while inspecting Codex sessions.");let G;try{G=await fQ(Q)}catch{return[]}let J=[];for(let z of $.files){let j=await aZ(G,z,Z);if(j)J.push(j)}return J.sort((z,j)=>j.modifiedAtMs-z.modifiedAtMs||z.path.localeCompare(j.path))}async function aZ(Q,Z,$){try{let[G,J]=await Promise.all([m(Z),fQ(Z)]);if(!G.isFile()||!v(Q,J))return $.push("Could not inspect a local Codex session file safely."),null;return{path:Z,modifiedAtMs:G.mtimeMs,size:G.size,dev:G.dev,ino:G.ino}}catch{return $.push("Could not inspect a local Codex session file safely."),null}}async function wQ(Q,Z,$,G){if(Z>rZ||$.files.length>=h){$.hitLimit||=$.files.length>=h;return}if($.directories>=oZ){$.hitLimit=!0;return}$.directories+=1;let J;try{J=await eZ(Q,$)}catch{if(Z>0)G.push("Could not inspect part of the local Codex sessions directory safely.");return}for(let z of J){if($.files.length>=h){$.hitLimit=!0;return}let j=SQ(Q,z.name);if(z.isSymbolicLink()){$.skippedSymlink=!0;continue}if(z.isDirectory()){await wQ(j,Z+1,$,G);continue}if(z.isFile()&&sZ.test(z.name)){if($.files.push(j),$.files.length>=h){$.hitLimit=!0;return}}}}async function eZ(Q,Z){let $=await dZ(Q),G=[];for await(let J of $){if(G.length>=iZ){Z.hitLimit=!0;break}G.push(J)}return G.sort((J,z)=>z.name.localeCompare(J.name))}async function Q0(Q,Z){let $=Z.path,G=R(Q,$),J=await Z0(Z),z=null,j=null,K="",X=0,Y=0,W=!1,V=!1,O=(C)=>{let q=G0(C.endsWith("\r")?C.slice(0,-1):C);if(q.threadId)z=q.threadId;if(q.rateLimits)j={sessionFile:$,relativePath:G,threadId:z,eventTimestamp:q.timestamp,rateLimits:q.rateLimits}};for await(let C of J){let q=String(C);if(Y+=Buffer.byteLength(q,"utf8"),Y>GQ)throw new c;let F=0;while(F<q.length){let P=q.indexOf(`
5
- `,F),PZ=P===-1?q.length:P,FQ=q.slice(F,PZ);if(!W){let PQ=Buffer.byteLength(FQ,"utf8");if(X+PQ>nZ)K="",X=0,W=!0,V=!0;else K+=FQ,X+=PQ}if(P===-1)break;if(!W)O(K);K="",X=0,W=!1,F=P+1}}if(!W&&K.length>0)O(K);return{snapshot:j,skippedOversizedLine:V}}async function Z0(Q){let Z;try{let $=await m(Q.path);if(!$.isFile()||!QQ($,Q))throw new $Q;let G=a.O_NOFOLLOW,J=typeof G==="number"?a.O_RDONLY|G:a.O_RDONLY;Z=await lZ(Q.path,J);let[z,j]=await Promise.all([Z.stat(),m(Q.path)]);if(!z.isFile()||!j.isFile()||!QQ(z,Q)||!QQ(z,j))throw new $Q;if(z.size>GQ)throw new c;return Z.createReadStream({encoding:"utf8",highWaterMark:65536})}catch($){throw await Z?.close().catch(()=>{return}),$}}function QQ(Q,Z){return Q.dev===Z.dev&&Q.ino===Z.ino}function $0(Q,Z){let $=T(Q.eventTimestamp)?.getTime()??null,G=T(Z.eventTimestamp)?.getTime()??null;if($===null)return!1;return G===null||$>G}function G0(Q){let Z=J0(Q);if(!Z)return{threadId:null,timestamp:null,rateLimits:null};return{threadId:z0(Z),timestamp:N(Z,"timestamp"),rateLimits:j0(Z)}}function J0(Q){let Z=Q.trim();if(!Z)return null;try{let $=JSON.parse(Z);return H($)?$:null}catch{return null}}function z0(Q){if(Q.type!=="session_meta"||!H(Q.payload))return null;return N(Q.payload,"id")}function j0(Q){if(Q.type!=="event_msg"||!H(Q.payload))return null;if(Q.payload.type!=="token_count"||!H(Q.payload.rate_limits))return null;return Q.payload.rate_limits}function ZQ(Q,Z,$,G,J){return{path:Q,relativePath:Z,modifiedAtMs:$,hasSnapshot:G,error:J}}async function K0(Q){try{return(await m(Q)).isSymbolicLink()}catch{return!1}}class c extends Error{}class $Q extends Error{}import{opendir as Y0,realpath as mQ}from"node:fs/promises";import{extname as H0,join as W0}from"node:path";import{constants as JQ}from"node:fs";import{lstat as gQ,open as X0}from"node:fs/promises";class U extends Error{code;constructor(Q){super(Q);this.name="BoundedFileError",this.code=Q}}async function p(Q,Z){let $;try{let G=await gQ(Q);if(!G.isFile())throw new U("not-file");let J=JQ.O_NOFOLLOW,z=typeof J==="number"?JQ.O_RDONLY|J:JQ.O_RDONLY;$=await X0(Q,z);let j=await $.stat(),K=await gQ(Q);if(!j.isFile()||!K.isFile()||!vQ(G,j)||!vQ(j,K))throw new U("not-file");if(j.size>Z)throw new U("too-large");let X=Buffer.allocUnsafe(Z+1),Y=0;while(Y<=Z){let W=await $.read(X,Y,Z+1-Y,null);if(W.bytesRead===0)break;Y+=W.bytesRead}if(Y>Z)throw new U("too-large");return X.subarray(0,Y).toString("utf8")}catch(G){if(G instanceof U)throw G;if(hQ(G)&&G.code==="ENOENT")throw new U("not-found");if(hQ(G)&&G.code==="ELOOP")throw new U("not-file");throw new U("read-error")}finally{await $?.close().catch(()=>{return})}}function vQ(Q,Z){return Q.dev===Z.dev&&Q.ino===Z.ino}function hQ(Q){return Q instanceof Error&&"code"in Q}var V0=2,zQ=25,jQ=100,M0=64,U0=500,q0=1e6,x0=/(?:auth|token|cookie|session|secret|credential|api[-_]?key|keychain)/i;async function cQ(Q){let Z={directories:0,files:[],hitDirectoryLimit:!1,hitEntryLimit:!1,hitFileLimit:!1,skippedSensitive:!1,skippedSymlink:!1,warnings:[]},$;try{$=await mQ(Q)}catch{return{homePath:Q,files:[],warnings:["Could not inspect the local Codex state directory safely."]}}if(await pQ(Q,0,Z),Z.hitDirectoryLimit||Z.hitEntryLimit||Z.hitFileLimit)Z.warnings.push("Stopped local state discovery after reaching a safe inspection limit.");if(Z.skippedSensitive)Z.warnings.push("Skipped a sensitive-looking local file.");if(Z.skippedSymlink)Z.warnings.push("Skipped symbolic links while inspecting local Codex state.");let G=Z.files.sort((z,j)=>z.localeCompare(j)),J=[];for(let z of G.slice(0,zQ)){let j=R(Q,z);try{let K=await mQ(z);if(!v($,K))throw new U("not-file");let X=await p(z,q0),Y=B0(X,Z.warnings);J.push({path:z,relativePath:j,json:Y.value,error:Y.error})}catch(K){Z.warnings.push(K instanceof U&&K.code==="too-large"?"Skipped a local Codex state file because it is too large to inspect safely.":"Could not read a local Codex state file safely.")}}if(G.length>zQ)Z.warnings.push(`Skipped ${G.length-zQ} extra files to keep inspection small.`);return{homePath:Q,files:J,warnings:Z.warnings}}async function pQ(Q,Z,$){if(Z>V0||$.files.length>=jQ){$.hitFileLimit||=$.files.length>=jQ;return}if($.directories>=M0){$.hitDirectoryLimit=!0;return}$.directories+=1;let G=await N0(Q,$);for(let J of G){if($.files.length>=jQ){$.hitFileLimit=!0;return}if(x0.test(J.name)){$.skippedSensitive=!0;continue}let z=W0(Q,J.name);if(J.isSymbolicLink())$.skippedSymlink=!0;else if(J.isDirectory())await pQ(z,Z+1,$);else if(J.isFile()&&H0(J.name).toLowerCase()===".json")$.files.push(z)}}async function N0(Q,Z){try{let $=await Y0(Q),G=[];for await(let J of $){if(G.length>=U0){Z.hitEntryLimit=!0;break}G.push(J)}return G.sort((J,z)=>J.name.localeCompare(z.name))}catch{return Z.warnings.push("Could not inspect part of the local Codex state directory safely."),[]}}function B0(Q,Z){try{return{value:JSON.parse(Q),error:null}}catch{return Z.push("Could not parse JSON in a local Codex state file."),{value:null,error:"invalid-json"}}}import{join as O0,normalize as C0}from"node:path";function B(Q,Z,$){return{code:Q,source:Z,severity:"warning",message:$}}function I(Q){return Q.map((Z)=>_(Z.message))}var D0=1e6;async function u(Q={}){let Z=A(Q.env),$=x(Z,"CODEX_LIMITS_ACCESS_TOKEN"),G=x(Z,"CODEX_LIMITS_ACCOUNT_ID");if($&&G)return{credentials:{accessToken:$,accountId:G},status:"configured",diagnostics:[]};if($||G)return{credentials:null,status:"partial",diagnostics:[B("auth.environment.partial","authentication","Codex authentication environment variables are incomplete.")]};let J=await T0(Q);return J?F0(J):{credentials:null,status:"missing",diagnostics:[]}}async function T0(Q){if(Q.authFile)return C0(Q.authFile);let Z=await g(Q);return Z.foundHome?O0(Z.foundHome,"auth.json"):null}async function F0(Q){let Z;try{Z=await p(Q,D0)}catch($){if($ instanceof U&&$.code==="not-found")return{credentials:null,status:"missing",diagnostics:[]};let G=$ instanceof U&&$.code==="too-large";return{credentials:null,status:"unreadable",diagnostics:[B(G?"auth.file.too-large":"auth.file.unreadable","authentication",G?"Codex auth.json is too large to inspect safely.":"Codex auth.json could not be read safely.")]}}try{let $=JSON.parse(Z);if(!H($))return KQ();let G=H($.tokens)?$.tokens:$,J=N(G,"access_token"),z=N(G,"account_id");return J&&z?{credentials:{accessToken:J,accountId:z},status:"configured",diagnostics:[]}:KQ()}catch{return KQ()}}function KQ(){return{credentials:null,status:"malformed",diagnostics:[B("auth.file.malformed","authentication","Codex auth.json is malformed or does not contain required credentials.")]}}var P0=/[\u0000-\u0020\u007f-\u009f]/;function XQ(Q){return Q.length>0&&Q.length<=512&&!P0.test(Q)}import{request as A0}from"node:http";import{request as b0}from"node:https";var k0=new Set(["127.0.0.1","::1","[::1]","localhost"]);function f(Q){try{let Z=new URL(Q);return Z.username="",Z.password="",Z.search="",Z.hash="",Z.href}catch{return"[invalid endpoint]"}}async function lQ(Q){let Z=I0(Q.endpoint);if(!Z.ok)return Z;if(Q.signal?.aborted)return M("aborted");let $=Q.fetch??globalThis.fetch;if(!$)return uQ(Z.url,Q);let G=await L0(Z.url,Q,$);if(G.ok||G.code==="aborted"||!y0(G,Q.fallbackOnHttpError??!1))return G;let J=await uQ(Z.url,Q);if(J.ok||J.code==="http-error"||J.code==="invalid-json"||J.code==="response-too-large")return J;return G}function l(Q){let Z={...Q,method:"GET"};return delete Z.body,lQ(Z)}function I0(Q){let Z;try{Z=new URL(Q)}catch{return M("invalid-url")}if(Z.username||Z.password)return M("invalid-url");if(Z.protocol==="https:")return{ok:!0,url:Z};if(Z.protocol==="http:"&&k0.has(Z.hostname.toLowerCase()))return{ok:!0,url:Z};return M("unsupported-protocol")}async function L0(Q,Z,$){let G=rQ(Z.timeoutMs,Z.signal);try{let J=await $(Q.href,{method:Z.method??"GET",headers:Z.headers,redirect:"error",signal:G.signal,...Z.body===void 0?{}:{body:Z.body}});if(!J.ok)return await dQ(J),M("http-error",WQ(J.status));let z=await _0(J,Z.maxResponseBytes);return{ok:!0,status:WQ(J.status)??200,payload:z,transport:"fetch"}}catch(J){if(J instanceof y)return M("response-too-large");if(J instanceof d)return M("invalid-json");if(Z.signal?.aborted)return M("aborted");if(G.didTimeout())return M("timeout");return M("network-error")}finally{G.dispose()}}async function _0(Q,Z){let $=Number(Q.headers?.get("content-length"));if(Number.isFinite($)&&$>Z)throw await dQ(Q),new y;if(Q.body){let G=Q.body.getReader(),J=[],z=0;while(!0){let K=await G.read();if(K.done)break;if(!K.value)continue;if(z+=K.value.byteLength,z>Z)throw await G.cancel?.(),new y;J.push(K.value)}let j=Buffer.concat(J.map((K)=>Buffer.from(K)),z).toString("utf8");return HQ(j)}if(Q.text){let G=await Q.text();if(Buffer.byteLength(G,"utf8")>Z)throw new y;return HQ(G)}throw new d}async function dQ(Q){if(!Q.body)return;try{await Q.body.getReader().cancel?.()}catch{}}function uQ(Q,Z){return new Promise(($)=>{let G=rQ(Z.timeoutMs,Z.signal),J=!1,z=null,j=(X)=>{if(J)return;J=!0,G.dispose(),$(X)},K=()=>{z?.destroy(),j(M(Z.signal?.aborted?"aborted":"timeout"))};G.signal.addEventListener("abort",K,{once:!0});try{z=(Q.protocol==="http:"?A0:b0)(Q,{method:Z.method??"GET",headers:Z.headers,signal:G.signal},(Y)=>R0(Y,Z.maxResponseBytes,j)),z.on("error",()=>{if(Z.signal?.aborted)j(M("aborted"));else if(G.didTimeout())j(M("timeout"));else j(M("network-error"))}),z.end(Z.body)}catch{j(M("network-error"))}})}function R0(Q,Z,$){let G=WQ(Q.statusCode);if(G===null||G<200||G>=300){$(M("http-error",G)),YQ(Q);return}let J=Number(Q.headers["content-length"]);if(Number.isFinite(J)&&J>Z){$(M("response-too-large")),YQ(Q);return}let z=[],j=0;Q.on("data",(K)=>{let X=Buffer.isBuffer(K)?K:Buffer.from(K);if(j+=X.length,j>Z){$(M("response-too-large")),YQ(Q);return}z.push(X)}),Q.on("end",()=>{try{let K=HQ(Buffer.concat(z,j).toString("utf8"));$({ok:!0,status:G,payload:K,transport:"node"})}catch{$(M("invalid-json"))}}),Q.on("error",()=>$(M("network-error")))}function YQ(Q){Q.destroy(),Q.socket.destroy()}function rQ(Q,Z){let $=new AbortController,G=!1,J=Number.isFinite(Q)&&Q>0?Math.min(Math.floor(Q),2147483647):1,z=setTimeout(()=>{G=!0,$.abort()},J),j=()=>$.abort();if(Z?.addEventListener("abort",j,{once:!0}),Z?.aborted)j();return{signal:$.signal,didTimeout:()=>G,dispose:()=>{clearTimeout(z),Z?.removeEventListener("abort",j)}}}function y0(Q,Z){return Q.code==="network-error"||Q.code==="timeout"||Q.code==="invalid-json"||Z&&Q.code==="http-error"}function HQ(Q){try{return JSON.parse(Q)}catch{throw new d}}function WQ(Q){return typeof Q==="number"&&Number.isInteger(Q)&&Q>=0?Q:null}function M(Q,Z=null){return{ok:!1,code:Q,status:Z}}class y extends Error{}class d extends Error{}function r(Q,Z){switch(Q.code){case"aborted":return B("network.request.aborted","network",`${Z} lookup was cancelled.`);case"http-error":return B("network.response.http","network",Q.status===null?`${Z} endpoint returned an invalid HTTP status.`:`${Z} endpoint returned HTTP ${Q.status}.`);case"invalid-json":return B("network.response.invalid-json","network",`${Z} endpoint returned malformed JSON.`);case"invalid-url":return B("network.endpoint.invalid","network",`${Z} endpoint URL is invalid.`);case"response-too-large":return B("network.response.too-large","network",`${Z} endpoint response was too large.`);case"timeout":return B("network.request.timeout","network",`${Z} lookup timed out.`);case"unsupported-protocol":return B("network.endpoint.protocol","network",`${Z} endpoint must use HTTPS or loopback HTTP.`);case"network-error":return B("network.request.failed","network",`${Z} lookup failed.`)}}var sQ=["credits","reset_credits","items"],tQ=["available_count","availableCount","available"],aQ=["total_earned_count","earned_this_period","earnedThisPeriod","totalEarnedCount"],f0=64,S0=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(?:Z|[+-](\d{2}):(\d{2}))$/i;function eQ(Q,Z,$){if(!H(Q)||!E0(Q))return S(Z,["Live reset coupon endpoint returned an unexpected payload."]);let G=h0(Q,sQ);if(G.malformed)return S(Z,["Live reset coupon endpoint returned an unexpected payload."]);let J=G.value,z=J.map((V,O)=>w0(V,O+1,$)).filter((V)=>V!==null).sort(v0).map((V,O)=>({...V,index:O+1})),j=z.filter((V)=>V.status?.toLowerCase()==="available"),K=j[0]??z[0]??null,X=nQ(Q,tQ),Y=nQ(Q,aQ),W=[];if(J.length!==z.length)W.push("Live reset coupon endpoint ignored malformed coupon entries.");if(X.malformed||Y.malformed)W.push("Live reset coupon endpoint ignored malformed summary fields.");if(X.value!==null&&X.value!==j.length)W.push("Live reset coupon endpoint returned inconsistent availability data.");return{status:W.length>0?"partial":"available",available:X.value,earnedThisPeriod:Y.value,nextExpirationDate:K?.expirationDate??null,nextExpirationIn:K?.expiresIn??null,items:z,warnings:W,source:{live:!0,label:"live Codex reset-credit endpoint",endpoint:Z}}}function S(Q,Z=[]){return{status:"unavailable",available:null,earnedThisPeriod:null,nextExpirationDate:null,nextExpirationIn:null,items:[],warnings:Z,source:{live:!1,label:"live Codex reset-credit endpoint",endpoint:Q}}}function E0(Q){return[...sQ,...tQ,...aQ].some((Z)=>(Z in Q))}function w0(Q,Z,$){if(!H(Q))return null;let G=Q.id,J=typeof G==="string"&&XQ(G)?G:null,z=Q.reset_type??Q.resetType,j=typeof z==="string"&&/^[a-z][a-z0-9_-]{0,63}$/i.test(z)?z:null,K="expires_at"in Q||"expiresAt"in Q,X="granted_at"in Q||"grantedAt"in Q,Y=N(Q,"expires_at")??N(Q,"expiresAt"),W=N(Q,"granted_at")??N(Q,"grantedAt"),V=oQ(Y),O=oQ(W),C=N(Q,"status"),q=C&&/^[a-z][a-z0-9_-]{0,63}$/i.test(C)?C:null,F=O?W:null,P=V?Y:null;if("id"in Q&&!J||X&&!O||K&&!V||!q&&!F&&!P)return null;return{id:J,resetType:j,index:Z,status:q,grantedAt:F,expiresAt:P,expirationDate:V?LQ(V):null,expiresIn:V?L(V.getTime()-$.getTime()):null}}function oQ(Q){if(!Q||Q.length>f0)return null;let Z=S0.exec(Q);if(!Z)return null;let $=Number(Z[1]),G=Number(Z[2]),J=Number(Z[3]),z=Number(Z[4]),j=Number(Z[5]),K=Number(Z[6]),X=Z[8]===void 0?0:Number(Z[8]),Y=Z[9]===void 0?0:Number(Z[9]);if(G<1||G>12||J<1||J>g0($,G)||z>23||j>59||K>59||X>23||Y>59)return null;let W=new Date(Q);return Number.isNaN(W.getTime())?null:W}function g0(Q,Z){if(Z===2)return Q%4===0&&(Q%100!==0||Q%400===0)?29:28;return Z===4||Z===6||Z===9||Z===11?30:31}function v0(Q,Z){return iQ(Q.expiresAt)-iQ(Z.expiresAt)}function iQ(Q){return T(Q)?.getTime()??Number.POSITIVE_INFINITY}function h0(Q,Z){let $=!1;for(let G of Z){if(!(G in Q))continue;$=!0;let J=Q[G];if(Array.isArray(J))return{value:J,malformed:!1}}return{value:[],malformed:$}}function nQ(Q,Z){let $=!1;for(let G of Z){if(!(G in Q))continue;$=!0;let J=Q[G];if(typeof J==="number"&&Number.isInteger(J)&&J>=0)return{value:J,malformed:!1}}return{value:null,malformed:$}}var VQ="https://chatgpt.com/backend-api/wham/rate-limit-reset-credits",_2=`${VQ}/consume`,m0=1e4,c0=1e6;async function ZZ(Q={}){let Z=Q.endpoint??VQ,$=f(Z),G=await u(Q);if(!G.credentials){let z=I(G.diagnostics);return p0($,z.length>0?z:["Live reset coupons require a readable Codex auth.json file or CODEX_LIMITS_ACCESS_TOKEN and CODEX_LIMITS_ACCOUNT_ID."])}let J=u0(Z,G.credentials,Q);try{let z=await(Q.transport??l)(J);return z.ok?eQ(z.payload,$,Q.now??new Date):QZ($,z)}catch{return QZ($,{ok:!1,code:"network-error",status:null})}}function p0(Q=VQ,Z=[]){return S(f(Q),Z)}function QZ(Q,Z){return S(Q,I([r(Z,"Live reset coupon")]))}function u0(Q,Z,$){return{endpoint:Q,headers:l0(Z),timeoutMs:$.timeoutMs??m0,maxResponseBytes:c0,...$.fetch?{fetch:$.fetch}:{},...$.signal?{signal:$.signal}:{}}}function l0(Q){return{Authorization:`Bearer ${Q.accessToken}`,"ChatGPT-Account-ID":Q.accountId,"OpenAI-Beta":"codex-1",originator:"Codex Desktop",Accept:"application/json"}}var jZ=5,qQ="5-hour usage limit",xQ="Weekly usage limit",NQ=["fiveHour","five_hour","fiveHourWindow","five_hour_window","primary","primaryWindow","primary_window","main","mainWindow"],BQ=["weekly","week","weeklyWindow","weekly_window","secondary","secondaryWindow","secondary_window","backup","backupWindow"],d0=["used_percent","usedPercent","used","usage","percentUsed","usagePercent","usagePercentage","percent"],r0=["remaining_percent","remainingPercent","remaining","percentRemaining","availablePercent","available_percentage"],o0=["resets_at","resetsAt","resetAt","resetTime","reset_at","reset","ends_at","endsAt","windowEnd"],i0=["resetsIn","resetIn","resets_in","reset_in","timeUntilReset"],n0=["limit_window_seconds","limitWindowSeconds","window_seconds","windowSeconds","window_length_seconds","windowLengthSeconds"],s0=["window_minutes","windowMinutes","window_length_minutes","windowLengthMinutes"],t0=18000,a0=604800,e0=/^(?:(\d+)d)?(?:\s*(\d+)h)?(?:\s*(\d+)m)?(?:\s*(\d+)s)?$/i;function KZ(Q,Z=new Date){let $=Q.latestSnapshot;if(!$)return DQ(Q.warnings);return n(OQ($.rateLimits,Z),Q.warnings)}function OQ(Q,Z=new Date){return VZ(o(Q,NQ),o(Q,BQ),Z)}function XZ(Q){return o(Q,NQ)!==null||o(Q,BQ)!==null}function E(Q){let Z=zZ(b(Q,n0,!1)),$=zZ(b(Q,s0,!1)),G=Z??($===null?null:$*60);if(G===t0)return"fiveHour";if(G===a0)return"weekly";return null}function YZ(Q,Z){return{...Q,source:Z}}function CQ(Q,Z,$=[]){return{...n(Q,$),source:Z}}function HZ(Q,Z=new Date){let $={fiveHour:null,weekly:null};for(let G of Q.files){if(!G.json)continue;let J=Q1(G.json,Z);$=MZ($,J.windows)}return n($,Q.warnings)}function DQ(Q=[]){return{status:"unavailable",windows:{fiveHour:null,weekly:null},warnings:Q}}function WZ(Q,Z){let $=MZ(Q.windows,Z.windows);return n($,[...Q.warnings,...Z.warnings])}function Q1(Q,Z){if(!H(Q))return{windows:{fiveHour:null,weekly:null}};let $=UQ(Q,NQ),G=UQ(Q,BQ);if($||G)return{windows:VZ($,G,Z)};let J=E(Q)??"fiveHour",z=MQ(Q,J==="weekly"?xQ:qQ,Z);return{windows:{fiveHour:J==="fiveHour"?z:null,weekly:J==="weekly"?z:null}}}function VZ(Q,Z,$){let G=[];if(Q)G.push({fallbackKind:"fiveHour",value:Q});if(Z)G.push({fallbackKind:"weekly",value:Z});return{fiveHour:MQ($Z(G,"fiveHour"),qQ,$),weekly:MQ($Z(G,"weekly"),xQ,$)}}function MQ(Q,Z,$){if(!Q)return null;let G=JZ(b(Q,d0,!0)),J=JZ(b(Q,r0,!0)),z=G??(J===null?null:i(100-J)),j=J??(G===null?null:i(100-G)),K=b(Q,o0,!0),X=T(K),Y=X?X.toISOString():null,W=X?L(X.getTime()-$.getTime()):G1(b(Q,i0,!0)),V={label:Z,remainingPercent:j,usedPercent:z,resetsAt:Y,resetsIn:W};return UZ(V)?V:null}function n(Q,Z){return{status:Z1(Q),windows:Q,warnings:Z}}function Z1(Q){let Z=[Q.fiveHour,Q.weekly].filter(($)=>UZ($));if(Z.length===0)return"unavailable";return Z.every($1)?"available":"partial"}function $Z(Q,Z){let $=Q.find((G)=>E(G.value)===Z);if($)return $.value;return Q.find((G)=>G.fallbackKind===Z&&E(G.value)===null)?.value??null}function MZ(Q,Z){return{fiveHour:GZ(Q.fiveHour,Z.fiveHour,qQ),weekly:GZ(Q.weekly,Z.weekly,xQ)}}function GZ(Q,Z,$){if(!Q&&!Z)return null;return{label:$,remainingPercent:Q?.remainingPercent??Z?.remainingPercent??null,usedPercent:Q?.usedPercent??Z?.usedPercent??null,resetsAt:Q?.resetsAt??Z?.resetsAt??null,resetsIn:Q?.resetsIn??Z?.resetsIn??null}}function UZ(Q){return Q!==null&&(Q.remainingPercent!==null||Q.usedPercent!==null||Q.resetsAt!==null||Q.resetsIn!==null)}function $1(Q){return Q!==null&&Q.remainingPercent!==null&&Q.usedPercent!==null&&(Q.resetsAt!==null||Q.resetsIn!==null)}function UQ(Q,Z,$=0){if($>jZ)return null;for(let G of Z){let J=Q[G];if(H(J))return J}for(let G of Object.values(Q)){if(!H(G))continue;let J=UQ(G,Z,$+1);if(J)return J}return null}function o(Q,Z){for(let $ of Z){let G=Q[$];if(H(G))return G}return null}function b(Q,Z,$,G=0){if(G>jZ)return;for(let J of Z)if(J in Q)return Q[J];if(!$)return;for(let J of Object.values(Q)){if(!H(J))continue;let z=b(J,Z,$,G+1);if(z!==void 0)return z}return}function JZ(Q){if(typeof Q==="number"&&Number.isFinite(Q))return i(Q);if(typeof Q==="string"&&Q.trim().length>0){let Z=Q.trim(),$=Z.endsWith("%")?Z.slice(0,-1):Z,G=Number($);return Number.isFinite(G)?i(G):null}return null}function i(Q){return Math.round(Math.min(Math.max(Q,0),100)*10)/10}function zZ(Q){if(typeof Q==="number"&&Number.isFinite(Q))return Q;if(typeof Q==="string"&&Q.trim().length>0){let Z=Number(Q);return Number.isFinite(Z)?Z:null}return null}function G1(Q){let Z=J1(Q);if(!Z||Z.length>100)return null;let G=e0.exec(Z)?.slice(1);if(!G||G.every((j)=>j===void 0))return null;let J=[86400,3600,60,1],z=0;for(let[j,K]of G.entries()){if(K===void 0)continue;let X=Number(K),Y=X*J[j];if(!Number.isSafeInteger(X)||!Number.isSafeInteger(Y))return null;if(z+=Y,!Number.isSafeInteger(z))return null}return z<=Math.floor(Number.MAX_SAFE_INTEGER/1000)?L(z*1000):null}function J1(Q){if(typeof Q==="string"&&Q.trim().length>0)return Q.trim();return null}var z1=5,j1=1000,K1={kind:"unavailable",label:"Unavailable"};function xZ(Q,Z,$){let G=X1(Q)??Y1(Q);if(!G)return w(["Live usage endpoint returned an unexpected payload."]);let J=CQ(OQ(G,$),{kind:"api",label:"API",endpoint:Z});if(J.status==="unavailable")return w(["Live usage endpoint returned an unexpected payload."]);if(J.status==="partial")return{...J,warnings:["Live usage endpoint returned incomplete usage data."]};return J}function w(Q){return CQ({fiveHour:null,weekly:null},K1,Q)}function X1(Q){return NZ(Q,(Z)=>{if(!H(Z))return null;let $=Z.rate_limits??Z.rateLimits??Z.rate_limit??Z.rateLimit;if(H($))return $;return XZ(Z)?Z:null})}function Y1(Q){return NZ(Q,(Z)=>{if(!Array.isArray(Z))return null;let $=Z.find((J)=>qZ(J,"fiveHour")),G=Z.find((J)=>qZ(J,"weekly"));return $||G?{fiveHour:$,weekly:G}:null})}function NZ(Q,Z){let $=[{value:Q,depth:0}],G=new WeakSet;for(let J=0;J<$.length;J+=1){let z=$[J];if(!z)break;let j=Z(z.value);if(j)return j;if(z.depth>=z1||typeof z.value!=="object"||!z.value)continue;if(G.has(z.value))continue;G.add(z.value);let K=Array.isArray(z.value)?z.value:H(z.value)?Object.values(z.value):[];for(let X of K){if($.length>=j1)break;$.push({value:X,depth:z.depth+1})}}return null}function qZ(Q,Z){if(!H(Q))return!1;let $=E(Q);if($)return $===Z;let G=String(Q.type??Q.kind??Q.name??Q.label??Q.window??"").toLowerCase();return Z==="fiveHour"?G.includes("primary")||G.includes("5-hour")||G.includes("five"):G.includes("secondary")||G.includes("weekly")||G.includes("week")}var H1="https://chatgpt.com/backend-api/codex/usage",W1=1e4,V1=1e6;async function BZ(Q={}){return(await M1(Q)).usage}async function M1(Q={}){let Z=q1(Q),$=f(Z),G=await u(Q);if(!G.credentials){let j=I(G.diagnostics);return{usage:w(j.length>0?j:["Live usage requires Codex authentication."]),authenticationFound:!1,endpointStatus:"not-checked"}}let J={endpoint:Z,headers:U1(G.credentials),timeoutMs:Q.timeoutMs??W1,maxResponseBytes:V1,fallbackOnHttpError:!0,...Q.fetch?{fetch:Q.fetch}:{},...Q.signal?{signal:Q.signal}:{}},z;try{z=await(Q.transport??l)(J)}catch{z={ok:!1,code:"network-error",status:null}}return{usage:z.ok?xZ(z.payload,$,Q.now??new Date):N1(z),authenticationFound:!0,endpointStatus:x1(z)}}function U1(Q){return{Authorization:`Bearer ${Q.accessToken}`,"ChatGPT-Account-ID":Q.accountId,"OpenAI-Beta":"codex-1",originator:"Codex Desktop",Accept:"application/json","User-Agent":"Codex Desktop",Referer:"https://chatgpt.com/codex/cloud/settings/analytics",Origin:"https://chatgpt.com"}}function q1(Q){let Z=A(Q.env);return Q.usageEndpoint??x(Z,"CODEX_LIMITS_USAGE_ENDPOINT")??H1}function x1(Q){if(Q.ok)return"reachable";switch(Q.code){case"http-error":case"invalid-json":case"response-too-large":return"reachable";case"aborted":return"not-checked";case"invalid-url":case"network-error":case"timeout":case"unsupported-protocol":return"unreachable"}}function N1(Q){return w(I([r(Q,"Live usage")]))}var B1={kind:"local",label:"Local"};async function OZ(Q={}){let Z=Q.includeCoupons===!1?Promise.resolve(null):ZZ(Q),[$,G]=await Promise.all([O1(Q),Z]),J=G?C1(G):null;return{windows:$.windows,coupons:J,warnings:t([...$.warnings,...J?.warnings??[]])}}async function O1(Q={}){let Z=await BZ(Q);if(Z.status!=="unavailable")return Z;let $=YZ(await D1(Q),B1);return $.status!=="unavailable"?$:{...$,warnings:[...Z.warnings,...$.warnings]}}function C1(Q){return{status:Q.status,available:Q.available,earnedThisPeriod:Q.earnedThisPeriod,nextExpirationDate:Q.nextExpirationDate,nextExpirationIn:Q.nextExpirationIn,items:Q.items.map((Z)=>({index:Z.index,status:Z.status,grantedAt:Z.grantedAt,expiresAt:Z.expiresAt,expirationDate:Z.expirationDate,expiresIn:Z.expiresIn})),warnings:t(Q.warnings)}}async function D1(Q={}){let Z=Q.now??new Date,$=await g(Q);if(!$.foundHome)return DQ(["No readable local Codex home directory was found."]);let[G,J]=await Promise.all([EQ($.foundHome),cQ($.foundHome)]);return WZ(KZ(G,Z),HZ(J,Z))}var TQ="Codex Limits",T1="Check Codex limits, resets, and credits.",CZ="Could not load Codex limits.";function F1(Q={}){let Z=new WeakSet,$=Q.getLimits??OZ,G=Q.nextFrame??(()=>new Promise((J)=>setTimeout(J,0)));return{id:"codex-limits",tui:async(J)=>{if(Z.has(J))return;let z=P1(J,$,G),j;try{let X=A1(J,z);j=typeof X==="function"?X:void 0}catch{throw Error("Could not register the codex-limits OpenCode command.")}let K=()=>{if(!Z.delete(J))return;try{j?.()}catch{}};Z.add(J);try{J.lifecycle.onDispose(K)}catch{throw K(),Error("Could not register the codex-limits OpenCode lifecycle.")}}}}function P1(Q,Z,$){let G=0;return{title:TQ,value:"codex-limits.show",description:T1,category:"Codex",slash:{name:"codex-limits"},onSelect:async(J)=>{let z=++G;J?.clear(),Q.ui.dialog.clear(),await $();let j=Q.ui.dialog,K=(X)=>j.replace(()=>Q.ui.DialogAlert({title:TQ,message:X}));j.setSize("large"),K("Loading Codex limits...");try{let X=await Z();if(z===G)K(kQ(X))}catch{if(z===G)Q.ui.toast({variant:"error",title:TQ,message:CZ}),K(CZ)}}}}function A1(Q,Z){let $=Q;if(typeof $.keymap?.registerLayer==="function")return $.keymap.registerLayer({commands:[{namespace:"palette",name:Z.value,title:Z.title,desc:Z.description,category:Z.category,slashName:Z.slash?.name,slashAliases:Z.slash?.aliases,run:()=>Z.onSelect?.()}],bindings:[]});if(typeof $.command?.register==="function")return $.command.register(()=>[Z]);throw Error("No supported OpenCode command API is available.")}var b1=F1(),DZ=b1;function TZ(Q){return Q}var FZ=TZ(DZ),K3=FZ,z3=FZ.tui;export{z3 as tui,K3 as default};
4
+ `)}function bQ(Q,Z){let $=Z.remainingPercent;return[`${Q} ${kZ($)}`,`Remaining ${$===null?"Unknown":`${Math.round($)}% remaining`}`,AZ($),`Reset ${Z.resetsIn?`in ${Z.resetsIn}`:"unknown"}`]}function AZ(Q){if(Q===null)return`[${" ".repeat(22)}] Unknown`;let Z=Math.min(Math.max(Q,0),100),$=Math.round(Z/100*22);return`[${"=".repeat($)}${" ".repeat(22-$)}] ${Math.round(Z)}%`}function bZ(Q){let Z=Q.coupons?.available,G=[`Reset credits ${Z===null||Z===void 0?"Unknown":`${Z} ${Z===1?"credit":"credits"} available`}`],J=Q.coupons?.nextExpirationIn,z=Q.coupons?.nextExpirationDate,j=J&&z?`${J} (${z})`:J??z;if(j!==null&&j!==void 0)G.push(`Next expires ${j}`);return G}function kZ(Q){if(Q===null)return"Unknown";if(Q>=50)return"Healthy";if(Q>=15)return"Low";return"Critical"}function IQ(Q){return kQ(Q)}import{constants as IZ}from"node:fs";import{access as LZ,stat as _Z}from"node:fs/promises";import{homedir as RZ}from"node:os";import{join as k,normalize as t}from"node:path";function x(Q,Z){let $=Q[Z]?.trim();return $?$:null}function A(Q){return Q??process.env}var LQ="CODEX_LIMITS_HOME";function yZ(Q={}){let Z=A(Q.env),$=Q.homeDirectory??x(Z,"HOME")??x(Z,"USERPROFILE")??RZ(),G=Q.appData??x(Z,"APPDATA"),J=Q.localAppData??x(Z,"LOCALAPPDATA"),z=[];if(D(z,x(Z,LQ),"env"),D(z,x(Z,"CODEX_HOME"),"env"),$)D(z,k($,".codex"),"default"),D(z,k($,".config","codex"),"default"),D(z,k($,"Library","Application Support","Codex"),"default"),D(z,k($,"Library","Application Support","Parall","Codex",".codex"),"default");return D(z,G?k(G,"Codex"):null,"default"),D(z,J?k(J,"Codex"):null,"default"),SZ(z)}async function m(Q={}){let Z=A(Q.env),$=x(Z,LQ),G=await Promise.all(yZ(Q).map(async(J)=>({...J,exists:await fZ(J.path)})));return{overrideHome:$?t($):null,candidates:G,foundHome:G.find((J)=>J.exists)?.path??null}}function D(Q,Z,$){if(Z)Q.push({path:t(Z),source:$})}async function fZ(Q){try{if(!(await _Z(Q)).isDirectory())return!1;return await LZ(Q,IZ.R_OK),!0}catch{return!1}}function SZ(Q){let Z=new Set,$=[];for(let G of Q){let J=t(G.path),z=process.platform==="win32"?J.toLowerCase():J;if(!Z.has(z))Z.add(z),$.push({path:J,source:G.source})}return $}import{constants as e}from"node:fs";import{lstat as f,open as lZ,opendir as dZ,realpath as $Q}from"node:fs/promises";import{join as SQ}from"node:path";var EZ=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],wZ=["January","February","March","April","May","June","July","August","September","October","November","December"];function L(Q,Z={}){let $=Z.includeSeconds??!1,G=Math.max(Math.floor(Q/1000),0),J=Math.floor(G/86400);G%=86400;let z=Math.floor(G/3600);G%=3600;let j=Math.floor(G/60),K=G%60,X=[];if(J>0)X.push(`${J}d`);if(z>0)X.push(`${z}h`);if(j>0)X.push(`${j}m`);if($&&K>0)X.push(`${K}s`);return X.length>0?X.join(" "):$?`${K}s`:"0m"}function T(Q){if(typeof Q==="number"&&Number.isFinite(Q)){let Z=Q<10000000000?Q*1000:Q,$=new Date(Z);return Number.isNaN($.getTime())?null:$}if(typeof Q==="string"&&Q.trim().length>0){let Z=Q.trim(),$=Number(Z);if(Number.isFinite($))return T($);let G=new Date(Z);return Number.isNaN(G.getTime())?null:G}return null}function _Q(Q){return`${EZ[Q.getDay()]} ${Q.getDate()} ${wZ[Q.getMonth()]} ${Q.getFullYear()}`}import{isAbsolute as cZ,relative as yQ,resolve as RQ,sep as pZ}from"node:path";var gZ=/(?:chatgpt[-_]?account[-_]?id|access[-_]?token|refresh[-_]?token|id[-_]?token|session[-_]?token|api[-_]?key|account[-_]?id|authorization|cookie|client[-_]?secret|password|credential|secret|token)/,vZ=/[\u0000-\u001f\u007f-\u009f]/g,mZ=new RegExp(`["']?${gZ.source}["']?\\s*[:=]\\s*(?:"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|[^,\\r\\n}\\]&]+)`,"gi"),hZ=[mZ,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}(?:\.[A-Za-z0-9_-]{5,})?\b/g,/sk-[A-Za-z0-9_-]{10,}/g,/\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b/gi,/[A-Za-z0-9_-]{32,}/g];function _(Q){let Z=Q;for(let $ of hZ)Z=Z.replace($,"[redacted]");return Z.replace(vZ,"?")}function a(Q){return Q.map(_)}function R(Q,Z){let $=yQ(RQ(Q),RQ(Z));return $===""||!fQ($)}function y(Q,Z){let $=yQ(Q,Z);return $&&!fQ($)?uZ($):"."}function uZ(Q){let Z=_(Q);return Z.length<=240?Z:`${Z.slice(0,239)}…`}function fQ(Q){return Q===".."||Q.startsWith(`..${pZ}`)||cZ(Q)}function W(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function N(Q,Z){let $=Q[Z];return typeof $==="string"&&$.trim()?$.trim():null}var rZ=8,QQ=20,h=1000,oZ=512,iZ=1000,JQ=25000000,nZ=1e6,sZ=/^rollout-.*\.jsonl$/i;async function EQ(Q){let Z=SQ(Q,"sessions"),$=[],G=await tZ(Q,Z,$);if(!G)return{homePath:Q,sessionsRoot:Z,files:[],latestSnapshot:null,warnings:$};let J=await aZ(Z,G,$),z=[],j=null;for(let K of J.slice(0,QQ)){let X=y(Q,K.path);if(K.size>JQ){$.push("Skipped a local Codex session file because it is too large to inspect safely."),z.push(ZQ(K.path,X,K.modifiedAtMs,!1,"too-large"));continue}try{let Y=await Z0(Q,K);if(z.push(ZQ(K.path,X,K.modifiedAtMs,Y.snapshot!==null,null)),Y.skippedOversizedLine)$.push("Skipped an oversized JSONL line in a local Codex session file.");if(Y.snapshot&&(!j||G0(Y.snapshot,j)))j=Y.snapshot}catch(Y){let H=Y instanceof p;$.push(H?"Skipped a local Codex session file because it grew too large to inspect safely.":"Could not inspect a local Codex session file safely."),z.push(ZQ(K.path,X,K.modifiedAtMs,!1,H?"too-large":"read-error"))}}if(J.length>QQ)$.push(`Skipped ${J.length-QQ} older session files to keep inspection small.`);if(J.length>0&&!j)$.push("No token-count rate-limit snapshot was found in local Codex session logs.");return{homePath:Q,sessionsRoot:Z,files:z,latestSnapshot:j,warnings:$}}async function tZ(Q,Z,$){try{let G=await f(Z);if(G.isSymbolicLink())return $.push("Skipped the symbolic-link Codex sessions directory."),null;if(!G.isDirectory())return null;let[J,z]=await Promise.all([$Q(Q),$Q(Z)]),j=await f(Z);if(!R(J,z)||!j.isDirectory()||j.isSymbolicLink()||!c(G,j))return $.push("Could not inspect the local Codex sessions directory safely."),null;return z}catch{return null}}async function aZ(Q,Z,$){let G={directories:0,files:[],hitLimit:!1,skippedSymlink:!1};if(await wQ(Q,0,G,$),G.hitLimit)$.push("Stopped session discovery after reaching a safe inspection limit.");if(G.skippedSymlink)$.push("Skipped symbolic links while inspecting Codex sessions.");let J=[];for(let z of G.files){let j=await eZ(Z,z,$);if(j)J.push(j)}return J.sort((z,j)=>j.modifiedAtMs-z.modifiedAtMs||z.path.localeCompare(j.path))}async function eZ(Q,Z,$){try{let[G,J]=await Promise.all([f(Z),$Q(Z)]);if(!G.isFile()||!R(Q,J))return $.push("Could not inspect a local Codex session file safely."),null;return{path:Z,modifiedAtMs:G.mtimeMs,size:G.size,dev:G.dev,ino:G.ino}}catch{return $.push("Could not inspect a local Codex session file safely."),null}}async function wQ(Q,Z,$,G){if(Z>rZ||$.files.length>=h){$.hitLimit||=$.files.length>=h;return}if($.directories>=oZ){$.hitLimit=!0;return}$.directories+=1;let J;try{J=await Q0(Q,$)}catch{if(Z>0)G.push("Could not inspect part of the local Codex sessions directory safely.");return}for(let z of J){if($.files.length>=h){$.hitLimit=!0;return}let j=SQ(Q,z.name);if(z.isSymbolicLink()){$.skippedSymlink=!0;continue}if(z.isDirectory()){await wQ(j,Z+1,$,G);continue}if(z.isFile()&&sZ.test(z.name)){if($.files.push(j),$.files.length>=h){$.hitLimit=!0;return}}}}async function Q0(Q,Z){let $=await dZ(Q),G=[];for await(let J of $){if(G.length>=iZ){Z.hitLimit=!0;break}G.push(J)}return G.sort((J,z)=>z.name.localeCompare(J.name))}async function Z0(Q,Z){let $=Z.path,G=y(Q,$),J=await $0(Z),z=null,j=null,K="",X=0,Y=0,H=!1,V=!1,O=(C)=>{let q=J0(C.endsWith("\r")?C.slice(0,-1):C);if(q.threadId)z=q.threadId;if(q.rateLimits)j={sessionFile:$,relativePath:G,threadId:z,eventTimestamp:q.timestamp,rateLimits:q.rateLimits}};for await(let C of J){let q=String(C);if(Y+=Buffer.byteLength(q,"utf8"),Y>JQ)throw new p;let F=0;while(F<q.length){let P=q.indexOf(`
5
+ `,F),PZ=P===-1?q.length:P,PQ=q.slice(F,PZ);if(!H){let AQ=Buffer.byteLength(PQ,"utf8");if(X+AQ>nZ)K="",X=0,H=!0,V=!0;else K+=PQ,X+=AQ}if(P===-1)break;if(!H)O(K);K="",X=0,H=!1,F=P+1}}if(!H&&K.length>0)O(K);return{snapshot:j,skippedOversizedLine:V}}async function $0(Q){let Z;try{let $=await f(Q.path);if(!$.isFile()||!c($,Q))throw new GQ;let G=e.O_NOFOLLOW,J=typeof G==="number"?e.O_RDONLY|G:e.O_RDONLY;Z=await lZ(Q.path,J);let[z,j]=await Promise.all([Z.stat(),f(Q.path)]);if(!z.isFile()||!j.isFile()||!c(z,Q)||!c(z,j))throw new GQ;if(z.size>JQ)throw new p;return Z.createReadStream({encoding:"utf8",highWaterMark:65536})}catch($){throw await Z?.close().catch(()=>{return}),$}}function c(Q,Z){return Q.dev===Z.dev&&Q.ino===Z.ino}function G0(Q,Z){let $=T(Q.eventTimestamp)?.getTime()??null,G=T(Z.eventTimestamp)?.getTime()??null;if($===null)return!1;return G===null||$>G}function J0(Q){let Z=z0(Q);if(!Z)return{threadId:null,timestamp:null,rateLimits:null};return{threadId:j0(Z),timestamp:N(Z,"timestamp"),rateLimits:K0(Z)}}function z0(Q){let Z=Q.trim();if(!Z)return null;try{let $=JSON.parse(Z);return W($)?$:null}catch{return null}}function j0(Q){if(Q.type!=="session_meta"||!W(Q.payload))return null;return N(Q.payload,"id")}function K0(Q){if(Q.type!=="event_msg"||!W(Q.payload))return null;if(Q.payload.type!=="token_count"||!W(Q.payload.rate_limits))return null;return Q.payload.rate_limits}function ZQ(Q,Z,$,G,J){return{path:Q,relativePath:Z,modifiedAtMs:$,hasSnapshot:G,error:J}}class p extends Error{}class GQ extends Error{}import{opendir as Y0,realpath as hQ}from"node:fs/promises";import{extname as H0,join as W0}from"node:path";import{constants as zQ}from"node:fs";import{lstat as gQ,open as X0}from"node:fs/promises";class U extends Error{code;constructor(Q){super(Q);this.name="BoundedFileError",this.code=Q}}async function u(Q,Z){let $;try{let G=await gQ(Q);if(!G.isFile())throw new U("not-file");let J=zQ.O_NOFOLLOW,z=typeof J==="number"?zQ.O_RDONLY|J:zQ.O_RDONLY;$=await X0(Q,z);let j=await $.stat(),K=await gQ(Q);if(!j.isFile()||!K.isFile()||!vQ(G,j)||!vQ(j,K))throw new U("not-file");if(j.size>Z)throw new U("too-large");let X=Buffer.allocUnsafe(Z+1),Y=0;while(Y<=Z){let H=await $.read(X,Y,Z+1-Y,null);if(H.bytesRead===0)break;Y+=H.bytesRead}if(Y>Z)throw new U("too-large");return X.subarray(0,Y).toString("utf8")}catch(G){if(G instanceof U)throw G;if(mQ(G)&&G.code==="ENOENT")throw new U("not-found");if(mQ(G)&&G.code==="ELOOP")throw new U("not-file");throw new U("read-error")}finally{await $?.close().catch(()=>{return})}}function vQ(Q,Z){return Q.dev===Z.dev&&Q.ino===Z.ino}function mQ(Q){return Q instanceof Error&&"code"in Q}var V0=2,jQ=25,KQ=100,M0=64,U0=500,q0=1e6,x0=/(?:auth|token|cookie|session|secret|credential|api[-_]?key|keychain)/i;async function cQ(Q){let Z={directories:0,files:[],hitDirectoryLimit:!1,hitEntryLimit:!1,hitFileLimit:!1,skippedSensitive:!1,skippedSymlink:!1,warnings:[]},$;try{$=await hQ(Q)}catch{return{homePath:Q,files:[],warnings:["Could not inspect the local Codex state directory safely."]}}if(await pQ(Q,0,Z),Z.hitDirectoryLimit||Z.hitEntryLimit||Z.hitFileLimit)Z.warnings.push("Stopped local state discovery after reaching a safe inspection limit.");if(Z.skippedSensitive)Z.warnings.push("Skipped a sensitive-looking local file.");if(Z.skippedSymlink)Z.warnings.push("Skipped symbolic links while inspecting local Codex state.");let G=Z.files.sort((z,j)=>z.localeCompare(j)),J=[];for(let z of G.slice(0,jQ)){let j=y(Q,z);try{let K=await hQ(z);if(!R($,K))throw new U("not-file");let X=await u(z,q0),Y=B0(X,Z.warnings);J.push({path:z,relativePath:j,json:Y.value,error:Y.error})}catch(K){Z.warnings.push(K instanceof U&&K.code==="too-large"?"Skipped a local Codex state file because it is too large to inspect safely.":"Could not read a local Codex state file safely.")}}if(G.length>jQ)Z.warnings.push(`Skipped ${G.length-jQ} extra files to keep inspection small.`);return{homePath:Q,files:J,warnings:Z.warnings}}async function pQ(Q,Z,$){if(Z>V0||$.files.length>=KQ){$.hitFileLimit||=$.files.length>=KQ;return}if($.directories>=M0){$.hitDirectoryLimit=!0;return}$.directories+=1;let G=await N0(Q,$);for(let J of G){if($.files.length>=KQ){$.hitFileLimit=!0;return}if(x0.test(J.name)){$.skippedSensitive=!0;continue}let z=W0(Q,J.name);if(J.isSymbolicLink())$.skippedSymlink=!0;else if(J.isDirectory())await pQ(z,Z+1,$);else if(J.isFile()&&H0(J.name).toLowerCase()===".json")$.files.push(z)}}async function N0(Q,Z){try{let $=await Y0(Q),G=[];for await(let J of $){if(G.length>=U0){Z.hitEntryLimit=!0;break}G.push(J)}return G.sort((J,z)=>J.name.localeCompare(z.name))}catch{return Z.warnings.push("Could not inspect part of the local Codex state directory safely."),[]}}function B0(Q,Z){try{return{value:JSON.parse(Q),error:null}}catch{return Z.push("Could not parse JSON in a local Codex state file."),{value:null,error:"invalid-json"}}}import{join as O0,normalize as C0}from"node:path";function B(Q,Z,$){return{code:Q,source:Z,severity:"warning",message:$}}function I(Q){return Q.map((Z)=>_(Z.message))}var D0=1e6;async function l(Q={}){let Z=A(Q.env),$=x(Z,"CODEX_LIMITS_ACCESS_TOKEN"),G=x(Z,"CODEX_LIMITS_ACCOUNT_ID");if($&&G)return{credentials:{accessToken:$,accountId:G},status:"configured",diagnostics:[]};if($||G)return{credentials:null,status:"partial",diagnostics:[B("auth.environment.partial","authentication","Codex authentication environment variables are incomplete.")]};let J=await T0(Q);return J?F0(J):{credentials:null,status:"missing",diagnostics:[]}}async function T0(Q){if(Q.authFile)return C0(Q.authFile);let Z=await m(Q);return Z.foundHome?O0(Z.foundHome,"auth.json"):null}async function F0(Q){let Z;try{Z=await u(Q,D0)}catch($){if($ instanceof U&&$.code==="not-found")return{credentials:null,status:"missing",diagnostics:[]};let G=$ instanceof U&&$.code==="too-large";return{credentials:null,status:"unreadable",diagnostics:[B(G?"auth.file.too-large":"auth.file.unreadable","authentication",G?"Codex auth.json is too large to inspect safely.":"Codex auth.json could not be read safely.")]}}try{let $=JSON.parse(Z);if(!W($))return XQ();let G=W($.tokens)?$.tokens:$,J=N(G,"access_token"),z=N(G,"account_id");return J&&z?{credentials:{accessToken:J,accountId:z},status:"configured",diagnostics:[]}:XQ()}catch{return XQ()}}function XQ(){return{credentials:null,status:"malformed",diagnostics:[B("auth.file.malformed","authentication","Codex auth.json is malformed or does not contain required credentials.")]}}var P0=/[\u0000-\u0020\u007f-\u009f]/;function YQ(Q){return Q.length>0&&Q.length<=512&&!P0.test(Q)}import{request as A0}from"node:http";import{request as b0}from"node:https";var k0=new Set(["127.0.0.1","::1","[::1]","localhost"]);function E(Q){try{let Z=new URL(Q);return Z.username="",Z.password="",Z.search="",Z.hash="",Z.href}catch{return"[invalid endpoint]"}}async function lQ(Q){let Z=I0(Q.endpoint);if(!Z.ok)return Z;if(Q.signal?.aborted)return M("aborted");let $=Q.fetch??globalThis.fetch;if(!$)return uQ(Z.url,Q);let G=await L0(Z.url,Q,$);if(G.ok||G.code==="aborted"||!y0(G,Q.fallbackOnHttpError??!1))return G;let J=await uQ(Z.url,Q);if(J.ok||J.code==="http-error"||J.code==="invalid-json"||J.code==="response-too-large")return J;return G}function d(Q){let Z={...Q,method:"GET"};return delete Z.body,lQ(Z)}function I0(Q){let Z;try{Z=new URL(Q)}catch{return M("invalid-url")}if(Z.username||Z.password)return M("invalid-url");if(Z.protocol==="https:")return{ok:!0,url:Z};if(Z.protocol==="http:"&&k0.has(Z.hostname.toLowerCase()))return{ok:!0,url:Z};return M("unsupported-protocol")}async function L0(Q,Z,$){let G=rQ(Z.timeoutMs,Z.signal);try{let J=await $(Q.href,{method:Z.method??"GET",headers:Z.headers,redirect:"error",signal:G.signal,...Z.body===void 0?{}:{body:Z.body}});if(!J.ok)return await dQ(J),M("http-error",VQ(J.status));let z=await _0(J,Z.maxResponseBytes);return{ok:!0,status:VQ(J.status)??200,payload:z,transport:"fetch"}}catch(J){if(J instanceof S)return M("response-too-large");if(J instanceof r)return M("invalid-json");if(Z.signal?.aborted)return M("aborted");if(G.didTimeout())return M("timeout");return M("network-error")}finally{G.dispose()}}async function _0(Q,Z){let $=Number(Q.headers?.get("content-length"));if(Number.isFinite($)&&$>Z)throw await dQ(Q),new S;if(Q.body){let G=Q.body.getReader(),J=[],z=0;while(!0){let K=await G.read();if(K.done)break;if(!K.value)continue;if(z+=K.value.byteLength,z>Z)throw await G.cancel?.(),new S;J.push(K.value)}let j=Buffer.concat(J.map((K)=>Buffer.from(K)),z).toString("utf8");return WQ(j)}if(Q.text){let G=await Q.text();if(Buffer.byteLength(G,"utf8")>Z)throw new S;return WQ(G)}throw new r}async function dQ(Q){if(!Q.body)return;try{await Q.body.getReader().cancel?.()}catch{}}function uQ(Q,Z){return new Promise(($)=>{let G=rQ(Z.timeoutMs,Z.signal),J=!1,z=null,j=(X)=>{if(J)return;J=!0,G.dispose(),$(X)},K=()=>{z?.destroy(),j(M(Z.signal?.aborted?"aborted":"timeout"))};G.signal.addEventListener("abort",K,{once:!0});try{z=(Q.protocol==="http:"?A0:b0)(Q,{method:Z.method??"GET",headers:Z.headers,signal:G.signal},(Y)=>R0(Y,Z.maxResponseBytes,j)),z.on("error",()=>{if(Z.signal?.aborted)j(M("aborted"));else if(G.didTimeout())j(M("timeout"));else j(M("network-error"))}),z.end(Z.body)}catch{j(M("network-error"))}})}function R0(Q,Z,$){let G=VQ(Q.statusCode);if(G===null||G<200||G>=300){$(M("http-error",G)),HQ(Q);return}let J=Number(Q.headers["content-length"]);if(Number.isFinite(J)&&J>Z){$(M("response-too-large")),HQ(Q);return}let z=[],j=0;Q.on("data",(K)=>{let X=Buffer.isBuffer(K)?K:Buffer.from(K);if(j+=X.length,j>Z){$(M("response-too-large")),HQ(Q);return}z.push(X)}),Q.on("end",()=>{try{let K=WQ(Buffer.concat(z,j).toString("utf8"));$({ok:!0,status:G,payload:K,transport:"node"})}catch{$(M("invalid-json"))}}),Q.on("error",()=>$(M("network-error")))}function HQ(Q){Q.destroy(),Q.socket.destroy()}function rQ(Q,Z){let $=new AbortController,G=!1,J=Number.isFinite(Q)&&Q>0?Math.min(Math.floor(Q),2147483647):1,z=setTimeout(()=>{G=!0,$.abort()},J),j=()=>$.abort();if(Z?.addEventListener("abort",j,{once:!0}),Z?.aborted)j();return{signal:$.signal,didTimeout:()=>G,dispose:()=>{clearTimeout(z),Z?.removeEventListener("abort",j)}}}function y0(Q,Z){return Q.code==="network-error"||Q.code==="timeout"||Q.code==="invalid-json"||Z&&Q.code==="http-error"}function WQ(Q){try{return JSON.parse(Q)}catch{throw new r}}function VQ(Q){return typeof Q==="number"&&Number.isInteger(Q)&&Q>=0?Q:null}function M(Q,Z=null){return{ok:!1,code:Q,status:Z}}class S extends Error{}class r extends Error{}function o(Q,Z){switch(Q.code){case"aborted":return B("network.request.aborted","network",`${Z} lookup was cancelled.`);case"http-error":return B("network.response.http","network",Q.status===null?`${Z} endpoint returned an invalid HTTP status.`:`${Z} endpoint returned HTTP ${Q.status}.`);case"invalid-json":return B("network.response.invalid-json","network",`${Z} endpoint returned malformed JSON.`);case"invalid-url":return B("network.endpoint.invalid","network",`${Z} endpoint URL is invalid.`);case"response-too-large":return B("network.response.too-large","network",`${Z} endpoint response was too large.`);case"timeout":return B("network.request.timeout","network",`${Z} lookup timed out.`);case"unsupported-protocol":return B("network.endpoint.protocol","network",`${Z} endpoint must use HTTPS or loopback HTTP.`);case"network-error":return B("network.request.failed","network",`${Z} lookup failed.`)}}var sQ=["credits","reset_credits","items"],tQ=["available_count","availableCount","available"],aQ=["total_earned_count","earned_this_period","earnedThisPeriod","totalEarnedCount"],f0=64,S0=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(?:Z|[+-](\d{2}):(\d{2}))$/i;function eQ(Q,Z,$){if(!W(Q)||!E0(Q))return w(Z,["Live reset coupon endpoint returned an unexpected payload."]);let G=m0(Q,sQ);if(G.malformed)return w(Z,["Live reset coupon endpoint returned an unexpected payload."]);let J=G.value,z=J.map((V,O)=>w0(V,O+1,$)).filter((V)=>V!==null).sort(v0).map((V,O)=>({...V,index:O+1})),j=z.filter((V)=>V.status?.toLowerCase()==="available"),K=j[0]??z[0]??null,X=nQ(Q,tQ),Y=nQ(Q,aQ),H=[];if(J.length!==z.length)H.push("Live reset coupon endpoint ignored malformed coupon entries.");if(X.malformed||Y.malformed)H.push("Live reset coupon endpoint ignored malformed summary fields.");if(X.value!==null&&X.value!==j.length)H.push("Live reset coupon endpoint returned inconsistent availability data.");return{status:H.length>0?"partial":"available",available:X.value,earnedThisPeriod:Y.value,nextExpirationDate:K?.expirationDate??null,nextExpirationIn:K?.expiresIn??null,items:z,warnings:H,source:{live:!0,label:"live Codex reset-credit endpoint",endpoint:Z}}}function w(Q,Z=[]){return{status:"unavailable",available:null,earnedThisPeriod:null,nextExpirationDate:null,nextExpirationIn:null,items:[],warnings:Z,source:{live:!1,label:"live Codex reset-credit endpoint",endpoint:Q}}}function E0(Q){return[...sQ,...tQ,...aQ].some((Z)=>(Z in Q))}function w0(Q,Z,$){if(!W(Q))return null;let G=Q.id,J=typeof G==="string"&&YQ(G)?G:null,z=Q.reset_type??Q.resetType,j=typeof z==="string"&&/^[a-z][a-z0-9_-]{0,63}$/i.test(z)?z:null,K="expires_at"in Q||"expiresAt"in Q,X="granted_at"in Q||"grantedAt"in Q,Y=N(Q,"expires_at")??N(Q,"expiresAt"),H=N(Q,"granted_at")??N(Q,"grantedAt"),V=oQ(Y),O=oQ(H),C=N(Q,"status"),q=C&&/^[a-z][a-z0-9_-]{0,63}$/i.test(C)?C:null,F=O?H:null,P=V?Y:null;if("id"in Q&&!J||X&&!O||K&&!V||!q&&!F&&!P)return null;return{id:J,resetType:j,index:Z,status:q,grantedAt:F,expiresAt:P,expirationDate:V?_Q(V):null,expiresIn:V?L(V.getTime()-$.getTime()):null}}function oQ(Q){if(!Q||Q.length>f0)return null;let Z=S0.exec(Q);if(!Z)return null;let $=Number(Z[1]),G=Number(Z[2]),J=Number(Z[3]),z=Number(Z[4]),j=Number(Z[5]),K=Number(Z[6]),X=Z[8]===void 0?0:Number(Z[8]),Y=Z[9]===void 0?0:Number(Z[9]);if(G<1||G>12||J<1||J>g0($,G)||z>23||j>59||K>59||X>23||Y>59)return null;let H=new Date(Q);return Number.isNaN(H.getTime())?null:H}function g0(Q,Z){if(Z===2)return Q%4===0&&(Q%100!==0||Q%400===0)?29:28;return Z===4||Z===6||Z===9||Z===11?30:31}function v0(Q,Z){return iQ(Q.expiresAt)-iQ(Z.expiresAt)}function iQ(Q){return T(Q)?.getTime()??Number.POSITIVE_INFINITY}function m0(Q,Z){let $=!1;for(let G of Z){if(!(G in Q))continue;$=!0;let J=Q[G];if(Array.isArray(J))return{value:J,malformed:!1}}return{value:[],malformed:$}}function nQ(Q,Z){let $=!1;for(let G of Z){if(!(G in Q))continue;$=!0;let J=Q[G];if(typeof J==="number"&&Number.isSafeInteger(J)&&J>=0)return{value:J,malformed:!1}}return{value:null,malformed:$}}var MQ="https://chatgpt.com/backend-api/wham/rate-limit-reset-credits",_2=`${MQ}/consume`,h0=1e4,c0=1e6;async function ZZ(Q={}){let Z=Q.endpoint??MQ,$=E(Z),G=await l(Q);if(!G.credentials){let z=I(G.diagnostics);return p0($,z.length>0?z:["Live reset coupons require a readable Codex auth.json file or CODEX_LIMITS_ACCESS_TOKEN and CODEX_LIMITS_ACCOUNT_ID."])}let J=u0(Z,G.credentials,Q);try{let z=await(Q.transport??d)(J);return z.ok?eQ(z.payload,$,Q.now??new Date):QZ($,z)}catch{return QZ($,{ok:!1,code:"network-error",status:null})}}function p0(Q=MQ,Z=[]){return w(E(Q),Z)}function QZ(Q,Z){return w(Q,I([o(Z,"Live reset coupon")]))}function u0(Q,Z,$){return{endpoint:Q,headers:l0(Z),timeoutMs:$.timeoutMs??h0,maxResponseBytes:c0,...$.fetch?{fetch:$.fetch}:{},...$.signal?{signal:$.signal}:{}}}function l0(Q){return{Authorization:`Bearer ${Q.accessToken}`,"ChatGPT-Account-ID":Q.accountId,"OpenAI-Beta":"codex-1",originator:"Codex Desktop",Accept:"application/json"}}var jZ=5,xQ="5-hour usage limit",NQ="Weekly usage limit",BQ=["fiveHour","five_hour","fiveHourWindow","five_hour_window","primary","primaryWindow","primary_window","main","mainWindow"],OQ=["weekly","week","weeklyWindow","weekly_window","secondary","secondaryWindow","secondary_window","backup","backupWindow"],d0=["used_percent","usedPercent","used","usage","percentUsed","usagePercent","usagePercentage","percent"],r0=["remaining_percent","remainingPercent","remaining","percentRemaining","availablePercent","available_percentage"],o0=["resets_at","resetsAt","resetAt","resetTime","reset_at","reset","ends_at","endsAt","windowEnd"],i0=["resetsIn","resetIn","resets_in","reset_in","timeUntilReset"],n0=["limit_window_seconds","limitWindowSeconds","window_seconds","windowSeconds","window_length_seconds","windowLengthSeconds"],s0=["window_minutes","windowMinutes","window_length_minutes","windowLengthMinutes"],t0=18000,a0=604800,e0=/^(?:(\d+)d)?(?:\s*(\d+)h)?(?:\s*(\d+)m)?(?:\s*(\d+)s)?$/i;function KZ(Q,Z=new Date){let $=Q.latestSnapshot;if(!$)return TQ(Q.warnings);return s(CQ($.rateLimits,Z),Q.warnings)}function CQ(Q,Z=new Date){return VZ(i(Q,BQ),i(Q,OQ),Z)}function XZ(Q){return i(Q,BQ)!==null||i(Q,OQ)!==null}function g(Q){let Z=zZ(b(Q,n0,!1)),$=zZ(b(Q,s0,!1)),G=Z??($===null?null:$*60);if(G===t0)return"fiveHour";if(G===a0)return"weekly";return null}function YZ(Q,Z){return{...Q,source:Z}}function DQ(Q,Z,$=[]){return{...s(Q,$),source:Z}}function HZ(Q,Z=new Date){let $={fiveHour:null,weekly:null};for(let G of Q.files){if(!G.json)continue;let J=Q1(G.json,Z);$=MZ($,J.windows)}return s($,Q.warnings)}function TQ(Q=[]){return{status:"unavailable",windows:{fiveHour:null,weekly:null},warnings:Q}}function WZ(Q,Z){let $=MZ(Q.windows,Z.windows);return s($,[...Q.warnings,...Z.warnings])}function Q1(Q,Z){if(!W(Q))return{windows:{fiveHour:null,weekly:null}};let $=qQ(Q,BQ),G=qQ(Q,OQ);if($||G)return{windows:VZ($,G,Z)};let J=g(Q)??"fiveHour",z=UQ(Q,J==="weekly"?NQ:xQ,Z);return{windows:{fiveHour:J==="fiveHour"?z:null,weekly:J==="weekly"?z:null}}}function VZ(Q,Z,$){let G=[];if(Q)G.push({fallbackKind:"fiveHour",value:Q});if(Z)G.push({fallbackKind:"weekly",value:Z});return{fiveHour:UQ($Z(G,"fiveHour"),xQ,$),weekly:UQ($Z(G,"weekly"),NQ,$)}}function UQ(Q,Z,$){if(!Q)return null;let G=JZ(b(Q,d0,!0)),J=JZ(b(Q,r0,!0)),z=G??(J===null?null:n(100-J)),j=J??(G===null?null:n(100-G)),K=b(Q,o0,!0),X=T(K),Y=X?X.toISOString():null,H=X?L(X.getTime()-$.getTime()):G1(b(Q,i0,!0)),V={label:Z,remainingPercent:j,usedPercent:z,resetsAt:Y,resetsIn:H};return UZ(V)?V:null}function s(Q,Z){return{status:Z1(Q),windows:Q,warnings:Z}}function Z1(Q){let Z=[Q.fiveHour,Q.weekly].filter(($)=>UZ($));if(Z.length===0)return"unavailable";return Z.every($1)?"available":"partial"}function $Z(Q,Z){let $=Q.find((G)=>g(G.value)===Z);if($)return $.value;return Q.find((G)=>G.fallbackKind===Z&&g(G.value)===null)?.value??null}function MZ(Q,Z){return{fiveHour:GZ(Q.fiveHour,Z.fiveHour,xQ),weekly:GZ(Q.weekly,Z.weekly,NQ)}}function GZ(Q,Z,$){if(!Q&&!Z)return null;return{label:$,remainingPercent:Q?.remainingPercent??Z?.remainingPercent??null,usedPercent:Q?.usedPercent??Z?.usedPercent??null,resetsAt:Q?.resetsAt??Z?.resetsAt??null,resetsIn:Q?.resetsIn??Z?.resetsIn??null}}function UZ(Q){return Q!==null&&(Q.remainingPercent!==null||Q.usedPercent!==null||Q.resetsAt!==null||Q.resetsIn!==null)}function $1(Q){return Q!==null&&Q.remainingPercent!==null&&Q.usedPercent!==null&&(Q.resetsAt!==null||Q.resetsIn!==null)}function qQ(Q,Z,$=0){if($>jZ)return null;for(let G of Z){let J=Q[G];if(W(J))return J}for(let G of Object.values(Q)){if(!W(G))continue;let J=qQ(G,Z,$+1);if(J)return J}return null}function i(Q,Z){for(let $ of Z){let G=Q[$];if(W(G))return G}return null}function b(Q,Z,$,G=0){if(G>jZ)return;for(let J of Z)if(J in Q)return Q[J];if(!$)return;for(let J of Object.values(Q)){if(!W(J))continue;let z=b(J,Z,$,G+1);if(z!==void 0)return z}return}function JZ(Q){if(typeof Q==="number"&&Number.isFinite(Q))return n(Q);if(typeof Q==="string"&&Q.trim().length>0){let Z=Q.trim(),$=Z.endsWith("%")?Z.slice(0,-1):Z,G=Number($);return Number.isFinite(G)?n(G):null}return null}function n(Q){return Math.round(Math.min(Math.max(Q,0),100)*10)/10}function zZ(Q){if(typeof Q==="number"&&Number.isFinite(Q))return Q;if(typeof Q==="string"&&Q.trim().length>0){let Z=Number(Q);return Number.isFinite(Z)?Z:null}return null}function G1(Q){let Z=J1(Q);if(!Z||Z.length>100)return null;let G=e0.exec(Z)?.slice(1);if(!G||G.every((j)=>j===void 0))return null;let J=[86400,3600,60,1],z=0;for(let[j,K]of G.entries()){if(K===void 0)continue;let X=Number(K),Y=X*J[j];if(!Number.isSafeInteger(X)||!Number.isSafeInteger(Y))return null;if(z+=Y,!Number.isSafeInteger(z))return null}return z<=Math.floor(Number.MAX_SAFE_INTEGER/1000)?L(z*1000):null}function J1(Q){if(typeof Q==="string"&&Q.trim().length>0)return Q.trim();return null}var z1=5,j1=1000,K1={kind:"unavailable",label:"Unavailable"};function xZ(Q,Z,$){let G=X1(Q)??Y1(Q);if(!G)return v(["Live usage endpoint returned an unexpected payload."]);let J=DQ(CQ(G,$),{kind:"api",label:"API",endpoint:Z});if(J.status==="unavailable")return v(["Live usage endpoint returned an unexpected payload."]);if(J.status==="partial")return{...J,warnings:["Live usage endpoint returned incomplete usage data."]};return J}function v(Q){return DQ({fiveHour:null,weekly:null},K1,Q)}function X1(Q){return NZ(Q,(Z)=>{if(!W(Z))return null;let $=Z.rate_limits??Z.rateLimits??Z.rate_limit??Z.rateLimit;if(W($))return $;return XZ(Z)?Z:null})}function Y1(Q){return NZ(Q,(Z)=>{if(!Array.isArray(Z))return null;let $=Z.find((J)=>qZ(J,"fiveHour")),G=Z.find((J)=>qZ(J,"weekly"));return $||G?{fiveHour:$,weekly:G}:null})}function NZ(Q,Z){let $=[{value:Q,depth:0}],G=new WeakSet;for(let J=0;J<$.length;J+=1){let z=$[J];if(!z)break;let j=Z(z.value);if(j)return j;if(z.depth>=z1||typeof z.value!=="object"||!z.value)continue;if(G.has(z.value))continue;G.add(z.value);let K=Array.isArray(z.value)?z.value:W(z.value)?Object.values(z.value):[];for(let X of K){if($.length>=j1)break;$.push({value:X,depth:z.depth+1})}}return null}function qZ(Q,Z){if(!W(Q))return!1;let $=g(Q);if($)return $===Z;let G=String(Q.type??Q.kind??Q.name??Q.label??Q.window??"").toLowerCase();return Z==="fiveHour"?G.includes("primary")||G.includes("5-hour")||G.includes("five"):G.includes("secondary")||G.includes("weekly")||G.includes("week")}var H1="https://chatgpt.com/backend-api/codex/usage",W1=1e4,V1=1e6;async function BZ(Q={}){return(await M1(Q)).usage}async function M1(Q={}){let Z=q1(Q),$=E(Z),G=await l(Q);if(!G.credentials){let j=I(G.diagnostics);return{usage:v(j.length>0?j:["Live usage requires Codex authentication."]),authenticationFound:!1,endpointStatus:"not-checked"}}let J={endpoint:Z,headers:U1(G.credentials),timeoutMs:Q.timeoutMs??W1,maxResponseBytes:V1,fallbackOnHttpError:!0,...Q.fetch?{fetch:Q.fetch}:{},...Q.signal?{signal:Q.signal}:{}},z;try{z=await(Q.transport??d)(J)}catch{z={ok:!1,code:"network-error",status:null}}return{usage:z.ok?xZ(z.payload,$,Q.now??new Date):N1(z),authenticationFound:!0,endpointStatus:x1(z)}}function U1(Q){return{Authorization:`Bearer ${Q.accessToken}`,"ChatGPT-Account-ID":Q.accountId,"OpenAI-Beta":"codex-1",originator:"Codex Desktop",Accept:"application/json","User-Agent":"Codex Desktop",Referer:"https://chatgpt.com/codex/cloud/settings/analytics",Origin:"https://chatgpt.com"}}function q1(Q){let Z=A(Q.env);return Q.usageEndpoint??x(Z,"CODEX_LIMITS_USAGE_ENDPOINT")??H1}function x1(Q){if(Q.ok)return"reachable";switch(Q.code){case"http-error":case"invalid-json":case"response-too-large":return"reachable";case"aborted":return"not-checked";case"invalid-url":case"network-error":case"timeout":case"unsupported-protocol":return"unreachable"}}function N1(Q){return v(I([o(Q,"Live usage")]))}var B1={kind:"local",label:"Local"};async function OZ(Q={}){let Z=Q.includeCoupons===!1?Promise.resolve(null):ZZ(Q),[$,G]=await Promise.all([O1(Q),Z]),J=G?C1(G):null;return{windows:$.windows,coupons:J,warnings:a([...$.warnings,...J?.warnings??[]])}}async function O1(Q={}){let Z=await BZ(Q);if(Z.status!=="unavailable")return Z;let $=YZ(await D1(Q),B1);return $.status!=="unavailable"?$:{...$,warnings:[...Z.warnings,...$.warnings]}}function C1(Q){return{status:Q.status,available:Q.available,earnedThisPeriod:Q.earnedThisPeriod,nextExpirationDate:Q.nextExpirationDate,nextExpirationIn:Q.nextExpirationIn,items:Q.items.map((Z)=>({index:Z.index,status:Z.status,grantedAt:Z.grantedAt,expiresAt:Z.expiresAt,expirationDate:Z.expirationDate,expiresIn:Z.expiresIn})),warnings:a(Q.warnings)}}async function D1(Q={}){let Z=Q.now??new Date,$=await m(Q);if(!$.foundHome)return TQ(["No readable local Codex home directory was found."]);let[G,J]=await Promise.all([EQ($.foundHome),cQ($.foundHome)]);return WZ(KZ(G,Z),HZ(J,Z))}var FQ="Codex Limits",T1="Check Codex limits, resets, and credits.",CZ="Could not load Codex limits.";function F1(Q={}){let Z=new WeakSet,$=Q.getLimits??OZ,G=Q.nextFrame??(()=>new Promise((J)=>setTimeout(J,0)));return{id:"codex-limits",tui:async(J)=>{if(Z.has(J))return;let z=P1(J,$,G),j;try{let X=A1(J,z);j=typeof X==="function"?X:void 0}catch{throw Error("Could not register the codex-limits OpenCode command.")}let K=()=>{if(!Z.delete(J))return;try{j?.()}catch{}};Z.add(J);try{J.lifecycle.onDispose(K)}catch{throw K(),Error("Could not register the codex-limits OpenCode lifecycle.")}}}}function P1(Q,Z,$){let G=0;return{title:FQ,value:"codex-limits.show",description:T1,category:"Codex",slash:{name:"codex-limits"},onSelect:async(J)=>{let z=++G;J?.clear(),Q.ui.dialog.clear(),await $();let j=Q.ui.dialog,K=(X)=>j.replace(()=>Q.ui.DialogAlert({title:FQ,message:X}));j.setSize("large"),K("Loading Codex limits...");try{let X=await Z();if(z===G)K(IQ(X))}catch{if(z===G)Q.ui.toast({variant:"error",title:FQ,message:CZ}),K(CZ)}}}}function A1(Q,Z){let $=Q;if(typeof $.keymap?.registerLayer==="function")return $.keymap.registerLayer({commands:[{namespace:"palette",name:Z.value,title:Z.title,desc:Z.description,category:Z.category,slashName:Z.slash?.name,slashAliases:Z.slash?.aliases,run:()=>Z.onSelect?.()}],bindings:[]});if(typeof $.command?.register==="function")return $.command.register(()=>[Z]);throw Error("No supported OpenCode command API is available.")}var b1=F1(),DZ=b1;function TZ(Q){return Q}var FZ=TZ(DZ),K3=FZ,z3=FZ.tui;export{z3 as tui,K3 as default};
package/dist/pi.js CHANGED
@@ -1,5 +1,5 @@
1
- import{DynamicBorder as DZ}from"@earendil-works/pi-coding-agent";import{Container as A1,matchesKey as TQ,Text as FQ}from"@earendil-works/pi-tui";function IQ(Q){let Z=[];if(Q.windows.fiveHour)Z.push(bQ("5-hour",Q.windows.fiveHour));if(Q.windows.weekly)Z.push(bQ("Weekly",Q.windows.weekly));if(Z.length===0)Z.push(["Usage limits Unavailable"]);if(Z.push(kZ(Q)),Q.warnings.length>0)Z.push(["Warnings",...Q.warnings.map(($)=>`- ${$}`)]);return Z.map(($)=>$.join(`
1
+ import{DynamicBorder as TZ}from"@earendil-works/pi-coding-agent";import{Container as A1,matchesKey as DQ,Text as AQ}from"@earendil-works/pi-tui";function kQ(Q){let Z=[];if(Q.windows.fiveHour)Z.push(PQ("5-hour",Q.windows.fiveHour));if(Q.windows.weekly)Z.push(PQ("Weekly",Q.windows.weekly));if(Z.length===0)Z.push(["Usage limits Unavailable"]);if(Z.push(kZ(Q)),Q.warnings.length>0)Z.push(["Warnings",...Q.warnings.map(($)=>`- ${$}`)]);return Z.map(($)=>$.join(`
2
2
  `)).join(`
3
3
 
4
- `)}function bQ(Q,Z){let $=Z.remainingPercent;return[`${Q} ${LZ($)}`,`Remaining ${$===null?"Unknown":`${Math.round($)}% remaining`}`,IZ($),`Reset ${Z.resetsIn?`in ${Z.resetsIn}`:"unknown"}`]}function IZ(Q){if(Q===null)return`[${" ".repeat(22)}] Unknown`;let Z=Math.min(Math.max(Q,0),100),$=Math.round(Z/100*22);return`[${"=".repeat($)}${" ".repeat(22-$)}] ${Math.round(Z)}%`}function kZ(Q){let Z=Q.coupons?.available,G=[`Reset credits ${Z===null||Z===void 0?"Unknown":`${Z} ${Z===1?"credit":"credits"} available`}`],J=Q.coupons?.nextExpirationIn,z=Q.coupons?.nextExpirationDate,j=J&&z?`${J} (${z})`:J??z;if(j!==null&&j!==void 0)G.push(`Next expires ${j}`);return G}function LZ(Q){if(Q===null)return"Unknown";if(Q>=50)return"Healthy";if(Q>=15)return"Low";return"Critical"}function kQ(Q){return IQ(Q)}import{constants as _Z}from"node:fs";import{access as RZ,stat as yZ}from"node:fs/promises";import{homedir as fZ}from"node:os";import{join as I,normalize as s}from"node:path";function N(Q,Z){let $=Q[Z]?.trim();return $?$:null}function P(Q){return Q??process.env}var LQ="CODEX_LIMITS_HOME";function SZ(Q={}){let Z=P(Q.env),$=Q.homeDirectory??N(Z,"HOME")??N(Z,"USERPROFILE")??fZ(),G=Q.appData??N(Z,"APPDATA"),J=Q.localAppData??N(Z,"LOCALAPPDATA"),z=[];if(D(z,N(Z,LQ),"env"),D(z,N(Z,"CODEX_HOME"),"env"),$)D(z,I($,".codex"),"default"),D(z,I($,".config","codex"),"default"),D(z,I($,"Library","Application Support","Codex"),"default"),D(z,I($,"Library","Application Support","Parall","Codex",".codex"),"default");return D(z,G?I(G,"Codex"):null,"default"),D(z,J?I(J,"Codex"):null,"default"),wZ(z)}async function v(Q={}){let Z=P(Q.env),$=N(Z,LQ),G=await Promise.all(SZ(Q).map(async(J)=>({...J,exists:await EZ(J.path)})));return{overrideHome:$?s($):null,candidates:G,foundHome:G.find((J)=>J.exists)?.path??null}}function D(Q,Z,$){if(Z)Q.push({path:s(Z),source:$})}async function EZ(Q){try{if(!(await yZ(Q)).isDirectory())return!1;return await RZ(Q,_Z.R_OK),!0}catch{return!1}}function wZ(Q){let Z=new Set,$=[];for(let G of Q){let J=s(G.path),z=process.platform==="win32"?J.toLowerCase():J;if(!Z.has(z))Z.add(z),$.push({path:J,source:G.source})}return $}import{constants as t}from"node:fs";import{lstat as h,open as rZ,opendir as oZ,realpath as SQ}from"node:fs/promises";import{join as EQ}from"node:path";var vZ=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],gZ=["January","February","March","April","May","June","July","August","September","October","November","December"];function L(Q,Z={}){let $=Z.includeSeconds??!1,G=Math.max(Math.floor(Q/1000),0),J=Math.floor(G/86400);G%=86400;let z=Math.floor(G/3600);G%=3600;let j=Math.floor(G/60),K=G%60,X=[];if(J>0)X.push(`${J}d`);if(z>0)X.push(`${z}h`);if(j>0)X.push(`${j}m`);if($&&K>0)X.push(`${K}s`);return X.length>0?X.join(" "):$?`${K}s`:"0m"}function T(Q){if(typeof Q==="number"&&Number.isFinite(Q)){let Z=Q<10000000000?Q*1000:Q,$=new Date(Z);return Number.isNaN($.getTime())?null:$}if(typeof Q==="string"&&Q.trim().length>0){let Z=Q.trim(),$=Number(Z);if(Number.isFinite($))return T($);let G=new Date(Z);return Number.isNaN(G.getTime())?null:G}return null}function _Q(Q){return`${vZ[Q.getDay()]} ${Q.getDate()} ${gZ[Q.getMonth()]} ${Q.getFullYear()}`}import{isAbsolute as uZ,relative as yQ,resolve as RQ,sep as lZ}from"node:path";var mZ=/(?:chatgpt[-_]?account[-_]?id|access[-_]?token|refresh[-_]?token|id[-_]?token|session[-_]?token|api[-_]?key|account[-_]?id|authorization|cookie|client[-_]?secret|password|credential|secret|token)/,hZ=/[\u0000-\u001f\u007f-\u009f]/g,pZ=new RegExp(`["']?${mZ.source}["']?\\s*[:=]\\s*(?:"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|[^,\\r\\n}\\]&]+)`,"gi"),cZ=[pZ,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}(?:\.[A-Za-z0-9_-]{5,})?\b/g,/sk-[A-Za-z0-9_-]{10,}/g,/\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b/gi,/[A-Za-z0-9_-]{32,}/g];function _(Q){let Z=Q;for(let $ of cZ)Z=Z.replace($,"[redacted]");return Z.replace(hZ,"?")}function a(Q){return Q.map(_)}function g(Q,Z){let $=yQ(RQ(Q),RQ(Z));return $===""||!fQ($)}function R(Q,Z){let $=yQ(Q,Z);return $&&!fQ($)?dZ($):"."}function dZ(Q){let Z=_(Q);return Z.length<=240?Z:`${Z.slice(0,239)}…`}function fQ(Q){return Q===".."||Q.startsWith(`..${lZ}`)||uZ(Q)}function H(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function B(Q,Z){let $=Q[Z];return typeof $==="string"&&$.trim()?$.trim():null}var iZ=8,e=20,m=1000,nZ=512,sZ=1000,GQ=25000000,aZ=1e6,tZ=/^rollout-.*\.jsonl$/i;async function wQ(Q){let Z=EQ(Q,"sessions"),$=[];if(await Y0(Z))return $.push("Skipped the symbolic-link Codex sessions directory."),{homePath:Q,sessionsRoot:Z,files:[],latestSnapshot:null,warnings:$};let G=await eZ(Z,$),J=[],z=null;for(let j of G.slice(0,e)){let K=R(Q,j.path);if(j.size>GQ){$.push("Skipped a local Codex session file because it is too large to inspect safely."),J.push(ZQ(j.path,K,j.modifiedAtMs,!1,"too-large"));continue}try{let X=await $0(Q,j);if(J.push(ZQ(j.path,K,j.modifiedAtMs,X.snapshot!==null,null)),X.skippedOversizedLine)$.push("Skipped an oversized JSONL line in a local Codex session file.");if(X.snapshot&&(!z||J0(X.snapshot,z)))z=X.snapshot}catch(X){let Y=X instanceof p;$.push(Y?"Skipped a local Codex session file because it grew too large to inspect safely.":"Could not inspect a local Codex session file safely."),J.push(ZQ(j.path,K,j.modifiedAtMs,!1,Y?"too-large":"read-error"))}}if(G.length>e)$.push(`Skipped ${G.length-e} older session files to keep inspection small.`);if(G.length>0&&!z)$.push("No token-count rate-limit snapshot was found in local Codex session logs.");return{homePath:Q,sessionsRoot:Z,files:J,latestSnapshot:z,warnings:$}}async function eZ(Q,Z){let $={directories:0,files:[],hitLimit:!1,skippedSymlink:!1};if(await vQ(Q,0,$,Z),$.hitLimit)Z.push("Stopped session discovery after reaching a safe inspection limit.");if($.skippedSymlink)Z.push("Skipped symbolic links while inspecting Codex sessions.");let G;try{G=await SQ(Q)}catch{return[]}let J=[];for(let z of $.files){let j=await Q0(G,z,Z);if(j)J.push(j)}return J.sort((z,j)=>j.modifiedAtMs-z.modifiedAtMs||z.path.localeCompare(j.path))}async function Q0(Q,Z,$){try{let[G,J]=await Promise.all([h(Z),SQ(Z)]);if(!G.isFile()||!g(Q,J))return $.push("Could not inspect a local Codex session file safely."),null;return{path:Z,modifiedAtMs:G.mtimeMs,size:G.size,dev:G.dev,ino:G.ino}}catch{return $.push("Could not inspect a local Codex session file safely."),null}}async function vQ(Q,Z,$,G){if(Z>iZ||$.files.length>=m){$.hitLimit||=$.files.length>=m;return}if($.directories>=nZ){$.hitLimit=!0;return}$.directories+=1;let J;try{J=await Z0(Q,$)}catch{if(Z>0)G.push("Could not inspect part of the local Codex sessions directory safely.");return}for(let z of J){if($.files.length>=m){$.hitLimit=!0;return}let j=EQ(Q,z.name);if(z.isSymbolicLink()){$.skippedSymlink=!0;continue}if(z.isDirectory()){await vQ(j,Z+1,$,G);continue}if(z.isFile()&&tZ.test(z.name)){if($.files.push(j),$.files.length>=m){$.hitLimit=!0;return}}}}async function Z0(Q,Z){let $=await oZ(Q),G=[];for await(let J of $){if(G.length>=sZ){Z.hitLimit=!0;break}G.push(J)}return G.sort((J,z)=>z.name.localeCompare(J.name))}async function $0(Q,Z){let $=Z.path,G=R(Q,$),J=await G0(Z),z=null,j=null,K="",X=0,Y=0,W=!1,V=!1,C=(x)=>{let q=z0(x.endsWith("\r")?x.slice(0,-1):x);if(q.threadId)z=q.threadId;if(q.rateLimits)j={sessionFile:$,relativePath:G,threadId:z,eventTimestamp:q.timestamp,rateLimits:q.rateLimits}};for await(let x of J){let q=String(x);if(Y+=Buffer.byteLength(q,"utf8"),Y>GQ)throw new p;let F=0;while(F<q.length){let A=q.indexOf(`
5
- `,F),bZ=A===-1?q.length:A,AQ=q.slice(F,bZ);if(!W){let PQ=Buffer.byteLength(AQ,"utf8");if(X+PQ>aZ)K="",X=0,W=!0,V=!0;else K+=AQ,X+=PQ}if(A===-1)break;if(!W)C(K);K="",X=0,W=!1,F=A+1}}if(!W&&K.length>0)C(K);return{snapshot:j,skippedOversizedLine:V}}async function G0(Q){let Z;try{let $=await h(Q.path);if(!$.isFile()||!QQ($,Q))throw new $Q;let G=t.O_NOFOLLOW,J=typeof G==="number"?t.O_RDONLY|G:t.O_RDONLY;Z=await rZ(Q.path,J);let[z,j]=await Promise.all([Z.stat(),h(Q.path)]);if(!z.isFile()||!j.isFile()||!QQ(z,Q)||!QQ(z,j))throw new $Q;if(z.size>GQ)throw new p;return Z.createReadStream({encoding:"utf8",highWaterMark:65536})}catch($){throw await Z?.close().catch(()=>{return}),$}}function QQ(Q,Z){return Q.dev===Z.dev&&Q.ino===Z.ino}function J0(Q,Z){let $=T(Q.eventTimestamp)?.getTime()??null,G=T(Z.eventTimestamp)?.getTime()??null;if($===null)return!1;return G===null||$>G}function z0(Q){let Z=j0(Q);if(!Z)return{threadId:null,timestamp:null,rateLimits:null};return{threadId:K0(Z),timestamp:B(Z,"timestamp"),rateLimits:X0(Z)}}function j0(Q){let Z=Q.trim();if(!Z)return null;try{let $=JSON.parse(Z);return H($)?$:null}catch{return null}}function K0(Q){if(Q.type!=="session_meta"||!H(Q.payload))return null;return B(Q.payload,"id")}function X0(Q){if(Q.type!=="event_msg"||!H(Q.payload))return null;if(Q.payload.type!=="token_count"||!H(Q.payload.rate_limits))return null;return Q.payload.rate_limits}function ZQ(Q,Z,$,G,J){return{path:Q,relativePath:Z,modifiedAtMs:$,hasSnapshot:G,error:J}}async function Y0(Q){try{return(await h(Q)).isSymbolicLink()}catch{return!1}}class p extends Error{}class $Q extends Error{}import{opendir as W0,realpath as pQ}from"node:fs/promises";import{extname as V0,join as M0}from"node:path";import{constants as JQ}from"node:fs";import{lstat as gQ,open as H0}from"node:fs/promises";class U extends Error{code;constructor(Q){super(Q);this.name="BoundedFileError",this.code=Q}}async function c(Q,Z){let $;try{let G=await gQ(Q);if(!G.isFile())throw new U("not-file");let J=JQ.O_NOFOLLOW,z=typeof J==="number"?JQ.O_RDONLY|J:JQ.O_RDONLY;$=await H0(Q,z);let j=await $.stat(),K=await gQ(Q);if(!j.isFile()||!K.isFile()||!mQ(G,j)||!mQ(j,K))throw new U("not-file");if(j.size>Z)throw new U("too-large");let X=Buffer.allocUnsafe(Z+1),Y=0;while(Y<=Z){let W=await $.read(X,Y,Z+1-Y,null);if(W.bytesRead===0)break;Y+=W.bytesRead}if(Y>Z)throw new U("too-large");return X.subarray(0,Y).toString("utf8")}catch(G){if(G instanceof U)throw G;if(hQ(G)&&G.code==="ENOENT")throw new U("not-found");if(hQ(G)&&G.code==="ELOOP")throw new U("not-file");throw new U("read-error")}finally{await $?.close().catch(()=>{return})}}function mQ(Q,Z){return Q.dev===Z.dev&&Q.ino===Z.ino}function hQ(Q){return Q instanceof Error&&"code"in Q}var U0=2,zQ=25,jQ=100,q0=64,N0=500,B0=1e6,O0=/(?:auth|token|cookie|session|secret|credential|api[-_]?key|keychain)/i;async function cQ(Q){let Z={directories:0,files:[],hitDirectoryLimit:!1,hitEntryLimit:!1,hitFileLimit:!1,skippedSensitive:!1,skippedSymlink:!1,warnings:[]},$;try{$=await pQ(Q)}catch{return{homePath:Q,files:[],warnings:["Could not inspect the local Codex state directory safely."]}}if(await uQ(Q,0,Z),Z.hitDirectoryLimit||Z.hitEntryLimit||Z.hitFileLimit)Z.warnings.push("Stopped local state discovery after reaching a safe inspection limit.");if(Z.skippedSensitive)Z.warnings.push("Skipped a sensitive-looking local file.");if(Z.skippedSymlink)Z.warnings.push("Skipped symbolic links while inspecting local Codex state.");let G=Z.files.sort((z,j)=>z.localeCompare(j)),J=[];for(let z of G.slice(0,zQ)){let j=R(Q,z);try{let K=await pQ(z);if(!g($,K))throw new U("not-file");let X=await c(z,B0),Y=x0(X,Z.warnings);J.push({path:z,relativePath:j,json:Y.value,error:Y.error})}catch(K){Z.warnings.push(K instanceof U&&K.code==="too-large"?"Skipped a local Codex state file because it is too large to inspect safely.":"Could not read a local Codex state file safely.")}}if(G.length>zQ)Z.warnings.push(`Skipped ${G.length-zQ} extra files to keep inspection small.`);return{homePath:Q,files:J,warnings:Z.warnings}}async function uQ(Q,Z,$){if(Z>U0||$.files.length>=jQ){$.hitFileLimit||=$.files.length>=jQ;return}if($.directories>=q0){$.hitDirectoryLimit=!0;return}$.directories+=1;let G=await C0(Q,$);for(let J of G){if($.files.length>=jQ){$.hitFileLimit=!0;return}if(O0.test(J.name)){$.skippedSensitive=!0;continue}let z=M0(Q,J.name);if(J.isSymbolicLink())$.skippedSymlink=!0;else if(J.isDirectory())await uQ(z,Z+1,$);else if(J.isFile()&&V0(J.name).toLowerCase()===".json")$.files.push(z)}}async function C0(Q,Z){try{let $=await W0(Q),G=[];for await(let J of $){if(G.length>=N0){Z.hitEntryLimit=!0;break}G.push(J)}return G.sort((J,z)=>J.name.localeCompare(z.name))}catch{return Z.warnings.push("Could not inspect part of the local Codex state directory safely."),[]}}function x0(Q,Z){try{return{value:JSON.parse(Q),error:null}}catch{return Z.push("Could not parse JSON in a local Codex state file."),{value:null,error:"invalid-json"}}}import{join as D0,normalize as T0}from"node:path";function O(Q,Z,$){return{code:Q,source:Z,severity:"warning",message:$}}function k(Q){return Q.map((Z)=>_(Z.message))}var F0=1e6;async function u(Q={}){let Z=P(Q.env),$=N(Z,"CODEX_LIMITS_ACCESS_TOKEN"),G=N(Z,"CODEX_LIMITS_ACCOUNT_ID");if($&&G)return{credentials:{accessToken:$,accountId:G},status:"configured",diagnostics:[]};if($||G)return{credentials:null,status:"partial",diagnostics:[O("auth.environment.partial","authentication","Codex authentication environment variables are incomplete.")]};let J=await A0(Q);return J?P0(J):{credentials:null,status:"missing",diagnostics:[]}}async function A0(Q){if(Q.authFile)return T0(Q.authFile);let Z=await v(Q);return Z.foundHome?D0(Z.foundHome,"auth.json"):null}async function P0(Q){let Z;try{Z=await c(Q,F0)}catch($){if($ instanceof U&&$.code==="not-found")return{credentials:null,status:"missing",diagnostics:[]};let G=$ instanceof U&&$.code==="too-large";return{credentials:null,status:"unreadable",diagnostics:[O(G?"auth.file.too-large":"auth.file.unreadable","authentication",G?"Codex auth.json is too large to inspect safely.":"Codex auth.json could not be read safely.")]}}try{let $=JSON.parse(Z);if(!H($))return KQ();let G=H($.tokens)?$.tokens:$,J=B(G,"access_token"),z=B(G,"account_id");return J&&z?{credentials:{accessToken:J,accountId:z},status:"configured",diagnostics:[]}:KQ()}catch{return KQ()}}function KQ(){return{credentials:null,status:"malformed",diagnostics:[O("auth.file.malformed","authentication","Codex auth.json is malformed or does not contain required credentials.")]}}var b0=/[\u0000-\u0020\u007f-\u009f]/;function XQ(Q){return Q.length>0&&Q.length<=512&&!b0.test(Q)}import{request as I0}from"node:http";import{request as k0}from"node:https";var L0=new Set(["127.0.0.1","::1","[::1]","localhost"]);function f(Q){try{let Z=new URL(Q);return Z.username="",Z.password="",Z.search="",Z.hash="",Z.href}catch{return"[invalid endpoint]"}}async function dQ(Q){let Z=_0(Q.endpoint);if(!Z.ok)return Z;if(Q.signal?.aborted)return M("aborted");let $=Q.fetch??globalThis.fetch;if(!$)return lQ(Z.url,Q);let G=await R0(Z.url,Q,$);if(G.ok||G.code==="aborted"||!S0(G,Q.fallbackOnHttpError??!1))return G;let J=await lQ(Z.url,Q);if(J.ok||J.code==="http-error"||J.code==="invalid-json"||J.code==="response-too-large")return J;return G}function l(Q){let Z={...Q,method:"GET"};return delete Z.body,dQ(Z)}function _0(Q){let Z;try{Z=new URL(Q)}catch{return M("invalid-url")}if(Z.username||Z.password)return M("invalid-url");if(Z.protocol==="https:")return{ok:!0,url:Z};if(Z.protocol==="http:"&&L0.has(Z.hostname.toLowerCase()))return{ok:!0,url:Z};return M("unsupported-protocol")}async function R0(Q,Z,$){let G=oQ(Z.timeoutMs,Z.signal);try{let J=await $(Q.href,{method:Z.method??"GET",headers:Z.headers,redirect:"error",signal:G.signal,...Z.body===void 0?{}:{body:Z.body}});if(!J.ok)return await rQ(J),M("http-error",WQ(J.status));let z=await y0(J,Z.maxResponseBytes);return{ok:!0,status:WQ(J.status)??200,payload:z,transport:"fetch"}}catch(J){if(J instanceof y)return M("response-too-large");if(J instanceof d)return M("invalid-json");if(Z.signal?.aborted)return M("aborted");if(G.didTimeout())return M("timeout");return M("network-error")}finally{G.dispose()}}async function y0(Q,Z){let $=Number(Q.headers?.get("content-length"));if(Number.isFinite($)&&$>Z)throw await rQ(Q),new y;if(Q.body){let G=Q.body.getReader(),J=[],z=0;while(!0){let K=await G.read();if(K.done)break;if(!K.value)continue;if(z+=K.value.byteLength,z>Z)throw await G.cancel?.(),new y;J.push(K.value)}let j=Buffer.concat(J.map((K)=>Buffer.from(K)),z).toString("utf8");return HQ(j)}if(Q.text){let G=await Q.text();if(Buffer.byteLength(G,"utf8")>Z)throw new y;return HQ(G)}throw new d}async function rQ(Q){if(!Q.body)return;try{await Q.body.getReader().cancel?.()}catch{}}function lQ(Q,Z){return new Promise(($)=>{let G=oQ(Z.timeoutMs,Z.signal),J=!1,z=null,j=(X)=>{if(J)return;J=!0,G.dispose(),$(X)},K=()=>{z?.destroy(),j(M(Z.signal?.aborted?"aborted":"timeout"))};G.signal.addEventListener("abort",K,{once:!0});try{z=(Q.protocol==="http:"?I0:k0)(Q,{method:Z.method??"GET",headers:Z.headers,signal:G.signal},(Y)=>f0(Y,Z.maxResponseBytes,j)),z.on("error",()=>{if(Z.signal?.aborted)j(M("aborted"));else if(G.didTimeout())j(M("timeout"));else j(M("network-error"))}),z.end(Z.body)}catch{j(M("network-error"))}})}function f0(Q,Z,$){let G=WQ(Q.statusCode);if(G===null||G<200||G>=300){$(M("http-error",G)),YQ(Q);return}let J=Number(Q.headers["content-length"]);if(Number.isFinite(J)&&J>Z){$(M("response-too-large")),YQ(Q);return}let z=[],j=0;Q.on("data",(K)=>{let X=Buffer.isBuffer(K)?K:Buffer.from(K);if(j+=X.length,j>Z){$(M("response-too-large")),YQ(Q);return}z.push(X)}),Q.on("end",()=>{try{let K=HQ(Buffer.concat(z,j).toString("utf8"));$({ok:!0,status:G,payload:K,transport:"node"})}catch{$(M("invalid-json"))}}),Q.on("error",()=>$(M("network-error")))}function YQ(Q){Q.destroy(),Q.socket.destroy()}function oQ(Q,Z){let $=new AbortController,G=!1,J=Number.isFinite(Q)&&Q>0?Math.min(Math.floor(Q),2147483647):1,z=setTimeout(()=>{G=!0,$.abort()},J),j=()=>$.abort();if(Z?.addEventListener("abort",j,{once:!0}),Z?.aborted)j();return{signal:$.signal,didTimeout:()=>G,dispose:()=>{clearTimeout(z),Z?.removeEventListener("abort",j)}}}function S0(Q,Z){return Q.code==="network-error"||Q.code==="timeout"||Q.code==="invalid-json"||Z&&Q.code==="http-error"}function HQ(Q){try{return JSON.parse(Q)}catch{throw new d}}function WQ(Q){return typeof Q==="number"&&Number.isInteger(Q)&&Q>=0?Q:null}function M(Q,Z=null){return{ok:!1,code:Q,status:Z}}class y extends Error{}class d extends Error{}function r(Q,Z){switch(Q.code){case"aborted":return O("network.request.aborted","network",`${Z} lookup was cancelled.`);case"http-error":return O("network.response.http","network",Q.status===null?`${Z} endpoint returned an invalid HTTP status.`:`${Z} endpoint returned HTTP ${Q.status}.`);case"invalid-json":return O("network.response.invalid-json","network",`${Z} endpoint returned malformed JSON.`);case"invalid-url":return O("network.endpoint.invalid","network",`${Z} endpoint URL is invalid.`);case"response-too-large":return O("network.response.too-large","network",`${Z} endpoint response was too large.`);case"timeout":return O("network.request.timeout","network",`${Z} lookup timed out.`);case"unsupported-protocol":return O("network.endpoint.protocol","network",`${Z} endpoint must use HTTPS or loopback HTTP.`);case"network-error":return O("network.request.failed","network",`${Z} lookup failed.`)}}var aQ=["credits","reset_credits","items"],tQ=["available_count","availableCount","available"],eQ=["total_earned_count","earned_this_period","earnedThisPeriod","totalEarnedCount"],E0=64,w0=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(?:Z|[+-](\d{2}):(\d{2}))$/i;function QZ(Q,Z,$){if(!H(Q)||!v0(Q))return S(Z,["Live reset coupon endpoint returned an unexpected payload."]);let G=p0(Q,aQ);if(G.malformed)return S(Z,["Live reset coupon endpoint returned an unexpected payload."]);let J=G.value,z=J.map((V,C)=>g0(V,C+1,$)).filter((V)=>V!==null).sort(h0).map((V,C)=>({...V,index:C+1})),j=z.filter((V)=>V.status?.toLowerCase()==="available"),K=j[0]??z[0]??null,X=sQ(Q,tQ),Y=sQ(Q,eQ),W=[];if(J.length!==z.length)W.push("Live reset coupon endpoint ignored malformed coupon entries.");if(X.malformed||Y.malformed)W.push("Live reset coupon endpoint ignored malformed summary fields.");if(X.value!==null&&X.value!==j.length)W.push("Live reset coupon endpoint returned inconsistent availability data.");return{status:W.length>0?"partial":"available",available:X.value,earnedThisPeriod:Y.value,nextExpirationDate:K?.expirationDate??null,nextExpirationIn:K?.expiresIn??null,items:z,warnings:W,source:{live:!0,label:"live Codex reset-credit endpoint",endpoint:Z}}}function S(Q,Z=[]){return{status:"unavailable",available:null,earnedThisPeriod:null,nextExpirationDate:null,nextExpirationIn:null,items:[],warnings:Z,source:{live:!1,label:"live Codex reset-credit endpoint",endpoint:Q}}}function v0(Q){return[...aQ,...tQ,...eQ].some((Z)=>(Z in Q))}function g0(Q,Z,$){if(!H(Q))return null;let G=Q.id,J=typeof G==="string"&&XQ(G)?G:null,z=Q.reset_type??Q.resetType,j=typeof z==="string"&&/^[a-z][a-z0-9_-]{0,63}$/i.test(z)?z:null,K="expires_at"in Q||"expiresAt"in Q,X="granted_at"in Q||"grantedAt"in Q,Y=B(Q,"expires_at")??B(Q,"expiresAt"),W=B(Q,"granted_at")??B(Q,"grantedAt"),V=iQ(Y),C=iQ(W),x=B(Q,"status"),q=x&&/^[a-z][a-z0-9_-]{0,63}$/i.test(x)?x:null,F=C?W:null,A=V?Y:null;if("id"in Q&&!J||X&&!C||K&&!V||!q&&!F&&!A)return null;return{id:J,resetType:j,index:Z,status:q,grantedAt:F,expiresAt:A,expirationDate:V?_Q(V):null,expiresIn:V?L(V.getTime()-$.getTime()):null}}function iQ(Q){if(!Q||Q.length>E0)return null;let Z=w0.exec(Q);if(!Z)return null;let $=Number(Z[1]),G=Number(Z[2]),J=Number(Z[3]),z=Number(Z[4]),j=Number(Z[5]),K=Number(Z[6]),X=Z[8]===void 0?0:Number(Z[8]),Y=Z[9]===void 0?0:Number(Z[9]);if(G<1||G>12||J<1||J>m0($,G)||z>23||j>59||K>59||X>23||Y>59)return null;let W=new Date(Q);return Number.isNaN(W.getTime())?null:W}function m0(Q,Z){if(Z===2)return Q%4===0&&(Q%100!==0||Q%400===0)?29:28;return Z===4||Z===6||Z===9||Z===11?30:31}function h0(Q,Z){return nQ(Q.expiresAt)-nQ(Z.expiresAt)}function nQ(Q){return T(Q)?.getTime()??Number.POSITIVE_INFINITY}function p0(Q,Z){let $=!1;for(let G of Z){if(!(G in Q))continue;$=!0;let J=Q[G];if(Array.isArray(J))return{value:J,malformed:!1}}return{value:[],malformed:$}}function sQ(Q,Z){let $=!1;for(let G of Z){if(!(G in Q))continue;$=!0;let J=Q[G];if(typeof J==="number"&&Number.isInteger(J)&&J>=0)return{value:J,malformed:!1}}return{value:null,malformed:$}}var VQ="https://chatgpt.com/backend-api/wham/rate-limit-reset-credits",S2=`${VQ}/consume`,c0=1e4,u0=1e6;async function $Z(Q={}){let Z=Q.endpoint??VQ,$=f(Z),G=await u(Q);if(!G.credentials){let z=k(G.diagnostics);return l0($,z.length>0?z:["Live reset coupons require a readable Codex auth.json file or CODEX_LIMITS_ACCESS_TOKEN and CODEX_LIMITS_ACCOUNT_ID."])}let J=d0(Z,G.credentials,Q);try{let z=await(Q.transport??l)(J);return z.ok?QZ(z.payload,$,Q.now??new Date):ZZ($,z)}catch{return ZZ($,{ok:!1,code:"network-error",status:null})}}function l0(Q=VQ,Z=[]){return S(f(Q),Z)}function ZZ(Q,Z){return S(Q,k([r(Z,"Live reset coupon")]))}function d0(Q,Z,$){return{endpoint:Q,headers:r0(Z),timeoutMs:$.timeoutMs??c0,maxResponseBytes:u0,...$.fetch?{fetch:$.fetch}:{},...$.signal?{signal:$.signal}:{}}}function r0(Q){return{Authorization:`Bearer ${Q.accessToken}`,"ChatGPT-Account-ID":Q.accountId,"OpenAI-Beta":"codex-1",originator:"Codex Desktop",Accept:"application/json"}}var KZ=5,qQ="5-hour usage limit",NQ="Weekly usage limit",BQ=["fiveHour","five_hour","fiveHourWindow","five_hour_window","primary","primaryWindow","primary_window","main","mainWindow"],OQ=["weekly","week","weeklyWindow","weekly_window","secondary","secondaryWindow","secondary_window","backup","backupWindow"],o0=["used_percent","usedPercent","used","usage","percentUsed","usagePercent","usagePercentage","percent"],i0=["remaining_percent","remainingPercent","remaining","percentRemaining","availablePercent","available_percentage"],n0=["resets_at","resetsAt","resetAt","resetTime","reset_at","reset","ends_at","endsAt","windowEnd"],s0=["resetsIn","resetIn","resets_in","reset_in","timeUntilReset"],a0=["limit_window_seconds","limitWindowSeconds","window_seconds","windowSeconds","window_length_seconds","windowLengthSeconds"],t0=["window_minutes","windowMinutes","window_length_minutes","windowLengthMinutes"],e0=18000,Q1=604800,Z1=/^(?:(\d+)d)?(?:\s*(\d+)h)?(?:\s*(\d+)m)?(?:\s*(\d+)s)?$/i;function XZ(Q,Z=new Date){let $=Q.latestSnapshot;if(!$)return DQ(Q.warnings);return n(CQ($.rateLimits,Z),Q.warnings)}function CQ(Q,Z=new Date){return MZ(o(Q,BQ),o(Q,OQ),Z)}function YZ(Q){return o(Q,BQ)!==null||o(Q,OQ)!==null}function E(Q){let Z=jZ(b(Q,a0,!1)),$=jZ(b(Q,t0,!1)),G=Z??($===null?null:$*60);if(G===e0)return"fiveHour";if(G===Q1)return"weekly";return null}function HZ(Q,Z){return{...Q,source:Z}}function xQ(Q,Z,$=[]){return{...n(Q,$),source:Z}}function WZ(Q,Z=new Date){let $={fiveHour:null,weekly:null};for(let G of Q.files){if(!G.json)continue;let J=$1(G.json,Z);$=UZ($,J.windows)}return n($,Q.warnings)}function DQ(Q=[]){return{status:"unavailable",windows:{fiveHour:null,weekly:null},warnings:Q}}function VZ(Q,Z){let $=UZ(Q.windows,Z.windows);return n($,[...Q.warnings,...Z.warnings])}function $1(Q,Z){if(!H(Q))return{windows:{fiveHour:null,weekly:null}};let $=UQ(Q,BQ),G=UQ(Q,OQ);if($||G)return{windows:MZ($,G,Z)};let J=E(Q)??"fiveHour",z=MQ(Q,J==="weekly"?NQ:qQ,Z);return{windows:{fiveHour:J==="fiveHour"?z:null,weekly:J==="weekly"?z:null}}}function MZ(Q,Z,$){let G=[];if(Q)G.push({fallbackKind:"fiveHour",value:Q});if(Z)G.push({fallbackKind:"weekly",value:Z});return{fiveHour:MQ(GZ(G,"fiveHour"),qQ,$),weekly:MQ(GZ(G,"weekly"),NQ,$)}}function MQ(Q,Z,$){if(!Q)return null;let G=zZ(b(Q,o0,!0)),J=zZ(b(Q,i0,!0)),z=G??(J===null?null:i(100-J)),j=J??(G===null?null:i(100-G)),K=b(Q,n0,!0),X=T(K),Y=X?X.toISOString():null,W=X?L(X.getTime()-$.getTime()):z1(b(Q,s0,!0)),V={label:Z,remainingPercent:j,usedPercent:z,resetsAt:Y,resetsIn:W};return qZ(V)?V:null}function n(Q,Z){return{status:G1(Q),windows:Q,warnings:Z}}function G1(Q){let Z=[Q.fiveHour,Q.weekly].filter(($)=>qZ($));if(Z.length===0)return"unavailable";return Z.every(J1)?"available":"partial"}function GZ(Q,Z){let $=Q.find((G)=>E(G.value)===Z);if($)return $.value;return Q.find((G)=>G.fallbackKind===Z&&E(G.value)===null)?.value??null}function UZ(Q,Z){return{fiveHour:JZ(Q.fiveHour,Z.fiveHour,qQ),weekly:JZ(Q.weekly,Z.weekly,NQ)}}function JZ(Q,Z,$){if(!Q&&!Z)return null;return{label:$,remainingPercent:Q?.remainingPercent??Z?.remainingPercent??null,usedPercent:Q?.usedPercent??Z?.usedPercent??null,resetsAt:Q?.resetsAt??Z?.resetsAt??null,resetsIn:Q?.resetsIn??Z?.resetsIn??null}}function qZ(Q){return Q!==null&&(Q.remainingPercent!==null||Q.usedPercent!==null||Q.resetsAt!==null||Q.resetsIn!==null)}function J1(Q){return Q!==null&&Q.remainingPercent!==null&&Q.usedPercent!==null&&(Q.resetsAt!==null||Q.resetsIn!==null)}function UQ(Q,Z,$=0){if($>KZ)return null;for(let G of Z){let J=Q[G];if(H(J))return J}for(let G of Object.values(Q)){if(!H(G))continue;let J=UQ(G,Z,$+1);if(J)return J}return null}function o(Q,Z){for(let $ of Z){let G=Q[$];if(H(G))return G}return null}function b(Q,Z,$,G=0){if(G>KZ)return;for(let J of Z)if(J in Q)return Q[J];if(!$)return;for(let J of Object.values(Q)){if(!H(J))continue;let z=b(J,Z,$,G+1);if(z!==void 0)return z}return}function zZ(Q){if(typeof Q==="number"&&Number.isFinite(Q))return i(Q);if(typeof Q==="string"&&Q.trim().length>0){let Z=Q.trim(),$=Z.endsWith("%")?Z.slice(0,-1):Z,G=Number($);return Number.isFinite(G)?i(G):null}return null}function i(Q){return Math.round(Math.min(Math.max(Q,0),100)*10)/10}function jZ(Q){if(typeof Q==="number"&&Number.isFinite(Q))return Q;if(typeof Q==="string"&&Q.trim().length>0){let Z=Number(Q);return Number.isFinite(Z)?Z:null}return null}function z1(Q){let Z=j1(Q);if(!Z||Z.length>100)return null;let G=Z1.exec(Z)?.slice(1);if(!G||G.every((j)=>j===void 0))return null;let J=[86400,3600,60,1],z=0;for(let[j,K]of G.entries()){if(K===void 0)continue;let X=Number(K),Y=X*J[j];if(!Number.isSafeInteger(X)||!Number.isSafeInteger(Y))return null;if(z+=Y,!Number.isSafeInteger(z))return null}return z<=Math.floor(Number.MAX_SAFE_INTEGER/1000)?L(z*1000):null}function j1(Q){if(typeof Q==="string"&&Q.trim().length>0)return Q.trim();return null}var K1=5,X1=1000,Y1={kind:"unavailable",label:"Unavailable"};function BZ(Q,Z,$){let G=H1(Q)??W1(Q);if(!G)return w(["Live usage endpoint returned an unexpected payload."]);let J=xQ(CQ(G,$),{kind:"api",label:"API",endpoint:Z});if(J.status==="unavailable")return w(["Live usage endpoint returned an unexpected payload."]);if(J.status==="partial")return{...J,warnings:["Live usage endpoint returned incomplete usage data."]};return J}function w(Q){return xQ({fiveHour:null,weekly:null},Y1,Q)}function H1(Q){return OZ(Q,(Z)=>{if(!H(Z))return null;let $=Z.rate_limits??Z.rateLimits??Z.rate_limit??Z.rateLimit;if(H($))return $;return YZ(Z)?Z:null})}function W1(Q){return OZ(Q,(Z)=>{if(!Array.isArray(Z))return null;let $=Z.find((J)=>NZ(J,"fiveHour")),G=Z.find((J)=>NZ(J,"weekly"));return $||G?{fiveHour:$,weekly:G}:null})}function OZ(Q,Z){let $=[{value:Q,depth:0}],G=new WeakSet;for(let J=0;J<$.length;J+=1){let z=$[J];if(!z)break;let j=Z(z.value);if(j)return j;if(z.depth>=K1||typeof z.value!=="object"||!z.value)continue;if(G.has(z.value))continue;G.add(z.value);let K=Array.isArray(z.value)?z.value:H(z.value)?Object.values(z.value):[];for(let X of K){if($.length>=X1)break;$.push({value:X,depth:z.depth+1})}}return null}function NZ(Q,Z){if(!H(Q))return!1;let $=E(Q);if($)return $===Z;let G=String(Q.type??Q.kind??Q.name??Q.label??Q.window??"").toLowerCase();return Z==="fiveHour"?G.includes("primary")||G.includes("5-hour")||G.includes("five"):G.includes("secondary")||G.includes("weekly")||G.includes("week")}var V1="https://chatgpt.com/backend-api/codex/usage",M1=1e4,U1=1e6;async function CZ(Q={}){return(await q1(Q)).usage}async function q1(Q={}){let Z=B1(Q),$=f(Z),G=await u(Q);if(!G.credentials){let j=k(G.diagnostics);return{usage:w(j.length>0?j:["Live usage requires Codex authentication."]),authenticationFound:!1,endpointStatus:"not-checked"}}let J={endpoint:Z,headers:N1(G.credentials),timeoutMs:Q.timeoutMs??M1,maxResponseBytes:U1,fallbackOnHttpError:!0,...Q.fetch?{fetch:Q.fetch}:{},...Q.signal?{signal:Q.signal}:{}},z;try{z=await(Q.transport??l)(J)}catch{z={ok:!1,code:"network-error",status:null}}return{usage:z.ok?BZ(z.payload,$,Q.now??new Date):C1(z),authenticationFound:!0,endpointStatus:O1(z)}}function N1(Q){return{Authorization:`Bearer ${Q.accessToken}`,"ChatGPT-Account-ID":Q.accountId,"OpenAI-Beta":"codex-1",originator:"Codex Desktop",Accept:"application/json","User-Agent":"Codex Desktop",Referer:"https://chatgpt.com/codex/cloud/settings/analytics",Origin:"https://chatgpt.com"}}function B1(Q){let Z=P(Q.env);return Q.usageEndpoint??N(Z,"CODEX_LIMITS_USAGE_ENDPOINT")??V1}function O1(Q){if(Q.ok)return"reachable";switch(Q.code){case"http-error":case"invalid-json":case"response-too-large":return"reachable";case"aborted":return"not-checked";case"invalid-url":case"network-error":case"timeout":case"unsupported-protocol":return"unreachable"}}function C1(Q){return w(k([r(Q,"Live usage")]))}var x1={kind:"local",label:"Local"};async function xZ(Q={}){let Z=Q.includeCoupons===!1?Promise.resolve(null):$Z(Q),[$,G]=await Promise.all([D1(Q),Z]),J=G?T1(G):null;return{windows:$.windows,coupons:J,warnings:a([...$.warnings,...J?.warnings??[]])}}async function D1(Q={}){let Z=await CZ(Q);if(Z.status!=="unavailable")return Z;let $=HZ(await F1(Q),x1);return $.status!=="unavailable"?$:{...$,warnings:[...Z.warnings,...$.warnings]}}function T1(Q){return{status:Q.status,available:Q.available,earnedThisPeriod:Q.earnedThisPeriod,nextExpirationDate:Q.nextExpirationDate,nextExpirationIn:Q.nextExpirationIn,items:Q.items.map((Z)=>({index:Z.index,status:Z.status,grantedAt:Z.grantedAt,expiresAt:Z.expiresAt,expirationDate:Z.expirationDate,expiresIn:Z.expiresIn})),warnings:a(Q.warnings)}}async function F1(Q={}){let Z=Q.now??new Date,$=await v(Q);if(!$.foundHome)return DQ(["No readable local Codex home directory was found."]);let[G,J]=await Promise.all([wQ($.foundHome),cQ($.foundHome)]);return VZ(XZ(G,Z),WZ(J,Z))}var P1="Codex Limits",TZ="Could not load Codex limits.",b1="Could not display Codex limits.";function I1(Q={}){let Z=Q.getLimits??xZ;return($)=>{$.registerCommand("codex-limits",{description:"Check Codex limits, resets, and credits",handler:async(G,J)=>{if(!J.hasUI||J.mode!=="tui")return;J.ui.setStatus("codex-limits","Loading Codex limits...");let z;try{z=kQ(await Z())}catch{z=TZ,J.ui.notify(TZ,"error")}finally{J.ui.setStatus("codex-limits",void 0)}try{await k1(z,J)}catch{J.ui.notify(b1,"error")}}})}}async function k1(Q,Z){await Z.ui.custom(($,G,J,z)=>{let j=FZ(Q,G);return{render:(K)=>j.render(K),invalidate:()=>{j=FZ(Q,G)},handleInput:(K)=>{if(TQ(K,"enter")||TQ(K,"escape")||TQ(K,"ctrl+c"))z(void 0)}}},{overlay:!0,overlayOptions:{width:56,minWidth:36,maxHeight:"90%",margin:1}})}function FZ(Q,Z){let $=new A1;return $.addChild(new DZ((G)=>Z.fg("accent",G))),$.addChild(new FQ(Z.fg("accent",Z.bold(P1)),1,0)),$.addChild(new FQ(Q,1,1)),$.addChild(new FQ(Z.fg("dim","Press Enter or Esc to close"),1,0)),$.addChild(new DZ((G)=>Z.fg("accent",G))),$}var L1=I1(),AZ=L1;function PZ(Q){return Q}var _1=PZ(AZ),V3=_1;export{V3 as default};
4
+ `)}function PQ(Q,Z){let $=Z.remainingPercent;return[`${Q} ${LZ($)}`,`Remaining ${$===null?"Unknown":`${Math.round($)}% remaining`}`,PZ($),`Reset ${Z.resetsIn?`in ${Z.resetsIn}`:"unknown"}`]}function PZ(Q){if(Q===null)return`[${" ".repeat(22)}] Unknown`;let Z=Math.min(Math.max(Q,0),100),$=Math.round(Z/100*22);return`[${"=".repeat($)}${" ".repeat(22-$)}] ${Math.round(Z)}%`}function kZ(Q){let Z=Q.coupons?.available,G=[`Reset credits ${Z===null||Z===void 0?"Unknown":`${Z} ${Z===1?"credit":"credits"} available`}`],J=Q.coupons?.nextExpirationIn,z=Q.coupons?.nextExpirationDate,j=J&&z?`${J} (${z})`:J??z;if(j!==null&&j!==void 0)G.push(`Next expires ${j}`);return G}function LZ(Q){if(Q===null)return"Unknown";if(Q>=50)return"Healthy";if(Q>=15)return"Low";return"Critical"}function LQ(Q){return kQ(Q)}import{constants as _Z}from"node:fs";import{access as RZ,stat as yZ}from"node:fs/promises";import{homedir as fZ}from"node:os";import{join as P,normalize as a}from"node:path";function N(Q,Z){let $=Q[Z]?.trim();return $?$:null}function b(Q){return Q??process.env}var _Q="CODEX_LIMITS_HOME";function SZ(Q={}){let Z=b(Q.env),$=Q.homeDirectory??N(Z,"HOME")??N(Z,"USERPROFILE")??fZ(),G=Q.appData??N(Z,"APPDATA"),J=Q.localAppData??N(Z,"LOCALAPPDATA"),z=[];if(T(z,N(Z,_Q),"env"),T(z,N(Z,"CODEX_HOME"),"env"),$)T(z,P($,".codex"),"default"),T(z,P($,".config","codex"),"default"),T(z,P($,"Library","Application Support","Codex"),"default"),T(z,P($,"Library","Application Support","Parall","Codex",".codex"),"default");return T(z,G?P(G,"Codex"):null,"default"),T(z,J?P(J,"Codex"):null,"default"),wZ(z)}async function m(Q={}){let Z=b(Q.env),$=N(Z,_Q),G=await Promise.all(SZ(Q).map(async(J)=>({...J,exists:await EZ(J.path)})));return{overrideHome:$?a($):null,candidates:G,foundHome:G.find((J)=>J.exists)?.path??null}}function T(Q,Z,$){if(Z)Q.push({path:a(Z),source:$})}async function EZ(Q){try{if(!(await yZ(Q)).isDirectory())return!1;return await RZ(Q,_Z.R_OK),!0}catch{return!1}}function wZ(Q){let Z=new Set,$=[];for(let G of Q){let J=a(G.path),z=process.platform==="win32"?J.toLowerCase():J;if(!Z.has(z))Z.add(z),$.push({path:J,source:G.source})}return $}import{constants as e}from"node:fs";import{lstat as f,open as rZ,opendir as oZ,realpath as $Q}from"node:fs/promises";import{join as EQ}from"node:path";var vZ=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],gZ=["January","February","March","April","May","June","July","August","September","October","November","December"];function L(Q,Z={}){let $=Z.includeSeconds??!1,G=Math.max(Math.floor(Q/1000),0),J=Math.floor(G/86400);G%=86400;let z=Math.floor(G/3600);G%=3600;let j=Math.floor(G/60),K=G%60,X=[];if(J>0)X.push(`${J}d`);if(z>0)X.push(`${z}h`);if(j>0)X.push(`${j}m`);if($&&K>0)X.push(`${K}s`);return X.length>0?X.join(" "):$?`${K}s`:"0m"}function F(Q){if(typeof Q==="number"&&Number.isFinite(Q)){let Z=Q<10000000000?Q*1000:Q,$=new Date(Z);return Number.isNaN($.getTime())?null:$}if(typeof Q==="string"&&Q.trim().length>0){let Z=Q.trim(),$=Number(Z);if(Number.isFinite($))return F($);let G=new Date(Z);return Number.isNaN(G.getTime())?null:G}return null}function RQ(Q){return`${vZ[Q.getDay()]} ${Q.getDate()} ${gZ[Q.getMonth()]} ${Q.getFullYear()}`}import{isAbsolute as uZ,relative as fQ,resolve as yQ,sep as lZ}from"node:path";var mZ=/(?:chatgpt[-_]?account[-_]?id|access[-_]?token|refresh[-_]?token|id[-_]?token|session[-_]?token|api[-_]?key|account[-_]?id|authorization|cookie|client[-_]?secret|password|credential|secret|token)/,hZ=/[\u0000-\u001f\u007f-\u009f]/g,pZ=new RegExp(`["']?${mZ.source}["']?\\s*[:=]\\s*(?:"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|[^,\\r\\n}\\]&]+)`,"gi"),cZ=[pZ,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}(?:\.[A-Za-z0-9_-]{5,})?\b/g,/sk-[A-Za-z0-9_-]{10,}/g,/\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b/gi,/[A-Za-z0-9_-]{32,}/g];function _(Q){let Z=Q;for(let $ of cZ)Z=Z.replace($,"[redacted]");return Z.replace(hZ,"?")}function t(Q){return Q.map(_)}function R(Q,Z){let $=fQ(yQ(Q),yQ(Z));return $===""||!SQ($)}function y(Q,Z){let $=fQ(Q,Z);return $&&!SQ($)?dZ($):"."}function dZ(Q){let Z=_(Q);return Z.length<=240?Z:`${Z.slice(0,239)}…`}function SQ(Q){return Q===".."||Q.startsWith(`..${lZ}`)||uZ(Q)}function W(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function B(Q,Z){let $=Q[Z];return typeof $==="string"&&$.trim()?$.trim():null}var iZ=8,QQ=20,h=1000,nZ=512,sZ=1000,JQ=25000000,aZ=1e6,tZ=/^rollout-.*\.jsonl$/i;async function wQ(Q){let Z=EQ(Q,"sessions"),$=[],G=await eZ(Q,Z,$);if(!G)return{homePath:Q,sessionsRoot:Z,files:[],latestSnapshot:null,warnings:$};let J=await Q0(Z,G,$),z=[],j=null;for(let K of J.slice(0,QQ)){let X=y(Q,K.path);if(K.size>JQ){$.push("Skipped a local Codex session file because it is too large to inspect safely."),z.push(ZQ(K.path,X,K.modifiedAtMs,!1,"too-large"));continue}try{let Y=await G0(Q,K);if(z.push(ZQ(K.path,X,K.modifiedAtMs,Y.snapshot!==null,null)),Y.skippedOversizedLine)$.push("Skipped an oversized JSONL line in a local Codex session file.");if(Y.snapshot&&(!j||z0(Y.snapshot,j)))j=Y.snapshot}catch(Y){let H=Y instanceof c;$.push(H?"Skipped a local Codex session file because it grew too large to inspect safely.":"Could not inspect a local Codex session file safely."),z.push(ZQ(K.path,X,K.modifiedAtMs,!1,H?"too-large":"read-error"))}}if(J.length>QQ)$.push(`Skipped ${J.length-QQ} older session files to keep inspection small.`);if(J.length>0&&!j)$.push("No token-count rate-limit snapshot was found in local Codex session logs.");return{homePath:Q,sessionsRoot:Z,files:z,latestSnapshot:j,warnings:$}}async function eZ(Q,Z,$){try{let G=await f(Z);if(G.isSymbolicLink())return $.push("Skipped the symbolic-link Codex sessions directory."),null;if(!G.isDirectory())return null;let[J,z]=await Promise.all([$Q(Q),$Q(Z)]),j=await f(Z);if(!R(J,z)||!j.isDirectory()||j.isSymbolicLink()||!p(G,j))return $.push("Could not inspect the local Codex sessions directory safely."),null;return z}catch{return null}}async function Q0(Q,Z,$){let G={directories:0,files:[],hitLimit:!1,skippedSymlink:!1};if(await vQ(Q,0,G,$),G.hitLimit)$.push("Stopped session discovery after reaching a safe inspection limit.");if(G.skippedSymlink)$.push("Skipped symbolic links while inspecting Codex sessions.");let J=[];for(let z of G.files){let j=await Z0(Z,z,$);if(j)J.push(j)}return J.sort((z,j)=>j.modifiedAtMs-z.modifiedAtMs||z.path.localeCompare(j.path))}async function Z0(Q,Z,$){try{let[G,J]=await Promise.all([f(Z),$Q(Z)]);if(!G.isFile()||!R(Q,J))return $.push("Could not inspect a local Codex session file safely."),null;return{path:Z,modifiedAtMs:G.mtimeMs,size:G.size,dev:G.dev,ino:G.ino}}catch{return $.push("Could not inspect a local Codex session file safely."),null}}async function vQ(Q,Z,$,G){if(Z>iZ||$.files.length>=h){$.hitLimit||=$.files.length>=h;return}if($.directories>=nZ){$.hitLimit=!0;return}$.directories+=1;let J;try{J=await $0(Q,$)}catch{if(Z>0)G.push("Could not inspect part of the local Codex sessions directory safely.");return}for(let z of J){if($.files.length>=h){$.hitLimit=!0;return}let j=EQ(Q,z.name);if(z.isSymbolicLink()){$.skippedSymlink=!0;continue}if(z.isDirectory()){await vQ(j,Z+1,$,G);continue}if(z.isFile()&&tZ.test(z.name)){if($.files.push(j),$.files.length>=h){$.hitLimit=!0;return}}}}async function $0(Q,Z){let $=await oZ(Q),G=[];for await(let J of $){if(G.length>=sZ){Z.hitLimit=!0;break}G.push(J)}return G.sort((J,z)=>z.name.localeCompare(J.name))}async function G0(Q,Z){let $=Z.path,G=y(Q,$),J=await J0(Z),z=null,j=null,K="",X=0,Y=0,H=!1,V=!1,C=(x)=>{let q=j0(x.endsWith("\r")?x.slice(0,-1):x);if(q.threadId)z=q.threadId;if(q.rateLimits)j={sessionFile:$,relativePath:G,threadId:z,eventTimestamp:q.timestamp,rateLimits:q.rateLimits}};for await(let x of J){let q=String(x);if(Y+=Buffer.byteLength(q,"utf8"),Y>JQ)throw new c;let D=0;while(D<q.length){let A=q.indexOf(`
5
+ `,D),IZ=A===-1?q.length:A,bQ=q.slice(D,IZ);if(!H){let IQ=Buffer.byteLength(bQ,"utf8");if(X+IQ>aZ)K="",X=0,H=!0,V=!0;else K+=bQ,X+=IQ}if(A===-1)break;if(!H)C(K);K="",X=0,H=!1,D=A+1}}if(!H&&K.length>0)C(K);return{snapshot:j,skippedOversizedLine:V}}async function J0(Q){let Z;try{let $=await f(Q.path);if(!$.isFile()||!p($,Q))throw new GQ;let G=e.O_NOFOLLOW,J=typeof G==="number"?e.O_RDONLY|G:e.O_RDONLY;Z=await rZ(Q.path,J);let[z,j]=await Promise.all([Z.stat(),f(Q.path)]);if(!z.isFile()||!j.isFile()||!p(z,Q)||!p(z,j))throw new GQ;if(z.size>JQ)throw new c;return Z.createReadStream({encoding:"utf8",highWaterMark:65536})}catch($){throw await Z?.close().catch(()=>{return}),$}}function p(Q,Z){return Q.dev===Z.dev&&Q.ino===Z.ino}function z0(Q,Z){let $=F(Q.eventTimestamp)?.getTime()??null,G=F(Z.eventTimestamp)?.getTime()??null;if($===null)return!1;return G===null||$>G}function j0(Q){let Z=K0(Q);if(!Z)return{threadId:null,timestamp:null,rateLimits:null};return{threadId:X0(Z),timestamp:B(Z,"timestamp"),rateLimits:Y0(Z)}}function K0(Q){let Z=Q.trim();if(!Z)return null;try{let $=JSON.parse(Z);return W($)?$:null}catch{return null}}function X0(Q){if(Q.type!=="session_meta"||!W(Q.payload))return null;return B(Q.payload,"id")}function Y0(Q){if(Q.type!=="event_msg"||!W(Q.payload))return null;if(Q.payload.type!=="token_count"||!W(Q.payload.rate_limits))return null;return Q.payload.rate_limits}function ZQ(Q,Z,$,G,J){return{path:Q,relativePath:Z,modifiedAtMs:$,hasSnapshot:G,error:J}}class c extends Error{}class GQ extends Error{}import{opendir as W0,realpath as pQ}from"node:fs/promises";import{extname as V0,join as M0}from"node:path";import{constants as zQ}from"node:fs";import{lstat as gQ,open as H0}from"node:fs/promises";class U extends Error{code;constructor(Q){super(Q);this.name="BoundedFileError",this.code=Q}}async function u(Q,Z){let $;try{let G=await gQ(Q);if(!G.isFile())throw new U("not-file");let J=zQ.O_NOFOLLOW,z=typeof J==="number"?zQ.O_RDONLY|J:zQ.O_RDONLY;$=await H0(Q,z);let j=await $.stat(),K=await gQ(Q);if(!j.isFile()||!K.isFile()||!mQ(G,j)||!mQ(j,K))throw new U("not-file");if(j.size>Z)throw new U("too-large");let X=Buffer.allocUnsafe(Z+1),Y=0;while(Y<=Z){let H=await $.read(X,Y,Z+1-Y,null);if(H.bytesRead===0)break;Y+=H.bytesRead}if(Y>Z)throw new U("too-large");return X.subarray(0,Y).toString("utf8")}catch(G){if(G instanceof U)throw G;if(hQ(G)&&G.code==="ENOENT")throw new U("not-found");if(hQ(G)&&G.code==="ELOOP")throw new U("not-file");throw new U("read-error")}finally{await $?.close().catch(()=>{return})}}function mQ(Q,Z){return Q.dev===Z.dev&&Q.ino===Z.ino}function hQ(Q){return Q instanceof Error&&"code"in Q}var U0=2,jQ=25,KQ=100,q0=64,N0=500,B0=1e6,O0=/(?:auth|token|cookie|session|secret|credential|api[-_]?key|keychain)/i;async function cQ(Q){let Z={directories:0,files:[],hitDirectoryLimit:!1,hitEntryLimit:!1,hitFileLimit:!1,skippedSensitive:!1,skippedSymlink:!1,warnings:[]},$;try{$=await pQ(Q)}catch{return{homePath:Q,files:[],warnings:["Could not inspect the local Codex state directory safely."]}}if(await uQ(Q,0,Z),Z.hitDirectoryLimit||Z.hitEntryLimit||Z.hitFileLimit)Z.warnings.push("Stopped local state discovery after reaching a safe inspection limit.");if(Z.skippedSensitive)Z.warnings.push("Skipped a sensitive-looking local file.");if(Z.skippedSymlink)Z.warnings.push("Skipped symbolic links while inspecting local Codex state.");let G=Z.files.sort((z,j)=>z.localeCompare(j)),J=[];for(let z of G.slice(0,jQ)){let j=y(Q,z);try{let K=await pQ(z);if(!R($,K))throw new U("not-file");let X=await u(z,B0),Y=x0(X,Z.warnings);J.push({path:z,relativePath:j,json:Y.value,error:Y.error})}catch(K){Z.warnings.push(K instanceof U&&K.code==="too-large"?"Skipped a local Codex state file because it is too large to inspect safely.":"Could not read a local Codex state file safely.")}}if(G.length>jQ)Z.warnings.push(`Skipped ${G.length-jQ} extra files to keep inspection small.`);return{homePath:Q,files:J,warnings:Z.warnings}}async function uQ(Q,Z,$){if(Z>U0||$.files.length>=KQ){$.hitFileLimit||=$.files.length>=KQ;return}if($.directories>=q0){$.hitDirectoryLimit=!0;return}$.directories+=1;let G=await C0(Q,$);for(let J of G){if($.files.length>=KQ){$.hitFileLimit=!0;return}if(O0.test(J.name)){$.skippedSensitive=!0;continue}let z=M0(Q,J.name);if(J.isSymbolicLink())$.skippedSymlink=!0;else if(J.isDirectory())await uQ(z,Z+1,$);else if(J.isFile()&&V0(J.name).toLowerCase()===".json")$.files.push(z)}}async function C0(Q,Z){try{let $=await W0(Q),G=[];for await(let J of $){if(G.length>=N0){Z.hitEntryLimit=!0;break}G.push(J)}return G.sort((J,z)=>J.name.localeCompare(z.name))}catch{return Z.warnings.push("Could not inspect part of the local Codex state directory safely."),[]}}function x0(Q,Z){try{return{value:JSON.parse(Q),error:null}}catch{return Z.push("Could not parse JSON in a local Codex state file."),{value:null,error:"invalid-json"}}}import{join as T0,normalize as F0}from"node:path";function O(Q,Z,$){return{code:Q,source:Z,severity:"warning",message:$}}function k(Q){return Q.map((Z)=>_(Z.message))}var D0=1e6;async function l(Q={}){let Z=b(Q.env),$=N(Z,"CODEX_LIMITS_ACCESS_TOKEN"),G=N(Z,"CODEX_LIMITS_ACCOUNT_ID");if($&&G)return{credentials:{accessToken:$,accountId:G},status:"configured",diagnostics:[]};if($||G)return{credentials:null,status:"partial",diagnostics:[O("auth.environment.partial","authentication","Codex authentication environment variables are incomplete.")]};let J=await A0(Q);return J?b0(J):{credentials:null,status:"missing",diagnostics:[]}}async function A0(Q){if(Q.authFile)return F0(Q.authFile);let Z=await m(Q);return Z.foundHome?T0(Z.foundHome,"auth.json"):null}async function b0(Q){let Z;try{Z=await u(Q,D0)}catch($){if($ instanceof U&&$.code==="not-found")return{credentials:null,status:"missing",diagnostics:[]};let G=$ instanceof U&&$.code==="too-large";return{credentials:null,status:"unreadable",diagnostics:[O(G?"auth.file.too-large":"auth.file.unreadable","authentication",G?"Codex auth.json is too large to inspect safely.":"Codex auth.json could not be read safely.")]}}try{let $=JSON.parse(Z);if(!W($))return XQ();let G=W($.tokens)?$.tokens:$,J=B(G,"access_token"),z=B(G,"account_id");return J&&z?{credentials:{accessToken:J,accountId:z},status:"configured",diagnostics:[]}:XQ()}catch{return XQ()}}function XQ(){return{credentials:null,status:"malformed",diagnostics:[O("auth.file.malformed","authentication","Codex auth.json is malformed or does not contain required credentials.")]}}var I0=/[\u0000-\u0020\u007f-\u009f]/;function YQ(Q){return Q.length>0&&Q.length<=512&&!I0.test(Q)}import{request as P0}from"node:http";import{request as k0}from"node:https";var L0=new Set(["127.0.0.1","::1","[::1]","localhost"]);function E(Q){try{let Z=new URL(Q);return Z.username="",Z.password="",Z.search="",Z.hash="",Z.href}catch{return"[invalid endpoint]"}}async function dQ(Q){let Z=_0(Q.endpoint);if(!Z.ok)return Z;if(Q.signal?.aborted)return M("aborted");let $=Q.fetch??globalThis.fetch;if(!$)return lQ(Z.url,Q);let G=await R0(Z.url,Q,$);if(G.ok||G.code==="aborted"||!S0(G,Q.fallbackOnHttpError??!1))return G;let J=await lQ(Z.url,Q);if(J.ok||J.code==="http-error"||J.code==="invalid-json"||J.code==="response-too-large")return J;return G}function d(Q){let Z={...Q,method:"GET"};return delete Z.body,dQ(Z)}function _0(Q){let Z;try{Z=new URL(Q)}catch{return M("invalid-url")}if(Z.username||Z.password)return M("invalid-url");if(Z.protocol==="https:")return{ok:!0,url:Z};if(Z.protocol==="http:"&&L0.has(Z.hostname.toLowerCase()))return{ok:!0,url:Z};return M("unsupported-protocol")}async function R0(Q,Z,$){let G=oQ(Z.timeoutMs,Z.signal);try{let J=await $(Q.href,{method:Z.method??"GET",headers:Z.headers,redirect:"error",signal:G.signal,...Z.body===void 0?{}:{body:Z.body}});if(!J.ok)return await rQ(J),M("http-error",VQ(J.status));let z=await y0(J,Z.maxResponseBytes);return{ok:!0,status:VQ(J.status)??200,payload:z,transport:"fetch"}}catch(J){if(J instanceof S)return M("response-too-large");if(J instanceof r)return M("invalid-json");if(Z.signal?.aborted)return M("aborted");if(G.didTimeout())return M("timeout");return M("network-error")}finally{G.dispose()}}async function y0(Q,Z){let $=Number(Q.headers?.get("content-length"));if(Number.isFinite($)&&$>Z)throw await rQ(Q),new S;if(Q.body){let G=Q.body.getReader(),J=[],z=0;while(!0){let K=await G.read();if(K.done)break;if(!K.value)continue;if(z+=K.value.byteLength,z>Z)throw await G.cancel?.(),new S;J.push(K.value)}let j=Buffer.concat(J.map((K)=>Buffer.from(K)),z).toString("utf8");return WQ(j)}if(Q.text){let G=await Q.text();if(Buffer.byteLength(G,"utf8")>Z)throw new S;return WQ(G)}throw new r}async function rQ(Q){if(!Q.body)return;try{await Q.body.getReader().cancel?.()}catch{}}function lQ(Q,Z){return new Promise(($)=>{let G=oQ(Z.timeoutMs,Z.signal),J=!1,z=null,j=(X)=>{if(J)return;J=!0,G.dispose(),$(X)},K=()=>{z?.destroy(),j(M(Z.signal?.aborted?"aborted":"timeout"))};G.signal.addEventListener("abort",K,{once:!0});try{z=(Q.protocol==="http:"?P0:k0)(Q,{method:Z.method??"GET",headers:Z.headers,signal:G.signal},(Y)=>f0(Y,Z.maxResponseBytes,j)),z.on("error",()=>{if(Z.signal?.aborted)j(M("aborted"));else if(G.didTimeout())j(M("timeout"));else j(M("network-error"))}),z.end(Z.body)}catch{j(M("network-error"))}})}function f0(Q,Z,$){let G=VQ(Q.statusCode);if(G===null||G<200||G>=300){$(M("http-error",G)),HQ(Q);return}let J=Number(Q.headers["content-length"]);if(Number.isFinite(J)&&J>Z){$(M("response-too-large")),HQ(Q);return}let z=[],j=0;Q.on("data",(K)=>{let X=Buffer.isBuffer(K)?K:Buffer.from(K);if(j+=X.length,j>Z){$(M("response-too-large")),HQ(Q);return}z.push(X)}),Q.on("end",()=>{try{let K=WQ(Buffer.concat(z,j).toString("utf8"));$({ok:!0,status:G,payload:K,transport:"node"})}catch{$(M("invalid-json"))}}),Q.on("error",()=>$(M("network-error")))}function HQ(Q){Q.destroy(),Q.socket.destroy()}function oQ(Q,Z){let $=new AbortController,G=!1,J=Number.isFinite(Q)&&Q>0?Math.min(Math.floor(Q),2147483647):1,z=setTimeout(()=>{G=!0,$.abort()},J),j=()=>$.abort();if(Z?.addEventListener("abort",j,{once:!0}),Z?.aborted)j();return{signal:$.signal,didTimeout:()=>G,dispose:()=>{clearTimeout(z),Z?.removeEventListener("abort",j)}}}function S0(Q,Z){return Q.code==="network-error"||Q.code==="timeout"||Q.code==="invalid-json"||Z&&Q.code==="http-error"}function WQ(Q){try{return JSON.parse(Q)}catch{throw new r}}function VQ(Q){return typeof Q==="number"&&Number.isInteger(Q)&&Q>=0?Q:null}function M(Q,Z=null){return{ok:!1,code:Q,status:Z}}class S extends Error{}class r extends Error{}function o(Q,Z){switch(Q.code){case"aborted":return O("network.request.aborted","network",`${Z} lookup was cancelled.`);case"http-error":return O("network.response.http","network",Q.status===null?`${Z} endpoint returned an invalid HTTP status.`:`${Z} endpoint returned HTTP ${Q.status}.`);case"invalid-json":return O("network.response.invalid-json","network",`${Z} endpoint returned malformed JSON.`);case"invalid-url":return O("network.endpoint.invalid","network",`${Z} endpoint URL is invalid.`);case"response-too-large":return O("network.response.too-large","network",`${Z} endpoint response was too large.`);case"timeout":return O("network.request.timeout","network",`${Z} lookup timed out.`);case"unsupported-protocol":return O("network.endpoint.protocol","network",`${Z} endpoint must use HTTPS or loopback HTTP.`);case"network-error":return O("network.request.failed","network",`${Z} lookup failed.`)}}var aQ=["credits","reset_credits","items"],tQ=["available_count","availableCount","available"],eQ=["total_earned_count","earned_this_period","earnedThisPeriod","totalEarnedCount"],E0=64,w0=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(?:Z|[+-](\d{2}):(\d{2}))$/i;function QZ(Q,Z,$){if(!W(Q)||!v0(Q))return w(Z,["Live reset coupon endpoint returned an unexpected payload."]);let G=p0(Q,aQ);if(G.malformed)return w(Z,["Live reset coupon endpoint returned an unexpected payload."]);let J=G.value,z=J.map((V,C)=>g0(V,C+1,$)).filter((V)=>V!==null).sort(h0).map((V,C)=>({...V,index:C+1})),j=z.filter((V)=>V.status?.toLowerCase()==="available"),K=j[0]??z[0]??null,X=sQ(Q,tQ),Y=sQ(Q,eQ),H=[];if(J.length!==z.length)H.push("Live reset coupon endpoint ignored malformed coupon entries.");if(X.malformed||Y.malformed)H.push("Live reset coupon endpoint ignored malformed summary fields.");if(X.value!==null&&X.value!==j.length)H.push("Live reset coupon endpoint returned inconsistent availability data.");return{status:H.length>0?"partial":"available",available:X.value,earnedThisPeriod:Y.value,nextExpirationDate:K?.expirationDate??null,nextExpirationIn:K?.expiresIn??null,items:z,warnings:H,source:{live:!0,label:"live Codex reset-credit endpoint",endpoint:Z}}}function w(Q,Z=[]){return{status:"unavailable",available:null,earnedThisPeriod:null,nextExpirationDate:null,nextExpirationIn:null,items:[],warnings:Z,source:{live:!1,label:"live Codex reset-credit endpoint",endpoint:Q}}}function v0(Q){return[...aQ,...tQ,...eQ].some((Z)=>(Z in Q))}function g0(Q,Z,$){if(!W(Q))return null;let G=Q.id,J=typeof G==="string"&&YQ(G)?G:null,z=Q.reset_type??Q.resetType,j=typeof z==="string"&&/^[a-z][a-z0-9_-]{0,63}$/i.test(z)?z:null,K="expires_at"in Q||"expiresAt"in Q,X="granted_at"in Q||"grantedAt"in Q,Y=B(Q,"expires_at")??B(Q,"expiresAt"),H=B(Q,"granted_at")??B(Q,"grantedAt"),V=iQ(Y),C=iQ(H),x=B(Q,"status"),q=x&&/^[a-z][a-z0-9_-]{0,63}$/i.test(x)?x:null,D=C?H:null,A=V?Y:null;if("id"in Q&&!J||X&&!C||K&&!V||!q&&!D&&!A)return null;return{id:J,resetType:j,index:Z,status:q,grantedAt:D,expiresAt:A,expirationDate:V?RQ(V):null,expiresIn:V?L(V.getTime()-$.getTime()):null}}function iQ(Q){if(!Q||Q.length>E0)return null;let Z=w0.exec(Q);if(!Z)return null;let $=Number(Z[1]),G=Number(Z[2]),J=Number(Z[3]),z=Number(Z[4]),j=Number(Z[5]),K=Number(Z[6]),X=Z[8]===void 0?0:Number(Z[8]),Y=Z[9]===void 0?0:Number(Z[9]);if(G<1||G>12||J<1||J>m0($,G)||z>23||j>59||K>59||X>23||Y>59)return null;let H=new Date(Q);return Number.isNaN(H.getTime())?null:H}function m0(Q,Z){if(Z===2)return Q%4===0&&(Q%100!==0||Q%400===0)?29:28;return Z===4||Z===6||Z===9||Z===11?30:31}function h0(Q,Z){return nQ(Q.expiresAt)-nQ(Z.expiresAt)}function nQ(Q){return F(Q)?.getTime()??Number.POSITIVE_INFINITY}function p0(Q,Z){let $=!1;for(let G of Z){if(!(G in Q))continue;$=!0;let J=Q[G];if(Array.isArray(J))return{value:J,malformed:!1}}return{value:[],malformed:$}}function sQ(Q,Z){let $=!1;for(let G of Z){if(!(G in Q))continue;$=!0;let J=Q[G];if(typeof J==="number"&&Number.isSafeInteger(J)&&J>=0)return{value:J,malformed:!1}}return{value:null,malformed:$}}var MQ="https://chatgpt.com/backend-api/wham/rate-limit-reset-credits",S2=`${MQ}/consume`,c0=1e4,u0=1e6;async function $Z(Q={}){let Z=Q.endpoint??MQ,$=E(Z),G=await l(Q);if(!G.credentials){let z=k(G.diagnostics);return l0($,z.length>0?z:["Live reset coupons require a readable Codex auth.json file or CODEX_LIMITS_ACCESS_TOKEN and CODEX_LIMITS_ACCOUNT_ID."])}let J=d0(Z,G.credentials,Q);try{let z=await(Q.transport??d)(J);return z.ok?QZ(z.payload,$,Q.now??new Date):ZZ($,z)}catch{return ZZ($,{ok:!1,code:"network-error",status:null})}}function l0(Q=MQ,Z=[]){return w(E(Q),Z)}function ZZ(Q,Z){return w(Q,k([o(Z,"Live reset coupon")]))}function d0(Q,Z,$){return{endpoint:Q,headers:r0(Z),timeoutMs:$.timeoutMs??c0,maxResponseBytes:u0,...$.fetch?{fetch:$.fetch}:{},...$.signal?{signal:$.signal}:{}}}function r0(Q){return{Authorization:`Bearer ${Q.accessToken}`,"ChatGPT-Account-ID":Q.accountId,"OpenAI-Beta":"codex-1",originator:"Codex Desktop",Accept:"application/json"}}var KZ=5,NQ="5-hour usage limit",BQ="Weekly usage limit",OQ=["fiveHour","five_hour","fiveHourWindow","five_hour_window","primary","primaryWindow","primary_window","main","mainWindow"],CQ=["weekly","week","weeklyWindow","weekly_window","secondary","secondaryWindow","secondary_window","backup","backupWindow"],o0=["used_percent","usedPercent","used","usage","percentUsed","usagePercent","usagePercentage","percent"],i0=["remaining_percent","remainingPercent","remaining","percentRemaining","availablePercent","available_percentage"],n0=["resets_at","resetsAt","resetAt","resetTime","reset_at","reset","ends_at","endsAt","windowEnd"],s0=["resetsIn","resetIn","resets_in","reset_in","timeUntilReset"],a0=["limit_window_seconds","limitWindowSeconds","window_seconds","windowSeconds","window_length_seconds","windowLengthSeconds"],t0=["window_minutes","windowMinutes","window_length_minutes","windowLengthMinutes"],e0=18000,Q1=604800,Z1=/^(?:(\d+)d)?(?:\s*(\d+)h)?(?:\s*(\d+)m)?(?:\s*(\d+)s)?$/i;function XZ(Q,Z=new Date){let $=Q.latestSnapshot;if(!$)return FQ(Q.warnings);return s(xQ($.rateLimits,Z),Q.warnings)}function xQ(Q,Z=new Date){return MZ(i(Q,OQ),i(Q,CQ),Z)}function YZ(Q){return i(Q,OQ)!==null||i(Q,CQ)!==null}function v(Q){let Z=jZ(I(Q,a0,!1)),$=jZ(I(Q,t0,!1)),G=Z??($===null?null:$*60);if(G===e0)return"fiveHour";if(G===Q1)return"weekly";return null}function HZ(Q,Z){return{...Q,source:Z}}function TQ(Q,Z,$=[]){return{...s(Q,$),source:Z}}function WZ(Q,Z=new Date){let $={fiveHour:null,weekly:null};for(let G of Q.files){if(!G.json)continue;let J=$1(G.json,Z);$=UZ($,J.windows)}return s($,Q.warnings)}function FQ(Q=[]){return{status:"unavailable",windows:{fiveHour:null,weekly:null},warnings:Q}}function VZ(Q,Z){let $=UZ(Q.windows,Z.windows);return s($,[...Q.warnings,...Z.warnings])}function $1(Q,Z){if(!W(Q))return{windows:{fiveHour:null,weekly:null}};let $=qQ(Q,OQ),G=qQ(Q,CQ);if($||G)return{windows:MZ($,G,Z)};let J=v(Q)??"fiveHour",z=UQ(Q,J==="weekly"?BQ:NQ,Z);return{windows:{fiveHour:J==="fiveHour"?z:null,weekly:J==="weekly"?z:null}}}function MZ(Q,Z,$){let G=[];if(Q)G.push({fallbackKind:"fiveHour",value:Q});if(Z)G.push({fallbackKind:"weekly",value:Z});return{fiveHour:UQ(GZ(G,"fiveHour"),NQ,$),weekly:UQ(GZ(G,"weekly"),BQ,$)}}function UQ(Q,Z,$){if(!Q)return null;let G=zZ(I(Q,o0,!0)),J=zZ(I(Q,i0,!0)),z=G??(J===null?null:n(100-J)),j=J??(G===null?null:n(100-G)),K=I(Q,n0,!0),X=F(K),Y=X?X.toISOString():null,H=X?L(X.getTime()-$.getTime()):z1(I(Q,s0,!0)),V={label:Z,remainingPercent:j,usedPercent:z,resetsAt:Y,resetsIn:H};return qZ(V)?V:null}function s(Q,Z){return{status:G1(Q),windows:Q,warnings:Z}}function G1(Q){let Z=[Q.fiveHour,Q.weekly].filter(($)=>qZ($));if(Z.length===0)return"unavailable";return Z.every(J1)?"available":"partial"}function GZ(Q,Z){let $=Q.find((G)=>v(G.value)===Z);if($)return $.value;return Q.find((G)=>G.fallbackKind===Z&&v(G.value)===null)?.value??null}function UZ(Q,Z){return{fiveHour:JZ(Q.fiveHour,Z.fiveHour,NQ),weekly:JZ(Q.weekly,Z.weekly,BQ)}}function JZ(Q,Z,$){if(!Q&&!Z)return null;return{label:$,remainingPercent:Q?.remainingPercent??Z?.remainingPercent??null,usedPercent:Q?.usedPercent??Z?.usedPercent??null,resetsAt:Q?.resetsAt??Z?.resetsAt??null,resetsIn:Q?.resetsIn??Z?.resetsIn??null}}function qZ(Q){return Q!==null&&(Q.remainingPercent!==null||Q.usedPercent!==null||Q.resetsAt!==null||Q.resetsIn!==null)}function J1(Q){return Q!==null&&Q.remainingPercent!==null&&Q.usedPercent!==null&&(Q.resetsAt!==null||Q.resetsIn!==null)}function qQ(Q,Z,$=0){if($>KZ)return null;for(let G of Z){let J=Q[G];if(W(J))return J}for(let G of Object.values(Q)){if(!W(G))continue;let J=qQ(G,Z,$+1);if(J)return J}return null}function i(Q,Z){for(let $ of Z){let G=Q[$];if(W(G))return G}return null}function I(Q,Z,$,G=0){if(G>KZ)return;for(let J of Z)if(J in Q)return Q[J];if(!$)return;for(let J of Object.values(Q)){if(!W(J))continue;let z=I(J,Z,$,G+1);if(z!==void 0)return z}return}function zZ(Q){if(typeof Q==="number"&&Number.isFinite(Q))return n(Q);if(typeof Q==="string"&&Q.trim().length>0){let Z=Q.trim(),$=Z.endsWith("%")?Z.slice(0,-1):Z,G=Number($);return Number.isFinite(G)?n(G):null}return null}function n(Q){return Math.round(Math.min(Math.max(Q,0),100)*10)/10}function jZ(Q){if(typeof Q==="number"&&Number.isFinite(Q))return Q;if(typeof Q==="string"&&Q.trim().length>0){let Z=Number(Q);return Number.isFinite(Z)?Z:null}return null}function z1(Q){let Z=j1(Q);if(!Z||Z.length>100)return null;let G=Z1.exec(Z)?.slice(1);if(!G||G.every((j)=>j===void 0))return null;let J=[86400,3600,60,1],z=0;for(let[j,K]of G.entries()){if(K===void 0)continue;let X=Number(K),Y=X*J[j];if(!Number.isSafeInteger(X)||!Number.isSafeInteger(Y))return null;if(z+=Y,!Number.isSafeInteger(z))return null}return z<=Math.floor(Number.MAX_SAFE_INTEGER/1000)?L(z*1000):null}function j1(Q){if(typeof Q==="string"&&Q.trim().length>0)return Q.trim();return null}var K1=5,X1=1000,Y1={kind:"unavailable",label:"Unavailable"};function BZ(Q,Z,$){let G=H1(Q)??W1(Q);if(!G)return g(["Live usage endpoint returned an unexpected payload."]);let J=TQ(xQ(G,$),{kind:"api",label:"API",endpoint:Z});if(J.status==="unavailable")return g(["Live usage endpoint returned an unexpected payload."]);if(J.status==="partial")return{...J,warnings:["Live usage endpoint returned incomplete usage data."]};return J}function g(Q){return TQ({fiveHour:null,weekly:null},Y1,Q)}function H1(Q){return OZ(Q,(Z)=>{if(!W(Z))return null;let $=Z.rate_limits??Z.rateLimits??Z.rate_limit??Z.rateLimit;if(W($))return $;return YZ(Z)?Z:null})}function W1(Q){return OZ(Q,(Z)=>{if(!Array.isArray(Z))return null;let $=Z.find((J)=>NZ(J,"fiveHour")),G=Z.find((J)=>NZ(J,"weekly"));return $||G?{fiveHour:$,weekly:G}:null})}function OZ(Q,Z){let $=[{value:Q,depth:0}],G=new WeakSet;for(let J=0;J<$.length;J+=1){let z=$[J];if(!z)break;let j=Z(z.value);if(j)return j;if(z.depth>=K1||typeof z.value!=="object"||!z.value)continue;if(G.has(z.value))continue;G.add(z.value);let K=Array.isArray(z.value)?z.value:W(z.value)?Object.values(z.value):[];for(let X of K){if($.length>=X1)break;$.push({value:X,depth:z.depth+1})}}return null}function NZ(Q,Z){if(!W(Q))return!1;let $=v(Q);if($)return $===Z;let G=String(Q.type??Q.kind??Q.name??Q.label??Q.window??"").toLowerCase();return Z==="fiveHour"?G.includes("primary")||G.includes("5-hour")||G.includes("five"):G.includes("secondary")||G.includes("weekly")||G.includes("week")}var V1="https://chatgpt.com/backend-api/codex/usage",M1=1e4,U1=1e6;async function CZ(Q={}){return(await q1(Q)).usage}async function q1(Q={}){let Z=B1(Q),$=E(Z),G=await l(Q);if(!G.credentials){let j=k(G.diagnostics);return{usage:g(j.length>0?j:["Live usage requires Codex authentication."]),authenticationFound:!1,endpointStatus:"not-checked"}}let J={endpoint:Z,headers:N1(G.credentials),timeoutMs:Q.timeoutMs??M1,maxResponseBytes:U1,fallbackOnHttpError:!0,...Q.fetch?{fetch:Q.fetch}:{},...Q.signal?{signal:Q.signal}:{}},z;try{z=await(Q.transport??d)(J)}catch{z={ok:!1,code:"network-error",status:null}}return{usage:z.ok?BZ(z.payload,$,Q.now??new Date):C1(z),authenticationFound:!0,endpointStatus:O1(z)}}function N1(Q){return{Authorization:`Bearer ${Q.accessToken}`,"ChatGPT-Account-ID":Q.accountId,"OpenAI-Beta":"codex-1",originator:"Codex Desktop",Accept:"application/json","User-Agent":"Codex Desktop",Referer:"https://chatgpt.com/codex/cloud/settings/analytics",Origin:"https://chatgpt.com"}}function B1(Q){let Z=b(Q.env);return Q.usageEndpoint??N(Z,"CODEX_LIMITS_USAGE_ENDPOINT")??V1}function O1(Q){if(Q.ok)return"reachable";switch(Q.code){case"http-error":case"invalid-json":case"response-too-large":return"reachable";case"aborted":return"not-checked";case"invalid-url":case"network-error":case"timeout":case"unsupported-protocol":return"unreachable"}}function C1(Q){return g(k([o(Q,"Live usage")]))}var x1={kind:"local",label:"Local"};async function xZ(Q={}){let Z=Q.includeCoupons===!1?Promise.resolve(null):$Z(Q),[$,G]=await Promise.all([T1(Q),Z]),J=G?F1(G):null;return{windows:$.windows,coupons:J,warnings:t([...$.warnings,...J?.warnings??[]])}}async function T1(Q={}){let Z=await CZ(Q);if(Z.status!=="unavailable")return Z;let $=HZ(await D1(Q),x1);return $.status!=="unavailable"?$:{...$,warnings:[...Z.warnings,...$.warnings]}}function F1(Q){return{status:Q.status,available:Q.available,earnedThisPeriod:Q.earnedThisPeriod,nextExpirationDate:Q.nextExpirationDate,nextExpirationIn:Q.nextExpirationIn,items:Q.items.map((Z)=>({index:Z.index,status:Z.status,grantedAt:Z.grantedAt,expiresAt:Z.expiresAt,expirationDate:Z.expirationDate,expiresIn:Z.expiresIn})),warnings:t(Q.warnings)}}async function D1(Q={}){let Z=Q.now??new Date,$=await m(Q);if(!$.foundHome)return FQ(["No readable local Codex home directory was found."]);let[G,J]=await Promise.all([wQ($.foundHome),cQ($.foundHome)]);return VZ(XZ(G,Z),WZ(J,Z))}var b1="Codex Limits",FZ="Could not load Codex limits.",I1="Could not display Codex limits.";function P1(Q={}){let Z=Q.getLimits??xZ;return($)=>{$.registerCommand("codex-limits",{description:"Check Codex limits, resets, and credits",handler:async(G,J)=>{if(!J.hasUI||J.mode!=="tui")return;J.ui.setStatus("codex-limits","Loading Codex limits...");let z;try{z=LQ(await Z())}catch{z=FZ,J.ui.notify(FZ,"error")}finally{J.ui.setStatus("codex-limits",void 0)}try{await k1(z,J)}catch{J.ui.notify(I1,"error")}}})}}async function k1(Q,Z){await Z.ui.custom(($,G,J,z)=>{let j=DZ(Q,G);return{render:(K)=>j.render(K),invalidate:()=>{j=DZ(Q,G)},handleInput:(K)=>{if(DQ(K,"enter")||DQ(K,"escape")||DQ(K,"ctrl+c"))z(void 0)}}},{overlay:!0,overlayOptions:{width:56,minWidth:36,maxHeight:"90%",margin:1}})}function DZ(Q,Z){let $=new A1;return $.addChild(new TZ((G)=>Z.fg("accent",G))),$.addChild(new AQ(Z.fg("accent",Z.bold(b1)),1,0)),$.addChild(new AQ(Q,1,1)),$.addChild(new AQ(Z.fg("dim","Press Enter or Esc to close"),1,0)),$.addChild(new TZ((G)=>Z.fg("accent",G))),$}var L1=P1(),AZ=L1;function bZ(Q){return Q}var _1=bZ(AZ),V3=_1;export{V3 as default};