diff --git a/packages/core/src/kilocode/cost/max-cost-nudge.ts b/packages/core/src/kilocode/cost/max-cost-nudge.ts new file mode 100644 index 000000000000..b276689b433e --- /dev/null +++ b/packages/core/src/kilocode/cost/max-cost-nudge.ts @@ -0,0 +1,151 @@ +/** + * Soft per-session max-cost nudge. + * + * Alert (not hard-stop) the moment a session's cumulative cost crosses a + * whole-dollar threshold. The alert is non-blocking: the session keeps running + * while it is shown. Continue dismisses it (won't nag again for that limit); + * Stop is the surface's cue to abort. + * + * Cost signal: `SessionTable.cost` is written via direct SQL during message-part + * projection, so `session.updated` does NOT fire on cost change. The reliable + * signal is the per-assistant-message `cost`, summed here into a session total. + */ + +export type MaxCostChoice = "continue" | "stop" + +// Minimal shape of a message needed to aggregate session cost. +export interface MaxCostMessage { + id: string + sessionID: string + role?: string + cost?: number +} + +export class MaxCostNudge { + readonly #msgs = new Map() + readonly #totals = new Map() + readonly #floors = new Map() + readonly #alerted = new Map>() // sid -> limit values shown this run + readonly #acked = new Map>() // sid -> limit values continued past + + #limit: number | undefined + + // `> 0` rounds up to whole dollars; everything else disables (undefined). + static normalizeLimit(value: number | undefined | null): number | undefined { + if (value == null || !Number.isFinite(value) || value <= 0) return undefined + return Math.ceil(value) + } + + // Format a cost as `$X.XX`, with 4 decimals below $1. + static formatCost(value: number): string { + return `$${value.toFixed(value < 1 ? 4 : 2)}` + } + + setLimit(value: number | undefined | null): void { + this.#limit = MaxCostNudge.normalizeLimit(value) + } + + get limit(): number | undefined { + return this.#limit + } + + // Rebuild a session's total from a full message snapshot (seed on load). + resetMessageCosts(sid: string, messages: MaxCostMessage[]): number { + this.#dropMessages(sid) + let total = 0 + for (const msg of messages) { + if (msg.sessionID !== sid || msg.role !== "assistant" || !Number.isFinite(msg.cost)) continue + const cost = msg.cost ?? 0 + this.#msgs.set(msg.id, { sid, cost }) + total += cost + } + this.#totals.set(sid, total) + return this.sessionCost(sid) + } + + // Floor the session total with a direct cost signal (e.g. session.cost). Monotonic. + setSessionCost(sid: string, value: number): number { + if (Number.isFinite(value)) this.#floors.set(sid, Math.max(this.#floors.get(sid) ?? 0, value)) + return this.sessionCost(sid) + } + + // Record an assistant message cost (message.updated). Returns the session total. + updateMessageCost(sid: string, id: string, role: string | undefined, value: number | undefined): number { + if (role === "assistant") { + const prev = this.#msgs.get(id) + if (Number.isFinite(value)) { + if (prev && prev.sid !== sid) { + this.#totals.set(prev.sid, Math.max(0, (this.#totals.get(prev.sid) ?? 0) - prev.cost)) + } + const before = prev?.sid === sid ? prev.cost : 0 + const cost = value! + this.#msgs.set(id, { sid, cost }) + this.#totals.set(sid, Math.max(0, (this.#totals.get(sid) ?? 0) - before + cost)) + } else if (prev) { + // value became non-finite — drop the stale contribution + this.#totals.set(prev.sid, Math.max(0, (this.#totals.get(prev.sid) ?? 0) - prev.cost)) + this.#msgs.delete(id) + } + } + return this.sessionCost(sid) + } + + // Drop a message's contribution (message.removed). + removeMessageCost(id: string): void { + const prev = this.#msgs.get(id) + if (!prev) return + this.#msgs.delete(id) + this.#totals.set(prev.sid, Math.max(0, (this.#totals.get(prev.sid) ?? 0) - prev.cost)) + } + + sessionCost(sid: string): number { + return Math.max(this.#totals.get(sid) ?? 0, this.#floors.get(sid) ?? 0) + } + + /** + * Decide whether to alert for `sid` now. Returns the limit + cost to show + * once per run, or undefined (below limit, already acknowledged, or already + * showing). Re-arm with {@link rearm} when the session runs again. + */ + check(sid: string): { limit: number; cost: number } | undefined { + const limit = this.#limit + if (limit === undefined) return undefined + const cost = this.sessionCost(sid) + if (cost < limit || this.#acked.get(sid)?.has(limit) || this.#alerted.get(sid)?.has(limit)) return undefined + this.#remember(this.#alerted, sid, limit) + return { limit, cost } + } + + // Apply the user's choice. Continue suppresses re-alerts for the current limit. + resolve(sid: string, choice: MaxCostChoice, limit = this.#limit): void { + if (choice === "continue" && limit !== undefined) this.#remember(this.#acked, sid, limit) + } + + // Re-arm alerts for a session that started running again. + rearm(sid: string): void { + this.#alerted.delete(sid) + } + + // Forget all state for a deleted session. + onSessionDeleted(sid: string): void { + this.#dropMessages(sid) + this.#totals.delete(sid) + this.#floors.delete(sid) + this.#alerted.delete(sid) + this.#acked.delete(sid) + } + + // Drop every message contribution belonging to a session. + #dropMessages(sid: string): void { + for (const [id, msg] of this.#msgs) { + if (msg.sid === sid) this.#msgs.delete(id) + } + } + + // Record a limit value seen for a session. + #remember(map: Map>, sid: string, limit: number): void { + const seen = map.get(sid) + if (seen) seen.add(limit) + else map.set(sid, new Set([limit])) + } +} diff --git a/packages/core/test/kilocode/cost/max-cost-nudge.test.ts b/packages/core/test/kilocode/cost/max-cost-nudge.test.ts new file mode 100644 index 000000000000..adcded41c09c --- /dev/null +++ b/packages/core/test/kilocode/cost/max-cost-nudge.test.ts @@ -0,0 +1,280 @@ +import { describe, expect, test } from "bun:test" +import { MaxCostNudge } from "../../../src/kilocode/cost/max-cost-nudge" + +const sid = "ses_1" + +function assistant(id: string, cost: number, sessionID = sid) { + return { id, sessionID, role: "assistant", cost } +} + +describe("MaxCostNudge.normalizeLimit", () => { + test("disables unset and non-positive values", () => { + expect(MaxCostNudge.normalizeLimit(undefined)).toBeUndefined() + expect(MaxCostNudge.normalizeLimit(null)).toBeUndefined() + expect(MaxCostNudge.normalizeLimit(0)).toBeUndefined() + expect(MaxCostNudge.normalizeLimit(-1)).toBeUndefined() + expect(MaxCostNudge.normalizeLimit(Number.NaN)).toBeUndefined() + }) + + test("rounds positive values up to whole dollars", () => { + expect(MaxCostNudge.normalizeLimit(5)).toBe(5) + expect(MaxCostNudge.normalizeLimit(4.2)).toBe(5) + expect(MaxCostNudge.normalizeLimit(0.01)).toBe(1) + }) +}) + +describe("MaxCostNudge.formatCost", () => { + test("uses extra precision below one dollar", () => { + expect(MaxCostNudge.formatCost(0.5)).toBe("$0.5000") + expect(MaxCostNudge.formatCost(0.0001)).toBe("$0.0001") + expect(MaxCostNudge.formatCost(1.5)).toBe("$1.50") + expect(MaxCostNudge.formatCost(12)).toBe("$12.00") + }) +}) + +describe("MaxCostNudge cost aggregation", () => { + test("sums assistant costs for the requested session", () => { + const nudge = new MaxCostNudge() + const total = nudge.resetMessageCosts(sid, [ + assistant("a1", 1), + { id: "u1", sessionID: sid, role: "user" }, + assistant("a2", 2.5), + assistant("a3", 9, "ses_2"), + ]) + + expect(total).toBe(3.5) + expect(nudge.sessionCost(sid)).toBe(3.5) + expect(nudge.sessionCost("ses_2")).toBe(0) + }) + + test("replaces existing message cost instead of double counting", () => { + const nudge = new MaxCostNudge() + nudge.resetMessageCosts(sid, [assistant("a1", 1)]) + + expect(nudge.updateMessageCost(sid, "a1", "assistant", 4)).toBe(4) + expect(nudge.updateMessageCost(sid, "a2", "assistant", 1)).toBe(5) + expect(nudge.sessionCost(sid)).toBe(5) + }) + + test("reset replaces stale message costs for the session", () => { + const nudge = new MaxCostNudge() + nudge.resetMessageCosts(sid, [assistant("a1", 4), assistant("a2", 3)]) + nudge.resetMessageCosts(sid, [assistant("a2", 1)]) + + expect(nudge.sessionCost(sid)).toBe(1) + }) + + test("floors total from direct session cost signal", () => { + const nudge = new MaxCostNudge() + + nudge.updateMessageCost(sid, "a1", "assistant", 2) + + expect(nudge.setSessionCost(sid, 5)).toBe(5) + expect(nudge.setSessionCost(sid, 3)).toBe(5) + expect(nudge.setSessionCost(sid, Number.NaN)).toBe(5) + expect(nudge.sessionCost(sid)).toBe(5) + }) + + test("does not overcount when a floored message later updates", () => { + const nudge = new MaxCostNudge() + + nudge.updateMessageCost(sid, "a1", "assistant", 2) + nudge.setSessionCost(sid, 5) + // The message's own cost catches up to the floor; total must not stack to 8. + nudge.updateMessageCost(sid, "a1", "assistant", 5) + + expect(nudge.sessionCost(sid)).toBe(5) + }) + + test("moves message cost between sessions", () => { + const nudge = new MaxCostNudge() + + nudge.updateMessageCost("ses_a", "m1", "assistant", 5) + nudge.updateMessageCost("ses_b", "m1", "assistant", 7) + + expect(nudge.sessionCost("ses_a")).toBe(0) + expect(nudge.sessionCost("ses_b")).toBe(7) + }) + + test("removes a message contribution", () => { + const nudge = new MaxCostNudge() + nudge.resetMessageCosts(sid, [assistant("a1", 2), assistant("a2", 3)]) + nudge.removeMessageCost("a1") + + expect(nudge.sessionCost(sid)).toBe(3) + }) + + test("clears stale cost when value becomes non-finite", () => { + const nudge = new MaxCostNudge() + nudge.updateMessageCost(sid, "a1", "assistant", 5) + nudge.updateMessageCost(sid, "a1", "assistant", undefined) + + expect(nudge.sessionCost(sid)).toBe(0) + }) + + test("ignores non-assistant message costs", () => { + const nudge = new MaxCostNudge() + nudge.updateMessageCost(sid, "a1", "assistant", 3) + + expect(nudge.updateMessageCost(sid, "u1", "user", 10)).toBe(3) + expect(nudge.sessionCost(sid)).toBe(3) + }) + + test("ignores non-finite assistant costs for new messages", () => { + const nudge = new MaxCostNudge() + nudge.updateMessageCost(sid, "a1", "assistant", 3) + + expect(nudge.updateMessageCost(sid, "a2", "assistant", Number.NaN)).toBe(3) + expect(nudge.updateMessageCost(sid, "a3", "assistant", undefined)).toBe(3) + expect(nudge.sessionCost(sid)).toBe(3) + }) + + test("removing a message does not drop below the session-cost floor", () => { + const nudge = new MaxCostNudge() + nudge.updateMessageCost(sid, "a1", "assistant", 4) + nudge.setSessionCost(sid, 6) + + nudge.removeMessageCost("a1") + expect(nudge.sessionCost(sid)).toBe(6) + }) +}) + +describe("MaxCostNudge alerts", () => { + test("alerts once when the session crosses the limit", () => { + const nudge = new MaxCostNudge() + nudge.setLimit(5) + + nudge.updateMessageCost(sid, "a1", "assistant", 4.99) + expect(nudge.check(sid)).toBeUndefined() + + nudge.updateMessageCost(sid, "a2", "assistant", 0.01) + expect(nudge.check(sid)).toEqual({ limit: 5, cost: 5 }) + expect(nudge.check(sid)).toBeUndefined() + }) + + test("never alerts without a configured limit", () => { + const nudge = new MaxCostNudge() + nudge.updateMessageCost(sid, "a1", "assistant", 999) + + expect(nudge.check(sid)).toBeUndefined() + }) + + test("continue suppresses re-alerts until the limit changes", () => { + const nudge = new MaxCostNudge() + nudge.setLimit(5) + nudge.updateMessageCost(sid, "a1", "assistant", 6) + + expect(nudge.check(sid)?.cost).toBe(6) + nudge.resolve(sid, "continue") + + nudge.rearm(sid) + expect(nudge.check(sid)).toBeUndefined() + + nudge.setLimit(10) + nudge.updateMessageCost(sid, "a2", "assistant", 5) + expect(nudge.check(sid)).toEqual({ limit: 10, cost: 11 }) + }) + + test("active alerts are keyed by limit", () => { + const nudge = new MaxCostNudge() + + nudge.setLimit(5) + nudge.updateMessageCost(sid, "a1", "assistant", 7) + + expect(nudge.check(sid)).toEqual({ limit: 5, cost: 7 }) + + nudge.setLimit(6) + expect(nudge.check(sid)).toEqual({ limit: 6, cost: 7 }) + }) + + test("resolving with explicit limit acks that limit", () => { + const nudge = new MaxCostNudge() + + nudge.setLimit(5) + nudge.updateMessageCost(sid, "a1", "assistant", 7) + + expect(nudge.check(sid)).toEqual({ limit: 5, cost: 7 }) + nudge.setLimit(6) + nudge.resolve(sid, "continue", 5) + + nudge.rearm(sid) + expect(nudge.check(sid)).toEqual({ limit: 6, cost: 7 }) + + nudge.setLimit(5) + nudge.rearm(sid) + expect(nudge.check(sid)).toBeUndefined() + }) + + test("does not re-alert a limit value already seen this run", () => { + const nudge = new MaxCostNudge() + nudge.setLimit(5) + nudge.updateMessageCost(sid, "a1", "assistant", 7) + + expect(nudge.check(sid)).toEqual({ limit: 5, cost: 7 }) + nudge.setLimit(6) + expect(nudge.check(sid)).toEqual({ limit: 6, cost: 7 }) + + // Flipping the limit back to an already-alerted value stays silent. + nudge.setLimit(5) + expect(nudge.check(sid)).toBeUndefined() + }) + + test("continue persists per limit value across other limits", () => { + const nudge = new MaxCostNudge() + nudge.setLimit(5) + nudge.updateMessageCost(sid, "a1", "assistant", 7) + nudge.check(sid) + nudge.resolve(sid, "continue") + + nudge.setLimit(10) + nudge.updateMessageCost(sid, "a2", "assistant", 5) + nudge.check(sid) + nudge.resolve(sid, "continue") + + // Dropping back to an already-continued value stays silent. + nudge.setLimit(5) + nudge.rearm(sid) + expect(nudge.check(sid)).toBeUndefined() + }) + + test("rearm re-alerts after a stop and a new run", () => { + const nudge = new MaxCostNudge() + nudge.setLimit(5) + nudge.updateMessageCost(sid, "a1", "assistant", 7) + + expect(nudge.check(sid)?.cost).toBe(7) + nudge.resolve(sid, "stop") + expect(nudge.check(sid)).toBeUndefined() + + nudge.rearm(sid) + nudge.updateMessageCost(sid, "a2", "assistant", 1) + expect(nudge.check(sid)).toEqual({ limit: 5, cost: 8 }) + }) +}) + +describe("MaxCostNudge.onSessionDeleted", () => { + test("clears cost and alert state", () => { + const nudge = new MaxCostNudge() + nudge.setLimit(5) + nudge.resetMessageCosts(sid, [assistant("a1", 9)]) + nudge.check(sid) + + nudge.onSessionDeleted(sid) + expect(nudge.sessionCost(sid)).toBe(0) + + // A reused session id starts fresh and can alert again. + nudge.updateMessageCost(sid, "a2", "assistant", 6) + expect(nudge.check(sid)).toEqual({ limit: 5, cost: 6 }) + }) + + test("leaves other sessions intact", () => { + const nudge = new MaxCostNudge() + nudge.updateMessageCost("ses_a", "a1", "assistant", 4) + nudge.updateMessageCost("ses_b", "b1", "assistant", 7) + + nudge.onSessionDeleted("ses_a") + + expect(nudge.sessionCost("ses_a")).toBe(0) + expect(nudge.sessionCost("ses_b")).toBe(7) + }) +})