From 0c15eee31a41e53dc5155878cf7a9c0187956f3b Mon Sep 17 00:00:00 2001 From: Aikhan Jumashukurov <117706338+aikhanj@users.noreply.github.com> Date: Thu, 8 Oct 2026 19:24:33 -0400 Subject: [PATCH 1/2] Log token usage and model cost for every chat turn Each turn now ends with one structured pi.usage log line: model, steps, uncached input, cache reads and writes, output, reasoning, web searches, estimated USD and wall time, with the student as a keyed pseudonym instead of a NetID. This is the data for the PI cost analysis and the basis for a per-student usage limit. Co-Authored-By: Claude Opus 5.5 (1M context) --- app/src/server/pi.ts | 59 +++++++++++++++++ app/src/server/usage.ts | 138 ++++++++++++++++++++++++++++++++++++++++ app/tests/usage.test.ts | 71 +++++++++++++++++++++ 3 files changed, 268 insertions(+) create mode 100644 app/src/server/usage.ts create mode 100644 app/tests/usage.test.ts diff --git a/app/src/server/pi.ts b/app/src/server/pi.ts index 6399ee1..d3902f9 100644 --- a/app/src/server/pi.ts +++ b/app/src/server/pi.ts @@ -6,6 +6,14 @@ import { hasToolCall, tool, type UIMessage } from "ai"; import { z } from "zod"; import { EMPTY_WORKSPACES, workspaceContext, type WorkspaceState } from "../shared/workspaces"; import { handleWorkspaceRequest, WORKSPACE_KEY } from "./workspaces"; +import { + addStep, + costUsd, + emptyTurnUsage, + pseudonym, + type StepUsage, + type TurnUsage, +} from "./usage"; import { GCAL_CALLBACK_PATH, GCAL_MCP_URL, @@ -214,6 +222,12 @@ export class Pi extends Think { */ chatStreamStallTimeoutMs = 120_000; + /** This turn's token counts so far (see usage.ts); null between turns. */ + private turnUsage: TurnUsage | null = null; + private turnStartedAt = 0; + /** The model getModel() resolved, for pricing the turn. */ + private turnModel = DEFAULT_CLAUDE_MODEL; + getDefaultTimezone() { return "America/New_York"; } @@ -230,6 +244,7 @@ export class Pi extends Think { const model = CLAUDE_MODELS.has(preference) ? preference : DEFAULT_CLAUDE_MODEL; + this.turnModel = model; return createAnthropic({ apiKey: key })(model); } @@ -520,6 +535,8 @@ export class Pi extends Think { override async beforeTurn( ctx: Parameters[0] ): Promise extends infer R ? Awaited : never> { + this.turnUsage = emptyTurnUsage(); + this.turnStartedAt = Date.now(); const inherited = await super.beforeTurn(ctx); const settings = this.getConfig(); if (!settings) return inherited ?? undefined; @@ -617,15 +634,57 @@ export class Pi extends Think { override async onChatResponse(result: Parameters[0]) { await super.onChatResponse(result); + await this.logTurnUsage(result.status); await this.releaseIdleMcp(); } override async onChatError(error: unknown, ctx?: Parameters[1]) { const out = await super.onChatError(error, ctx); + await this.logTurnUsage("error"); await this.releaseIdleMcp(); return out; } + /** Every model call in a turn is billed, so each one is added up. */ + override async onStepEnd(ctx: Parameters[0]) { + await super.onStepEnd(ctx); + if (this.turnUsage) { + this.turnUsage = addStep(this.turnUsage, ctx.usage as StepUsage); + } + } + + /** + * One `pi.usage` line per turn, for the cost analysis. Runs once per turn: + * whichever of onChatResponse and onChatError comes first takes the total. + * Never allowed to fail the turn it's describing. + */ + private async logTurnUsage(status: string): Promise { + const usage = this.turnUsage; + if (!usage) return; + this.turnUsage = null; + try { + const netid = this.getConfig()?.netid ?? ""; + const cost = costUsd(this.turnModel, usage); + if (cost === null) { + console.warn(`usage: no price for ${this.turnModel}, add it to MODEL_PRICES`); + } + console.log( + JSON.stringify({ + event: "pi.usage", + status, + user: netid ? await pseudonym(netid, this.env.SESSION_SECRET ?? "") : null, + chat: this.name.slice(`u-${netid}-`.length), + model: this.turnModel, + ...usage, + costUsd: cost === null ? null : Math.round(cost * 1e6) / 1e6, + ms: Date.now() - this.turnStartedAt, + }) + ); + } catch (err) { + console.warn("usage: couldn't log this turn", err); + } + } + /** * Direct MCP tool call for non-chat surfaces (planner, agenda). Returns the * tool's JSON payload parsed from its text content. diff --git a/app/src/server/usage.ts b/app/src/server/usage.ts new file mode 100644 index 0000000..ac0f15f --- /dev/null +++ b/app/src/server/usage.ts @@ -0,0 +1,138 @@ +/** + * What a chat turn costs in model spend. One turn is several model calls (one + * per agent step), each resending the system prompt, the tool definitions and + * the history, so the turn's bill is the sum over its steps. Pi adds each + * step up as it finishes and logs one `pi.usage` line per turn, which is what + * the cost analysis reads (Workers Logs parses JSON lines into fields). + */ + +/** USD per million tokens, from Anthropic's price list. */ +type Price = { + input: number; + output: number; + cacheRead: number; + /** 5-minute cache writes, 1.25x input. */ + cacheWrite5m: number; + /** 1-hour cache writes, 2x input. */ + cacheWrite1h: number; +}; + +export const MODEL_PRICES: Record = { + "claude-opus-5": { input: 5, output: 25, cacheRead: 0.5, cacheWrite5m: 6.25, cacheWrite1h: 10 }, + "claude-sonnet-5": { input: 2, output: 10, cacheRead: 0.2, cacheWrite5m: 2.5, cacheWrite1h: 4 }, + "claude-opus-5-5": { input: 4, output: 20, cacheRead: 0.2, cacheWrite5m: 5, cacheWrite1h: 8 }, + "claude-sonnet-5-5": { input: 2, output: 10, cacheRead: 0.2, cacheWrite5m: 2.5, cacheWrite1h: 4 }, +}; + +/** Anthropic's server-side web search: $10 per 1,000 searches. */ +export const WEB_SEARCH_USD = 0.01; + +/** Token counts summed over one turn's steps. */ +export type TurnUsage = { + steps: number; + /** Input tokens billed at the full rate (not read from or written to cache). */ + input: number; + cacheRead: number; + cacheWrite5m: number; + cacheWrite1h: number; + /** All output tokens, reasoning included. */ + output: number; + reasoning: number; + webSearches: number; +}; + +export function emptyTurnUsage(): TurnUsage { + return { + steps: 0, + input: 0, + cacheRead: 0, + cacheWrite5m: 0, + cacheWrite1h: 0, + output: 0, + reasoning: 0, + webSearches: 0, + }; +} + +/** + * The part of the AI SDK's step usage this reads. With the Anthropic + * provider, `noCacheTokens`, `cacheReadTokens` and `cacheWriteTokens` are + * Anthropic's `input_tokens`, `cache_read_input_tokens` and + * `cache_creation_input_tokens`, and `raw` is Anthropic's own usage object. + */ +export type StepUsage = { + inputTokens?: number | undefined; + inputTokenDetails?: { + noCacheTokens?: number | undefined; + cacheReadTokens?: number | undefined; + cacheWriteTokens?: number | undefined; + }; + outputTokens?: number | undefined; + outputTokenDetails?: { reasoningTokens?: number | undefined }; + raw?: unknown; +}; + +const n = (value: unknown): number => + typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0; + +/** Adds one finished step to the turn's running total. */ +export function addStep(total: TurnUsage, usage: StepUsage | undefined): TurnUsage { + const raw = (usage?.raw ?? {}) as { + server_tool_use?: { web_search_requests?: unknown }; + cache_creation?: { ephemeral_1h_input_tokens?: unknown }; + }; + const cacheRead = n(usage?.inputTokenDetails?.cacheReadTokens); + const cacheWrite = n(usage?.inputTokenDetails?.cacheWriteTokens); + // Anthropic splits cache writes by TTL only in its raw usage; anything it + // doesn't mark as 1-hour is priced as the default 5-minute write. + const cacheWrite1h = Math.min(cacheWrite, n(raw.cache_creation?.ephemeral_1h_input_tokens)); + const noCache = usage?.inputTokenDetails?.noCacheTokens; + const input = + noCache !== undefined + ? n(noCache) + : Math.max(0, n(usage?.inputTokens) - cacheRead - cacheWrite); + return { + steps: total.steps + 1, + input: total.input + input, + cacheRead: total.cacheRead + cacheRead, + cacheWrite5m: total.cacheWrite5m + cacheWrite - cacheWrite1h, + cacheWrite1h: total.cacheWrite1h + cacheWrite1h, + output: total.output + n(usage?.outputTokens), + reasoning: total.reasoning + n(usage?.outputTokenDetails?.reasoningTokens), + webSearches: total.webSearches + n(raw.server_tool_use?.web_search_requests), + }; +} + +/** + * The turn's model spend in USD, or null for a model missing from + * MODEL_PRICES, so an unpriced model shows up as a gap rather than as $0. + */ +export function costUsd(model: string, usage: TurnUsage): number | null { + const price = MODEL_PRICES[model]; + if (!price) return null; + const tokens = + usage.input * price.input + + usage.cacheRead * price.cacheRead + + usage.cacheWrite5m * price.cacheWrite5m + + usage.cacheWrite1h * price.cacheWrite1h + + usage.output * price.output; + return tokens / 1_000_000 + usage.webSearches * WEB_SEARCH_USD; +} + +/** + * A stable, non-reversible id for a student in the logs, so the analysis can + * see how usage spreads across people without the logs carrying NetIDs. Keyed + * with a server secret because NetIDs are short enough to guess and hash. + */ +export async function pseudonym(netid: string, secret: string): Promise { + const enc = new TextEncoder(); + const key = await crypto.subtle.importKey( + "raw", + enc.encode(secret || "pi-dev"), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"] + ); + const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(netid))); + return [...sig.slice(0, 8)].map((b) => b.toString(16).padStart(2, "0")).join(""); +} diff --git a/app/tests/usage.test.ts b/app/tests/usage.test.ts new file mode 100644 index 0000000..41b1976 --- /dev/null +++ b/app/tests/usage.test.ts @@ -0,0 +1,71 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { addStep, costUsd, emptyTurnUsage, pseudonym } from "../src/server/usage.ts"; + +// One Anthropic step as the AI SDK reports it: 1,000 uncached input tokens, +// 8,000 read from cache, 2,000 written (500 of them with the 1-hour TTL), +// 300 output of which 100 were reasoning, and two web searches. +const step = { + inputTokens: 11_000, + inputTokenDetails: { noCacheTokens: 1_000, cacheReadTokens: 8_000, cacheWriteTokens: 2_000 }, + outputTokens: 300, + outputTokenDetails: { reasoningTokens: 100 }, + raw: { + input_tokens: 1_000, + server_tool_use: { web_search_requests: 2 }, + cache_creation: { ephemeral_5m_input_tokens: 1_500, ephemeral_1h_input_tokens: 500 }, + }, +}; + +test("a step's tokens land in the right buckets", () => { + assert.deepEqual(addStep(emptyTurnUsage(), step), { + steps: 1, + input: 1_000, + cacheRead: 8_000, + cacheWrite5m: 1_500, + cacheWrite1h: 500, + output: 300, + reasoning: 100, + webSearches: 2, + }); +}); + +test("a turn's cost is every step priced at its own rate", () => { + const turn = addStep(addStep(emptyTurnUsage(), step), step); + assert.equal(turn.steps, 2); + // Per step on Opus 5: 1,000 x $5 + 8,000 x $0.50 + 1,500 x $6.25 + // + 500 x $10 + 300 x $25 = $30,875 per million tokens, plus $0.02 of search. + assert.ok(Math.abs(costUsd("claude-opus-5", turn)! - 2 * (0.030875 + 0.02)) < 1e-12); + // Sonnet 5: 1,000 x $2 + 8,000 x $0.20 + 1,500 x $2.50 + 500 x $4 + 300 x $10. + assert.ok(Math.abs(costUsd("claude-sonnet-5", addStep(emptyTurnUsage(), step))! - (0.01235 + 0.02)) < 1e-12); +}); + +test("missing detail falls back sensibly and never goes negative", () => { + const plain = addStep(emptyTurnUsage(), { inputTokens: 4_000, outputTokens: 50 }); + assert.equal(plain.input, 4_000); + assert.equal(plain.cacheWrite5m, 0); + assert.equal(plain.webSearches, 0); + + const derived = addStep(emptyTurnUsage(), { + inputTokens: 4_000, + inputTokenDetails: { cacheReadTokens: 3_000 }, + }); + assert.equal(derived.input, 1_000); + + const empty = addStep(emptyTurnUsage(), undefined); + assert.equal(empty.steps, 1); + assert.equal(costUsd("claude-opus-5", empty), 0); +}); + +test("an unpriced model reads as unknown, not free", () => { + assert.equal(costUsd("claude-mystery-9", addStep(emptyTurnUsage(), step)), null); +}); + +test("student ids in the logs are stable, short and not the NetID", async () => { + const a = await pseudonym("aj5828", "secret-one"); + assert.match(a, /^[0-9a-f]{16}$/); + assert.equal(await pseudonym("aj5828", "secret-one"), a); + assert.notEqual(await pseudonym("aj5828", "secret-two"), a); + assert.notEqual(await pseudonym("ab1234", "secret-one"), a); + assert.ok(!a.includes("aj5828")); +}); From bfbc63a05f354ed715514934679d2866f45da30d Mon Sep 17 00:00:00 2001 From: Aikhan Jumashukurov <117706338+aikhanj@users.noreply.github.com> Date: Thu, 8 Oct 2026 19:56:26 -0400 Subject: [PATCH 2/2] Add a weekly per-student model budget Copies PrincetonCourses' ask-gateway tiers in dollars: $3 on any model, then Sonnet 5 only for $1 more, then PI stops answering until enough spend ages out of a rolling 7-day window. Spend is recorded per turn on the student's desk object and pruned on write, so nothing wakes the desk on a timer. An exhausted student gets the limit note from a stand-in model that never calls Anthropic. Amounts are Worker vars. Co-Authored-By: Claude Opus 5.5 (1M context) --- app/src/client/pages/ChatPage.tsx | 15 +++- app/src/server/notice-model.ts | 49 +++++++++++ app/src/server/pi.ts | 131 ++++++++++++++++++++++++++++-- app/src/shared/usage-limit.ts | 128 +++++++++++++++++++++++++++++ app/tests/usage-limit.test.ts | 99 ++++++++++++++++++++++ app/wrangler.jsonc | 6 +- 6 files changed, 417 insertions(+), 11 deletions(-) create mode 100644 app/src/server/notice-model.ts create mode 100644 app/src/shared/usage-limit.ts create mode 100644 app/tests/usage-limit.test.ts diff --git a/app/src/client/pages/ChatPage.tsx b/app/src/client/pages/ChatPage.tsx index 42637ba..9dd8ff3 100644 --- a/app/src/client/pages/ChatPage.tsx +++ b/app/src/client/pages/ChatPage.tsx @@ -17,6 +17,7 @@ import { type PiModel, type PiSettings, } from "../../shared/apps"; +import { limitNote, type UsageStatus } from "../../shared/usage-limit"; import { Composer } from "../components/Composer"; import { IconArrowUp, @@ -114,7 +115,11 @@ const PLACEHOLDERS = [ ]; /** The slice of the agent's state a chat listens to (see PiState on the server). */ -type ChatAgentState = { connectError?: string; gcalReady?: boolean }; +type ChatAgentState = { + connectError?: string; + gcalReady?: boolean; + usage?: UsageStatus; +}; type ChatPageProps = { chatId: string; @@ -151,12 +156,15 @@ function ChatBody({ // a consent card must not call it on until it has. const [engineNote, setEngineNote] = useState(null); const [gcalReady, setGcalReady] = useState(false); + /** Why answers changed: Sonnet only, or nothing left this week. */ + const [usageNote, setUsageNote] = useState(null); const agent = useAgent({ agent: "pi", name: userInstance(identity.netid, chatId), onStateUpdate: (state: ChatAgentState | null) => { setEngineNote(state?.connectError ?? null); setGcalReady(state?.gcalReady === true); + setUsageNote(state?.usage ? limitNote(state.usage) : null); }, }); // `getInitialMessages: null` short-circuits the get-messages fetch, so a @@ -655,6 +663,11 @@ function ChatBody({ )} + {usageNote && ( +
+ {usageNote} +
+ )} {(setupFailed || engineNote) && (
{/* the server names the apps it couldn't use; a setup push that diff --git a/app/src/server/notice-model.ts b/app/src/server/notice-model.ts new file mode 100644 index 0000000..2a17e98 --- /dev/null +++ b/app/src/server/notice-model.ts @@ -0,0 +1,49 @@ +import type { LanguageModel } from "ai"; + +/** Model id logged for turns the notice model answered. */ +export const NOTICE_MODEL_ID = "pi-notice"; + +const NO_TOKENS = { + inputTokens: { total: 0, noCache: 0, cacheRead: 0, cacheWrite: 0 }, + outputTokens: { total: 0, text: 0, reasoning: 0 }, +}; + +/** + * A stand-in model that answers with a fixed note and never calls a provider, + * so a turn it handles costs nothing. Used when a student is out of budget: + * the note arrives as an ordinary assistant message, in the same chat. + */ +export function noticeModel(text: string): Exclude { + return { + specificationVersion: "v4", + provider: "pi", + modelId: NOTICE_MODEL_ID, + supportedUrls: {}, + async doGenerate() { + return { + content: [{ type: "text", text }], + finishReason: { unified: "stop", raw: "stop" }, + usage: NO_TOKENS, + warnings: [], + }; + }, + async doStream() { + return { + stream: new ReadableStream({ + start(controller) { + controller.enqueue({ type: "stream-start", warnings: [] }); + controller.enqueue({ type: "text-start", id: "notice" }); + controller.enqueue({ type: "text-delta", id: "notice", delta: text }); + controller.enqueue({ type: "text-end", id: "notice" }); + controller.enqueue({ + type: "finish", + finishReason: { unified: "stop", raw: "stop" }, + usage: NO_TOKENS, + }); + controller.close(); + }, + }), + }; + }, + }; +} diff --git a/app/src/server/pi.ts b/app/src/server/pi.ts index d3902f9..9d747ff 100644 --- a/app/src/server/pi.ts +++ b/app/src/server/pi.ts @@ -6,6 +6,16 @@ import { hasToolCall, tool, type UIMessage } from "ai"; import { z } from "zod"; import { EMPTY_WORKSPACES, workspaceContext, type WorkspaceState } from "../shared/workspaces"; import { handleWorkspaceRequest, WORKSPACE_KEY } from "./workspaces"; +import { + TIER2_MODEL, + budgetFrom, + limitNote, + usageStatus, + type Budget, + type Spend, + type UsageStatus, +} from "../shared/usage-limit"; +import { NOTICE_MODEL_ID, noticeModel } from "./notice-model"; import { addStep, costUsd, @@ -45,6 +55,8 @@ export type PiState = { * successful settings push. */ connectError?: string; + /** The student's standing against the weekly budget, from their desk. */ + usage?: UsageStatus; }; const CLAUDE_MODELS = new Set(["claude-opus-5", "claude-sonnet-5"]); @@ -233,18 +245,24 @@ export class Pi extends Think { } getModel() { - const settings = this.getConfig(); - const preference = settings?.model ?? DEFAULT_CLAUDE_MODEL; + const model = this.selectedModel(); + this.turnModel = model; + return this.claude(model); + } + + /** The Claude model the student picked in the composer. */ + private selectedModel(): string { + const preference = this.getConfig()?.model ?? DEFAULT_CLAUDE_MODEL; + // Stale configs may still carry the retired "campus" preference. + return CLAUDE_MODELS.has(preference) ? preference : DEFAULT_CLAUDE_MODEL; + } + + private claude(model: string) { const key = this.env.ANTHROPIC_API_KEY; if (!key) { // No silent fallback model: fail the turn loudly so ops notices. throw new Error("ANTHROPIC_API_KEY is not configured"); } - // Stale configs may still carry the retired "campus" preference. - const model = CLAUDE_MODELS.has(preference) - ? preference - : DEFAULT_CLAUDE_MODEL; - this.turnModel = model; return createAnthropic({ apiKey: key })(model); } @@ -540,6 +558,24 @@ export class Pi extends Think { const inherited = await super.beforeTurn(ctx); const settings = this.getConfig(); if (!settings) return inherited ?? undefined; + // The weekly budget decides which model answers, or whether one does. An + // exhausted student gets the limit note from a stand-in model: no + // provider call, no app connections, nothing billed. + const usage = await this.readUsage(settings.netid); + if (usage?.blocked) { + this.turnModel = NOTICE_MODEL_ID; + return { + ...(inherited ?? {}), + model: noticeModel(limitNote(usage) ?? "You've used this week's PI allowance."), + activeTools: [], + maxSteps: 1, + }; + } + // Past the Opus budget, every answer comes from Sonnet whatever the + // composer says, the same way PrincetonCourses steps down. + const selected = this.selectedModel(); + const downgrade = usage?.tier === 2 && selected !== TIER2_MODEL; + this.turnModel = downgrade ? TIER2_MODEL : selected; const workspaceNote = await (await this.deskStub(settings.netid)).getWorkspaceContext( this.name.slice(`u-${settings.netid}-`.length) ); @@ -604,6 +640,7 @@ export class Pi extends Think { : []; return { ...(inherited ?? {}), + ...(downgrade ? { model: this.claude(TIER2_MODEL) } : {}), // The system prompt is assembled before this hook runs, so a turn that // lost an app can only correct the record here — otherwise the model // reads "Connected TigerApps: TigerJunction" and answers with the @@ -664,7 +701,8 @@ export class Pi extends Think { this.turnUsage = null; try { const netid = this.getConfig()?.netid ?? ""; - const cost = costUsd(this.turnModel, usage); + const chat = this.name.slice(`u-${netid}-`.length); + const cost = this.turnModel === NOTICE_MODEL_ID ? 0 : costUsd(this.turnModel, usage); if (cost === null) { console.warn(`usage: no price for ${this.turnModel}, add it to MODEL_PRICES`); } @@ -673,18 +711,46 @@ export class Pi extends Think { event: "pi.usage", status, user: netid ? await pseudonym(netid, this.env.SESSION_SECRET ?? "") : null, - chat: this.name.slice(`u-${netid}-`.length), + chat, model: this.turnModel, ...usage, costUsd: cost === null ? null : Math.round(cost * 1e6) / 1e6, ms: Date.now() - this.turnStartedAt, }) ); + // Counted whatever the turn's outcome: a failed or stopped turn was + // still billed for what it used. + if (netid && cost) { + this.publishUsage(await (await this.deskStub(netid)).usageRecord(chat, cost)); + } } catch (err) { console.warn("usage: couldn't log this turn", err); } } + /** + * The student's standing against the weekly budget, also pushed to this + * chat's clients so the page can say why answers changed. A desk that can't + * answer doesn't stop the turn: the budget guards cost, and an outage there + * shouldn't take PI down with it. + */ + private async readUsage(netid: string): Promise { + try { + const status = await (await this.deskStub(netid)).usageStatus(); + this.publishUsage(status); + return status; + } catch (err) { + console.warn("usage: couldn't read the weekly budget, letting the turn run", err); + return null; + } + } + + /** Every setState reaches every client, so only a change is sent. */ + private publishUsage(status: UsageStatus): void { + if (JSON.stringify(this.state?.usage) === JSON.stringify(status)) return; + this.setState({ ...this.state, usage: status }); + } + /** * Direct MCP tool call for non-chat surfaces (planner, agenda). Returns the * tool's JSON payload parsed from its text content. @@ -895,6 +961,53 @@ export class Pi extends Think { await this.ctx.storage.put("gcal_tokens", tokens); } + /** DO-RPC (desk only): count one turn's spend against the student's week. */ + async usageRecord(chat: string, usd: number): Promise { + const now = Date.now(); + const budget = this.budget(); + this.usageTable(); + if (usd > 0) { + this.ctx.storage.sql.exec( + "INSERT INTO pi_usage (at, micros, chat) VALUES (?, ?, ?)", + now, + Math.round(usd * 1_000_000), + chat + ); + } + // Spend older than the window never counts again. Pruned here, on a write + // the turn already causes, so no timer has to wake the desk to do it. + this.ctx.storage.sql.exec("DELETE FROM pi_usage WHERE at <= ?", now - budget.windowMs); + return this.usageAt(now, budget); + } + + /** DO-RPC (desk only): the student's standing against the weekly budget. */ + async usageStatus(): Promise { + this.usageTable(); + return this.usageAt(Date.now(), this.budget()); + } + + private usageAt(now: number, budget: Budget): UsageStatus { + const spends: Spend[] = [ + ...this.ctx.storage.sql.exec<{ at: number; micros: number }>( + "SELECT at, micros FROM pi_usage WHERE at > ?", + now - budget.windowMs + ), + ].map((row) => ({ at: row.at, usd: row.micros / 1_000_000 })); + return usageStatus(spends, now, budget); + } + + /** Spend lives on the desk: one ledger per student, shared by every chat. */ + private usageTable(): void { + if (!this.isDesk()) throw new Error("usage is kept on the desk"); + this.ctx.storage.sql.exec( + "CREATE TABLE IF NOT EXISTS pi_usage (at INTEGER NOT NULL, micros INTEGER NOT NULL, chat TEXT NOT NULL)" + ); + } + + private budget(): Budget { + return budgetFrom(this.env); + } + /** DO-RPC: whether the user has connected Google Calendar. */ async gcalTokensHas(): Promise { return (await this.ctx.storage.get("gcal_tokens")) != null; diff --git a/app/src/shared/usage-limit.ts b/app/src/shared/usage-limit.ts new file mode 100644 index 0000000..76afb5d --- /dev/null +++ b/app/src/shared/usage-limit.ts @@ -0,0 +1,128 @@ +/** + * Each student's weekly model budget, in dollars. The tiers are copied from + * PrincetonCourses' ask gateway (tiger-junction, apps/ask-gateway/app/ + * usage_tracker.py): $3.00 of Opus 5, then Sonnet 5 for another $1.00, then + * nothing until spend frees up. PrincetonCourses resets every 8 hours; PI + * keeps one rolling 7-day window instead, so each turn's cost stops counting + * exactly a week after it was spent. + */ + +export type Budget = { + /** Spend allowed on any model, Opus included. */ + tier1Usd: number; + /** Further spend allowed on Sonnet only, once tier 1 is used up. */ + tier2Usd: number; + windowMs: number; +}; + +export const WEEK_MS = 7 * 24 * 60 * 60 * 1000; + +export const DEFAULT_BUDGET: Budget = { tier1Usd: 3, tier2Usd: 1, windowMs: WEEK_MS }; + +/** The model a student drops to once their Opus budget is spent. */ +export const TIER2_MODEL = "claude-sonnet-5"; + +/** + * The dollar amounts can be changed per deploy (Worker vars) without a code + * change. Anything unset, empty or not a non-negative number keeps the default. + */ +export function budgetFrom(env: { + USAGE_TIER1_USD?: string; + USAGE_TIER2_USD?: string; +}): Budget { + const usd = (raw: string | undefined, fallback: number) => { + const value = raw?.trim() ? Number(raw) : NaN; + return Number.isFinite(value) && value >= 0 ? value : fallback; + }; + return { + tier1Usd: usd(env.USAGE_TIER1_USD, DEFAULT_BUDGET.tier1Usd), + tier2Usd: usd(env.USAGE_TIER2_USD, DEFAULT_BUDGET.tier2Usd), + windowMs: WEEK_MS, + }; +} + +/** One turn's model spend. */ +export type Spend = { at: number; usd: number }; + +export type UsageStatus = { + spentUsd: number; + limitUsd: number; + /** 1: any model. 2: Opus budget spent, Sonnet only. Exhausted: nothing left. */ + tier: 1 | 2 | "exhausted"; + blocked: boolean; + percentUsed: number; + /** + * When enough old spend ages out to lift the student back up a tier (ms + * since epoch), or null when nothing is being held back. + */ + resetAt: number | null; +}; + +const round = (value: number, places: number) => + Math.round(value * 10 ** places) / 10 ** places; + +export function usageStatus( + spends: Spend[], + now: number, + budget: Budget = DEFAULT_BUDGET +): UsageStatus { + const live = spends + .filter((s) => s.at > now - budget.windowMs && s.at <= now) + .sort((a, b) => a.at - b.at); + const spent = live.reduce((total, s) => total + s.usd, 0); + const limit = budget.tier1Usd + budget.tier2Usd; + const tier: UsageStatus["tier"] = + spent < budget.tier1Usd ? 1 : spent < limit ? 2 : "exhausted"; + + // The next tier up comes back once enough of the oldest spend has aged out + // to drop the total below that tier's ceiling. + const ceiling = tier === 2 ? budget.tier1Usd : tier === "exhausted" ? limit : null; + let resetAt: number | null = null; + if (ceiling !== null) { + let remaining = spent; + for (const s of live) { + remaining -= s.usd; + if (remaining < ceiling) { + resetAt = s.at + budget.windowMs; + break; + } + } + } + + return { + spentUsd: round(spent, 4), + limitUsd: limit, + tier, + blocked: tier === "exhausted", + percentUsed: limit > 0 ? Math.min(100, round((spent / limit) * 100, 1)) : 100, + resetAt, + }; +} + +/** "Tue, Oct 14, 3:10 PM", in Princeton's time zone. */ +export function formatReset(at: number): string { + return new Date(at).toLocaleString("en-US", { + timeZone: "America/New_York", + weekday: "short", + month: "short", + day: "numeric", + hour: "numeric", + minute: "2-digit", + }); +} + +/** What a student reads when a limit changes how PI answers them. */ +export function limitNote(status: UsageStatus): string | null { + const when = status.resetAt == null ? null : formatReset(status.resetAt); + if (status.blocked) { + return when + ? `You've used this week's PI allowance. It frees up ${when}.` + : "You've used this week's PI allowance."; + } + if (status.tier === 2) { + return when + ? `You've used this week's Opus budget, so PI is answering with Sonnet 5 until ${when}.` + : "You've used this week's Opus budget, so PI is answering with Sonnet 5 for now."; + } + return null; +} diff --git a/app/tests/usage-limit.test.ts b/app/tests/usage-limit.test.ts new file mode 100644 index 0000000..546c4b7 --- /dev/null +++ b/app/tests/usage-limit.test.ts @@ -0,0 +1,99 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { streamText } from "ai"; +import { NOTICE_MODEL_ID, noticeModel } from "../src/server/notice-model.ts"; +import { + DEFAULT_BUDGET, + WEEK_MS, + budgetFrom, + formatReset, + limitNote, + usageStatus, +} from "../src/shared/usage-limit.ts"; + +const DAY = 24 * 60 * 60 * 1000; +// Wed, Oct 14 2026, 3:10 PM in Princeton (19:10 UTC, daylight time). +const now = Date.UTC(2026, 9, 14, 19, 10); + +test("under $3 a student can use any model", () => { + const s = usageStatus([{ at: now - DAY, usd: 1.25 }], now); + assert.equal(s.tier, 1); + assert.equal(s.blocked, false); + assert.equal(s.spentUsd, 1.25); + assert.equal(s.limitUsd, 4); + assert.equal(s.percentUsed, 31.3); + assert.equal(s.resetAt, null); + assert.equal(limitNote(s), null); +}); + +test("past $3 it's Sonnet only, until enough old spend ages out", () => { + const spends = [ + { at: now - 5 * DAY, usd: 2 }, + { at: now - 2 * DAY, usd: 1.2 }, + ]; + const s = usageStatus(spends, now); + assert.equal(s.tier, 2); + assert.equal(s.blocked, false); + // Dropping the $2 turn leaves $1.20, back under $3. + assert.equal(s.resetAt, now - 5 * DAY + WEEK_MS); + assert.match(limitNote(s)!, /^You've used this week's Opus budget, so PI is answering with Sonnet 5 until Fri, Oct 16, 3:10 PM\.$/); +}); + +test("at $4 PI stops answering until the week rolls over far enough", () => { + const spends = [ + { at: now - 6 * DAY, usd: 0.5 }, + { at: now - 4 * DAY, usd: 0.25 }, + { at: now - 3 * DAY, usd: 3.5 }, + ]; + const s = usageStatus(spends, now); + assert.equal(s.tier, "exhausted"); + assert.equal(s.blocked, true); + assert.equal(s.percentUsed, 100); + // $4.25 total: losing the $0.50 turn leaves $3.75, under $4. + assert.equal(s.resetAt, now - 6 * DAY + WEEK_MS); + assert.match(limitNote(s)!, /^You've used this week's PI allowance\. It frees up Thu, Oct 15, 3:10 PM\.$/); +}); + +test("only the last seven days count", () => { + const s = usageStatus( + [ + { at: now - WEEK_MS, usd: 10 }, + { at: now - WEEK_MS - DAY, usd: 10 }, + { at: now + DAY, usd: 10 }, + { at: now - 1, usd: 0.5 }, + ], + now + ); + assert.equal(s.spentUsd, 0.5); + assert.equal(s.tier, 1); +}); + +test("budget amounts come from Worker vars, with PrincetonCourses' numbers as the default", () => { + assert.deepEqual(budgetFrom({}), DEFAULT_BUDGET); + assert.deepEqual(budgetFrom({ USAGE_TIER1_USD: "5", USAGE_TIER2_USD: "2.5" }), { + tier1Usd: 5, + tier2Usd: 2.5, + windowMs: WEEK_MS, + }); + assert.equal(budgetFrom({ USAGE_TIER1_USD: "", USAGE_TIER2_USD: "-1" }).tier1Usd, 3); + assert.equal(budgetFrom({ USAGE_TIER2_USD: "lots" }).tier2Usd, 1); + assert.equal(budgetFrom({ USAGE_TIER2_USD: "0" }).tier2Usd, 0); +}); + +test("reset times read in Princeton's time zone", () => { + assert.equal(formatReset(now), "Wed, Oct 14, 3:10 PM"); +}); + +test("the stand-in model answers with the note and costs nothing", async () => { + const note = "You've used this week's PI allowance. It frees up Thu, Oct 15, 3:10 PM."; + const result = streamText({ model: noticeModel(note), prompt: "what's open at Whitman" }); + let text = ""; + for await (const part of result.fullStream) { + if (part.type === "text-delta") text += part.text; + } + assert.equal(text, note); + const usage = await result.usage; + assert.equal(usage.inputTokens, 0); + assert.equal(usage.outputTokens, 0); + assert.equal((await result.response).modelId, NOTICE_MODEL_ID); +}); diff --git a/app/wrangler.jsonc b/app/wrangler.jsonc index 2d25030..d75d61e 100644 --- a/app/wrangler.jsonc +++ b/app/wrangler.jsonc @@ -21,7 +21,11 @@ "ENGINE_MCP_BASE": "https://junction-engine.tigerapps.org", "APP_ORIGIN": "https://pi.tigerapps.org", // Public OAuth client id from the Google Cloud project; the secret is a Worker secret. - "GOOGLE_OAUTH_CLIENT_ID": "548956142814-upcmsgqr9pbafnlsorhimvje1negt5lm.apps.googleusercontent.com" + "GOOGLE_OAUTH_CLIENT_ID": "548956142814-upcmsgqr9pbafnlsorhimvje1negt5lm.apps.googleusercontent.com", + // Weekly model budget per student, in USD (src/shared/usage-limit.ts): + // any model up to tier 1, then Sonnet only for tier 2 more. + "USAGE_TIER1_USD": "3", + "USAGE_TIER2_USD": "1" }, "observability": { "enabled": true }