@simonesiega/codex-limits 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
- import{createRequire as OZ}from"node:module";var XZ=Object.create;var{getPrototypeOf:WZ,defineProperty:l,getOwnPropertyNames:VZ}=Object;var qZ=Object.prototype.hasOwnProperty;function MZ(Q){return this[Q]}var NZ,UZ,K1=(Q,Z,$)=>{var G=Q!=null&&typeof Q==="object";if(G){var J=Z?NZ??=new WeakMap:UZ??=new WeakMap,K=J.get(Q);if(K)return K}$=Q!=null?XZ(WZ(Q)):{};let z=Z||!Q||!Q.__esModule?l($,"default",{value:Q,enumerable:!0}):$;for(let j of VZ(Q))if(!qZ.call(z,j))l(z,j,{get:MZ.bind(Q,j),enumerable:!0});if(G)J.set(Q,z);return z};var z1=(Q,Z)=>()=>(Z||Q((Z={exports:{}}).exports,Z),Z.exports);var BZ=(Q)=>Q;function xZ(Q,Z){this[Q]=BZ.bind(null,Z)}var j1=(Q,Z)=>{for(var $ in Z)l(Q,$,{get:Z[$],enumerable:!0,configurable:!0,set:xZ.bind(Z,$)})};var CZ=(Q,Z)=>()=>(Q&&(Z=Q(Q=0)),Z);var H1=(Q)=>Promise.all(Q),X1=OZ(import.meta.url);function c(Q,Z={}){let $=Z.includeSeconds??!1,G=Math.max(Math.floor(Q/1000),0),J=Math.floor(G/86400);G%=86400;let K=Math.floor(G/3600);G%=3600;let z=Math.floor(G/60),j=G%60,H=[];if(J>0)H.push(`${J}d`);if(K>0)H.push(`${K}h`);if(z>0)H.push(`${z}m`);if($&&j>0)H.push(`${j}s`);return H.length>0?H.join(" "):$?`${j}s`:"0m"}function I(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 I($);let G=new Date(Z);return Number.isNaN(G.getTime())?null:G}return null}function RQ(Q){return`${F0[Q.getDay()]} ${Q.getDate()} ${I0[Q.getMonth()]} ${Q.getFullYear()}`}function a1(Q){return`${Q.getDate()} ${A0[Q.getMonth()]} ${Q.getFullYear()} ${k0(Q)}`}function k0(Q){return`${PQ(Q.getHours())}:${PQ(Q.getMinutes())}`}function e1(Q,Z){return Q.getFullYear()===Z.getFullYear()&&Q.getMonth()===Z.getMonth()&&Q.getDate()===Z.getDate()}function PQ(Q){return String(Q).padStart(2,"0")}var F0,I0,A0;var $Q=CZ(()=>{F0=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],I0=["January","February","March","April","May","June","July","August","September","October","November","December"],A0=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function qQ(Q){let Z=Q.warnings.length>0?["","Warnings",...Q.warnings.map(($)=>`- ${$}`)]:[];return[...VQ("5-hour",Q.windows.fiveHour),"",...VQ("Weekly",Q.windows.weekly),"",...TZ(Q),...Z].join(`
2
- `)}function VQ(Q,Z){let $=Z?.remainingPercent??null;return[`${Q} ${FZ($)}`,`Remaining ${$===null?"Unknown":`${Math.round($)}% remaining`}`,DZ($),`Reset ${Z?.resetsIn?`in ${Z.resetsIn}`:"unknown"}`]}function DZ(Q){let Z=Q===null?0:Math.min(Math.max(Q,0),100),$=Math.round(Z/100*22);return`[${"=".repeat($)}${" ".repeat(22-$)}] ${Math.round(Z)}%`}function TZ(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,K=Q.coupons?.nextExpirationDate,z=J&&K?`${J} (${K})`:J??K;if(z!==null&&z!==void 0)G.push(`Next expires ${z}`);return G}function FZ(Q){if(Q===null)return"Unknown";if(Q>=50)return"Healthy";if(Q>=15)return"Low";return"Critical"}import{constants as IZ}from"node:fs";import{access as AZ,stat as kZ}from"node:fs/promises";import{homedir as bZ}from"node:os";import{join as A,normalize as r}from"node:path";function M(Q,Z){let $=Q[Z]?.trim();return $?$:null}function T(Q){return Q??process.env}var MQ="CODEX_LIMITS_HOME";function LZ(Q={}){let Z=T(Q.env),$=Q.homeDirectory??M(Z,"HOME")??M(Z,"USERPROFILE")??bZ(),G=Q.appData??M(Z,"APPDATA"),J=Q.localAppData??M(Z,"LOCALAPPDATA"),K=[];if(D(K,M(Z,MQ),"env"),D(K,M(Z,"CODEX_HOME"),"env"),$)D(K,A($,".codex"),"default"),D(K,A($,".config","codex"),"default"),D(K,A($,"Library","Application Support","Codex"),"default"),D(K,A($,"Library","Application Support","Parall","Codex",".codex"),"default");return D(K,G?A(G,"Codex"):null,"default"),D(K,J?A(J,"Codex"):null,"default"),PZ(K)}async function S(Q={}){let Z=T(Q.env),$=M(Z,MQ),G=await Promise.all(LZ(Q).map(async(J)=>({...J,exists:await _Z(J.path)})));return{overrideHome:$?r($):null,candidates:G,foundHome:G.find((J)=>J.exists)?.path??null}}function D(Q,Z,$){if(Z)Q.push({path:r(Z),source:$})}async function _Z(Q){try{if(!(await kZ(Q)).isDirectory())return!1;return await AZ(Q,IZ.R_OK),!0}catch{return!1}}function PZ(Q){let Z=new Set,$=[];for(let G of Q){let J=r(G.path),K=process.platform==="win32"?J.toLowerCase():J;if(!Z.has(K))Z.add(K),$.push({path:J,source:G.source})}return $}import{createReadStream as EZ}from"node:fs";import{lstat as wZ,opendir as gZ,realpath as OQ,stat as vZ}from"node:fs/promises";import{join as DQ}from"node:path";import{isAbsolute as yZ,relative as UQ,resolve as NQ,sep as fZ}from"node:path";var RZ=[/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/["']?(?:access_token|refresh_token|api_key|account_id|authorization|chatgpt-account-id|cookie)["']?\s*[:=]\s*["']?[^"',\s}\]]+["']?/gi,/(?:access_token|refresh_token|api_key|account_id)=([^&\s]+)/gi,/sk-[A-Za-z0-9_-]{10,}/g];function F(Q){let Z=Q;for(let $ of RZ)Z=Z.replace($,"[redacted]");return Z}function o(Q){return Q.map(F)}function BQ(Q,Z){let $=UQ(NQ(Q),NQ(Z));return $===""||!xQ($)}function x(Q,Z){let $=UQ(Q,Z);return $&&!xQ($)?SZ($):"."}function SZ(Q){let Z=F(Q).replace(/[\u0000-\u001f\u007f]/g,"?").replace(/\b[0-9a-f]{8}-[0-9a-f-]{27,}\b/gi,"[id]").replace(/[A-Za-z0-9_-]{32,}/g,"[id]");return Z.length<=240?Z:`${Z.slice(0,239)}…`}function xQ(Q){return Q===".."||Q.startsWith(`..${fZ}`)||yZ(Q)}function Y(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function U(Q,Z){let $=Q[Z];return typeof $==="string"&&$.trim()?$.trim():null}var mZ=8,i=20,E=1000,hZ=512,cZ=1000,TQ=25000000,pZ=1e6,uZ=/^rollout-.*\.jsonl$/i;async function FQ(Q){let Z=DQ(Q,"sessions"),$=[];if(await tZ(Z))return $.push("Skipped the symbolic-link Codex sessions directory."),{homePath:Q,sessionsRoot:Z,files:[],latestSnapshot:null,warnings:$};let G=await dZ(Q,Z,$),J=[],K=null;for(let z of G.slice(0,i)){let j=x(Q,z.path);if(z.size>TQ){$.push(`Skipped ${j} because it is too large to inspect safely.`),J.push(n(z.path,j,z.modifiedAtMs,!1,"too-large"));continue}try{let H=await oZ(Q,z.path);if(J.push(n(z.path,j,z.modifiedAtMs,H.snapshot!==null,null)),H.skippedOversizedLine)$.push(`Skipped an oversized JSONL line in ${j}.`);if(H.snapshot&&!K)K=H.snapshot}catch(H){let X=H instanceof s;$.push(X?`Skipped ${j} because it grew too large to inspect safely.`:`Could not inspect ${j}.`),J.push(n(z.path,j,z.modifiedAtMs,!1,X?"too-large":"read-error"))}if(K)break}if(G.length>i)$.push(`Skipped ${G.length-i} older session files to keep inspection small.`);if(G.length>0&&!K)$.push("No token-count rate-limit snapshot was found in local Codex session logs.");return{homePath:Q,sessionsRoot:Z,files:J,latestSnapshot:K,warnings:$}}async function dZ(Q,Z,$){let G={directories:0,files:[],hitLimit:!1,skippedSymlink:!1};if(await IQ(Z,0,G,$,Q),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;try{J=await OQ(Z)}catch{return[]}let K=[];for(let z of G.files){let j=await lZ(Q,J,z,$);if(j)K.push(j)}return K.sort((z,j)=>j.modifiedAtMs-z.modifiedAtMs||z.path.localeCompare(j.path))}async function lZ(Q,Z,$,G){try{let[J,K]=await Promise.all([vZ($),OQ($)]);if(!J.isFile()||!BQ(Z,K))return G.push(`Could not inspect ${x(Q,$)}.`),null;return{path:$,modifiedAtMs:J.mtimeMs,size:J.size}}catch{return G.push(`Could not inspect ${x(Q,$)}.`),null}}async function IQ(Q,Z,$,G,J){if(Z>mZ||$.files.length>=E){$.hitLimit||=$.files.length>=E;return}if($.directories>=hZ){$.hitLimit=!0;return}$.directories+=1;let K;try{K=await rZ(Q,$)}catch{if(Z>0)G.push(`Could not inspect ${x(J,Q)}.`);return}for(let z of K){if($.files.length>=E){$.hitLimit=!0;return}let j=DQ(Q,z.name);if(z.isSymbolicLink()){$.skippedSymlink=!0;continue}if(z.isDirectory()){await IQ(j,Z+1,$,G,J);continue}if(z.isFile()&&uZ.test(z.name)){if($.files.push(j),$.files.length>=E){$.hitLimit=!0;return}}}}async function rZ(Q,Z){let $=await gZ(Q),G=[];for await(let J of $){if(G.length>=cZ){Z.hitLimit=!0;break}G.push(J)}return G.sort((J,K)=>K.name.localeCompare(J.name))}async function oZ(Q,Z){let $=x(Q,Z),G=EZ(Z,{encoding:"utf8",highWaterMark:65536}),J=null,K=null,z="",j=0,H=0,X=!1,V=!1;for await(let q of G){let C=String(q);if(H+=Buffer.byteLength(C,"utf8"),H>TQ)throw new s;let y=0;while(y<C.length){let f=C.indexOf(`
3
- `,y),YZ=f===-1?C.length:f,WQ=C.slice(y,YZ);if(!X){let O=Buffer.byteLength(WQ,"utf8");if(j+O>pZ)z="",j=0,X=!0,V=!0;else z+=WQ,j+=O}if(f===-1)break;if(!X){let O=CQ(z.endsWith("\r")?z.slice(0,-1):z);if(O.threadId)J=O.threadId;if(O.rateLimits)K={sessionFile:Z,relativePath:$,threadId:J,eventTimestamp:O.timestamp,rateLimits:O.rateLimits}}z="",j=0,X=!1,y=f+1}}if(!X&&z.length>0){let q=CQ(z.endsWith("\r")?z.slice(0,-1):z);if(q.threadId)J=q.threadId;if(q.rateLimits)K={sessionFile:Z,relativePath:$,threadId:J,eventTimestamp:q.timestamp,rateLimits:q.rateLimits}}return{snapshot:K,skippedOversizedLine:V}}function CQ(Q){let Z=iZ(Q);if(!Z)return{threadId:null,timestamp:null,rateLimits:null};return{threadId:nZ(Z),timestamp:U(Z,"timestamp"),rateLimits:sZ(Z)}}function iZ(Q){let Z=Q.trim();if(!Z)return null;try{let $=JSON.parse(Z);return Y($)?$:null}catch{return null}}function nZ(Q){if(Q.type!=="session_meta"||!Y(Q.payload))return null;return U(Q.payload,"id")}function sZ(Q){if(Q.type!=="event_msg"||!Y(Q.payload))return null;if(Q.payload.type!=="token_count"||!Y(Q.payload.rate_limits))return null;return Q.payload.rate_limits}function n(Q,Z,$,G,J){return{path:Q,relativePath:Z,modifiedAtMs:$,hasSnapshot:G,error:J}}async function tZ(Q){try{return(await wZ(Q)).isSymbolicLink()}catch{return!1}}class s extends Error{}import{opendir as Q0}from"node:fs/promises";import{extname as Z0,join as $0}from"node:path";import{open as aZ}from"node:fs/promises";class B extends Error{code;constructor(Q){super(Q);this.name="BoundedFileError",this.code=Q}}async function w(Q,Z){let $;try{$=await aZ(Q,"r");let G=await $.stat();if(!G.isFile())throw new B("not-file");if(G.size>Z)throw new B("too-large");let J=Buffer.allocUnsafe(Z+1),K=0;while(K<=Z){let z=await $.read(J,K,Z+1-K,null);if(z.bytesRead===0)break;K+=z.bytesRead}if(K>Z)throw new B("too-large");return J.subarray(0,K).toString("utf8")}catch(G){if(G instanceof B)throw G;if(eZ(G)&&G.code==="ENOENT")throw new B("not-found");throw new B("read-error")}finally{await $?.close().catch(()=>{return})}}function eZ(Q){return Q instanceof Error&&"code"in Q}var G0=2,t=25,a=100,J0=64,K0=500,z0=1e6,j0=/(?:auth|token|cookie|session|secret|credential|api[-_]?key|keychain)/i;async function AQ(Q){let Z={directories:0,files:[],hitDirectoryLimit:!1,hitEntryLimit:!1,hitFileLimit:!1,skippedSensitive:!1,skippedSymlink:!1,warnings:[]};if(await kQ(Q,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 $=Z.files.sort((J,K)=>J.localeCompare(K)),G=[];for(let J of $.slice(0,t)){let K=x(Q,J);try{let z=await w(J,z0),j=Y0(z,K,Z.warnings);G.push({path:J,relativePath:K,json:j.value,error:j.error})}catch(z){Z.warnings.push(z instanceof B&&z.code==="too-large"?`Skipped ${K} because it is too large to inspect safely.`:`Could not read ${K}.`)}}if($.length>t)Z.warnings.push(`Skipped ${$.length-t} extra files to keep inspection small.`);return{homePath:Q,files:G,warnings:Z.warnings}}async function kQ(Q,Z,$,G){if($>G0||G.files.length>=a){G.hitFileLimit||=G.files.length>=a;return}if(G.directories>=J0){G.hitDirectoryLimit=!0;return}G.directories+=1;let J=await H0(Q,Z,G);for(let K of J){if(G.files.length>=a){G.hitFileLimit=!0;return}if(j0.test(K.name)){G.skippedSensitive=!0;continue}let z=$0(Z,K.name);if(K.isSymbolicLink())G.skippedSymlink=!0;else if(K.isDirectory())await kQ(Q,z,$+1,G);else if(K.isFile()&&Z0(K.name).toLowerCase()===".json")G.files.push(z)}}async function H0(Q,Z,$){try{let G=await Q0(Z),J=[];for await(let K of G){if(J.length>=K0){$.hitEntryLimit=!0;break}J.push(K)}return J.sort((K,z)=>K.name.localeCompare(z.name))}catch{return $.warnings.push(`Could not inspect ${x(Q,Z)}.`),[]}}function Y0(Q,Z,$){try{return{value:JSON.parse(Q),error:null}}catch{return $.push(`Could not parse JSON in ${Z}.`),{value:null,error:"invalid-json"}}}import{join as X0,normalize as W0}from"node:path";function N(Q,Z,$){return{code:Q,source:Z,severity:"warning",message:$}}function k(Q){return Q.map((Z)=>F(Z.message))}var V0=1e6;async function g(Q={}){let Z=T(Q.env),$=M(Z,"CODEX_LIMITS_ACCESS_TOKEN"),G=M(Z,"CODEX_LIMITS_ACCOUNT_ID");if($&&G)return{credentials:{accessToken:$,accountId:G},status:"configured",diagnostics:[]};if($||G)return{credentials:null,status:"partial",diagnostics:[N("auth.environment.partial","authentication","Codex authentication environment variables are incomplete.")]};let J=await q0(Q);return J?M0(J):{credentials:null,status:"missing",diagnostics:[]}}async function q0(Q){if(Q.authFile)return W0(Q.authFile);let Z=await S(Q);return Z.foundHome?X0(Z.foundHome,"auth.json"):null}async function M0(Q){let Z;try{Z=await w(Q,V0)}catch($){if($ instanceof B&&$.code==="not-found")return{credentials:null,status:"missing",diagnostics:[]};let G=$ instanceof B&&$.code==="too-large";return{credentials:null,status:"unreadable",diagnostics:[N(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(!Y($))return e();let G=Y($.tokens)?$.tokens:$,J=U(G,"access_token"),K=U(G,"account_id");return J&&K?{credentials:{accessToken:J,accountId:K},status:"configured",diagnostics:[]}:e()}catch{return e()}}function e(){return{credentials:null,status:"malformed",diagnostics:[N("auth.file.malformed","authentication","Codex auth.json is malformed or does not contain required credentials.")]}}import{request as N0}from"node:http";import{request as U0}from"node:https";var B0=new Set(["127.0.0.1","::1","[::1]","localhost"]);function L(Q){try{let Z=new URL(Q);return Z.username="",Z.password="",Z.search="",Z.hash="",Z.href}catch{return"[invalid endpoint]"}}async function v(Q){let Z=x0(Q.endpoint);if(!Z.ok)return Z;if(Q.signal?.aborted)return W("aborted");let $=Q.fetch??globalThis.fetch;if(!$)return bQ(Z.url,Q);let G=await C0(Z.url,Q,$);if(G.ok||G.code==="aborted"||!T0(G,Q.fallbackOnHttpError??!1))return G;let J=await bQ(Z.url,Q);if(J.ok||J.code==="http-error"||J.code==="invalid-json"||J.code==="response-too-large")return J;return G}function x0(Q){let Z;try{Z=new URL(Q)}catch{return W("invalid-url")}if(Z.username||Z.password)return W("invalid-url");if(Z.protocol==="https:")return{ok:!0,url:Z};if(Z.protocol==="http:"&&B0.has(Z.hostname.toLowerCase()))return{ok:!0,url:Z};return W("unsupported-protocol")}async function C0(Q,Z,$){let G=_Q(Z.timeoutMs,Z.signal);try{let J=await $(Q.href,{method:"GET",headers:Z.headers,redirect:"error",signal:G.signal});if(!J.ok)return await LQ(J),W("http-error",ZQ(J.status));let K=await O0(J,Z.maxResponseBytes);return{ok:!0,status:ZQ(J.status)??200,payload:K,transport:"fetch"}}catch(J){if(J instanceof b)return W("response-too-large");if(J instanceof m)return W("invalid-json");if(Z.signal?.aborted)return W("aborted");if(G.didTimeout())return W("timeout");return W("network-error")}finally{G.dispose()}}async function O0(Q,Z){let $=Number(Q.headers?.get("content-length"));if(Number.isFinite($)&&$>Z)throw await LQ(Q),new b;if(Q.body){let G=Q.body.getReader(),J=[],K=0;while(!0){let j=await G.read();if(j.done)break;if(!j.value)continue;if(K+=j.value.byteLength,K>Z)throw await G.cancel?.(),new b;J.push(j.value)}let z=Buffer.concat(J.map((j)=>Buffer.from(j)),K).toString("utf8");return QQ(z)}if(Q.text){let G=await Q.text();if(Buffer.byteLength(G,"utf8")>Z)throw new b;return QQ(G)}throw new m}async function LQ(Q){if(!Q.body)return;try{await Q.body.getReader().cancel?.()}catch{}}function bQ(Q,Z){return new Promise(($)=>{let G=_Q(Z.timeoutMs,Z.signal),J=!1,K=null,z=(H)=>{if(J)return;J=!0,G.dispose(),$(H)},j=()=>{K?.destroy(),z(W(Z.signal?.aborted?"aborted":"timeout"))};G.signal.addEventListener("abort",j,{once:!0});try{K=(Q.protocol==="http:"?N0:U0)(Q,{method:"GET",headers:Z.headers,signal:G.signal},(X)=>D0(X,Z.maxResponseBytes,z)),K.on("error",()=>{if(Z.signal?.aborted)z(W("aborted"));else if(G.didTimeout())z(W("timeout"));else z(W("network-error"))}),K.end()}catch{z(W("network-error"))}})}function D0(Q,Z,$){let G=ZQ(Q.statusCode);if(G===null||G<200||G>=300){Q.resume(),$(W("http-error",G));return}let J=Number(Q.headers["content-length"]);if(Number.isFinite(J)&&J>Z){Q.destroy(),$(W("response-too-large"));return}let K=[],z=0;Q.on("data",(j)=>{let H=Buffer.isBuffer(j)?j:Buffer.from(j);if(z+=H.length,z>Z){Q.destroy(),$(W("response-too-large"));return}K.push(H)}),Q.on("end",()=>{try{let j=QQ(Buffer.concat(K,z).toString("utf8"));$({ok:!0,status:G,payload:j,transport:"node"})}catch{$(W("invalid-json"))}}),Q.on("error",()=>$(W("network-error")))}function _Q(Q,Z){let $=new AbortController,G=!1,J=Number.isFinite(Q)&&Q>0?Math.min(Math.floor(Q),2147483647):1,K=setTimeout(()=>{G=!0,$.abort()},J),z=()=>$.abort();return Z?.addEventListener("abort",z,{once:!0}),{signal:$.signal,didTimeout:()=>G,dispose:()=>{clearTimeout(K),Z?.removeEventListener("abort",z)}}}function T0(Q,Z){return Q.code==="network-error"||Q.code==="timeout"||Q.code==="invalid-json"||Z&&Q.code==="http-error"}function QQ(Q){try{return JSON.parse(Q)}catch{throw new m}}function ZQ(Q){return typeof Q==="number"&&Number.isInteger(Q)&&Q>=0?Q:null}function W(Q,Z=null){return{ok:!1,code:Q,status:Z}}class b extends Error{}class m extends Error{}function h(Q,Z){switch(Q.code){case"aborted":return N("network.request.aborted","network",`${Z} lookup was cancelled.`);case"http-error":return N("network.response.http","network",Q.status===null?`${Z} endpoint returned an invalid HTTP status.`:`${Z} endpoint returned HTTP ${Q.status}.`);case"invalid-json":return N("network.response.invalid-json","network",`${Z} endpoint returned malformed JSON.`);case"invalid-url":return N("network.endpoint.invalid","network",`${Z} endpoint URL is invalid.`);case"response-too-large":return N("network.response.too-large","network",`${Z} endpoint response was too large.`);case"timeout":return N("network.request.timeout","network",`${Z} lookup timed out.`);case"unsupported-protocol":return N("network.endpoint.protocol","network",`${Z} endpoint must use HTTPS or loopback HTTP.`);case"network-error":return N("network.request.failed","network",`${Z} lookup failed.`)}}$Q();var SQ=["credits","reset_credits","items"],EQ=["available_count","availableCount","available"],wQ=["total_earned_count","earned_this_period","earnedThisPeriod","totalEarnedCount"];function gQ(Q,Z,$){if(!Y(Q)||!b0(Q))return _(Z,["Live reset coupon endpoint returned an unexpected payload."]);let G=P0(Q,SQ);if(G.malformed)return _(Z,["Live reset coupon endpoint returned an unexpected payload."]);let J=G.value,K=J.map((V,q)=>L0(V,q+1,$)).filter((V)=>V!==null).sort(_0).map((V,q)=>({...V,index:q+1})),z=K.find((V)=>V.status?.toLowerCase()==="available")??K[0]??null,j=fQ(Q,EQ),H=fQ(Q,wQ),X=[];if(J.length!==K.length)X.push("Live reset coupon endpoint ignored malformed coupon entries.");if(j.malformed||H.malformed)X.push("Live reset coupon endpoint ignored malformed summary fields.");return{status:X.length>0?"partial":"available",available:j.value,earnedThisPeriod:H.value,nextExpirationDate:z?.expirationDate??null,nextExpirationIn:z?.expiresIn??null,items:K,warnings:X,source:{live:!0,label:"live Codex reset-credit endpoint",endpoint:Z}}}function _(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 b0(Q){return[...SQ,...EQ,...wQ].some((Z)=>(Z in Q))}function L0(Q,Z,$){if(!Y(Q))return null;let G=U(Q,"expires_at")??U(Q,"expiresAt"),J=U(Q,"granted_at")??U(Q,"grantedAt"),K=I(G),z=I(J),j=U(Q,"status"),H=j&&/^[a-z][a-z0-9_-]{0,63}$/i.test(j)?j:null,X=z?J:null,V=K?G:null;if(!H&&!X&&!V)return null;return{index:Z,status:H,grantedAt:X,expiresAt:V,expirationDate:K?RQ(K):null,expiresIn:K?c(K.getTime()-$.getTime()):null}}function _0(Q,Z){return yQ(Q.expiresAt)-yQ(Z.expiresAt)}function yQ(Q){return I(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 fQ(Q,Z){let $=!1;for(let G of Z){if(!(G in Q))continue;$=!0;let J=Q[G];if(typeof J==="number"&&Number.isFinite(J)&&J>=0)return{value:J,malformed:!1}}return{value:null,malformed:$}}var mQ="https://chatgpt.com/backend-api/wham/rate-limit-reset-credits",R0=1e4,y0=1e6;async function hQ(Q={}){let Z=Q.endpoint??mQ,$=L(Z),G=await g(Q);if(!G.credentials){let K=k(G.diagnostics);return f0($,K.length>0?K:["Live reset coupons require a readable Codex auth.json file or CODEX_LIMITS_ACCESS_TOKEN and CODEX_LIMITS_ACCOUNT_ID."])}let J={endpoint:Z,headers:{Authorization:`Bearer ${G.credentials.accessToken}`,"ChatGPT-Account-ID":G.credentials.accountId,"OpenAI-Beta":"codex-1",originator:"Codex Desktop",Accept:"application/json"},timeoutMs:Q.timeoutMs??R0,maxResponseBytes:y0,...Q.fetch?{fetch:Q.fetch}:{},...Q.signal?{signal:Q.signal}:{}};try{let K=await(Q.transport??v)(J);return K.ok?gQ(K.payload,$,Q.now??new Date):vQ($,K)}catch{return vQ($,{ok:!1,code:"network-error",status:null})}}function f0(Q=mQ,Z=[]){return _(L(Q),Z)}function vQ(Q,Z){return _(Q,k([h(Z,"Live reset coupon")]))}$Q();var lQ=5,KQ="5-hour usage limit",zQ="Weekly usage limit",rQ=["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"],S0=["used_percent","usedPercent","used","usage","percentUsed","usagePercent","usagePercentage","percent"],E0=["remaining_percent","remainingPercent","remaining","percentRemaining","availablePercent","available_percentage"],w0=["resets_at","resetsAt","resetAt","resetTime","reset_at","reset","ends_at","endsAt","windowEnd"],g0=["resetsIn","resetIn","resets_in","reset_in","timeUntilReset"];function iQ(Q,Z=new Date){let $=Q.latestSnapshot;if(!$)return YQ(Q.warnings);return d(jQ($.rateLimits,Z),Q.warnings)}function jQ(Q,Z=new Date){return{fiveHour:p(uQ(Q,rQ),KQ,Z),weekly:p(uQ(Q,oQ),zQ,Z)}}function nQ(Q,Z){return{...Q,source:Z}}function HQ(Q,Z,$=[]){return{...d(Q,$),source:Z}}function sQ(Q,Z=new Date){let $={fiveHour:null,weekly:null};for(let G of Q.files){if(!G.json)continue;let J=v0(G.json,Z);$=aQ($,J.windows)}return d($,Q.warnings)}function YQ(Q=[]){return{status:"unavailable",windows:{fiveHour:null,weekly:null},warnings:Q}}function tQ(Q,Z){let $=aQ(Q.windows,Z.windows);return d($,[...Q.warnings,...Z.warnings])}function v0(Q,Z){if(!Y(Q))return{windows:{fiveHour:null,weekly:null}};let $=JQ(Q,rQ),G=JQ(Q,oQ),J=p($??(G?null:Q),KQ,Z),K=p(G,zQ,Z);return{windows:{fiveHour:J,weekly:K}}}function p(Q,Z,$){if(!Q)return null;let G=dQ(P(Q,S0,!0)),J=dQ(P(Q,E0,!0)),K=G??(J===null?null:u(100-J)),z=J??(G===null?null:u(100-G)),j=P(Q,w0,!0),H=I(j),X=H?H.toISOString():null,V=h0(P(Q,g0,!0)),q=H?c(H.getTime()-$.getTime()):V&&V.length<=100?F(V):null,C={label:Z,remainingPercent:z,usedPercent:K,resetsAt:X,resetsIn:q};return GQ(C)?C:null}function d(Q,Z){return{status:m0(Q),windows:Q,warnings:Z}}function m0(Q){if(pQ(Q.fiveHour)&&pQ(Q.weekly))return"available";if(GQ(Q.fiveHour)||GQ(Q.weekly))return"partial";return"unavailable"}function aQ(Q,Z){return{fiveHour:cQ(Q.fiveHour,Z.fiveHour,KQ),weekly:cQ(Q.weekly,Z.weekly,zQ)}}function cQ(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 GQ(Q){return Q!==null&&(Q.remainingPercent!==null||Q.usedPercent!==null||Q.resetsAt!==null||Q.resetsIn!==null)}function pQ(Q){return Q!==null&&Q.remainingPercent!==null&&Q.usedPercent!==null&&(Q.resetsAt!==null||Q.resetsIn!==null)}function JQ(Q,Z,$=0){if($>lQ)return null;for(let G of Z){let J=Q[G];if(Y(J))return J}for(let G of Object.values(Q)){if(!Y(G))continue;let J=JQ(G,Z,$+1);if(J)return J}return null}function uQ(Q,Z){for(let $ of Z){let G=Q[$];if(Y(G))return G}return null}function P(Q,Z,$,G=0){if(G>lQ)return;for(let J of Z)if(J in Q)return Q[J];if(!$)return;for(let J of Object.values(Q)){if(!Y(J))continue;let K=P(J,Z,$,G+1);if(K!==void 0)return K}return}function dQ(Q){if(typeof Q==="number"&&Number.isFinite(Q))return u(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)?u(G):null}return null}function u(Q){return Math.round(Math.min(Math.max(Q,0),100)*10)/10}function h0(Q){if(typeof Q==="string"&&Q.trim().length>0)return Q.trim();return null}var c0=5,p0=1000,u0={kind:"unavailable",label:"Unavailable"};function QZ(Q,Z,$){let G=d0(Q)??l0(Q);if(!G)return R(["Live usage endpoint returned an unexpected payload."]);let J=HQ(jQ(G,$),{kind:"api",label:"API",endpoint:Z});if(J.status==="unavailable")return R(["Live usage endpoint returned an unexpected payload."]);if(J.status==="partial")return{...J,warnings:["Live usage endpoint returned incomplete usage data."]};return J}function R(Q){return HQ({fiveHour:null,weekly:null},u0,Q)}function d0(Q){return ZZ(Q,(Z)=>{if(!Y(Z))return null;let $=Z.rate_limits??Z.rateLimits??Z.rate_limit??Z.rateLimit;if(Y($))return $;return Y(Z.primary)||Y(Z.secondary)||Y(Z.primary_window)||Y(Z.secondary_window)?Z:null})}function l0(Q){return ZZ(Q,(Z)=>{if(!Array.isArray(Z))return null;let $=Z.find((J)=>eQ(J,"primary")),G=Z.find((J)=>eQ(J,"secondary"));return $||G?{primary:$,secondary:G}:null})}function ZZ(Q,Z){let $=[{value:Q,depth:0}],G=new WeakSet;for(let J=0;J<$.length;J+=1){let K=$[J];if(!K)break;let z=Z(K.value);if(z)return z;if(K.depth>=c0||typeof K.value!=="object"||!K.value)continue;if(G.has(K.value))continue;G.add(K.value);let j=Array.isArray(K.value)?K.value:Y(K.value)?Object.values(K.value):[];for(let H of j){if($.length>=p0)break;$.push({value:H,depth:K.depth+1})}}return null}function eQ(Q,Z){if(!Y(Q))return!1;let $=String(Q.type??Q.kind??Q.name??Q.label??Q.window??"").toLowerCase();if(Z==="primary"&&($.includes("primary")||$.includes("5-hour")||$.includes("five")))return!0;if(Z==="secondary"&&($.includes("secondary")||$.includes("weekly")||$.includes("week")))return!0;let G=Q.window_minutes??Q.windowMinutes??Q.window_length_minutes??Q.windowLengthMinutes;return Z==="primary"?G===300:G===10080}var r0="https://chatgpt.com/backend-api/codex/usage",o0=1e4,i0=1e6;async function GZ(Q={}){let Z=s0(Q),$=L(Z),G=await g(Q);if(!G.credentials){let K=k(G.diagnostics);return R(K.length>0?K:["Live usage requires Codex authentication."])}let J={endpoint:Z,headers:n0(G.credentials),timeoutMs:Q.timeoutMs??o0,maxResponseBytes:i0,fallbackOnHttpError:!0,...Q.fetch?{fetch:Q.fetch}:{},...Q.signal?{signal:Q.signal}:{}};try{let K=await(Q.transport??v)(J);return K.ok?QZ(K.payload,$,Q.now??new Date):$Z(K)}catch{return $Z({ok:!1,code:"network-error",status:null})}}function n0(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 s0(Q){let Z=T(Q.env);return Q.usageEndpoint??M(Z,"CODEX_LIMITS_USAGE_ENDPOINT")??r0}function $Z(Q){return R(k([h(Q,"Live usage")]))}var t0={kind:"local",label:"Local"};async function JZ(Q={}){let Z=await a0(Q),$=Q.includeCoupons===!1?null:await hQ(Q),G=$?{...$,warnings:o($.warnings)}:null;return{windows:Z.windows,usageSource:Z.source,coupons:G,warnings:o([...Z.warnings,...G?.warnings??[]])}}async function a0(Q={}){let Z=await GZ(Q);if(Z.status==="available")return Z;let $=nQ(await Q1(Q),t0);return e0(Z,$)}function e0(Q,Z){if(Z.status!=="unavailable")return Z;if(Q.status==="partial")return{...Q,warnings:[...Q.warnings,...Z.warnings]};return{...Z,warnings:[...Q.warnings,...Z.warnings]}}async function Q1(Q={}){let Z=Q.now??new Date,$=await S(Q);if(!$.foundHome)return YQ(["No readable local Codex home directory was found."]);let[G,J]=await Promise.all([FQ($.foundHome),AQ($.foundHome)]);return tQ(iQ(G,Z),sQ(J,Z))}var XQ="Codex Limits",Z1="Check Codex limits, resets, and credits.",KZ="Could not load Codex limits.";function $1(Q={}){let Z=new WeakSet,$=Q.getLimits??JZ,G=Q.nextFrame??(()=>new Promise((J)=>setTimeout(J,0)));return{id:"codex-limits",tui:async(J)=>{if(Z.has(J))return;let K=G1(J,$,G),z;try{let H=J1(J,K);z=typeof H==="function"?H:void 0}catch{throw Error("Could not register the codex-limits OpenCode command.")}let j=()=>{if(!Z.delete(J))return;try{z?.()}catch{}};Z.add(J);try{J.lifecycle.onDispose(j)}catch{throw j(),Error("Could not register the codex-limits OpenCode lifecycle.")}}}}function G1(Q,Z,$){let G=0;return{title:XQ,value:"codex-limits.show",description:Z1,category:"Codex",slash:{name:"codex-limits"},onSelect:async(J)=>{let K=++G;J?.clear(),Q.ui.dialog.clear(),await $();let z=Q.ui.dialog,j=(H)=>z.replace(()=>Q.ui.DialogAlert({title:XQ,message:H}));z.setSize("large"),j("Loading Codex limits...");try{let H=await Z();if(K===G)j(qQ(H))}catch{if(K===G)Q.ui.toast({variant:"error",title:XQ,message:KZ}),j(KZ)}}}}function J1(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 zZ=$1(),jZ=zZ,E2=zZ.tui;var HZ=jZ,h2=HZ,v2=HZ.tui;export{v2 as tui,h2 as default};
1
+ import{createRequire as LZ}from"node:module";var BZ=Object.create;var{getPrototypeOf:CZ,defineProperty:r,getOwnPropertyNames:OZ}=Object;var DZ=Object.prototype.hasOwnProperty;function TZ(Q){return this[Q]}var AZ,FZ,A1=(Q,Z,$)=>{var G=Q!=null&&typeof Q==="object";if(G){var J=Z?AZ??=new WeakMap:FZ??=new WeakMap,z=J.get(Q);if(z)return z}$=Q!=null?BZ(CZ(Q)):{};let j=Z||!Q||!Q.__esModule?r($,"default",{value:Q,enumerable:!0}):$;for(let K of OZ(Q))if(!DZ.call(j,K))r(j,K,{get:TZ.bind(Q,K),enumerable:!0});if(G)J.set(Q,j);return j};var F1=(Q,Z)=>()=>(Z||Q((Z={exports:{}}).exports,Z),Z.exports);var IZ=(Q)=>Q;function bZ(Q,Z){this[Q]=IZ.bind(null,Z)}var I1=(Q,Z)=>{for(var $ in Z)r(Q,$,{get:Z[$],enumerable:!0,configurable:!0,set:bZ.bind(Z,$)})};var kZ=(Q,Z)=>()=>(Q&&(Z=Q(Q=0)),Z);var b1=(Q)=>Promise.all(Q),L1=LZ(import.meta.url);function p(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 mQ(Q){return`${f0[Q.getDay()]} ${Q.getDate()} ${S0[Q.getMonth()]} ${Q.getFullYear()}`}function C2(Q){return`${Q.getDate()} ${E0[Q.getMonth()]} ${Q.getFullYear()} ${w0(Q)}`}function w0(Q){return`${vQ(Q.getHours())}:${vQ(Q.getMinutes())}`}function O2(Q,Z){return Q.getFullYear()===Z.getFullYear()&&Q.getMonth()===Z.getMonth()&&Q.getDate()===Z.getDate()}function vQ(Q){return String(Q).padStart(2,"0")}var f0,S0,E0;var JQ=kZ(()=>{f0=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],S0=["January","February","March","April","May","June","July","August","September","October","November","December"],E0=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function xQ(Q){let Z=[];if(Q.windows.fiveHour)Z.push(NQ("5-hour",Q.windows.fiveHour));if(Q.windows.weekly)Z.push(NQ("Weekly",Q.windows.weekly));if(Z.length===0)Z.push(["Usage limits Unavailable"]);if(Z.push(PZ(Q)),Q.warnings.length>0)Z.push(["Warnings",...Q.warnings.map(($)=>`- ${$}`)]);return Z.map(($)=>$.join(`
2
+ `)).join(`
3
+
4
+ `)}function NQ(Q,Z){let $=Z.remainingPercent;return[`${Q} ${RZ($)}`,`Remaining ${$===null?"Unknown":`${Math.round($)}% remaining`}`,_Z($),`Reset ${Z.resetsIn?`in ${Z.resetsIn}`:"unknown"}`]}function _Z(Q){let Z=Q===null?0:Math.min(Math.max(Q,0),100),$=Math.round(Z/100*22);return`[${"=".repeat($)}${" ".repeat(22-$)}] ${Math.round(Z)}%`}function PZ(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 RZ(Q){if(Q===null)return"Unknown";if(Q>=50)return"Healthy";if(Q>=15)return"Low";return"Critical"}function BQ(Q){return xQ(Q)}import{constants as yZ}from"node:fs";import{access as fZ,stat as SZ}from"node:fs/promises";import{homedir as EZ}from"node:os";import{join as b,normalize as o}from"node:path";function U(Q,Z){let $=Q[Z]?.trim();return $?$:null}function T(Q){return Q??process.env}var CQ="CODEX_LIMITS_HOME";function wZ(Q={}){let Z=T(Q.env),$=Q.homeDirectory??U(Z,"HOME")??U(Z,"USERPROFILE")??EZ(),G=Q.appData??U(Z,"APPDATA"),J=Q.localAppData??U(Z,"LOCALAPPDATA"),z=[];if(D(z,U(Z,CQ),"env"),D(z,U(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"),vZ(z)}async function E(Q={}){let Z=T(Q.env),$=U(Z,CQ),G=await Promise.all(wZ(Q).map(async(J)=>({...J,exists:await gZ(J.path)})));return{overrideHome:$?o($):null,candidates:G,foundHome:G.find((J)=>J.exists)?.path??null}}function D(Q,Z,$){if(Z)Q.push({path:o(Z),source:$})}async function gZ(Q){try{if(!(await SZ(Q)).isDirectory())return!1;return await fZ(Q,yZ.R_OK),!0}catch{return!1}}function vZ(Q){let Z=new Set,$=[];for(let G of Q){let J=o(G.path),z=process.platform==="win32"?J.toLowerCase():J;if(!Z.has(z))Z.add(z),$.push({path:J,source:G.source})}return $}import{createReadStream as rZ}from"node:fs";import{lstat as oZ,opendir as iZ,realpath as IQ,stat as nZ}from"node:fs/promises";import{join as bQ}from"node:path";import{isAbsolute as uZ,relative as DQ,resolve as OQ,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 A(Q){let Z=Q;for(let $ of pZ)Z=Z.replace($,"[redacted]");return Z.replace(hZ,"?")}function i(Q){return Q.map(A)}function TQ(Q,Z){let $=DQ(OQ(Q),OQ(Z));return $===""||!AQ($)}function B(Q,Z){let $=DQ(Q,Z);return $&&!AQ($)?lZ($):"."}function lZ(Q){let Z=A(Q);return Z.length<=240?Z:`${Z.slice(0,239)}…`}function AQ(Q){return Q===".."||Q.startsWith(`..${dZ}`)||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 sZ=8,n=20,w=1000,tZ=512,aZ=1000,kQ=25000000,eZ=1e6,Q0=/^rollout-.*\.jsonl$/i;async function LQ(Q){let Z=bQ(Q,"sessions"),$=[];if(await X0(Z))return $.push("Skipped the symbolic-link Codex sessions directory."),{homePath:Q,sessionsRoot:Z,files:[],latestSnapshot:null,warnings:$};let G=await Z0(Q,Z,$),J=[],z=null;for(let j of G.slice(0,n)){let K=B(Q,j.path);if(j.size>kQ){$.push(`Skipped ${K} because it is too large to inspect safely.`),J.push(s(j.path,K,j.modifiedAtMs,!1,"too-large"));continue}try{let X=await J0(Q,j.path);if(J.push(s(j.path,K,j.modifiedAtMs,X.snapshot!==null,null)),X.skippedOversizedLine)$.push(`Skipped an oversized JSONL line in ${K}.`);if(X.snapshot&&!z)z=X.snapshot}catch(X){let Y=X instanceof t;$.push(Y?`Skipped ${K} because it grew too large to inspect safely.`:`Could not inspect ${K}.`),J.push(s(j.path,K,j.modifiedAtMs,!1,Y?"too-large":"read-error"))}if(z)break}if(G.length>n)$.push(`Skipped ${G.length-n} 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 Z0(Q,Z,$){let G={directories:0,files:[],hitLimit:!1,skippedSymlink:!1};if(await _Q(Z,0,G,$,Q),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;try{J=await IQ(Z)}catch{return[]}let z=[];for(let j of G.files){let K=await $0(Q,J,j,$);if(K)z.push(K)}return z.sort((j,K)=>K.modifiedAtMs-j.modifiedAtMs||j.path.localeCompare(K.path))}async function $0(Q,Z,$,G){try{let[J,z]=await Promise.all([nZ($),IQ($)]);if(!J.isFile()||!TQ(Z,z))return G.push(`Could not inspect ${B(Q,$)}.`),null;return{path:$,modifiedAtMs:J.mtimeMs,size:J.size}}catch{return G.push(`Could not inspect ${B(Q,$)}.`),null}}async function _Q(Q,Z,$,G,J){if(Z>sZ||$.files.length>=w){$.hitLimit||=$.files.length>=w;return}if($.directories>=tZ){$.hitLimit=!0;return}$.directories+=1;let z;try{z=await G0(Q,$)}catch{if(Z>0)G.push(`Could not inspect ${B(J,Q)}.`);return}for(let j of z){if($.files.length>=w){$.hitLimit=!0;return}let K=bQ(Q,j.name);if(j.isSymbolicLink()){$.skippedSymlink=!0;continue}if(j.isDirectory()){await _Q(K,Z+1,$,G,J);continue}if(j.isFile()&&Q0.test(j.name)){if($.files.push(K),$.files.length>=w){$.hitLimit=!0;return}}}}async function G0(Q,Z){let $=await iZ(Q),G=[];for await(let J of $){if(G.length>=aZ){Z.hitLimit=!0;break}G.push(J)}return G.sort((J,z)=>z.name.localeCompare(J.name))}async function J0(Q,Z){let $=B(Q,Z),G=rZ(Z,{encoding:"utf8",highWaterMark:65536}),J=null,z=null,j="",K=0,X=0,Y=!1,V=!1;for await(let M of G){let C=String(M);if(X+=Buffer.byteLength(C,"utf8"),X>kQ)throw new t;let f=0;while(f<C.length){let S=C.indexOf(`
5
+ `,f),xZ=S===-1?C.length:S,UQ=C.slice(f,xZ);if(!Y){let O=Buffer.byteLength(UQ,"utf8");if(K+O>eZ)j="",K=0,Y=!0,V=!0;else j+=UQ,K+=O}if(S===-1)break;if(!Y){let O=FQ(j.endsWith("\r")?j.slice(0,-1):j);if(O.threadId)J=O.threadId;if(O.rateLimits)z={sessionFile:Z,relativePath:$,threadId:J,eventTimestamp:O.timestamp,rateLimits:O.rateLimits}}j="",K=0,Y=!1,f=S+1}}if(!Y&&j.length>0){let M=FQ(j.endsWith("\r")?j.slice(0,-1):j);if(M.threadId)J=M.threadId;if(M.rateLimits)z={sessionFile:Z,relativePath:$,threadId:J,eventTimestamp:M.timestamp,rateLimits:M.rateLimits}}return{snapshot:z,skippedOversizedLine:V}}function FQ(Q){let Z=z0(Q);if(!Z)return{threadId:null,timestamp:null,rateLimits:null};return{threadId:j0(Z),timestamp:x(Z,"timestamp"),rateLimits:K0(Z)}}function z0(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 K0(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 s(Q,Z,$,G,J){return{path:Q,relativePath:Z,modifiedAtMs:$,hasSnapshot:G,error:J}}async function X0(Q){try{return(await oZ(Q)).isSymbolicLink()}catch{return!1}}class t extends Error{}import{opendir as H0}from"node:fs/promises";import{extname as V0,join as q0}from"node:path";import{constants as a}from"node:fs";import{lstat as PQ,open as Y0}from"node:fs/promises";class W extends Error{code;constructor(Q){super(Q);this.name="BoundedFileError",this.code=Q}}async function g(Q,Z){let $;try{let G=await PQ(Q);if(!G.isFile())throw new W("not-file");let J=a.O_NOFOLLOW,z=typeof J==="number"?a.O_RDONLY|J:a.O_RDONLY;$=await Y0(Q,z);let j=await $.stat(),K=await PQ(Q);if(!j.isFile()||!K.isFile()||!RQ(G,j)||!RQ(j,K))throw new W("not-file");if(j.size>Z)throw new W("too-large");let X=Buffer.allocUnsafe(Z+1),Y=0;while(Y<=Z){let V=await $.read(X,Y,Z+1-Y,null);if(V.bytesRead===0)break;Y+=V.bytesRead}if(Y>Z)throw new W("too-large");return X.subarray(0,Y).toString("utf8")}catch(G){if(G instanceof W)throw G;if(yQ(G)&&G.code==="ENOENT")throw new W("not-found");if(yQ(G)&&G.code==="ELOOP")throw new W("not-file");throw new W("read-error")}finally{await $?.close().catch(()=>{return})}}function RQ(Q,Z){return Q.dev===Z.dev&&Q.ino===Z.ino}function yQ(Q){return Q instanceof Error&&"code"in Q}var W0=2,e=25,QQ=100,M0=64,U0=500,N0=1e6,x0=/(?:auth|token|cookie|session|secret|credential|api[-_]?key|keychain)/i;async function fQ(Q){let Z={directories:0,files:[],hitDirectoryLimit:!1,hitEntryLimit:!1,hitFileLimit:!1,skippedSensitive:!1,skippedSymlink:!1,warnings:[]};if(await SQ(Q,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 $=Z.files.sort((J,z)=>J.localeCompare(z)),G=[];for(let J of $.slice(0,e)){let z=B(Q,J);try{let j=await g(J,N0),K=C0(j,z,Z.warnings);G.push({path:J,relativePath:z,json:K.value,error:K.error})}catch(j){Z.warnings.push(j instanceof W&&j.code==="too-large"?`Skipped ${z} because it is too large to inspect safely.`:`Could not read ${z}.`)}}if($.length>e)Z.warnings.push(`Skipped ${$.length-e} extra files to keep inspection small.`);return{homePath:Q,files:G,warnings:Z.warnings}}async function SQ(Q,Z,$,G){if($>W0||G.files.length>=QQ){G.hitFileLimit||=G.files.length>=QQ;return}if(G.directories>=M0){G.hitDirectoryLimit=!0;return}G.directories+=1;let J=await B0(Q,Z,G);for(let z of J){if(G.files.length>=QQ){G.hitFileLimit=!0;return}if(x0.test(z.name)){G.skippedSensitive=!0;continue}let j=q0(Z,z.name);if(z.isSymbolicLink())G.skippedSymlink=!0;else if(z.isDirectory())await SQ(Q,j,$+1,G);else if(z.isFile()&&V0(z.name).toLowerCase()===".json")G.files.push(j)}}async function B0(Q,Z,$){try{let G=await H0(Z),J=[];for await(let z of G){if(J.length>=U0){$.hitEntryLimit=!0;break}J.push(z)}return J.sort((z,j)=>z.name.localeCompare(j.name))}catch{return $.warnings.push(`Could not inspect ${B(Q,Z)}.`),[]}}function C0(Q,Z,$){try{return{value:JSON.parse(Q),error:null}}catch{return $.push(`Could not parse JSON in ${Z}.`),{value:null,error:"invalid-json"}}}import{join as O0,normalize as D0}from"node:path";function N(Q,Z,$){return{code:Q,source:Z,severity:"warning",message:$}}function k(Q){return Q.map((Z)=>A(Z.message))}var T0=1e6;async function v(Q={}){let Z=T(Q.env),$=U(Z,"CODEX_LIMITS_ACCESS_TOKEN"),G=U(Z,"CODEX_LIMITS_ACCOUNT_ID");if($&&G)return{credentials:{accessToken:$,accountId:G},status:"configured",diagnostics:[]};if($||G)return{credentials:null,status:"partial",diagnostics:[N("auth.environment.partial","authentication","Codex authentication environment variables are incomplete.")]};let J=await A0(Q);return J?F0(J):{credentials:null,status:"missing",diagnostics:[]}}async function A0(Q){if(Q.authFile)return D0(Q.authFile);let Z=await E(Q);return Z.foundHome?O0(Z.foundHome,"auth.json"):null}async function F0(Q){let Z;try{Z=await g(Q,T0)}catch($){if($ instanceof W&&$.code==="not-found")return{credentials:null,status:"missing",diagnostics:[]};let G=$ instanceof W&&$.code==="too-large";return{credentials:null,status:"unreadable",diagnostics:[N(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 ZQ();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:[]}:ZQ()}catch{return ZQ()}}function ZQ(){return{credentials:null,status:"malformed",diagnostics:[N("auth.file.malformed","authentication","Codex auth.json is malformed or does not contain required credentials.")]}}import{request as I0}from"node:http";import{request as b0}from"node:https";var k0=new Set(["127.0.0.1","::1","[::1]","localhost"]);function _(Q){try{let Z=new URL(Q);return Z.username="",Z.password="",Z.search="",Z.hash="",Z.href}catch{return"[invalid endpoint]"}}async function m(Q){let Z=L0(Q.endpoint);if(!Z.ok)return Z;if(Q.signal?.aborted)return q("aborted");let $=Q.fetch??globalThis.fetch;if(!$)return EQ(Z.url,Q);let G=await _0(Z.url,Q,$);if(G.ok||G.code==="aborted"||!y0(G,Q.fallbackOnHttpError??!1))return G;let J=await EQ(Z.url,Q);if(J.ok||J.code==="http-error"||J.code==="invalid-json"||J.code==="response-too-large")return J;return G}function L0(Q){let Z;try{Z=new URL(Q)}catch{return q("invalid-url")}if(Z.username||Z.password)return q("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 q("unsupported-protocol")}async function _0(Q,Z,$){let G=gQ(Z.timeoutMs,Z.signal);try{let J=await $(Q.href,{method:"GET",headers:Z.headers,redirect:"error",signal:G.signal});if(!J.ok)return await wQ(J),q("http-error",GQ(J.status));let z=await P0(J,Z.maxResponseBytes);return{ok:!0,status:GQ(J.status)??200,payload:z,transport:"fetch"}}catch(J){if(J instanceof L)return q("response-too-large");if(J instanceof h)return q("invalid-json");if(Z.signal?.aborted)return q("aborted");if(G.didTimeout())return q("timeout");return q("network-error")}finally{G.dispose()}}async function P0(Q,Z){let $=Number(Q.headers?.get("content-length"));if(Number.isFinite($)&&$>Z)throw await wQ(Q),new L;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 L;J.push(K.value)}let j=Buffer.concat(J.map((K)=>Buffer.from(K)),z).toString("utf8");return $Q(j)}if(Q.text){let G=await Q.text();if(Buffer.byteLength(G,"utf8")>Z)throw new L;return $Q(G)}throw new h}async function wQ(Q){if(!Q.body)return;try{await Q.body.getReader().cancel?.()}catch{}}function EQ(Q,Z){return new Promise(($)=>{let G=gQ(Z.timeoutMs,Z.signal),J=!1,z=null,j=(X)=>{if(J)return;J=!0,G.dispose(),$(X)},K=()=>{z?.destroy(),j(q(Z.signal?.aborted?"aborted":"timeout"))};G.signal.addEventListener("abort",K,{once:!0});try{z=(Q.protocol==="http:"?I0:b0)(Q,{method:"GET",headers:Z.headers,signal:G.signal},(Y)=>R0(Y,Z.maxResponseBytes,j)),z.on("error",()=>{if(Z.signal?.aborted)j(q("aborted"));else if(G.didTimeout())j(q("timeout"));else j(q("network-error"))}),z.end()}catch{j(q("network-error"))}})}function R0(Q,Z,$){let G=GQ(Q.statusCode);if(G===null||G<200||G>=300){Q.resume(),$(q("http-error",G));return}let J=Number(Q.headers["content-length"]);if(Number.isFinite(J)&&J>Z){Q.destroy(),$(q("response-too-large"));return}let z=[],j=0;Q.on("data",(K)=>{let X=Buffer.isBuffer(K)?K:Buffer.from(K);if(j+=X.length,j>Z){Q.destroy(),$(q("response-too-large"));return}z.push(X)}),Q.on("end",()=>{try{let K=$Q(Buffer.concat(z,j).toString("utf8"));$({ok:!0,status:G,payload:K,transport:"node"})}catch{$(q("invalid-json"))}}),Q.on("error",()=>$(q("network-error")))}function gQ(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 $Q(Q){try{return JSON.parse(Q)}catch{throw new h}}function GQ(Q){return typeof Q==="number"&&Number.isInteger(Q)&&Q>=0?Q:null}function q(Q,Z=null){return{ok:!1,code:Q,status:Z}}class L extends Error{}class h extends Error{}function c(Q,Z){switch(Q.code){case"aborted":return N("network.request.aborted","network",`${Z} lookup was cancelled.`);case"http-error":return N("network.response.http","network",Q.status===null?`${Z} endpoint returned an invalid HTTP status.`:`${Z} endpoint returned HTTP ${Q.status}.`);case"invalid-json":return N("network.response.invalid-json","network",`${Z} endpoint returned malformed JSON.`);case"invalid-url":return N("network.endpoint.invalid","network",`${Z} endpoint URL is invalid.`);case"response-too-large":return N("network.response.too-large","network",`${Z} endpoint response was too large.`);case"timeout":return N("network.request.timeout","network",`${Z} lookup timed out.`);case"unsupported-protocol":return N("network.endpoint.protocol","network",`${Z} endpoint must use HTTPS or loopback HTTP.`);case"network-error":return N("network.request.failed","network",`${Z} lookup failed.`)}}JQ();var pQ=["credits","reset_credits","items"],uQ=["available_count","availableCount","available"],dQ=["total_earned_count","earned_this_period","earnedThisPeriod","totalEarnedCount"];function lQ(Q,Z,$){if(!H(Q)||!g0(Q))return P(Z,["Live reset coupon endpoint returned an unexpected payload."]);let G=h0(Q,pQ);if(G.malformed)return P(Z,["Live reset coupon endpoint returned an unexpected payload."]);let J=G.value,z=J.map((V,M)=>v0(V,M+1,$)).filter((V)=>V!==null).sort(m0).map((V,M)=>({...V,index:M+1})),j=z.find((V)=>V.status?.toLowerCase()==="available")??z[0]??null,K=cQ(Q,uQ),X=cQ(Q,dQ),Y=[];if(J.length!==z.length)Y.push("Live reset coupon endpoint ignored malformed coupon entries.");if(K.malformed||X.malformed)Y.push("Live reset coupon endpoint ignored malformed summary fields.");return{status:Y.length>0?"partial":"available",available:K.value,earnedThisPeriod:X.value,nextExpirationDate:j?.expirationDate??null,nextExpirationIn:j?.expiresIn??null,items:z,warnings:Y,source:{live:!0,label:"live Codex reset-credit endpoint",endpoint:Z}}}function P(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[...pQ,...uQ,...dQ].some((Z)=>(Z in Q))}function v0(Q,Z,$){if(!H(Q))return null;let G=x(Q,"expires_at")??x(Q,"expiresAt"),J=x(Q,"granted_at")??x(Q,"grantedAt"),z=F(G),j=F(J),K=x(Q,"status"),X=K&&/^[a-z][a-z0-9_-]{0,63}$/i.test(K)?K:null,Y=j?J:null,V=z?G:null;if(!X&&!Y&&!V)return null;return{index:Z,status:X,grantedAt:Y,expiresAt:V,expirationDate:z?mQ(z):null,expiresIn:z?p(z.getTime()-$.getTime()):null}}function m0(Q,Z){return hQ(Q.expiresAt)-hQ(Z.expiresAt)}function hQ(Q){return F(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 cQ(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 oQ="https://chatgpt.com/backend-api/wham/rate-limit-reset-credits",c0=1e4,p0=1e6;async function iQ(Q={}){let Z=Q.endpoint??oQ,$=_(Z),G=await v(Q);if(!G.credentials){let z=k(G.diagnostics);return u0($,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={endpoint:Z,headers:{Authorization:`Bearer ${G.credentials.accessToken}`,"ChatGPT-Account-ID":G.credentials.accountId,"OpenAI-Beta":"codex-1",originator:"Codex Desktop",Accept:"application/json"},timeoutMs:Q.timeoutMs??c0,maxResponseBytes:p0,...Q.fetch?{fetch:Q.fetch}:{},...Q.signal?{signal:Q.signal}:{}};try{let z=await(Q.transport??m)(J);return z.ok?lQ(z.payload,$,Q.now??new Date):rQ($,z)}catch{return rQ($,{ok:!1,code:"network-error",status:null})}}function u0(Q=oQ,Z=[]){return P(_(Q),Z)}function rQ(Q,Z){return P(Q,k([c(Z,"Live reset coupon")]))}JQ();var eQ=5,KQ="5-hour usage limit",XQ="Weekly usage limit",YQ=["fiveHour","five_hour","fiveHourWindow","five_hour_window","primary","primaryWindow","primary_window","main","mainWindow"],HQ=["weekly","week","weeklyWindow","weekly_window","secondary","secondaryWindow","secondary_window","backup","backupWindow"],d0=["used_percent","usedPercent","used","usage","percentUsed","usagePercent","usagePercentage","percent"],l0=["remaining_percent","remainingPercent","remaining","percentRemaining","availablePercent","available_percentage"],r0=["resets_at","resetsAt","resetAt","resetTime","reset_at","reset","ends_at","endsAt","windowEnd"],o0=["resetsIn","resetIn","resets_in","reset_in","timeUntilReset"],i0=["limit_window_seconds","limitWindowSeconds","window_seconds","windowSeconds","window_length_seconds","windowLengthSeconds"],n0=["window_minutes","windowMinutes","window_length_minutes","windowLengthMinutes"],s0=18000,t0=604800;function QZ(Q,Z=new Date){let $=Q.latestSnapshot;if(!$)return WQ(Q.warnings);return l(VQ($.rateLimits,Z),Q.warnings)}function VQ(Q,Z=new Date){return zZ(u(Q,YQ),u(Q,HQ),Z)}function ZZ(Q){return u(Q,YQ)!==null||u(Q,HQ)!==null}function R(Q){let Z=aQ(I(Q,i0,!1)),$=aQ(I(Q,n0,!1)),G=Z??($===null?null:$*60);if(G===s0)return"fiveHour";if(G===t0)return"weekly";return null}function $Z(Q,Z){return{...Q,source:Z}}function qQ(Q,Z,$=[]){return{...l(Q,$),source:Z}}function GZ(Q,Z=new Date){let $={fiveHour:null,weekly:null};for(let G of Q.files){if(!G.json)continue;let J=a0(G.json,Z);$=jZ($,J.windows)}return l($,Q.warnings)}function WQ(Q=[]){return{status:"unavailable",windows:{fiveHour:null,weekly:null},warnings:Q}}function JZ(Q,Z){let $=jZ(Q.windows,Z.windows);return l($,[...Q.warnings,...Z.warnings])}function a0(Q,Z){if(!H(Q))return{windows:{fiveHour:null,weekly:null}};let $=jQ(Q,YQ),G=jQ(Q,HQ);if($||G)return{windows:zZ($,G,Z)};let J=R(Q)??"fiveHour",z=zQ(Q,J==="weekly"?XQ:KQ,Z);return{windows:{fiveHour:J==="fiveHour"?z:null,weekly:J==="weekly"?z:null}}}function zZ(Q,Z,$){let G=[];if(Q)G.push({fallbackKind:"fiveHour",value:Q});if(Z)G.push({fallbackKind:"weekly",value:Z});return{fiveHour:zQ(nQ(G,"fiveHour"),KQ,$),weekly:zQ(nQ(G,"weekly"),XQ,$)}}function zQ(Q,Z,$){if(!Q)return null;let G=tQ(I(Q,d0,!0)),J=tQ(I(Q,l0,!0)),z=G??(J===null?null:d(100-J)),j=J??(G===null?null:d(100-G)),K=I(Q,r0,!0),X=F(K),Y=X?X.toISOString():null,V=Z1(I(Q,o0,!0)),M=X?p(X.getTime()-$.getTime()):V&&V.length<=100?A(V):null,C={label:Z,remainingPercent:j,usedPercent:z,resetsAt:Y,resetsIn:M};return KZ(C)?C:null}function l(Q,Z){return{status:e0(Q),windows:Q,warnings:Z}}function e0(Q){let Z=[Q.fiveHour,Q.weekly].filter(($)=>KZ($));if(Z.length===0)return"unavailable";return Z.every(Q1)?"available":"partial"}function nQ(Q,Z){let $=Q.find((G)=>R(G.value)===Z);if($)return $.value;return Q.find((G)=>G.fallbackKind===Z&&R(G.value)===null)?.value??null}function jZ(Q,Z){return{fiveHour:sQ(Q.fiveHour,Z.fiveHour,KQ),weekly:sQ(Q.weekly,Z.weekly,XQ)}}function sQ(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 KZ(Q){return Q!==null&&(Q.remainingPercent!==null||Q.usedPercent!==null||Q.resetsAt!==null||Q.resetsIn!==null)}function Q1(Q){return Q!==null&&Q.remainingPercent!==null&&Q.usedPercent!==null&&(Q.resetsAt!==null||Q.resetsIn!==null)}function jQ(Q,Z,$=0){if($>eQ)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=jQ(G,Z,$+1);if(J)return J}return null}function u(Q,Z){for(let $ of Z){let G=Q[$];if(H(G))return G}return null}function I(Q,Z,$,G=0){if(G>eQ)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 tQ(Q){if(typeof Q==="number"&&Number.isFinite(Q))return d(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)?d(G):null}return null}function d(Q){return Math.round(Math.min(Math.max(Q,0),100)*10)/10}function aQ(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){if(typeof Q==="string"&&Q.trim().length>0)return Q.trim();return null}var $1=5,G1=1000,J1={kind:"unavailable",label:"Unavailable"};function YZ(Q,Z,$){let G=z1(Q)??j1(Q);if(!G)return y(["Live usage endpoint returned an unexpected payload."]);let J=qQ(VQ(G,$),{kind:"api",label:"API",endpoint:Z});if(J.status==="unavailable")return y(["Live usage endpoint returned an unexpected payload."]);if(J.status==="partial")return{...J,warnings:["Live usage endpoint returned incomplete usage data."]};return J}function y(Q){return qQ({fiveHour:null,weekly:null},J1,Q)}function z1(Q){return HZ(Q,(Z)=>{if(!H(Z))return null;let $=Z.rate_limits??Z.rateLimits??Z.rate_limit??Z.rateLimit;if(H($))return $;return ZZ(Z)?Z:null})}function j1(Q){return HZ(Q,(Z)=>{if(!Array.isArray(Z))return null;let $=Z.find((J)=>XZ(J,"fiveHour")),G=Z.find((J)=>XZ(J,"weekly"));return $||G?{fiveHour:$,weekly:G}:null})}function HZ(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>=$1||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>=G1)break;$.push({value:X,depth:z.depth+1})}}return null}function XZ(Q,Z){if(!H(Q))return!1;let $=R(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 K1="https://chatgpt.com/backend-api/codex/usage",X1=1e4,Y1=1e6;async function VZ(Q={}){return(await H1(Q)).usage}async function H1(Q={}){let Z=q1(Q),$=_(Z),G=await v(Q);if(!G.credentials){let j=k(G.diagnostics);return{usage:y(j.length>0?j:["Live usage requires Codex authentication."]),authenticationFound:!1,endpointStatus:"not-checked"}}let J={endpoint:Z,headers:V1(G.credentials),timeoutMs:Q.timeoutMs??X1,maxResponseBytes:Y1,fallbackOnHttpError:!0,...Q.fetch?{fetch:Q.fetch}:{},...Q.signal?{signal:Q.signal}:{}},z;try{z=await(Q.transport??m)(J)}catch{z={ok:!1,code:"network-error",status:null}}return{usage:z.ok?YZ(z.payload,$,Q.now??new Date):M1(z),authenticationFound:!0,endpointStatus:W1(z)}}function V1(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=T(Q.env);return Q.usageEndpoint??U(Z,"CODEX_LIMITS_USAGE_ENDPOINT")??K1}function W1(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 M1(Q){return y(k([c(Q,"Live usage")]))}var U1={kind:"local",label:"Local"};async function qZ(Q={}){let Z=await N1(Q),$=Q.includeCoupons===!1?null:await iQ(Q),G=$?{...$,warnings:i($.warnings)}:null;return{windows:Z.windows,usageSource:Z.source,coupons:G,warnings:i([...Z.warnings,...G?.warnings??[]])}}async function N1(Q={}){let Z=await VZ(Q);if(Z.status!=="unavailable")return Z;let $=$Z(await B1(Q),U1);return x1(Z,$)}function x1(Q,Z){if(Q.status!=="unavailable")return Q;if(Z.status!=="unavailable")return Z;return{...Z,warnings:[...Q.warnings,...Z.warnings]}}async function B1(Q={}){let Z=Q.now??new Date,$=await E(Q);if(!$.foundHome)return WQ(["No readable local Codex home directory was found."]);let[G,J]=await Promise.all([LQ($.foundHome),fQ($.foundHome)]);return JZ(QZ(G,Z),GZ(J,Z))}var MQ="Codex Limits",C1="Check Codex limits, resets, and credits.",WZ="Could not load Codex limits.";function O1(Q={}){let Z=new WeakSet,$=Q.getLimits??qZ,G=Q.nextFrame??(()=>new Promise((J)=>setTimeout(J,0)));return{id:"codex-limits",tui:async(J)=>{if(Z.has(J))return;let z=D1(J,$,G),j;try{let X=T1(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 D1(Q,Z,$){let G=0;return{title:MQ,value:"codex-limits.show",description:C1,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:MQ,message:X}));j.setSize("large"),K("Loading Codex limits...");try{let X=await Z();if(z===G)K(BQ(X))}catch{if(z===G)Q.ui.toast({variant:"error",title:MQ,message:WZ}),K(WZ)}}}}function T1(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 MZ=O1(),UZ=MZ,$3=MZ.tui;var NZ=UZ,K3=NZ,z3=NZ.tui;export{z3 as tui,K3 as default};
package/dist/pi.js ADDED
@@ -0,0 +1,5 @@
1
+ import{DynamicBorder as VZ}from"@earendil-works/pi-coding-agent";import{Container as G1,matchesKey as qQ,Text as WQ}from"@earendil-works/pi-tui";function UQ(Q){let Z=[];if(Q.windows.fiveHour)Z.push(NQ("5-hour",Q.windows.fiveHour));if(Q.windows.weekly)Z.push(NQ("Weekly",Q.windows.weekly));if(Z.length===0)Z.push(["Usage limits Unavailable"]);if(Z.push(UZ(Q)),Q.warnings.length>0)Z.push(["Warnings",...Q.warnings.map(($)=>`- ${$}`)]);return Z.map(($)=>$.join(`
2
+ `)).join(`
3
+
4
+ `)}function NQ(Q,Z){let $=Z.remainingPercent;return[`${Q} ${BZ($)}`,`Remaining ${$===null?"Unknown":`${Math.round($)}% remaining`}`,NZ($),`Reset ${Z.resetsIn?`in ${Z.resetsIn}`:"unknown"}`]}function NZ(Q){let Z=Q===null?0:Math.min(Math.max(Q,0),100),$=Math.round(Z/100*22);return`[${"=".repeat($)}${" ".repeat(22-$)}] ${Math.round(Z)}%`}function UZ(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 BZ(Q){if(Q===null)return"Unknown";if(Q>=50)return"Healthy";if(Q>=15)return"Low";return"Critical"}function BQ(Q){return UQ(Q)}import{constants as CZ}from"node:fs";import{access as OZ,stat as TZ}from"node:fs/promises";import{homedir as xZ}from"node:os";import{join as b,normalize as r}from"node:path";function N(Q,Z){let $=Q[Z]?.trim();return $?$:null}function D(Q){return Q??process.env}var CQ="CODEX_LIMITS_HOME";function DZ(Q={}){let Z=D(Q.env),$=Q.homeDirectory??N(Z,"HOME")??N(Z,"USERPROFILE")??xZ(),G=Q.appData??N(Z,"APPDATA"),J=Q.localAppData??N(Z,"LOCALAPPDATA"),z=[];if(x(z,N(Z,CQ),"env"),x(z,N(Z,"CODEX_HOME"),"env"),$)x(z,b($,".codex"),"default"),x(z,b($,".config","codex"),"default"),x(z,b($,"Library","Application Support","Codex"),"default"),x(z,b($,"Library","Application Support","Parall","Codex",".codex"),"default");return x(z,G?b(G,"Codex"):null,"default"),x(z,J?b(J,"Codex"):null,"default"),FZ(z)}async function E(Q={}){let Z=D(Q.env),$=N(Z,CQ),G=await Promise.all(DZ(Q).map(async(J)=>({...J,exists:await AZ(J.path)})));return{overrideHome:$?r($):null,candidates:G,foundHome:G.find((J)=>J.exists)?.path??null}}function x(Q,Z,$){if(Z)Q.push({path:r(Z),source:$})}async function AZ(Q){try{if(!(await TZ(Q)).isDirectory())return!1;return await OZ(Q,CZ.R_OK),!0}catch{return!1}}function FZ(Q){let Z=new Set,$=[];for(let G of Q){let J=r(G.path),z=process.platform==="win32"?J.toLowerCase():J;if(!Z.has(z))Z.add(z),$.push({path:J,source:G.source})}return $}import{createReadStream as yZ}from"node:fs";import{lstat as fZ,opendir as SZ,realpath as FQ,stat as EZ}from"node:fs/promises";import{join as IQ}from"node:path";import{isAbsolute as _Z,relative as TQ,resolve as OQ,sep as PZ}from"node:path";var IZ=/(?:chatgpt[-_]?account[-_]?id|access[-_]?token|refresh[-_]?token|id[-_]?token|session[-_]?token|api[-_]?key|account[-_]?id|authorization|cookie|client[-_]?secret|password|credential|secret|token)/,bZ=/[\u0000-\u001f\u007f-\u009f]/g,kZ=new RegExp(`["']?${IZ.source}["']?\\s*[:=]\\s*(?:"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|[^,\\r\\n}\\]&]+)`,"gi"),LZ=[kZ,/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 A(Q){let Z=Q;for(let $ of LZ)Z=Z.replace($,"[redacted]");return Z.replace(bZ,"?")}function o(Q){return Q.map(A)}function xQ(Q,Z){let $=TQ(OQ(Q),OQ(Z));return $===""||!DQ($)}function C(Q,Z){let $=TQ(Q,Z);return $&&!DQ($)?RZ($):"."}function RZ(Q){let Z=A(Q);return Z.length<=240?Z:`${Z.slice(0,239)}…`}function DQ(Q){return Q===".."||Q.startsWith(`..${PZ}`)||_Z(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 wZ=8,i=20,w=1000,mZ=512,vZ=1000,bQ=25000000,gZ=1e6,hZ=/^rollout-.*\.jsonl$/i;async function kQ(Q){let Z=IQ(Q,"sessions"),$=[];if(await iZ(Z))return $.push("Skipped the symbolic-link Codex sessions directory."),{homePath:Q,sessionsRoot:Z,files:[],latestSnapshot:null,warnings:$};let G=await pZ(Q,Z,$),J=[],z=null;for(let j of G.slice(0,i)){let X=C(Q,j.path);if(j.size>bQ){$.push(`Skipped ${X} because it is too large to inspect safely.`),J.push(n(j.path,X,j.modifiedAtMs,!1,"too-large"));continue}try{let K=await dZ(Q,j.path);if(J.push(n(j.path,X,j.modifiedAtMs,K.snapshot!==null,null)),K.skippedOversizedLine)$.push(`Skipped an oversized JSONL line in ${X}.`);if(K.snapshot&&!z)z=K.snapshot}catch(K){let Y=K instanceof s;$.push(Y?`Skipped ${X} because it grew too large to inspect safely.`:`Could not inspect ${X}.`),J.push(n(j.path,X,j.modifiedAtMs,!1,Y?"too-large":"read-error"))}if(z)break}if(G.length>i)$.push(`Skipped ${G.length-i} 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 pZ(Q,Z,$){let G={directories:0,files:[],hitLimit:!1,skippedSymlink:!1};if(await LQ(Z,0,G,$,Q),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;try{J=await FQ(Z)}catch{return[]}let z=[];for(let j of G.files){let X=await cZ(Q,J,j,$);if(X)z.push(X)}return z.sort((j,X)=>X.modifiedAtMs-j.modifiedAtMs||j.path.localeCompare(X.path))}async function cZ(Q,Z,$,G){try{let[J,z]=await Promise.all([EZ($),FQ($)]);if(!J.isFile()||!xQ(Z,z))return G.push(`Could not inspect ${C(Q,$)}.`),null;return{path:$,modifiedAtMs:J.mtimeMs,size:J.size}}catch{return G.push(`Could not inspect ${C(Q,$)}.`),null}}async function LQ(Q,Z,$,G,J){if(Z>wZ||$.files.length>=w){$.hitLimit||=$.files.length>=w;return}if($.directories>=mZ){$.hitLimit=!0;return}$.directories+=1;let z;try{z=await uZ(Q,$)}catch{if(Z>0)G.push(`Could not inspect ${C(J,Q)}.`);return}for(let j of z){if($.files.length>=w){$.hitLimit=!0;return}let X=IQ(Q,j.name);if(j.isSymbolicLink()){$.skippedSymlink=!0;continue}if(j.isDirectory()){await LQ(X,Z+1,$,G,J);continue}if(j.isFile()&&hZ.test(j.name)){if($.files.push(X),$.files.length>=w){$.hitLimit=!0;return}}}}async function uZ(Q,Z){let $=await SZ(Q),G=[];for await(let J of $){if(G.length>=vZ){Z.hitLimit=!0;break}G.push(J)}return G.sort((J,z)=>z.name.localeCompare(J.name))}async function dZ(Q,Z){let $=C(Q,Z),G=yZ(Z,{encoding:"utf8",highWaterMark:65536}),J=null,z=null,j="",X=0,K=0,Y=!1,V=!1;for await(let M of G){let O=String(M);if(K+=Buffer.byteLength(O,"utf8"),K>bQ)throw new s;let f=0;while(f<O.length){let S=O.indexOf(`
5
+ `,f),MZ=S===-1?O.length:S,MQ=O.slice(f,MZ);if(!Y){let T=Buffer.byteLength(MQ,"utf8");if(X+T>gZ)j="",X=0,Y=!0,V=!0;else j+=MQ,X+=T}if(S===-1)break;if(!Y){let T=AQ(j.endsWith("\r")?j.slice(0,-1):j);if(T.threadId)J=T.threadId;if(T.rateLimits)z={sessionFile:Z,relativePath:$,threadId:J,eventTimestamp:T.timestamp,rateLimits:T.rateLimits}}j="",X=0,Y=!1,f=S+1}}if(!Y&&j.length>0){let M=AQ(j.endsWith("\r")?j.slice(0,-1):j);if(M.threadId)J=M.threadId;if(M.rateLimits)z={sessionFile:Z,relativePath:$,threadId:J,eventTimestamp:M.timestamp,rateLimits:M.rateLimits}}return{snapshot:z,skippedOversizedLine:V}}function AQ(Q){let Z=lZ(Q);if(!Z)return{threadId:null,timestamp:null,rateLimits:null};return{threadId:rZ(Z),timestamp:B(Z,"timestamp"),rateLimits:oZ(Z)}}function lZ(Q){let Z=Q.trim();if(!Z)return null;try{let $=JSON.parse(Z);return H($)?$:null}catch{return null}}function rZ(Q){if(Q.type!=="session_meta"||!H(Q.payload))return null;return B(Q.payload,"id")}function oZ(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 n(Q,Z,$,G,J){return{path:Q,relativePath:Z,modifiedAtMs:$,hasSnapshot:G,error:J}}async function iZ(Q){try{return(await fZ(Q)).isSymbolicLink()}catch{return!1}}class s extends Error{}import{opendir as sZ}from"node:fs/promises";import{extname as tZ,join as aZ}from"node:path";import{constants as t}from"node:fs";import{lstat as _Q,open as nZ}from"node:fs/promises";class W extends Error{code;constructor(Q){super(Q);this.name="BoundedFileError",this.code=Q}}async function m(Q,Z){let $;try{let G=await _Q(Q);if(!G.isFile())throw new W("not-file");let J=t.O_NOFOLLOW,z=typeof J==="number"?t.O_RDONLY|J:t.O_RDONLY;$=await nZ(Q,z);let j=await $.stat(),X=await _Q(Q);if(!j.isFile()||!X.isFile()||!PQ(G,j)||!PQ(j,X))throw new W("not-file");if(j.size>Z)throw new W("too-large");let K=Buffer.allocUnsafe(Z+1),Y=0;while(Y<=Z){let V=await $.read(K,Y,Z+1-Y,null);if(V.bytesRead===0)break;Y+=V.bytesRead}if(Y>Z)throw new W("too-large");return K.subarray(0,Y).toString("utf8")}catch(G){if(G instanceof W)throw G;if(RQ(G)&&G.code==="ENOENT")throw new W("not-found");if(RQ(G)&&G.code==="ELOOP")throw new W("not-file");throw new W("read-error")}finally{await $?.close().catch(()=>{return})}}function PQ(Q,Z){return Q.dev===Z.dev&&Q.ino===Z.ino}function RQ(Q){return Q instanceof Error&&"code"in Q}var eZ=2,a=25,e=100,Q0=64,Z0=500,$0=1e6,G0=/(?:auth|token|cookie|session|secret|credential|api[-_]?key|keychain)/i;async function yQ(Q){let Z={directories:0,files:[],hitDirectoryLimit:!1,hitEntryLimit:!1,hitFileLimit:!1,skippedSensitive:!1,skippedSymlink:!1,warnings:[]};if(await fQ(Q,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 $=Z.files.sort((J,z)=>J.localeCompare(z)),G=[];for(let J of $.slice(0,a)){let z=C(Q,J);try{let j=await m(J,$0),X=z0(j,z,Z.warnings);G.push({path:J,relativePath:z,json:X.value,error:X.error})}catch(j){Z.warnings.push(j instanceof W&&j.code==="too-large"?`Skipped ${z} because it is too large to inspect safely.`:`Could not read ${z}.`)}}if($.length>a)Z.warnings.push(`Skipped ${$.length-a} extra files to keep inspection small.`);return{homePath:Q,files:G,warnings:Z.warnings}}async function fQ(Q,Z,$,G){if($>eZ||G.files.length>=e){G.hitFileLimit||=G.files.length>=e;return}if(G.directories>=Q0){G.hitDirectoryLimit=!0;return}G.directories+=1;let J=await J0(Q,Z,G);for(let z of J){if(G.files.length>=e){G.hitFileLimit=!0;return}if(G0.test(z.name)){G.skippedSensitive=!0;continue}let j=aZ(Z,z.name);if(z.isSymbolicLink())G.skippedSymlink=!0;else if(z.isDirectory())await fQ(Q,j,$+1,G);else if(z.isFile()&&tZ(z.name).toLowerCase()===".json")G.files.push(j)}}async function J0(Q,Z,$){try{let G=await sZ(Z),J=[];for await(let z of G){if(J.length>=Z0){$.hitEntryLimit=!0;break}J.push(z)}return J.sort((z,j)=>z.name.localeCompare(j.name))}catch{return $.warnings.push(`Could not inspect ${C(Q,Z)}.`),[]}}function z0(Q,Z,$){try{return{value:JSON.parse(Q),error:null}}catch{return $.push(`Could not parse JSON in ${Z}.`),{value:null,error:"invalid-json"}}}import{join as j0,normalize as X0}from"node:path";function U(Q,Z,$){return{code:Q,source:Z,severity:"warning",message:$}}function k(Q){return Q.map((Z)=>A(Z.message))}var K0=1e6;async function v(Q={}){let Z=D(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:[U("auth.environment.partial","authentication","Codex authentication environment variables are incomplete.")]};let J=await Y0(Q);return J?H0(J):{credentials:null,status:"missing",diagnostics:[]}}async function Y0(Q){if(Q.authFile)return X0(Q.authFile);let Z=await E(Q);return Z.foundHome?j0(Z.foundHome,"auth.json"):null}async function H0(Q){let Z;try{Z=await m(Q,K0)}catch($){if($ instanceof W&&$.code==="not-found")return{credentials:null,status:"missing",diagnostics:[]};let G=$ instanceof W&&$.code==="too-large";return{credentials:null,status:"unreadable",diagnostics:[U(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 QQ();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:[]}:QQ()}catch{return QQ()}}function QQ(){return{credentials:null,status:"malformed",diagnostics:[U("auth.file.malformed","authentication","Codex auth.json is malformed or does not contain required credentials.")]}}import{request as V0}from"node:http";import{request as q0}from"node:https";var W0=new Set(["127.0.0.1","::1","[::1]","localhost"]);function _(Q){try{let Z=new URL(Q);return Z.username="",Z.password="",Z.search="",Z.hash="",Z.href}catch{return"[invalid endpoint]"}}async function g(Q){let Z=M0(Q.endpoint);if(!Z.ok)return Z;if(Q.signal?.aborted)return q("aborted");let $=Q.fetch??globalThis.fetch;if(!$)return SQ(Z.url,Q);let G=await N0(Z.url,Q,$);if(G.ok||G.code==="aborted"||!C0(G,Q.fallbackOnHttpError??!1))return G;let J=await SQ(Z.url,Q);if(J.ok||J.code==="http-error"||J.code==="invalid-json"||J.code==="response-too-large")return J;return G}function M0(Q){let Z;try{Z=new URL(Q)}catch{return q("invalid-url")}if(Z.username||Z.password)return q("invalid-url");if(Z.protocol==="https:")return{ok:!0,url:Z};if(Z.protocol==="http:"&&W0.has(Z.hostname.toLowerCase()))return{ok:!0,url:Z};return q("unsupported-protocol")}async function N0(Q,Z,$){let G=wQ(Z.timeoutMs,Z.signal);try{let J=await $(Q.href,{method:"GET",headers:Z.headers,redirect:"error",signal:G.signal});if(!J.ok)return await EQ(J),q("http-error",$Q(J.status));let z=await U0(J,Z.maxResponseBytes);return{ok:!0,status:$Q(J.status)??200,payload:z,transport:"fetch"}}catch(J){if(J instanceof L)return q("response-too-large");if(J instanceof h)return q("invalid-json");if(Z.signal?.aborted)return q("aborted");if(G.didTimeout())return q("timeout");return q("network-error")}finally{G.dispose()}}async function U0(Q,Z){let $=Number(Q.headers?.get("content-length"));if(Number.isFinite($)&&$>Z)throw await EQ(Q),new L;if(Q.body){let G=Q.body.getReader(),J=[],z=0;while(!0){let X=await G.read();if(X.done)break;if(!X.value)continue;if(z+=X.value.byteLength,z>Z)throw await G.cancel?.(),new L;J.push(X.value)}let j=Buffer.concat(J.map((X)=>Buffer.from(X)),z).toString("utf8");return ZQ(j)}if(Q.text){let G=await Q.text();if(Buffer.byteLength(G,"utf8")>Z)throw new L;return ZQ(G)}throw new h}async function EQ(Q){if(!Q.body)return;try{await Q.body.getReader().cancel?.()}catch{}}function SQ(Q,Z){return new Promise(($)=>{let G=wQ(Z.timeoutMs,Z.signal),J=!1,z=null,j=(K)=>{if(J)return;J=!0,G.dispose(),$(K)},X=()=>{z?.destroy(),j(q(Z.signal?.aborted?"aborted":"timeout"))};G.signal.addEventListener("abort",X,{once:!0});try{z=(Q.protocol==="http:"?V0:q0)(Q,{method:"GET",headers:Z.headers,signal:G.signal},(Y)=>B0(Y,Z.maxResponseBytes,j)),z.on("error",()=>{if(Z.signal?.aborted)j(q("aborted"));else if(G.didTimeout())j(q("timeout"));else j(q("network-error"))}),z.end()}catch{j(q("network-error"))}})}function B0(Q,Z,$){let G=$Q(Q.statusCode);if(G===null||G<200||G>=300){Q.resume(),$(q("http-error",G));return}let J=Number(Q.headers["content-length"]);if(Number.isFinite(J)&&J>Z){Q.destroy(),$(q("response-too-large"));return}let z=[],j=0;Q.on("data",(X)=>{let K=Buffer.isBuffer(X)?X:Buffer.from(X);if(j+=K.length,j>Z){Q.destroy(),$(q("response-too-large"));return}z.push(K)}),Q.on("end",()=>{try{let X=ZQ(Buffer.concat(z,j).toString("utf8"));$({ok:!0,status:G,payload:X,transport:"node"})}catch{$(q("invalid-json"))}}),Q.on("error",()=>$(q("network-error")))}function wQ(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 C0(Q,Z){return Q.code==="network-error"||Q.code==="timeout"||Q.code==="invalid-json"||Z&&Q.code==="http-error"}function ZQ(Q){try{return JSON.parse(Q)}catch{throw new h}}function $Q(Q){return typeof Q==="number"&&Number.isInteger(Q)&&Q>=0?Q:null}function q(Q,Z=null){return{ok:!1,code:Q,status:Z}}class L extends Error{}class h extends Error{}function p(Q,Z){switch(Q.code){case"aborted":return U("network.request.aborted","network",`${Z} lookup was cancelled.`);case"http-error":return U("network.response.http","network",Q.status===null?`${Z} endpoint returned an invalid HTTP status.`:`${Z} endpoint returned HTTP ${Q.status}.`);case"invalid-json":return U("network.response.invalid-json","network",`${Z} endpoint returned malformed JSON.`);case"invalid-url":return U("network.endpoint.invalid","network",`${Z} endpoint URL is invalid.`);case"response-too-large":return U("network.response.too-large","network",`${Z} endpoint response was too large.`);case"timeout":return U("network.request.timeout","network",`${Z} lookup timed out.`);case"unsupported-protocol":return U("network.endpoint.protocol","network",`${Z} endpoint must use HTTPS or loopback HTTP.`);case"network-error":return U("network.request.failed","network",`${Z} lookup failed.`)}}var O0=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],T0=["January","February","March","April","May","June","July","August","September","October","November","December"];function c(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),X=G%60,K=[];if(J>0)K.push(`${J}d`);if(z>0)K.push(`${z}h`);if(j>0)K.push(`${j}m`);if($&&X>0)K.push(`${X}s`);return K.length>0?K.join(" "):$?`${X}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 mQ(Q){return`${O0[Q.getDay()]} ${Q.getDate()} ${T0[Q.getMonth()]} ${Q.getFullYear()}`}var hQ=["credits","reset_credits","items"],pQ=["available_count","availableCount","available"],cQ=["total_earned_count","earned_this_period","earnedThisPeriod","totalEarnedCount"];function uQ(Q,Z,$){if(!H(Q)||!x0(Q))return P(Z,["Live reset coupon endpoint returned an unexpected payload."]);let G=F0(Q,hQ);if(G.malformed)return P(Z,["Live reset coupon endpoint returned an unexpected payload."]);let J=G.value,z=J.map((V,M)=>D0(V,M+1,$)).filter((V)=>V!==null).sort(A0).map((V,M)=>({...V,index:M+1})),j=z.find((V)=>V.status?.toLowerCase()==="available")??z[0]??null,X=gQ(Q,pQ),K=gQ(Q,cQ),Y=[];if(J.length!==z.length)Y.push("Live reset coupon endpoint ignored malformed coupon entries.");if(X.malformed||K.malformed)Y.push("Live reset coupon endpoint ignored malformed summary fields.");return{status:Y.length>0?"partial":"available",available:X.value,earnedThisPeriod:K.value,nextExpirationDate:j?.expirationDate??null,nextExpirationIn:j?.expiresIn??null,items:z,warnings:Y,source:{live:!0,label:"live Codex reset-credit endpoint",endpoint:Z}}}function P(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 x0(Q){return[...hQ,...pQ,...cQ].some((Z)=>(Z in Q))}function D0(Q,Z,$){if(!H(Q))return null;let G=B(Q,"expires_at")??B(Q,"expiresAt"),J=B(Q,"granted_at")??B(Q,"grantedAt"),z=F(G),j=F(J),X=B(Q,"status"),K=X&&/^[a-z][a-z0-9_-]{0,63}$/i.test(X)?X:null,Y=j?J:null,V=z?G:null;if(!K&&!Y&&!V)return null;return{index:Z,status:K,grantedAt:Y,expiresAt:V,expirationDate:z?mQ(z):null,expiresIn:z?c(z.getTime()-$.getTime()):null}}function A0(Q,Z){return vQ(Q.expiresAt)-vQ(Z.expiresAt)}function vQ(Q){return F(Q)?.getTime()??Number.POSITIVE_INFINITY}function F0(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 gQ(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 lQ="https://chatgpt.com/backend-api/wham/rate-limit-reset-credits",I0=1e4,b0=1e6;async function rQ(Q={}){let Z=Q.endpoint??lQ,$=_(Z),G=await v(Q);if(!G.credentials){let z=k(G.diagnostics);return k0($,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={endpoint:Z,headers:{Authorization:`Bearer ${G.credentials.accessToken}`,"ChatGPT-Account-ID":G.credentials.accountId,"OpenAI-Beta":"codex-1",originator:"Codex Desktop",Accept:"application/json"},timeoutMs:Q.timeoutMs??I0,maxResponseBytes:b0,...Q.fetch?{fetch:Q.fetch}:{},...Q.signal?{signal:Q.signal}:{}};try{let z=await(Q.transport??g)(J);return z.ok?uQ(z.payload,$,Q.now??new Date):dQ($,z)}catch{return dQ($,{ok:!1,code:"network-error",status:null})}}function k0(Q=lQ,Z=[]){return P(_(Q),Z)}function dQ(Q,Z){return P(Q,k([p(Z,"Live reset coupon")]))}var tQ=5,zQ="5-hour usage limit",jQ="Weekly usage limit",XQ=["fiveHour","five_hour","fiveHourWindow","five_hour_window","primary","primaryWindow","primary_window","main","mainWindow"],KQ=["weekly","week","weeklyWindow","weekly_window","secondary","secondaryWindow","secondary_window","backup","backupWindow"],L0=["used_percent","usedPercent","used","usage","percentUsed","usagePercent","usagePercentage","percent"],_0=["remaining_percent","remainingPercent","remaining","percentRemaining","availablePercent","available_percentage"],P0=["resets_at","resetsAt","resetAt","resetTime","reset_at","reset","ends_at","endsAt","windowEnd"],R0=["resetsIn","resetIn","resets_in","reset_in","timeUntilReset"],y0=["limit_window_seconds","limitWindowSeconds","window_seconds","windowSeconds","window_length_seconds","windowLengthSeconds"],f0=["window_minutes","windowMinutes","window_length_minutes","windowLengthMinutes"],S0=18000,E0=604800;function aQ(Q,Z=new Date){let $=Q.latestSnapshot;if(!$)return VQ(Q.warnings);return l(YQ($.rateLimits,Z),Q.warnings)}function YQ(Q,Z=new Date){return GZ(u(Q,XQ),u(Q,KQ),Z)}function eQ(Q){return u(Q,XQ)!==null||u(Q,KQ)!==null}function R(Q){let Z=sQ(I(Q,y0,!1)),$=sQ(I(Q,f0,!1)),G=Z??($===null?null:$*60);if(G===S0)return"fiveHour";if(G===E0)return"weekly";return null}function QZ(Q,Z){return{...Q,source:Z}}function HQ(Q,Z,$=[]){return{...l(Q,$),source:Z}}function ZZ(Q,Z=new Date){let $={fiveHour:null,weekly:null};for(let G of Q.files){if(!G.json)continue;let J=w0(G.json,Z);$=JZ($,J.windows)}return l($,Q.warnings)}function VQ(Q=[]){return{status:"unavailable",windows:{fiveHour:null,weekly:null},warnings:Q}}function $Z(Q,Z){let $=JZ(Q.windows,Z.windows);return l($,[...Q.warnings,...Z.warnings])}function w0(Q,Z){if(!H(Q))return{windows:{fiveHour:null,weekly:null}};let $=JQ(Q,XQ),G=JQ(Q,KQ);if($||G)return{windows:GZ($,G,Z)};let J=R(Q)??"fiveHour",z=GQ(Q,J==="weekly"?jQ:zQ,Z);return{windows:{fiveHour:J==="fiveHour"?z:null,weekly:J==="weekly"?z:null}}}function GZ(Q,Z,$){let G=[];if(Q)G.push({fallbackKind:"fiveHour",value:Q});if(Z)G.push({fallbackKind:"weekly",value:Z});return{fiveHour:GQ(oQ(G,"fiveHour"),zQ,$),weekly:GQ(oQ(G,"weekly"),jQ,$)}}function GQ(Q,Z,$){if(!Q)return null;let G=nQ(I(Q,L0,!0)),J=nQ(I(Q,_0,!0)),z=G??(J===null?null:d(100-J)),j=J??(G===null?null:d(100-G)),X=I(Q,P0,!0),K=F(X),Y=K?K.toISOString():null,V=g0(I(Q,R0,!0)),M=K?c(K.getTime()-$.getTime()):V&&V.length<=100?A(V):null,O={label:Z,remainingPercent:j,usedPercent:z,resetsAt:Y,resetsIn:M};return zZ(O)?O:null}function l(Q,Z){return{status:m0(Q),windows:Q,warnings:Z}}function m0(Q){let Z=[Q.fiveHour,Q.weekly].filter(($)=>zZ($));if(Z.length===0)return"unavailable";return Z.every(v0)?"available":"partial"}function oQ(Q,Z){let $=Q.find((G)=>R(G.value)===Z);if($)return $.value;return Q.find((G)=>G.fallbackKind===Z&&R(G.value)===null)?.value??null}function JZ(Q,Z){return{fiveHour:iQ(Q.fiveHour,Z.fiveHour,zQ),weekly:iQ(Q.weekly,Z.weekly,jQ)}}function iQ(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 zZ(Q){return Q!==null&&(Q.remainingPercent!==null||Q.usedPercent!==null||Q.resetsAt!==null||Q.resetsIn!==null)}function v0(Q){return Q!==null&&Q.remainingPercent!==null&&Q.usedPercent!==null&&(Q.resetsAt!==null||Q.resetsIn!==null)}function JQ(Q,Z,$=0){if($>tQ)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=JQ(G,Z,$+1);if(J)return J}return null}function u(Q,Z){for(let $ of Z){let G=Q[$];if(H(G))return G}return null}function I(Q,Z,$,G=0){if(G>tQ)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 nQ(Q){if(typeof Q==="number"&&Number.isFinite(Q))return d(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)?d(G):null}return null}function d(Q){return Math.round(Math.min(Math.max(Q,0),100)*10)/10}function sQ(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 g0(Q){if(typeof Q==="string"&&Q.trim().length>0)return Q.trim();return null}var h0=5,p0=1000,c0={kind:"unavailable",label:"Unavailable"};function XZ(Q,Z,$){let G=u0(Q)??d0(Q);if(!G)return y(["Live usage endpoint returned an unexpected payload."]);let J=HQ(YQ(G,$),{kind:"api",label:"API",endpoint:Z});if(J.status==="unavailable")return y(["Live usage endpoint returned an unexpected payload."]);if(J.status==="partial")return{...J,warnings:["Live usage endpoint returned incomplete usage data."]};return J}function y(Q){return HQ({fiveHour:null,weekly:null},c0,Q)}function u0(Q){return KZ(Q,(Z)=>{if(!H(Z))return null;let $=Z.rate_limits??Z.rateLimits??Z.rate_limit??Z.rateLimit;if(H($))return $;return eQ(Z)?Z:null})}function d0(Q){return KZ(Q,(Z)=>{if(!Array.isArray(Z))return null;let $=Z.find((J)=>jZ(J,"fiveHour")),G=Z.find((J)=>jZ(J,"weekly"));return $||G?{fiveHour:$,weekly:G}:null})}function KZ(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>=h0||typeof z.value!=="object"||!z.value)continue;if(G.has(z.value))continue;G.add(z.value);let X=Array.isArray(z.value)?z.value:H(z.value)?Object.values(z.value):[];for(let K of X){if($.length>=p0)break;$.push({value:K,depth:z.depth+1})}}return null}function jZ(Q,Z){if(!H(Q))return!1;let $=R(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 l0="https://chatgpt.com/backend-api/codex/usage",r0=1e4,o0=1e6;async function YZ(Q={}){return(await i0(Q)).usage}async function i0(Q={}){let Z=s0(Q),$=_(Z),G=await v(Q);if(!G.credentials){let j=k(G.diagnostics);return{usage:y(j.length>0?j:["Live usage requires Codex authentication."]),authenticationFound:!1,endpointStatus:"not-checked"}}let J={endpoint:Z,headers:n0(G.credentials),timeoutMs:Q.timeoutMs??r0,maxResponseBytes:o0,fallbackOnHttpError:!0,...Q.fetch?{fetch:Q.fetch}:{},...Q.signal?{signal:Q.signal}:{}},z;try{z=await(Q.transport??g)(J)}catch{z={ok:!1,code:"network-error",status:null}}return{usage:z.ok?XZ(z.payload,$,Q.now??new Date):a0(z),authenticationFound:!0,endpointStatus:t0(z)}}function n0(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 s0(Q){let Z=D(Q.env);return Q.usageEndpoint??N(Z,"CODEX_LIMITS_USAGE_ENDPOINT")??l0}function t0(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 a0(Q){return y(k([p(Q,"Live usage")]))}var e0={kind:"local",label:"Local"};async function HZ(Q={}){let Z=await Q1(Q),$=Q.includeCoupons===!1?null:await rQ(Q),G=$?{...$,warnings:o($.warnings)}:null;return{windows:Z.windows,usageSource:Z.source,coupons:G,warnings:o([...Z.warnings,...G?.warnings??[]])}}async function Q1(Q={}){let Z=await YZ(Q);if(Z.status!=="unavailable")return Z;let $=QZ(await $1(Q),e0);return Z1(Z,$)}function Z1(Q,Z){if(Q.status!=="unavailable")return Q;if(Z.status!=="unavailable")return Z;return{...Z,warnings:[...Q.warnings,...Z.warnings]}}async function $1(Q={}){let Z=Q.now??new Date,$=await E(Q);if(!$.foundHome)return VQ(["No readable local Codex home directory was found."]);let[G,J]=await Promise.all([kQ($.foundHome),yQ($.foundHome)]);return $Z(aQ(G,Z),ZZ(J,Z))}var J1="Codex Limits",qZ="Could not load Codex limits.",z1="Could not display Codex limits.";function j1(Q={}){let Z=Q.getLimits??HZ;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=BQ(await Z())}catch{z=qZ,J.ui.notify(qZ,"error")}finally{J.ui.setStatus("codex-limits",void 0)}try{await X1(z,J)}catch{J.ui.notify(z1,"error")}}})}}async function X1(Q,Z){await Z.ui.custom(($,G,J,z)=>{let j=WZ(Q,G);return{render:(X)=>j.render(X),invalidate:()=>{j=WZ(Q,G)},handleInput:(X)=>{if(qQ(X,"enter")||qQ(X,"escape")||qQ(X,"ctrl+c"))z(void 0)}}},{overlay:!0,overlayOptions:{width:56,minWidth:36,maxHeight:"90%",margin:1}})}function WZ(Q,Z){let $=new G1;return $.addChild(new VZ((G)=>Z.fg("accent",G))),$.addChild(new WQ(Z.fg("accent",Z.bold(J1)),1,0)),$.addChild(new WQ(Q,1,1)),$.addChild(new WQ(Z.fg("dim","Press Enter or Esc to close"),1,0)),$.addChild(new VZ((G)=>Z.fg("accent",G))),$}var K1=j1(),w2=K1;export{w2 as default,j1 as createPiPlugin};
@@ -0,0 +1,34 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 852 132" role="img" aria-labelledby="title description">
2
+ <title id="title">Codex Limits</title>
3
+ <desc id="description">An animated terminal-style Codex Limits title</desc>
4
+ <style>
5
+ .title {
6
+ fill: #24292f;
7
+ font-family: "Fira Code", "Cascadia Code", "SFMono-Regular", Consolas, "Liberation Mono", monospace;
8
+ font-size: 16px;
9
+ font-weight: 600;
10
+ white-space: pre;
11
+ }
12
+
13
+ @media (prefers-color-scheme: dark) {
14
+ .title {
15
+ fill: #f0f6fc;
16
+ }
17
+ }
18
+ </style>
19
+ <defs>
20
+ <clipPath id="typing-mask">
21
+ <rect x="0" y="0" width="0" height="132">
22
+ <animate attributeName="width" values="0;852;852;0" keyTimes="0;0.55;0.92;1" dur="6s" repeatCount="indefinite" />
23
+ </rect>
24
+ </clipPath>
25
+ </defs>
26
+ <g clip-path="url(#typing-mask)">
27
+ <text class="title" x="8" y="20" xml:space="preserve"> ██████╗ ██████╗ ██████╗ ███████╗██╗ ██╗ ██╗ ██╗███╗ ███╗██╗████████╗███████╗</text>
28
+ <text class="title" x="8" y="40" xml:space="preserve">██╔════╝██╔═══██╗██╔══██╗██╔════╝╚██╗██╔╝ ██║ ██║████╗ ████║██║╚══██╔══╝██╔════╝</text>
29
+ <text class="title" x="8" y="60" xml:space="preserve">██║ ██║ ██║██║ ██║█████╗ ╚███╔╝ ██║ ██║██╔████╔██║██║ ██║ ███████╗</text>
30
+ <text class="title" x="8" y="80" xml:space="preserve">██║ ██║ ██║██║ ██║██╔══╝ ██╔██╗ ██║ ██║██║╚██╔╝██║██║ ██║ ╚════██║</text>
31
+ <text class="title" x="8" y="100" xml:space="preserve">╚██████╗╚██████╔╝██████╔╝███████╗██╔╝ ██╗ ███████╗██║██║ ╚═╝ ██║██║ ██║ ███████║</text>
32
+ <text class="title" x="8" y="120" xml:space="preserve"> ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚══════╝╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝</text>
33
+ </g>
34
+ </svg>
package/package.json CHANGED
@@ -1,11 +1,16 @@
1
1
  {
2
2
  "name": "@simonesiega/codex-limits",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "Check Codex usage limits, reset times, and reset-credit coupons from a fast, read-only terminal dashboard.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "codex-limits": "dist/cli.js"
8
8
  },
9
+ "pi": {
10
+ "extensions": [
11
+ "./dist/pi.js"
12
+ ]
13
+ },
9
14
  "exports": {
10
15
  ".": {
11
16
  "types": "./types/index.d.ts",
@@ -29,10 +34,13 @@
29
34
  "build": "bun run scripts/build.ts",
30
35
  "format": "prettier --write .",
31
36
  "format:check": "prettier --check .",
37
+ "docs:link": "bun run scripts/check-doc-links.ts",
38
+ "docs:schema": "bun run scripts/check-doc-schema.ts",
39
+ "docs:check": "bun run docs:link && bun run docs:schema",
32
40
  "typecheck": "tsc --noEmit",
33
41
  "test": "bun test",
34
42
  "package:validate": "bun run scripts/validate-package.ts",
35
- "check": "bun run format:check && bun run typecheck && bun test && bun run build && bun run package:validate",
43
+ "check": "bun run format:check && bun run docs:check && bun run typecheck && bun test && bun run build && bun run package:validate",
36
44
  "prepack": "bun run build",
37
45
  "postinstall": "node ./scripts/postinstall.cjs"
38
46
  },
@@ -46,7 +54,8 @@
46
54
  "npm",
47
55
  "developer-tools",
48
56
  "rate-limits",
49
- "usage-tracker"
57
+ "usage-tracker",
58
+ "pi-package"
50
59
  ],
51
60
  "author": "Simone Siega",
52
61
  "license": "MIT",
@@ -62,16 +71,36 @@
62
71
  "node": ">=20"
63
72
  },
64
73
  "packageManager": "bun@1.3.14",
74
+ "overrides": {
75
+ "fast-uri": "3.1.4"
76
+ },
77
+ "peerDependencies": {
78
+ "@earendil-works/pi-coding-agent": "*",
79
+ "@earendil-works/pi-tui": "*"
80
+ },
81
+ "peerDependenciesMeta": {
82
+ "@earendil-works/pi-coding-agent": {
83
+ "optional": true
84
+ },
85
+ "@earendil-works/pi-tui": {
86
+ "optional": true
87
+ }
88
+ },
65
89
  "devDependencies": {
66
- "@opencode-ai/plugin": "^1.15.4",
67
- "@types/node": "^22.10.2",
90
+ "@earendil-works/pi-coding-agent": "^0.81.1",
91
+ "@earendil-works/pi-tui": "^0.81.1",
92
+ "@opencode-ai/plugin": "^1.18.4",
93
+ "@types/node": "^22.20.1",
68
94
  "@types/react": "^19.2.17",
69
- "bun-types": "^1.1.42",
70
- "ink": "^7.1.0",
95
+ "ajv": "^8.20.0",
96
+ "ajv-formats": "^3.0.1",
97
+ "bun-types": "^1.3.14",
98
+ "ink": "^6.8.0",
71
99
  "ink-testing-library": "^4.0.0",
72
- "prettier": "^3.9.4",
73
- "prettier-plugin-tailwindcss": "^0.8.0",
74
- "react": "^19.2.7",
75
- "typescript": "^5.7.2"
100
+ "prettier": "^3.9.6",
101
+ "prettier-plugin-tailwindcss": "^0.8.1",
102
+ "react": "^19.2.8",
103
+ "react-devtools-core": "^7.0.1",
104
+ "typescript": "^5.9.3"
76
105
  }
77
106
  }
@@ -17,6 +17,6 @@ const skip =
17
17
 
18
18
  if (!skip && isGlobalInstall) {
19
19
  process.stdout.write(
20
- "codex-limits: installed. Run `codex-limits init` to install optional agent integrations.\n"
20
+ "codex-limits: installed. Run `codex-limits agents install` to install optional agent integrations.\n"
21
21
  );
22
22
  }