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
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ agents through SQL and a CLI. Nothing leaves the machine.
## What you get

- **A status line in Claude Code:** `qx $3.42 · ctx 182k · cache 96%`, from the harness's own numbers.
- **Nudges** (toasts, never added to the model's context): the prompt cache expired after idle time and the next
call re-wrote it; the context passed 200k.
- **Nudges** (toasts, never added to the model's context): a call re-wrote the prompt cache, with the reason
(a compaction, a model switch, idle past the cache's lifetime, or a change at the start of the request, which
is worth a look); the context passed 200k.
- **`/clear-tools [outputs] [keep N]`:** compacts by replacing old tool calls (their inputs) and old tool outputs
with short stubs instead of a summary, in one pass, so the prompt cache is written once. `outputs` clears only
the outputs; `keep N` leaves the last N whole. Also as `/compact tools [outputs] [keep N]`. The next call
Expand Down
11 changes: 10 additions & 1 deletion packages/mod/src/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,16 @@ import { atom, read, update } from "claude-code";
import type { Live } from "../types/index.js";
import { tokens, usd } from "./format.ts";

export const EMPTY: Live = { ctx: 0, read: 0, input: 0, lastEndAt: 0, lastCtx: 0, bigCtxNudged: false };
export const EMPTY: Live = {
ctx: 0,
read: 0,
input: 0,
lastEndAt: 0,
lastCtx: 0,
bigCtxNudged: false,
compacted: false,
hourCache: false,
};
export const live = atom({ plugin: "quantext", key: "live" } as const, EMPTY);

// Function declarations: the mod's loader follows `$` across files only into those.
Expand Down
45 changes: 35 additions & 10 deletions packages/mod/src/nudges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,52 @@
import type { TurnUsage } from "claude-code";
import type { Live } from "../types/index.js";
import { tokens, usd } from "./format.ts";
import { cacheWriteUsd } from "./prices.ts";
import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteUsd } from "./prices.ts";

/** The prompt cache's default time to live: a longer idle gap may have let it expire. */
/** The prompt cache's two lifetimes: 5 minutes by default, 1 hour when the harness asks for it. */
export const CACHE_TTL_MS = 5 * 60_000;
export const CACHE_TTL_1H_MS = 60 * 60_000;
/** A re-write smaller than this is not worth a nudge. */
export const CACHE_REWRITE_NUDGE_TOKENS = 20_000;
/** Below this share of the last call's input read from the cache, the cache was lost rather than extended. */
export const CACHE_LOST_READ_SHARE = 0.5;
/** Context size at which every call gets expensive; nudged once until a compaction or /clear. */
export const CONTEXT_NUDGE_TOKENS = 200_000;

/** The expiry nudge for a main-loop call that started `startedAt`, or undefined when the cache held. */
export function cacheExpiryNudge(l: Live, u: TurnUsage, startedAt: number): string | undefined {
const CHANGED = "the start of the request changed (tools, MCP servers, CLAUDE.md?)";
const SEE = " /quantext view shows the first change.";

/** Whether a main-loop call read most of the last call's input from the cache. */
export const cacheHeld = (l: Live, u: TurnUsage): boolean =>
u.cache_read_input_tokens >= CACHE_LOST_READ_SHARE * l.lastCtx;

/**
* Why a main-loop call that started `startedAt` lost the cache, or undefined when it held. The reason, first that
* fits (as the engine's cache breaks): a compaction, a model switch, a pause past the cache's lifetime, else a
* change early in the request. The lifetime is known to be 1 hour once the cache held over a longer pause.
*/
export function cacheBreakNudge(l: Live, u: TurnUsage, startedAt: number): string | undefined {
if (l.lastEndAt === 0) return undefined;
const idle = startedAt - l.lastEndAt;
const rewrote = u.cache_creation_input_tokens;
if (idle <= CACHE_TTL_MS || rewrote <= CACHE_REWRITE_NUDGE_TOKENS) return undefined;
if (u.cache_read_input_tokens >= CACHE_LOST_READ_SHARE * l.lastCtx) return undefined;
const cost = cacheWriteUsd(u.model, rewrote);
const price = cost === undefined ? "" : ` (~${usd(cost)})`;
return `quantext: cache expired after ${Math.round(idle / 60_000)} min idle; this call re-wrote ${tokens(rewrote)} tokens${price}.`;
if (rewrote <= CACHE_REWRITE_NUDGE_TOKENS || cacheHeld(l, u)) return undefined;
const cost = cacheWriteUsd(u.model, rewrote, l.hourCache ? CACHE_WRITE_1H : CACHE_WRITE_5M);
const w = `${tokens(rewrote)} tokens${cost === undefined ? "" : ` (~${usd(cost)})`}`;
const idle = startedAt - l.lastEndAt;
const min = Math.round(idle / 60_000);
if (l.compacted) return `quantext: cache re-written after a compaction, as expected; this call wrote ${w}.`;
if (l.model !== undefined && l.model !== u.model) {
const from = `a switch from ${l.model} to ${u.model} (each model has its own cache)`;
return `quantext: cache re-written after ${from}; this call wrote ${w}.`;
}
if (idle > CACHE_TTL_1H_MS) return `quantext: cache expired after ${min} min idle; this call re-wrote ${w}.`;
if (idle <= CACHE_TTL_MS) {
return `quantext: cache lost after ${min} min, with no compaction or model switch: ${CHANGED}; this call re-wrote ${w}.${SEE}`;
}
if (l.hourCache) {
return `quantext: cache lost after ${min} min idle, within its 1-hour lifetime: ${CHANGED}; this call re-wrote ${w}.${SEE}`;
}
const both = "it expired if it lives 5 min, else the start of the request changed";
return `quantext: cache lost after ${min} min idle: ${both}; this call re-wrote ${w}.`;
}

/** The large-context nudge when `ctx` has reached the threshold and it was not shown since it was re-armed. */
Expand Down
11 changes: 8 additions & 3 deletions packages/mod/src/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { EngineInterface, Register } from "claude-code";
import type { ClearArgs } from "./clear-tools.ts";
import { clearRequest, clearTools, clearWhat, compactArgs, parseClearArgs, USAGE } from "./clear-tools.ts";
import { EMPTY, inputOf, readLive, statusLabel, updateLive } from "./live.ts";
import { cacheExpiryNudge, contextNudge } from "./nudges.ts";
import { CACHE_TTL_MS, cacheBreakNudge, cacheHeld, contextNudge } from "./nudges.ts";
import { openViewer } from "./viewer.ts";

/**
Expand Down Expand Up @@ -91,10 +91,15 @@ export const register: Register = (on) => {
const r = yield* next(e);
const u = r.usage;
if (u === null || e.agentId !== undefined) return r; // subagents have their own caches: count the main loop
const nudge = cacheExpiryNudge(await readLive($), u, startedAt);
const before = await readLive($);
const nudge = cacheBreakNudge(before, u, startedAt);
// A cache read after more than 5 minutes idle shows that this session's cache lives an hour.
const heldOverPause = before.lastEndAt > 0 && startedAt - before.lastEndAt > CACHE_TTL_MS && cacheHeld(before, u);
const endedAt = await $.clock.now();
await updateLive($, (l) => ({
...l,
compacted: false,
hourCache: l.hourCache || heldOverPause,
read: l.read + u.cache_read_input_tokens,
input: l.input + u.input_tokens + u.cache_creation_input_tokens,
lastEndAt: endedAt,
Expand Down Expand Up @@ -129,7 +134,7 @@ export const register: Register = (on) => {
r = { messages: cleared.messages };
}
if (e.agentId === undefined && e.trigger !== "precompute" && r.messages !== undefined) {
await updateLive($, (l) => ({ ...l, bigCtxNudged: false }));
await updateLive($, (l) => ({ ...l, bigCtxNudged: false, compacted: true }));
remeasureSoon($);
}
if (note !== undefined) $.ui.toast(note); // after the update, so a failed clear shows no "Cleared"
Expand Down
111 changes: 93 additions & 18 deletions packages/mod/test/nudges.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,53 +4,128 @@ import { measurer, stepper, toasts, usage } from "./kit.ts";

const MINUTE = 60_000;

test("a cache expiry after an idle gap raises one nudge with its cost", async ($, on) => {
const SUMMARY = [{ role: "user" as const, text: "summary", toolUses: [] }];
/** The kit hands the call's argument to the hooks as the event: give it the event's own fields. */
const compact = ($: Engine, trigger = "manual") => $.session.compact({ trigger, messages: SUMMARY } as never);

test("a cache lost after more than an hour idle is an expiry, with its cost", async ($, on) => {
const seen = toasts(on);
const { step, clock } = stepper(on);
await step($, usage(300_000, 1_000));
await clock.advance(70 * MINUTE);
await step($, usage(0, 301_000));
expect(seen).toEqual(["quantext: cache expired after 70 min idle; this call re-wrote 301k tokens (~$1.50)."]);
});

test("a cache lost after 5 to 60 minutes idle names both causes while the cache's lifetime is not known", async ($, on) => {
const seen = toasts(on);
const { step, clock } = stepper(on);
await step($, usage(300_000, 1_000));
await clock.advance(12 * MINUTE);
await step($, usage(0, 301_000));
expect(seen).toEqual(["quantext: cache expired after 12 min idle; this call re-wrote 301k tokens (~$1.50)."]);
expect(seen).toEqual([
"quantext: cache lost after 12 min idle: it expired if it lives 5 min, else the start of the request changed; " +
"this call re-wrote 301k tokens (~$1.50).",
]);
});

test("once the cache held over a pause, a loss within the hour is a prefix change, priced as a 1-hour write", async ($, on) => {
const seen = toasts(on);
const { step, clock } = stepper(on);
await step($, usage(300_000, 1_000));
await clock.advance(20 * MINUTE);
await step($, usage(301_000, 1_000)); // read after 20 min: this session's cache lives an hour
await clock.advance(40 * MINUTE);
await step($, usage(0, 302_000));
expect(seen).toEqual([
"quantext: cache lost after 40 min idle, within its 1-hour lifetime: the start of the request changed " +
"(tools, MCP servers, CLAUDE.md?); this call re-wrote 302k tokens (~$2.42). /quantext view shows the first change.",
]);
});

test("a cache lost with no pause is a prefix change", async ($, on) => {
const seen = toasts(on);
const { step, clock } = stepper(on);
await step($, usage(300_000, 1_000));
await clock.advance(1 * MINUTE);
await step($, usage(0, 301_000));
expect(seen).toEqual([
"quantext: cache lost after 1 min, with no compaction or model switch: the start of the request changed " +
"(tools, MCP servers, CLAUDE.md?); this call re-wrote 301k tokens (~$1.50). /quantext view shows the first change.",
]);
});

test("a re-write after a compaction is named as such, even after a long pause", async ($, on) => {
const seen = toasts(on);
const { step, clock } = stepper(on);
on("session.compact", () => ({ messages: SUMMARY }));
await step($, usage(300_000, 1_000));
await clock.advance(40 * MINUTE);
await compact($);
await step($, usage(0, 100_000));
await clock.advance(1 * MINUTE);
await step($, usage(0, 101_000)); // the compaction counts for one call only
expect(seen).toEqual([
"quantext: cache re-written after a compaction, as expected; this call wrote 100k tokens (~$0.50).",
"quantext: cache lost after 1 min, with no compaction or model switch: the start of the request changed " +
"(tools, MCP servers, CLAUDE.md?); this call re-wrote 101k tokens (~$0.51). /quantext view shows the first change.",
]);
});

test("a precompute compaction does not count as a compaction", async ($, on) => {
const seen = toasts(on);
const { step, clock } = stepper(on);
on("session.compact", () => ({ messages: SUMMARY }));
await step($, usage(300_000, 1_000));
await compact($, "precompute");
await clock.advance(1 * MINUTE);
await step($, usage(0, 301_000));
expect(seen[0]).toContain("the start of the request changed");
});

test("no expiry nudge within 5 minutes, for a small re-write, or when the cache was still read", async ($, on) => {
test("a re-write after a model switch is named as such", async ($, on) => {
const seen = toasts(on);
const { step, clock } = stepper(on);
await step($, usage(300_000, 1_000));
await clock.advance(4 * MINUTE);
await step($, usage(0, 301_000)); // within the time to live: not an expiry
await clock.advance(6 * MINUTE);
await clock.advance(1 * MINUTE);
await step($, { ...usage(0, 301_000), model: "claude-sonnet-5-5" });
expect(seen).toEqual([
"quantext: cache re-written after a switch from claude-opus-5-5 to claude-sonnet-5-5 (each model has its own " +
"cache); this call wrote 301k tokens (~$0.75).",
]);
});

test("no cache nudge for a small re-write, or when the cache was still read", async ($, on) => {
const seen = toasts(on);
const { step, clock } = stepper(on);
await step($, usage(10_000, 1_000));
await clock.advance(70 * MINUTE);
await step($, usage(0, 15_000)); // 15k re-written: below the threshold
await step($, usage(0, 300_000));
await clock.advance(6 * MINUTE);
await step($, usage(290_000, 40_000)); // the cache was read: new content, not an expiry
await clock.advance(1 * MINUTE);
await step($, usage(10_000, 40_000)); // the cache was read: new content, not a loss
expect(seen).toEqual([]);
});

test("a subagent's calls raise no expiry nudge and do not move the main loop's idle clock", async ($, on) => {
test("a subagent's calls raise no cache nudge and do not move the main loop's idle clock", async ($, on) => {
const seen = toasts(on);
const { step, clock } = stepper(on);
await step($, usage(300_000, 1_000));
await clock.advance(6 * MINUTE);
await clock.advance(66 * MINUTE);
await step($, usage(0, 300_000), "agent-1");
await clock.advance(1 * MINUTE);
await step($, usage(0, 301_000));
expect(seen).toEqual(["quantext: cache expired after 7 min idle; this call re-wrote 301k tokens (~$1.50)."]);
expect(seen).toEqual(["quantext: cache expired after 67 min idle; this call re-wrote 301k tokens (~$1.50)."]);
});

test("a model with no known price gets the nudge without a cost", async ($, on) => {
const seen = toasts(on);
const { step, clock } = stepper(on);
await step($, { ...usage(300_000, 1_000), model: "some-model" });
await clock.advance(6 * MINUTE);
await clock.advance(61 * MINUTE);
await step($, { ...usage(0, 301_000), model: "some-model" });
expect(seen).toEqual(["quantext: cache expired after 6 min idle; this call re-wrote 301k tokens."]);
expect(seen).toEqual(["quantext: cache expired after 61 min idle; this call re-wrote 301k tokens."]);
});

const SUMMARY = [{ role: "user" as const, text: "summary", toolUses: [] }];
/** The kit hands the call's argument to the hooks as the event: give it the event's own fields. */
const compact = ($: Engine) => $.session.compact({ trigger: "manual", messages: SUMMARY } as never);

test("crossing 200k context raises one nudge, re-armed after a compaction", async ($, on) => {
const seen = toasts(on);
const measure = measurer(on);
Expand Down
4 changes: 4 additions & 0 deletions packages/mod/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ export type Live = {
model?: string;
/** Whether the large-context nudge was shown since the last compaction or /clear. */
bigCtxNudged: boolean;
/** Whether the main loop compacted since its last call: the next cache re-write is expected. */
compacted: boolean;
/** Whether the cache held over a pause longer than 5 minutes: this session's cache lives an hour. */
hourCache: boolean;
};

declare module "claude-code" {
Expand Down
Loading