Usage Caching Mechanism
Usage Caching Mechanism
To ensure your terminal remains responsive, the generated script employs a local caching strategy for Anthropic API usage data. Without caching, the statusline would attempt to query the network every time you run a command, leading to noticeable "lag" in your prompt.
How it Works
The script monitors your 5-hour and Weekly usage limits by communicating with api.anthropic.com. To balance real-time accuracy with performance, the following logic is applied:
- Cache Duration: Usage data is cached for 2 minutes (120 seconds).
- Lookup Logic: Every time the statusline renders, the script checks the timestamp of the local cache file.
- If the cache is less than 2 minutes old, the script reads the data directly from the disk (near-instant).
- If the cache is older than 2 minutes, the script performs a network fetch to update the values.
- Network Timeout: API calls are wrapped in a 5-second timeout to prevent the terminal from hanging if you have a poor internet connection.
Cache Storage
The data is stored in a standard JSON format in your home directory:
~/.claude/.usage-cache.json
The script automatically sets strict file permissions (umask 077) when creating this file to ensure that your usage statistics remain private to your system user.
Manual Refresh
If you need to force an immediate update of your usage statistics (for example, after a known heavy session), you can simply delete the cache file. The statusline will refresh the data on the very next prompt:
rm ~/.claude/.usage-cache.json
Security and Credentials
The caching mechanism does not store your actual API credentials in the cache file. Instead, it securely retrieves your accessToken from your OS-specific credential manager (macOS Keychain, Linux libsecret, or Windows Credential Manager) only when a network refresh is required.
Requirements for Caching
For the caching and rate-limiting blocks to function correctly, ensure your environment has the following available:
- jq: Used to parse the cached JSON data.
- python3: Used to calculate the countdown timers and percentage logic.
- Platform-specific tools:
libsecret-tools(Linux) orCredentialManager(Windows) to allow the script to authorize the refresh requests.