Skip to content

Commit 5f01d55

Browse files
committed
feat!: replace environment variables with statusline CLI options for context thresholds
BREAKING CHANGE: Environment variables `CCUSAGE_CONTEXT_LOW_THRESHOLD` and `CCUSAGE_CONTEXT_MEDIUM_THRESHOLD` are no longer supported. Use CLI options `--context-low-threshold` and `--context-medium-threshold` instead. - Add `--context-low-threshold` and `--context-medium-threshold` options to statusline command - Implement zod validation for threshold values (0-100 range, integer, LOW < MEDIUM constraint) - Remove `getContextUsageThresholds()` function and related environment variable constants - Update documentation to reflect CLI option usage and configuration file support - Remove environment variable tests and validation logic - Update JSON schema to include new statusline options - Maintain backward compatibility through default values (50/80) Migration guide: - Old: `export CCUSAGE_CONTEXT_LOW_THRESHOLD=60` - New: `--context-low-threshold 60` - Configuration files also supported for persistent settings
1 parent 55947da commit 5f01d55

5 files changed

Lines changed: 61 additions & 185 deletions

File tree

‎config-schema.json‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -745,6 +745,18 @@
745745
"markdownDescription": "Refresh interval in seconds for cache expiry (default: 1)",
746746
"default": 1
747747
},
748+
"contextLowThreshold": {
749+
"type": "string",
750+
"description": "Context usage percentage below which status is shown in green (0-100)",
751+
"markdownDescription": "Context usage percentage below which status is shown in green (0-100)",
752+
"default": 50
753+
},
754+
"contextMediumThreshold": {
755+
"type": "string",
756+
"description": "Context usage percentage below which status is shown in yellow (0-100)",
757+
"markdownDescription": "Context usage percentage below which status is shown in yellow (0-100)",
758+
"default": 80
759+
},
748760
"debug": {
749761
"type": "boolean",
750762
"description": "Show pricing mismatch information for debugging",

‎docs/guide/statusline.md‎

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -183,37 +183,37 @@ bun x ccusage statusline --cost-source both
183183

184184
## Configuration
185185

186-
### Environment Variables
186+
### Context Usage Thresholds
187187

188-
You can customize the context usage color thresholds using environment variables:
188+
You can customize the context usage color thresholds using command-line options or configuration files:
189189

190-
- `CCUSAGE_CONTEXT_LOW_THRESHOLD` - Percentage below which context usage is shown in green (default: 50)
191-
- `CCUSAGE_CONTEXT_MEDIUM_THRESHOLD` - Percentage below which context usage is shown in yellow (default: 80)
190+
- `--context-low-threshold` - Percentage below which context usage is shown in green (default: 50)
191+
- `--context-medium-threshold` - Percentage below which context usage is shown in yellow (default: 80)
192192

193193
**Validation and Safety Features:**
194-
- Values are automatically clamped to the 0-100 range
195-
- Non-numeric values fall back to defaults
196-
- The `LOW` threshold must be less than the `MEDIUM` threshold; if not, both reset to defaults
197-
- Invalid configurations gracefully fall back to safe defaults (50% and 80%)
194+
- Values are automatically validated to be integers in the 0-100 range
195+
- The `LOW` threshold must be less than the `MEDIUM` threshold
196+
- Invalid configurations will show clear error messages
198197

199-
For example:
198+
**Command-line usage:**
200199
```bash
201-
export CCUSAGE_CONTEXT_LOW_THRESHOLD=60
202-
export CCUSAGE_CONTEXT_MEDIUM_THRESHOLD=90
200+
bun x ccusage statusline --context-low-threshold 60 --context-medium-threshold 90
203201
```
204202

203+
**Configuration file usage:**
204+
You can also set these options in your configuration file. See the [Configuration Guide](/guide/configuration) for more details.
205+
205206
With these settings:
206207
- Green: < 60%
207208
- Yellow: 60-90%
208209
- Red: > 90%
209210

210-
**Invalid Configuration Examples:**
211-
```bash
212-
# These will all fall back to defaults (50/80)
213-
export CCUSAGE_CONTEXT_LOW_THRESHOLD=invalid # Non-numeric
214-
export CCUSAGE_CONTEXT_MEDIUM_THRESHOLD=150 # Clamped to 100, then reset due to ordering
215-
export CCUSAGE_CONTEXT_LOW_THRESHOLD=90 # Would be >= MEDIUM (80), so both reset
216-
export CCUSAGE_CONTEXT_MEDIUM_THRESHOLD=30 # Would be <= LOW (50), so both reset
211+
**Example usage in Claude Code settings:**
212+
```json
213+
{
214+
"command": "bun x ccusage statusline --context-low-threshold 60 --context-medium-threshold 90",
215+
"timeout": 5000
216+
}
217217
```
218218

219219
### Visual Burn Rate

‎src/_consts.ts‎

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -126,16 +126,6 @@ export const DEFAULT_CONTEXT_USAGE_THRESHOLDS = {
126126
// Above 80% - red
127127
} as const;
128128

129-
/**
130-
* Environment variable name for configuring context usage low threshold
131-
*/
132-
export const CONTEXT_LOW_THRESHOLD_ENV = 'CCUSAGE_CONTEXT_LOW_THRESHOLD';
133-
134-
/**
135-
* Environment variable name for configuring context usage medium threshold
136-
*/
137-
export const CONTEXT_MEDIUM_THRESHOLD_ENV = 'CCUSAGE_CONTEXT_MEDIUM_THRESHOLD';
138-
139129
/**
140130
* Days of the week for weekly aggregation
141131
*/

‎src/commands/statusline.ts‎

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,15 @@ import { createLimoJson } from '@ryoppippi/limo';
88
import getStdin from 'get-stdin';
99
import { define } from 'gunshi';
1010
import pc from 'picocolors';
11+
import { z } from 'zod';
1112
import { loadConfig, mergeConfigWithArgs } from '../_config-loader-tokens.ts';
12-
import { DEFAULT_REFRESH_INTERVAL_SECONDS } from '../_consts.ts';
13+
import { DEFAULT_CONTEXT_USAGE_THRESHOLDS, DEFAULT_REFRESH_INTERVAL_SECONDS } from '../_consts.ts';
1314
import { calculateBurnRate } from '../_session-blocks.ts';
1415
import { sharedArgs } from '../_shared-args.ts';
1516
import { statuslineHookJsonSchema } from '../_types.ts';
1617
import { formatCurrency, getFileModifiedTime } from '../_utils.ts';
1718
import { calculateTotals } from '../calculate-cost.ts';
18-
import { calculateContextTokens, getContextUsageThresholds, loadDailyUsageData, loadSessionBlockData, loadSessionUsageById } from '../data-loader.ts';
19+
import { calculateContextTokens, loadDailyUsageData, loadSessionBlockData, loadSessionUsageById } from '../data-loader.ts';
1920
import { log, logger } from '../logger.ts';
2021

2122
/**
@@ -72,6 +73,9 @@ type SemaphoreType = {
7273
const visualBurnRateChoices = ['off', 'emoji', 'text', 'emoji-text'] as const;
7374
const costSourceChoices = ['auto', 'ccusage', 'cc', 'both'] as const;
7475

76+
// Zod schema for context threshold validation
77+
const contextThresholdSchema = z.coerce.number().int().min(0, 'Context threshold must be at least 0').max(100, 'Context threshold must be at most 100');
78+
7579
export const statuslineCommand = define({
7680
name: 'statusline',
7781
description: 'Display compact status line for Claude Code hooks with hybrid time+file caching (Beta)',
@@ -108,13 +112,30 @@ export const statuslineCommand = define({
108112
description: `Refresh interval in seconds for cache expiry (default: ${DEFAULT_REFRESH_INTERVAL_SECONDS})`,
109113
default: DEFAULT_REFRESH_INTERVAL_SECONDS,
110114
},
115+
contextLowThreshold: {
116+
type: 'custom',
117+
description: 'Context usage percentage below which status is shown in green (0-100)',
118+
parse: (value: string) => contextThresholdSchema.parse(value),
119+
default: DEFAULT_CONTEXT_USAGE_THRESHOLDS.LOW,
120+
},
121+
contextMediumThreshold: {
122+
type: 'custom',
123+
description: 'Context usage percentage below which status is shown in yellow (0-100)',
124+
parse: (value: string) => contextThresholdSchema.parse(value),
125+
default: DEFAULT_CONTEXT_USAGE_THRESHOLDS.MEDIUM,
126+
},
111127
config: sharedArgs.config,
112128
debug: sharedArgs.debug,
113129
},
114130
async run(ctx) {
115131
// Set logger to silent for statusline output
116132
logger.level = 0;
117133

134+
// Validate threshold ordering constraint: LOW must be less than MEDIUM
135+
if (ctx.values.contextLowThreshold >= ctx.values.contextMediumThreshold) {
136+
throw new Error(`Context low threshold (${ctx.values.contextLowThreshold}) must be less than medium threshold (${ctx.values.contextMediumThreshold})`);
137+
}
138+
118139
// Load configuration and merge with CLI args
119140
const config = loadConfig(ctx.values.config, ctx.values.debug);
120141
const mergedOptions = mergeConfigWithArgs(ctx, config, ctx.values.debug);
@@ -392,21 +413,20 @@ export const statuslineCommand = define({
392413
catch: error => error,
393414
}),
394415
Result.inspectError(error => logger.debug(`Failed to calculate context tokens: ${error instanceof Error ? error.message : String(error)}`)),
395-
Result.map((ctx) => {
396-
if (ctx == null) {
416+
Result.map((contextResult) => {
417+
if (contextResult == null) {
397418
return undefined;
398419
}
399-
// Format context percentage with color coding using configurable thresholds
400-
const thresholds = getContextUsageThresholds();
401-
const color = ctx.percentage < thresholds.LOW
420+
// Format context percentage with color coding using option thresholds
421+
const color = contextResult.percentage < ctx.values.contextLowThreshold
402422
? pc.green
403-
: ctx.percentage < thresholds.MEDIUM
423+
: contextResult.percentage < ctx.values.contextMediumThreshold
404424
? pc.yellow
405425
: pc.red;
406-
const coloredPercentage = color(`${ctx.percentage}%`);
426+
const coloredPercentage = color(`${contextResult.percentage}%`);
407427

408428
// Format token count with thousand separators
409-
const tokenDisplay = ctx.inputTokens.toLocaleString();
429+
const tokenDisplay = contextResult.inputTokens.toLocaleString();
410430
return `${tokenDisplay} (${coloredPercentage})`;
411431
}),
412432
Result.unwrap(undefined),

‎src/data-loader.ts‎

Lines changed: 1 addition & 147 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ import { createFixture } from 'fs-fixture';
3232
import { isDirectorySync } from 'path-type';
3333
import { glob } from 'tinyglobby';
3434
import { z } from 'zod';
35-
import { CLAUDE_CONFIG_DIR_ENV, CLAUDE_PROJECTS_DIR_NAME, CONTEXT_LOW_THRESHOLD_ENV, CONTEXT_MEDIUM_THRESHOLD_ENV, DEFAULT_CLAUDE_CODE_PATH, DEFAULT_CLAUDE_CONFIG_PATH, DEFAULT_CONTEXT_USAGE_THRESHOLDS, USAGE_DATA_GLOB_PATTERN, USER_HOME_DIR } from './_consts.ts';
35+
import { CLAUDE_CONFIG_DIR_ENV, CLAUDE_PROJECTS_DIR_NAME, DEFAULT_CLAUDE_CODE_PATH, DEFAULT_CLAUDE_CONFIG_PATH, USAGE_DATA_GLOB_PATTERN, USER_HOME_DIR } from './_consts.ts';
3636
import {
3737
identifySessionBlocks,
3838
} from './_session-blocks.ts';
@@ -133,48 +133,6 @@ export function getClaudePaths(): string[] {
133133
return paths;
134134
}
135135

136-
/**
137-
* Get context usage percentage thresholds for color coding
138-
* Can be configured via environment variables or uses defaults
139-
* Validates and clamps values to 0-100 range and enforces LOW < MEDIUM ordering
140-
* @returns Context usage thresholds with LOW and MEDIUM percentages
141-
*/
142-
export function getContextUsageThresholds(): { readonly LOW: number; readonly MEDIUM: number } {
143-
// Parse and validate environment variables
144-
const lowThresholdStr = process.env[CONTEXT_LOW_THRESHOLD_ENV];
145-
const mediumThresholdStr = process.env[CONTEXT_MEDIUM_THRESHOLD_ENV];
146-
147-
// Parse with validation - use defaults for invalid values
148-
let lowThreshold: number = DEFAULT_CONTEXT_USAGE_THRESHOLDS.LOW;
149-
let mediumThreshold: number = DEFAULT_CONTEXT_USAGE_THRESHOLDS.MEDIUM;
150-
151-
if (lowThresholdStr != null) {
152-
const parsed = Number.parseInt(lowThresholdStr, 10);
153-
if (!Number.isNaN(parsed)) {
154-
lowThreshold = Math.max(0, Math.min(100, parsed)); // Clamp to 0-100
155-
}
156-
}
157-
158-
if (mediumThresholdStr != null) {
159-
const parsed = Number.parseInt(mediumThresholdStr, 10);
160-
if (!Number.isNaN(parsed)) {
161-
mediumThreshold = Math.max(0, Math.min(100, parsed)); // Clamp to 0-100
162-
}
163-
}
164-
165-
// Enforce ordering: LOW must be less than MEDIUM
166-
// If ordering is violated, reset both to defaults
167-
if (lowThreshold >= mediumThreshold) {
168-
lowThreshold = DEFAULT_CONTEXT_USAGE_THRESHOLDS.LOW;
169-
mediumThreshold = DEFAULT_CONTEXT_USAGE_THRESHOLDS.MEDIUM;
170-
}
171-
172-
return {
173-
LOW: lowThreshold,
174-
MEDIUM: mediumThreshold,
175-
} as const;
176-
}
177-
178136
/**
179137
* Extract project name from Claude JSONL file path
180138
* @param jsonlPath - Absolute path to JSONL file
@@ -4775,108 +4733,4 @@ if (import.meta.vitest != null) {
47754733
expect(res?.percentage).toBe(100); // Should be clamped to 100
47764734
});
47774735
});
4778-
4779-
describe('getContextUsageThresholds', () => {
4780-
afterEach(() => {
4781-
vi.unstubAllEnvs();
4782-
});
4783-
4784-
it('returns default values when no environment variables are set', () => {
4785-
const thresholds = getContextUsageThresholds();
4786-
expect(thresholds.LOW).toBe(50);
4787-
expect(thresholds.MEDIUM).toBe(80);
4788-
});
4789-
4790-
it('parses valid environment variables correctly', () => {
4791-
vi.stubEnv('CCUSAGE_CONTEXT_LOW_THRESHOLD', '30');
4792-
vi.stubEnv('CCUSAGE_CONTEXT_MEDIUM_THRESHOLD', '70');
4793-
4794-
const thresholds = getContextUsageThresholds();
4795-
expect(thresholds.LOW).toBe(30);
4796-
expect(thresholds.MEDIUM).toBe(70);
4797-
});
4798-
4799-
it('clamps values to 0-100 range', () => {
4800-
vi.stubEnv('CCUSAGE_CONTEXT_LOW_THRESHOLD', '-10');
4801-
vi.stubEnv('CCUSAGE_CONTEXT_MEDIUM_THRESHOLD', '150');
4802-
4803-
const thresholds = getContextUsageThresholds();
4804-
expect(thresholds.LOW).toBe(0);
4805-
expect(thresholds.MEDIUM).toBe(100);
4806-
});
4807-
4808-
it('handles non-numeric values by falling back to defaults', () => {
4809-
vi.stubEnv('CCUSAGE_CONTEXT_LOW_THRESHOLD', 'invalid');
4810-
vi.stubEnv('CCUSAGE_CONTEXT_MEDIUM_THRESHOLD', 'not-a-number');
4811-
4812-
const thresholds = getContextUsageThresholds();
4813-
expect(thresholds.LOW).toBe(50);
4814-
expect(thresholds.MEDIUM).toBe(80);
4815-
});
4816-
4817-
it('handles empty string values by falling back to defaults', () => {
4818-
vi.stubEnv('CCUSAGE_CONTEXT_LOW_THRESHOLD', '');
4819-
vi.stubEnv('CCUSAGE_CONTEXT_MEDIUM_THRESHOLD', '');
4820-
4821-
const thresholds = getContextUsageThresholds();
4822-
expect(thresholds.LOW).toBe(50);
4823-
expect(thresholds.MEDIUM).toBe(80);
4824-
});
4825-
4826-
it('handles partial invalid values correctly', () => {
4827-
vi.stubEnv('CCUSAGE_CONTEXT_LOW_THRESHOLD', '25');
4828-
vi.stubEnv('CCUSAGE_CONTEXT_MEDIUM_THRESHOLD', 'invalid');
4829-
4830-
const thresholds = getContextUsageThresholds();
4831-
expect(thresholds.LOW).toBe(25);
4832-
expect(thresholds.MEDIUM).toBe(80); // Falls back to default
4833-
});
4834-
4835-
it('enforces ordering constraint: resets to defaults when LOW >= MEDIUM', () => {
4836-
vi.stubEnv('CCUSAGE_CONTEXT_LOW_THRESHOLD', '85');
4837-
vi.stubEnv('CCUSAGE_CONTEXT_MEDIUM_THRESHOLD', '60');
4838-
4839-
const thresholds = getContextUsageThresholds();
4840-
// Should reset both to defaults due to ordering violation
4841-
expect(thresholds.LOW).toBe(50);
4842-
expect(thresholds.MEDIUM).toBe(80);
4843-
});
4844-
4845-
it('enforces ordering constraint: resets to defaults when LOW equals MEDIUM', () => {
4846-
vi.stubEnv('CCUSAGE_CONTEXT_LOW_THRESHOLD', '70');
4847-
vi.stubEnv('CCUSAGE_CONTEXT_MEDIUM_THRESHOLD', '70');
4848-
4849-
const thresholds = getContextUsageThresholds();
4850-
// Should reset both to defaults due to ordering violation
4851-
expect(thresholds.LOW).toBe(50);
4852-
expect(thresholds.MEDIUM).toBe(80);
4853-
});
4854-
4855-
it('handles edge case: LOW=0, MEDIUM=100', () => {
4856-
vi.stubEnv('CCUSAGE_CONTEXT_LOW_THRESHOLD', '0');
4857-
vi.stubEnv('CCUSAGE_CONTEXT_MEDIUM_THRESHOLD', '100');
4858-
4859-
const thresholds = getContextUsageThresholds();
4860-
expect(thresholds.LOW).toBe(0);
4861-
expect(thresholds.MEDIUM).toBe(100);
4862-
});
4863-
4864-
it('handles decimal values by truncating to integer', () => {
4865-
vi.stubEnv('CCUSAGE_CONTEXT_LOW_THRESHOLD', '25.7');
4866-
vi.stubEnv('CCUSAGE_CONTEXT_MEDIUM_THRESHOLD', '75.9');
4867-
4868-
const thresholds = getContextUsageThresholds();
4869-
expect(thresholds.LOW).toBe(25); // parseInt truncates
4870-
expect(thresholds.MEDIUM).toBe(75); // parseInt truncates
4871-
});
4872-
4873-
it('handles values with extra whitespace', () => {
4874-
vi.stubEnv('CCUSAGE_CONTEXT_LOW_THRESHOLD', ' 30 ');
4875-
vi.stubEnv('CCUSAGE_CONTEXT_MEDIUM_THRESHOLD', ' 70 ');
4876-
4877-
const thresholds = getContextUsageThresholds();
4878-
expect(thresholds.LOW).toBe(30);
4879-
expect(thresholds.MEDIUM).toBe(70);
4880-
});
4881-
});
48824736
}

0 commit comments

Comments
 (0)