Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ Options:
--json machine-readable output (schemaVersion 2)
--since <date> include sessions starting on or after YYYY-MM-DD (UTC),
or a relative duration: 7d (last 7 days) or 2w (last 2 weeks)
--until <date> include sessions through the end of YYYY-MM-DD (UTC),
or the day resolved from 7d or 2w (same as --since)
--html [file] shareable single-file HTML report (default: tokenbill-report.html)
--md [file] GitHub Markdown report to stdout or a .md file (PR comments, job summaries)
--top <n> number of expensive turns to show (default 10)
Expand Down Expand Up @@ -185,6 +187,19 @@ npx tokenbill --since 7d # today and the previous 6 days
npx tokenbill --since 2w # today and the previous 13 days
```

Use `--until` to include sessions starting through the end of a UTC day:

```bash
npx tokenbill --since 2026-09-01 --until 2026-09-30 # all of September
npx tokenbill --all --until 2026-09-30 --json
```

`--until` accepts the same date forms as `--since`. For example, `--until 7d`
ends on the UTC day six days before today, including that entire day. An end
date before `--since` is an error; equal dates select one full day.
With `card --plan`, the plan fee ends on `--until` too. If `--since` is omitted,
the default 30-day comparison ends on that day.

This includes each matching session in full, even if it spans multiple days.
Sessions without a recorded start time are excluded when filtering. If no
sessions match, the command exits with code 1 and an explanatory message.
Expand Down
49 changes: 35 additions & 14 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ Options:
(cannot be combined with a session or project path)
--since <date> include sessions starting on or after YYYY-MM-DD (UTC),
or a relative duration: 7d (last 7 days) or 2w (last 2 weeks)
--until <date> include sessions starting through the end of YYYY-MM-DD (UTC),
or the day resolved from 7d or 2w (same as --since)
--json machine-readable output
--html [file] write a shareable single-file HTML report
(default: tokenbill-report.html)
Expand All @@ -56,7 +58,8 @@ Options:

Card options:
--plan <plan> pro, max5, max20 or a monthly USD amount: adds the
"N× my plan" figure (last 30 days unless --since is set)
"N× my plan" figure (30 days ending on --until or today,
unless --since is set)
--out <file> output path, .png or .svg (default: tokenbill-card.png)

Exit codes: 0 ok, 1 error, 2 budget exceeded.`;
Expand Down Expand Up @@ -173,6 +176,7 @@ let top = 10;
let budget: number | undefined;
let target: string | undefined;
let since: string | undefined;
let until: string | undefined;
let planArg: string | undefined;
let cardOut = path.resolve("tokenbill-card.png");

