diff --git a/app/src/client/pages/ChatPage.tsx b/app/src/client/pages/ChatPage.tsx index 7cf27ed..67f1c2c 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, @@ -116,7 +117,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; @@ -153,12 +158,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 @@ -657,6 +665,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 c6a568e..b0a4f82 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"]); @@ -254,18 +266,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); } @@ -576,6 +594,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) ); @@ -640,6 +676,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 @@ -701,7 +738,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`); } @@ -710,18 +748,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. @@ -932,6 +998,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 c6492bc..4294d28 100644 --- a/app/wrangler.jsonc +++ b/app/wrangler.jsonc @@ -25,7 +25,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 }