Expand Down Expand Up @@ -231,16 +235,17 @@ for (let i = 0; i < argv.length; i++) {
json = true;
} else if (a === "--all") {
all = true;
} else if (a === "--since") {
} else if (a === "--since" || a === "--until") {
const raw = argv[++i];
const resolved = resolveSince(raw);
if (resolved === undefined) {
console.error(
"--since expects a valid date in YYYY-MM-DD format (UTC), or a relative duration like 7d or 2w",
`${a} expects a valid date in YYYY-MM-DD format (UTC), or a relative duration like 7d or 2w`,
);
process.exit(1);
}
since = resolved;
if (a === "--since") since = resolved;
else until = resolved;
} else if (a === "--html") {
html =
argv[i + 1] && argv[i + 1].endsWith(".html") ? path.resolve(argv[++i]) : path.resolve("tokenbill-report.html");
Expand Down Expand Up @@ -316,21 +321,28 @@ if (card && (json || html || md || budget !== undefined)) {
}

/**
* The plan fee over the card's window. Without --since the card covers the
* last 30 days and compares against one month's fee.
* The plan fee over the card's window. Without --since the card covers
* 30 days ending on --until (or today), for one month's fee.
*/
function resolvePlan(): PlanInfo | undefined {
if (!planArg) return undefined;
const known = PLANS[planArg];
const monthly = known ? known.monthlyUSD : Number(planArg);
const name = known ? known.name : `$${monthly}/mo`;
if (!since || planWindowDefault) return { name, feeUSD: monthly, windowDays: 30 };
const days = Math.max(1, Math.ceil((Date.now() - Date.parse(`${since}T00:00:00.000Z`)) / 864e5));
const end = until ? Date.parse(`${until}T00:00:00.000Z`) + 864e5 : Date.now();
const days = Math.max(1, Math.ceil((end - Date.parse(`${since}T00:00:00.000Z`)) / 864e5));
return { name, feeUSD: (monthly * days) / 30, windowDays: days };
}
const planWindowDefault = card && !!planArg && !since;
if (planWindowDefault) {
since = new Date(Date.now() - 30 * 864e5).toISOString().slice(0, 10);
const end = until ? Date.parse(`${until}T00:00:00.000Z`) + 864e5 : Date.now();
since = new Date(end - 30 * 864e5).toISOString().slice(0, 10);
}

if (since && until && until < since) {
console.error("--until must be on or after --since");
process.exit(1);
}

function writeCard(result: ReturnType<typeof aggregate>, project: string): void {
Expand Down Expand Up @@ -382,13 +394,22 @@ try {
const resolved = resolveTarget(target, all);
// Filter whole sessions by their recorded start, never by file modification time.
const cutoff = since ? Date.parse(`${since}T00:00:00.000Z`) : undefined;
const matchesSince = (session: ReturnType<typeof claudeCodeAdapter.parse>): boolean =>
cutoff === undefined || (session.startTime !== undefined && Date.parse(session.startTime) >= cutoff);
const noMatches = () => new Error(`No sessions starting on or after ${since} (UTC)`);
const end = until ? Date.parse(`${until}T00:00:00.000Z`) + 864e5 : undefined;
const matchesWindow = (session: ReturnType<typeof claudeCodeAdapter.parse>): boolean => {
if (cutoff === undefined && end === undefined) return true;
if (session.startTime === undefined) return false;
const start = Date.parse(session.startTime);
return Number.isFinite(start) && (cutoff === undefined || start >= cutoff) &&
(end === undefined || start < end);
};
const noMatches = () => new Error(since && until
? `No sessions starting from ${since} through ${until} (UTC)`
: until ? `No sessions starting on or before ${until} (UTC)`
: `No sessions starting on or after ${since} (UTC)`);

if (resolved.mode === "single") {
const session = claudeCodeAdapter.parse(resolved.file);
if (!matchesSince(session)) throw noMatches();
if (!matchesWindow(session)) throw noMatches();
const cost = calculate(session);
const attr = attribute(session);
const turns = topTurns(session, top);
Expand All @@ -409,8 +430,8 @@ try {
);
}
} else {
const sessions = resolved.files.map((f) => claudeCodeAdapter.parse(f)).filter(matchesSince);
if (since && sessions.length === 0) throw noMatches();
const sessions = resolved.files.map((f) => claudeCodeAdapter.parse(f)).filter(matchesWindow);
if ((since || until) && sessions.length === 0) throw noMatches();
const result = aggregate(sessions, top);
const label = all
? resolved.label
Expand Down
102 changes: 102 additions & 0 deletions test/since.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,105 @@ describe("--since", () => {
expect(JSON.parse(weeksResult.stdout)).toEqual(JSON.parse(daysResult.stdout));
});
}, 60_000);


describe("--until", () => {
it.each([false, true])("includes the final UTC millisecond but not the next day with all=%s", (all) => {
const { home, project } = setup();
const args = all ? ["--all"] : [project];
const result = run(home, [...args, "--until", "2026-09-30", "--json"]);
expect(result.status).toBe(0);
const report = JSON.parse(result.stdout);
expect(report.sessions.map((s: { sessionId: string }) => s.sessionId)).toEqual(["before"]);
const single = run(home, [path.join(project, "before.jsonl"), "--until", "2026-09-30", "--json"]);
expect(single.status).toBe(0);
expect(report.totalUSD).toBeCloseTo(JSON.parse(single.stdout).totalUSD, 6);
});

it("combines both bounds and accepts a single-day window", () => {
const { home, project } = setup();
const result = run(home, [project, "--since", "2026-10-01", "--until", "2026-10-01", "--json"]);
expect(result.status).toBe(0);
expect(JSON.parse(result.stdout).sessions.map((s: { sessionId: string }) => s.sessionId))
.toEqual(["boundary"]);
});

it("rejects inverted windows in either argument order", () => {
const { home, project } = setup();
for (const flags of [
["--since", "2026-10-01", "--until", "2026-09-30"],
["--until", "2026-09-30", "--since", "2026-10-01"],
]) {
const result = run(home, [project, ...flags, "--json"]);
expect(result.status).toBe(1);
expect(result.stderr).toContain("--until must be on or after --since");
expect(result.stdout).toBe("");
}
});

it("reports no matches for projects, single sessions and --all", () => {
const { home, project } = setup();
for (const args of [[project], [path.join(project, "boundary.jsonl")], ["--all"]]) {
const result = run(home, [...args, "--until", "2026-09-01", "--json"]);
expect(result.status).toBe(1);
expect(result.stderr).toContain("No sessions starting on or before 2026-09-01");
expect(result.stdout).toBe("");
}
});

it("uses the same date validation as --since", () => {
const { home, project } = setup();
for (const value of [undefined, "yesterday", "2026-2-01", "2026-02-29", "2026-04-31", "0d", "-3d", "1.5d", "300000000d"]) {
const result = run(home, [project, "--until", ...(value ? [value] : [])]);
expect(result.status).toBe(1);
expect(result.stderr).toContain("--until expects a valid date");
}
});

it("resolves relative days and weeks to the end of the same UTC day", () => {
const { home, project } = setup();
const now = new Date();
const day = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()) - 6 * 864e5;
for (const [id, timestamp] of [
["inside", new Date(day + 864e5 - 1).toISOString()],
["outside", new Date(day + 864e5).toISOString()],
]) {
const records = fs.readFileSync("fixtures/basic.jsonl", "utf8").trim().split(/\r?\n/)
.map(line => {
const record = JSON.parse(line);
record.sessionId = id;
if (record.timestamp) record.timestamp = timestamp;
return JSON.stringify(record);
});
fs.writeFileSync(path.join(project, `${id}.jsonl`), records.join("\n"));
}
for (const value of ["7d", "1w"]) {
const inside = run(home, [path.join(project, "inside.jsonl"), "--until", value, "--json"]);
const outside = run(home, [path.join(project, "outside.jsonl"), "--until", value, "--json"]);
expect(inside.status).toBe(0);
expect(outside.status).toBe(1);
}
});
});

it("applies --until before the budget check", () => {
const { home, project } = setup();
const single = run(home, [path.join(project, "before.jsonl"), "--json"]);
const limit = JSON.parse(single.stdout).totalUSD * 1.1;
expect(run(home, [project, "--budget", String(limit), "--json"]).status).toBe(2);
const filtered = run(home, [project, "--until", "2026-09-30", "--budget", String(limit), "--json"]);
expect(filtered.status).toBe(0);
});

it("ends a card's plan comparison at --until", () => {
const { home, project } = setup();
const out = path.join(home, "card.svg");
const explicit = run(home, ["card", project, "--redact", "--plan", "30",
"--since", "2026-09-30", "--until", "2026-09-30", "--out", out]);
expect(explicit.status).toBe(0);
expect(fs.readFileSync(out, "utf8")).toContain("($1.00)");
const defaultWindow = run(home, ["card", project, "--redact", "--plan", "30",
"--until", "2026-09-30", "--out", out]);
expect(defaultWindow.status).toBe(0);
expect(fs.readFileSync(out, "utf8")).toContain("($30.00)");
});