Public: anyone can read this; the crew can change it.
A new account starts with a model budget of zero, and the owner can give it a capped grant on purpose #2140
scout/forge:scout/1145-a-new-account-starts-with-a-model-budget → main 2 commits fork
12 files
changed +756
−4
src/actions/model_grant.ts added +69
| @@ -0,0 +1,69 @@ | ||
| 1 | /** | |
| 2 | * An account's model budget: a forge admin gives a person a capped grant | |
| 3 | * (dollars a month) or takes it back, and a person adds their own | |
| 4 | * subscription. The grant is an event on the outbox, so the audit has it. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import { | |
| 9 | addOwnSubscription, | |
| 10 | ownSubscription, | |
| 11 | setModelGrant, | |
| 12 | validGrant, | |
| 13 | } from "../core/model_grant.ts"; | |
| 14 | import { getUserByName, type User } from "../core/users.ts"; | |
| 15 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 16 | import { requireUser } from "./access.ts"; | |
| 17 | import type { SubscriptionError } from "../core/subscriptions.ts"; | |
| 18 | ||
| 19 | export type ModelGrantError = "not_found" | "not_allowed" | "invalid_amount"; | |
| 20 | ||
| 21 | /** A person's account, for a forge admin who is a person: not an agent, not an org, not another admin. */ | |
| 22 | export function setAccountGrant( | |
| 23 | app: App, | |
| 24 | actor: User | undefined, | |
| 25 | username: string, | |
| 26 | usd: number | null, | |
| 27 | ): Result<{ username: string; usdPerMonth: number | null }, ModelGrantError> { | |
| 28 | const admin = requireUser(actor); | |
| 29 | if (!admin.ok || !admin.value.isAdmin || admin.value.kind !== "user") | |
| 30 | return err("not_found"); | |
| 31 | const user = getUserByName(app.db, username); | |
| 32 | if (user === undefined || user.kind === "org") return err("not_found"); | |
| 33 | if (user.kind === "agent" || user.isAdmin) return err("not_allowed"); | |
| 34 | if (usd !== null && !validGrant(usd)) return err("invalid_amount"); | |
| 35 | setModelGrant(app.db, user.id, usd, admin.value.id, new Date()); | |
| 36 | app.bus.append({ | |
| 37 | kind: "account.model_granted", | |
| 38 | actorId: admin.value.id, | |
| 39 | payload: { | |
| 40 | username: user.username, | |
| 41 | usdPerMonth: usd === null ? null : Math.round(usd * 100) / 100, | |
| 42 | }, | |
| 43 | }); | |
| 44 | return ok({ | |
| 45 | username: user.username, | |
| 46 | usdPerMonth: usd === null ? null : Math.round(usd * 100) / 100, | |
| 47 | }); | |
| 48 | } | |
| 49 | ||
| 50 | /** The signed-in person adds their own model subscription, for their own repositories. */ | |
| 51 | export function addOwnModel( | |
| 52 | app: App, | |
| 53 | actor: User | undefined, | |
| 54 | input: { token: string; apiBase?: string | undefined }, | |
| 55 | ): Result<null, SubscriptionError | "not_allowed"> { | |
| 56 | const user = requireUser(actor); | |
| 57 | if (!user.ok || user.value.kind !== "user") return err("not_allowed"); | |
| 58 | const added = addOwnSubscription(app.db, app.config.dataDir, user.value, input); | |
| 59 | if (!added.ok) return added; | |
| 60 | app.bus.append({ | |
| 61 | kind: "account.model_added", | |
| 62 | actorId: user.value.id, | |
| 63 | payload: { username: user.value.username }, | |
| 64 | }); | |
| 65 | return ok(null); | |
| 66 | } | |
| 67 | ||
| 68 | export const hasOwnModel = (app: App, user: User): boolean => | |
| 69 | ownSubscription(app.db, user.username) !== undefined; |
src/core/migrations/20261016140000-a-model-grant.ts added +10
| @@ -0,0 +1,10 @@ | ||
| 1 | // A new account has a model budget of zero (#1145). A forge admin may give one | |
| 2 | // a capped grant, in dollars per month, spent on the forge's own credential. | |
| 3 | export default ` | |
| 4 | CREATE TABLE model_grant ( | |
| 5 | user_id TEXT PRIMARY KEY REFERENCES user(id) ON DELETE CASCADE, | |
| 6 | usd_per_month REAL NOT NULL CHECK (usd_per_month > 0), | |
| 7 | granted_by TEXT, | |
| 8 | granted_at TEXT NOT NULL | |
| 9 | ) WITHOUT ROWID; | |
| 10 | `; |
src/core/model_grant.ts added +131
| @@ -0,0 +1,131 @@ | ||
| 1 | /** | |
| 2 | * What an account may spend on a model. A new account has nothing: its | |
| 3 | * crew runs only on a subscription it added itself (granted to its own | |
| 4 | * repositories alone), or on a capped grant a forge admin gave it — dollars | |
| 5 | * per month, spent on the forge's own credential and counted from the usage | |
| 6 | * ledger, so a run at work is counted already. Pure data; who may call is | |
| 7 | * the caller's to decide (`actions/model_grant.ts`). | |
| 8 | */ | |
| 9 | ||
| 10 | import type { Database } from "bun:sqlite"; | |
| 11 | import { | |
| 12 | addSubscription, | |
| 13 | getSubscriptionByName, | |
| 14 | NAME_MAX, | |
| 15 | PLATFORM, | |
| 16 | setGrants, | |
| 17 | EVERYONE, | |
| 18 | type Subscription, | |
| 19 | type SubscriptionError, | |
| 20 | } from "./subscriptions.ts"; | |
| 21 | import type { Result } from "../kernel/result.ts"; | |
| 22 | ||
| 23 | /** The most a monthly grant may be, in dollars. */ | |
| 24 | export const GRANT_MAX_USD = 10_000; | |
| 25 | ||
| 26 | export interface ModelGrant { | |
| 27 | readonly usdPerMonth: number; | |
| 28 | readonly grantedAt: string; | |
| 29 | } | |
| 30 | ||
| 31 | export const monthStart = (now: Date): string => | |
| 32 | new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString(); | |
| 33 | ||
| 34 | export function getModelGrant(db: Database, userId: string): ModelGrant | undefined { | |
| 35 | const row = db | |
| 36 | .query<{ usd_per_month: number; granted_at: string }, [string]>( | |
| 37 | "SELECT usd_per_month, granted_at FROM model_grant WHERE user_id = ?1", | |
| 38 | ) | |
| 39 | .get(userId); | |
| 40 | return row ? { usdPerMonth: row.usd_per_month, grantedAt: row.granted_at } : undefined; | |
| 41 | } | |
| 42 | ||
| 43 | /** Whole cents, above zero and within the ceiling; anything else is not a grant. */ | |
| 44 | export function validGrant(usd: number): boolean { | |
| 45 | return Number.isFinite(usd) && usd >= 0.01 && usd <= GRANT_MAX_USD; | |
| 46 | } | |
| 47 | ||
| 48 | /** Set (dollars) or take back (null) an account's monthly grant. False when the amount is not valid. */ | |
| 49 | export function setModelGrant( | |
| 50 | db: Database, | |
| 51 | userId: string, | |
| 52 | usd: number | null, | |
| 53 | by: string, | |
| 54 | now: Date, | |
| 55 | ): boolean { | |
| 56 | if (usd === null) { | |
| 57 | db.query("DELETE FROM model_grant WHERE user_id = ?1").run(userId); | |
| 58 | return true; | |
| 59 | } | |
| 60 | if (!validGrant(usd)) return false; | |
| 61 | db.query( | |
| 62 | `INSERT INTO model_grant (user_id, usd_per_month, granted_by, granted_at) | |
| 63 | VALUES (?1, ?2, ?3, ?4) | |
| 64 | ON CONFLICT(user_id) DO UPDATE SET usd_per_month = ?2, granted_by = ?3, granted_at = ?4`, | |
| 65 | ).run(userId, Math.round(usd * 100) / 100, by, now.toISOString()); | |
| 66 | return true; | |
| 67 | } | |
| 68 | ||
| 69 | /** | |
| 70 | * What the account's repositories have spent on the forge's own credential | |
| 71 | * this month (UTC), running runs included. | |
| 72 | */ | |
| 73 | export function monthSpent(db: Database, userId: string, now: Date): number { | |
| 74 | return ( | |
| 75 | db | |
| 76 | .query<{ n: number }, [string, string, string]>( | |
| 77 | `SELECT COALESCE(SUM(u.cost_usd), 0) AS n | |
| 78 | FROM usage u JOIN repo r ON r.id = u.repo_id | |
| 79 | WHERE r.owner_id = ?1 AND u.subscription_id = ?2 AND u.at >= ?3`, | |
| 80 | ) | |
| 81 | .get(userId, PLATFORM, monthStart(now))?.n ?? 0 | |
| 82 | ); | |
| 83 | } | |
| 84 | ||
| 85 | /** Dollars left of the grant this month; undefined when there is none. */ | |
| 86 | export function grantLeft(db: Database, userId: string, now: Date): number | undefined { | |
| 87 | const grant = getModelGrant(db, userId); | |
| 88 | return grant === undefined | |
| 89 | ? undefined | |
| 90 | : Math.max(0, grant.usdPerMonth - monthSpent(db, userId, now)); | |
| 91 | } | |
| 92 | ||
| 93 | const ownName = (username: string): string => `${username}-own`.slice(0, NAME_MAX); | |
| 94 | ||
| 95 | /** The subscription an account added itself, if it has. */ | |
| 96 | export function ownSubscription(db: Database, username: string): Subscription | undefined { | |
| 97 | return getSubscriptionByName(db, ownName(username)); | |
| 98 | } | |
| 99 | ||
| 100 | /** | |
| 101 | * Add the account's own model subscription and grant it to the account's own | |
| 102 | * repositories — the owner scope — and nowhere else. One per account. | |
| 103 | */ | |
| 104 | export function addOwnSubscription( | |
| 105 | db: Database, | |
| 106 | dataDir: string, | |
| 107 | user: { id: string; username: string }, | |
| 108 | input: { token: string; apiBase?: string | undefined }, | |
| 109 | ): Result<Subscription, SubscriptionError> { | |
| 110 | const added = addSubscription(db, dataDir, { | |
| 111 | name: ownName(user.username), | |
| 112 | token: input.token, | |
| 113 | apiBase: input.apiBase, | |
| 114 | createdBy: user.id, | |
| 115 | }); | |
| 116 | if (added.ok) setGrants(db, user.id, EVERYONE, [added.value.id]); | |
| 117 | return added; | |
| 118 | } | |
| 119 | ||
| 120 | /** The one line an account's page says about its model budget. */ | |
| 121 | export function budgetLine(db: Database, user: { id: string; username: string; isAdmin: boolean }, now: Date): string { | |
| 122 | if (user.isAdmin) return "Model budget: the forge's own credential."; | |
| 123 | if (ownSubscription(db, user.username) !== undefined) | |
| 124 | return "Model budget: its own subscription, for its own repositories."; | |
| 125 | const grant = getModelGrant(db, user.id); | |
| 126 | if (grant !== undefined) { | |
| 127 | const left = grantLeft(db, user.id, now)!; | |
| 128 | return `Model budget: a grant of $${grant.usdPerMonth.toFixed(2)} a month, $${left.toFixed(2)} left.`; | |
| 129 | } | |
| 130 | return "Model budget: $0. Add your own subscription, or ask an admin for a grant."; | |
| 131 | } |
src/crew/runner.ts +39 −4
| @@ -110,9 +110,11 @@ import { laterGate } from "./later.ts"; | ||
| 110 | 110 | import { parkedTwice } from "./parks.ts"; |
| 111 | 111 | import { noteLimit } from "../core/standing.ts"; |
| 112 | 112 | import { pauseReason } from "./pacing.ts"; |
| 113 | import { grantLeft } from "../core/model_grant.ts"; | |
| 113 | 114 | import { |
| 114 | 115 | credentialEnvOf, |
| 115 | 116 | hostOfApiBase, |
| 117 | MIN_RUN_USD, | |
| 116 | 118 | pickSubscription, |
| 117 | 119 | PLATFORM, |
| 118 | 120 | restSubscription, |
| @@ -312,6 +314,7 @@ export async function executeAgentRun( | ||
| 312 | 314 | subscriptionId: null, |
| 313 | 315 | kind: usageKind(app, claimed), |
| 314 | 316 | reportedAt: 0, |
| 317 | stop: () => controller.abort(), | |
| 315 | 318 | }; |
| 316 | 319 | let outcome: Outcome; |
| 317 | 320 | try { |
| @@ -536,6 +539,12 @@ interface Meter { | ||
| 536 | 539 | kind: UsageKind; |
| 537 | 540 | /** When a `running` line was last written (epoch ms); 0 for never. */ |
| 538 | 541 | reportedAt: number; |
| 542 | /** Ends the run. */ | |
| 543 | stop: () => void; | |
| 544 | /** Set when the run spends an owner's capped grant: whose. */ | |
| 545 | grantOwner?: string; | |
| 546 | /** Why the run was stopped by its grant's cap, when it was. */ | |
| 547 | stoppedFor?: string; | |
| 539 | 548 | } |
| 540 | 549 | |
| 541 | 550 | /** What a run is for, as the ledger sums it: its reason, or its agent's role. */ |
| @@ -553,6 +562,10 @@ function usageKind(app: App, run: Run): UsageKind { | ||
| 553 | 562 | /** How often a running session's spend is written and announced, at most. */ |
| 554 | 563 | const LIVE_MS = 2_000; |
| 555 | 564 | |
| 565 | /** Said on a run stopped at its grant's cap. */ | |
| 566 | const GRANT_SPENT = | |
| 567 | "This month's model grant is spent: the run stopped at the cap; an admin can raise it"; | |
| 568 | ||
| 556 | 569 | /** |
| 557 | 570 | * A running session's spend so far, as its `running` line in the ledger, |
| 558 | 571 | * and a `usage.delta` on the outbox so the board and the Subscriptions page |
| @@ -586,6 +599,14 @@ function meterLive( | ||
| 586 | 599 | outcome: "running", |
| 587 | 600 | at: new Date(now).toISOString(), |
| 588 | 601 | }); |
| 602 | // The cap is checked on each spend tick, not only at the start. | |
| 603 | if (meter.grantOwner !== undefined && meter.stoppedFor === undefined) { | |
| 604 | const left = grantLeft(app.db, meter.grantOwner, new Date(now)); | |
| 605 | if (left !== undefined && left <= 0) { | |
| 606 | meter.stoppedFor = GRANT_SPENT; | |
| 607 | meter.stop(); | |
| 608 | } | |
| 609 | } | |
| 589 | 610 | app.bus.append({ |
| 590 | 611 | kind: "usage.delta", |
| 591 | 612 | repoId: run.repoId, |
| @@ -973,9 +994,17 @@ async function work( | ||
| 973 | 994 | } |
| 974 | 995 | // The forge's own token is for admin-owned repositories only; anyone |
| 975 | 996 | // else's run waits for a grant rather than spend what is not theirs. |
| 976 | if (picked.kind === "none") { | |
| 997 | // The owner's capped monthly grant (`core/model_grant.ts`) is the one | |
| 998 | // way past it: the forge's token, up to what is left of the month. | |
| 999 | const grantCap = | |
| 1000 | picked.kind === "none" | |
| 1001 | ? grantLeft(app.db, repo.ownerId, new Date()) | |
| 1002 | : undefined; | |
| 1003 | if (picked.kind === "none" && (grantCap === undefined || grantCap < MIN_RUN_USD)) { | |
| 977 | 1004 | const said = |
| 978 | "This repository has no model account: ask an admin to grant one"; | |
| 1005 | grantCap === undefined | |
| 1006 | ? "This repository has no model account: ask an admin to grant one" | |
| 1007 | : "This month's model grant is spent: an admin can raise it"; | |
| 979 | 1008 | write(said); |
| 980 | 1009 | return { state: "failed", summary: said }; |
| 981 | 1010 | } |
| @@ -986,6 +1015,10 @@ async function work( | ||
| 986 | 1015 | }); |
| 987 | 1016 | meter.subscriptionId = picked.subscription.id; |
| 988 | 1017 | } else { |
| 1018 | if (grantCap !== undefined) { | |
| 1019 | meter.grantOwner = repo.ownerId; | |
| 1020 | write(`model grant: $${grantCap.toFixed(2)} left this month`); | |
| 1021 | } | |
| 989 | 1022 | write("subscription: platform (env)"); |
| 990 | 1023 | noteRunProgress(app.db, run.id, { subscriptionId: PLATFORM }); |
| 991 | 1024 | meter.subscriptionId = PLATFORM; |
| @@ -1012,7 +1045,9 @@ async function work( | ||
| 1012 | 1045 | const budget = |
| 1013 | 1046 | picked.kind === "ready" && picked.capUsd !== undefined |
| 1014 | 1047 | ? Math.min(ownBudget, picked.capUsd) |
| 1015 | : ownBudget; | |
| 1048 | : grantCap !== undefined | |
| 1049 | ? Math.min(ownBudget, grantCap) | |
| 1050 | : ownBudget; | |
| 1016 | 1051 | const reserve = wrapUpReserve(budget); |
| 1017 | 1052 | // Asked again for every invocation (`crew/sandbox.ts`): an agent made |
| 1018 | 1053 | // since the last one is denied from this one on. |
| @@ -1324,7 +1359,7 @@ async function work( | ||
| 1324 | 1359 | if (signal.aborted) |
| 1325 | 1360 | return { |
| 1326 | 1361 | state: "failed", |
| 1327 | summary: "cancelled", | |
| 1362 | summary: meter.stoppedFor ?? "cancelled", | |
| 1328 | 1363 | sessionId: result.sessionId, |
| 1329 | 1364 | costUsd: result.costUsd, |
| 1330 | 1365 | turns: result.turns, |
src/http/api.ts +18
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | * back to continue); errors are `{ error, message }`. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { setAccountGrant } from "../actions/model_grant.ts"; | |
| 11 | 12 | import { storageLimitMessage } from "../core/storage.ts"; |
| 12 | 13 | import { voteVariant } from "../actions/variants.ts"; |
| 13 | 14 | import { parentForgeFor } from "../core/parent_releases.ts"; |
| @@ -1586,6 +1587,23 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1586 | 1587 | return done.ok ? json({ username: done.value.username, suspendedAt: done.value.suspendedAt }) : accountError(done.error); |
| 1587 | 1588 | }); |
| 1588 | 1589 | |
| 1590 | // A capped model grant, dollars a month; null (or 0) takes it back. | |
| 1591 | router.add("POST", "/api/v1/admin/accounts/:username/model-grant", async (ctx) => { | |
| 1592 | const denied = accountAdmin(ctx, "admin"); | |
| 1593 | if (denied) return denied; | |
| 1594 | const input = await body(ctx.request); | |
| 1595 | const raw = input.usdPerMonth; | |
| 1596 | if (raw !== null && (typeof raw !== "number" || !Number.isFinite(raw))) | |
| 1597 | return apiError("invalid", 422, "usdPerMonth is a number of dollars, or null to take the grant back"); | |
| 1598 | const done = setAccountGrant(ctx.app, ctx.auth.user, ctx.params.username!, raw === 0 ? null : raw); | |
| 1599 | if (done.ok) return json(done.value); | |
| 1600 | return done.error === "invalid_amount" | |
| 1601 | ? apiError("invalid", 422, "usdPerMonth is from 0.01 to 10000 dollars") | |
| 1602 | : done.error === "not_allowed" | |
| 1603 | ? apiError("not_allowed", 422, "a grant is for a person who is not an admin") | |
| 1604 | : notFound(); | |
| 1605 | }); | |
| 1606 | ||
| 1589 | 1607 | router.add("POST", "/api/v1/admin/accounts/:username/unsuspend", (ctx) => { |
| 1590 | 1608 | const denied = accountAdmin(ctx, "admin"); |
| 1591 | 1609 | if (denied) return denied; |
src/http/mcp.ts +42
| @@ -61,6 +61,7 @@ import { | ||
| 61 | 61 | CARD_URI, |
| 62 | 62 | cardFor, |
| 63 | 63 | } from "../web/studio/cards.ts"; |
| 64 | import { setAccountGrant } from "../actions/model_grant.ts"; | |
| 64 | 65 | import { keepThought } from "../actions/thought.ts"; |
| 65 | 66 | import { |
| 66 | 67 | FROM_WORDS, |
| @@ -954,6 +955,47 @@ const TOOLS: readonly Tool[] = [ | ||
| 954 | 955 | ); |
| 955 | 956 | }, |
| 956 | 957 | }, |
| 958 | { | |
| 959 | name: "model_grant", | |
| 960 | description: | |
| 961 | "Give a person's account a capped model grant — dollars a month, spent on the forge's own credential; a run past the cap stops and says why — or take it back (`usdPerMonth` 0). A new account has none. A forge admin who is a person, with an admin token, sets it; `dryRun` is true unless you say false. Each change is recorded in the audit.", | |
| 962 | inputSchema: { | |
| 963 | type: "object", | |
| 964 | properties: { | |
| 965 | username: { type: "string" }, | |
| 966 | usdPerMonth: { type: "number", description: "0.01 to 10000; 0 takes it back." }, | |
| 967 | dryRun: { type: "boolean", description: "Plan only (the default). Send false to set it." }, | |
| 968 | }, | |
| 969 | required: ["username", "usdPerMonth"], | |
| 970 | }, | |
| 971 | writes: true, | |
| 972 | dryByDefault: true, | |
| 973 | run(ctx, user, args) { | |
| 974 | const usd = args["usdPerMonth"]; | |
| 975 | const username = args["username"]; | |
| 976 | if (typeof username !== "string" || typeof usd !== "number" || !Number.isFinite(usd)) | |
| 977 | return bad("invalid", "send a username and usdPerMonth in dollars"); | |
| 978 | if (!mayBoards(user)) return bad("forbidden", "a model grant is a forge admin's to give"); | |
| 979 | const dryRun = args["dryRun"] !== false; | |
| 980 | if (dryRun) | |
| 981 | return good({ | |
| 982 | username, | |
| 983 | usdPerMonth: usd === 0 ? null : usd, | |
| 984 | says: "This is the plan; nothing changed. Send dryRun: false to set it.", | |
| 985 | }); | |
| 986 | if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) | |
| 987 | return bad("forbidden", "a model grant needs an admin token"); | |
| 988 | const set = setAccountGrant(ctx.app, user, username, usd === 0 ? null : usd); | |
| 989 | if (!set.ok) | |
| 990 | return bad( | |
| 991 | set.error === "invalid_amount" ? "invalid" : "forbidden", | |
| 992 | set.error === "invalid_amount" | |
| 993 | ? "usdPerMonth is from 0.01 to 10000 dollars" | |
| 994 | : "no such person, or not one a grant is for", | |
| 995 | ); | |
| 996 | return good(set.value); | |
| 997 | }, | |
| 998 | }, | |
| 957 | 999 | { |
| 958 | 1000 | name: "outsiders", |
| 959 | 1001 | description: |
src/http/server.ts +4
| @@ -153,6 +153,7 @@ import { | ||
| 153 | 153 | subscriptionHeadroom, |
| 154 | 154 | subscriptionWake, |
| 155 | 155 | } from "../web/pages/subscriptions.ts"; |
| 156 | import { grantAct, modelAdd, modelPage } from "../web/pages/model.ts"; | |
| 156 | 157 | import { |
| 157 | 158 | changePassword, |
| 158 | 159 | iconPng, |
| @@ -794,6 +795,9 @@ export function buildRouter(): Router<Handler> { | ||
| 794 | 795 | router.add("POST", "/settings/backups/mirror/clear", backupsMirrorClear); |
| 795 | 796 | router.add("POST", "/settings/backups/mirror/now", backupsMirrorNow); |
| 796 | 797 | router.add("GET", "/settings/accounts", accountsPage); |
| 798 | router.add("GET", "/settings/model", modelPage); | |
| 799 | router.add("POST", "/settings/model", modelAdd); | |
| 800 | router.add("POST", "/settings/accounts/:username/model", grantAct); | |
| 797 | 801 | router.add("GET", "/settings/accounts/:username", personSignInsPage); |
| 798 | 802 | router.add( |
| 799 | 803 | "POST", |
src/web/pages/accounts.ts +2
| @@ -42,6 +42,7 @@ import { | ||
| 42 | 42 | userLink, |
| 43 | 43 | } from "../ui.ts"; |
| 44 | 44 | import { sessionsCard } from "./account.ts"; |
| 45 | import { grantCard } from "./model.ts"; | |
| 45 | 46 | import { accountSections } from "./origins.ts"; |
| 46 | 47 | import { markOf } from "../../core/marks.ts"; |
| 47 | 48 | |
| @@ -298,6 +299,7 @@ export function personSignInsPage(ctx: Ctx): Response { | ||
| 298 | 299 | <h3>Access tokens</h3>`, |
| 299 | 300 | }, |
| 300 | 301 | )} |
| 302 | ${grantCard(ctx, user, at)} | |
| 301 | 303 | ${sessionsCard(sessions, at)}`, |
| 302 | 304 | ); |
| 303 | 305 | } |
src/web/pages/model.ts added +150
| @@ -0,0 +1,150 @@ | ||
| 1 | /** | |
| 2 | * Model — what an account may spend on a crew. A new account has nothing: | |
| 3 | * the page says so in one line, takes the person's own subscription for | |
| 4 | * their own repositories, and shows a grant an admin gave. An admin sets or | |
| 5 | * takes back the grant from the account's page (`accounts.ts` shows the | |
| 6 | * card). A token is typed once and never shown again. | |
| 7 | */ | |
| 8 | ||
| 9 | import { addOwnModel, setAccountGrant } from "../../actions/model_grant.ts"; | |
| 10 | import { | |
| 11 | budgetLine, | |
| 12 | getModelGrant, | |
| 13 | GRANT_MAX_USD, | |
| 14 | ownSubscription, | |
| 15 | } from "../../core/model_grant.ts"; | |
| 16 | import { API_BASE_MAX } from "../../core/subscriptions.ts"; | |
| 17 | import type { User } from "../../core/users.ts"; | |
| 18 | import type { Ctx } from "../../http/context.ts"; | |
| 19 | import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts"; | |
| 20 | import { field, readForm } from "../form.ts"; | |
| 21 | import { html, type Html } from "../html.ts"; | |
| 22 | import { flashTo, page } from "../layout.ts"; | |
| 23 | import { btn, card } from "../ui.ts"; | |
| 24 | import { accountOnly, accountSections } from "./origins.ts"; | |
| 25 | ||
| 26 | const MESSAGES = { | |
| 27 | invalid_name: "That name will not do.", | |
| 28 | name_taken: "You already added your own subscription.", | |
| 29 | invalid_token: | |
| 30 | "That is not a model token: one line, no spaces. One from `claude setup-token` begins sk-ant-oat; anything else is taken as an API key.", | |
| 31 | invalid_api_base: | |
| 32 | "The API base URL must be https, with no credentials, query, or hash (a Claude subscription token takes none).", | |
| 33 | not_allowed: "Only a person adds their own subscription.", | |
| 34 | }; | |
| 35 | ||
| 36 | // GET /settings/model | |
| 37 | export function modelPage(ctx: Ctx): Response { | |
| 38 | const denied = accountOnly(ctx); | |
| 39 | if (denied) return denied; | |
| 40 | const user = ctx.auth.user!; | |
| 41 | const own = ownSubscription(ctx.app.db, user.username); | |
| 42 | const form = own | |
| 43 | ? html`<p class="muted"> | |
| 44 | Your subscription <strong>${own.name}</strong> pays for the crew on your | |
| 45 | own repositories, and on no one else's. | |
| 46 | </p>` | |
| 47 | : html`<form class="stack" method="post" action="/settings/model"> | |
| 48 | <div class="field"> | |
| 49 | <label for="f-token">Token</label> | |
| 50 | <input class="input" id="f-token" name="token" type="password" | |
| 51 | required autocomplete="off" spellcheck="false" | |
| 52 | placeholder="sk-ant-… or any provider's key" /> | |
| 53 | <span class="hint"><code>claude setup-token</code> prints a | |
| 54 | subscription's token. It is sealed on this forge, never shown | |
| 55 | again, and pays only for repositories you own.</span> | |
| 56 | </div> | |
| 57 | <div class="field"> | |
| 58 | <label for="f-api-base">API base URL (optional)</label> | |
| 59 | <input class="input" id="f-api-base" name="apiBase" type="url" | |
| 60 | maxlength="${API_BASE_MAX}" autocomplete="off" spellcheck="false" | |
| 61 | placeholder="https://openrouter.ai/api" /> | |
| 62 | </div> | |
| 63 | <div>${btn("Add", { variant: "primary", size: "sm" })}</div> | |
| 64 | </form>`; | |
| 65 | return page({ | |
| 66 | ctx, | |
| 67 | title: "Model", | |
| 68 | body: html`<div class="page-head"><h1>Model</h1></div> | |
| 69 | ${settingsLayout( | |
| 70 | accountSections("model", { admin: user.isAdmin }), | |
| 71 | card(html`${form}`, { | |
| 72 | head: html`<h2>Your model budget</h2> | |
| 73 | <p class="muted" id="model-budget"> | |
| 74 | ${budgetLine(ctx.app.db, user, new Date())} | |
| 75 | </p>`, | |
| 76 | }), | |
| 77 | "Account settings", | |
| 78 | )}`, | |
| 79 | }); | |
| 80 | } | |
| 81 | ||
| 82 | // POST /settings/model | |
| 83 | export async function modelAdd(ctx: Ctx): Promise<Response> { | |
| 84 | const denied = accountOnly(ctx); | |
| 85 | if (denied) return denied; | |
| 86 | const form = await readForm(ctx, "admin"); | |
| 87 | if (form instanceof Response) return form; | |
| 88 | const added = addOwnModel(ctx.app, ctx.auth.user, { | |
| 89 | token: field(form, "token").trim(), | |
| 90 | apiBase: field(form, "apiBase").trim(), | |
| 91 | }); | |
| 92 | return flashTo( | |
| 93 | ctx, | |
| 94 | "/settings/model", | |
| 95 | added.ok | |
| 96 | ? { message: "Your subscription is added, for your own repositories." } | |
| 97 | : { tone: "danger", message: MESSAGES[added.error] }, | |
| 98 | ); | |
| 99 | } | |
| 100 | ||
| 101 | /** The admin's card on a person's page: what they have, and the grant form. */ | |
| 102 | export function grantCard(ctx: Ctx, user: User, at: string): Html { | |
| 103 | const grant = getModelGrant(ctx.app.db, user.id); | |
| 104 | return card( | |
| 105 | html`<form class="stack" method="post" action="${at}/model"> | |
| 106 | <div class="field"> | |
| 107 | <label for="f-grant">Grant, dollars a month</label> | |
| 108 | <input class="input" id="f-grant" name="usd" inputmode="decimal" | |
| 109 | autocomplete="off" placeholder="0 takes it back" | |
| 110 | value="${grant === undefined ? "" : grant.usdPerMonth.toFixed(2)}" /> | |
| 111 | <span class="hint">Spent on the forge's own credential, up to | |
| 112 | $${GRANT_MAX_USD} a month; a run past the cap stops.</span> | |
| 113 | </div> | |
| 114 | <div>${btn("Save", { variant: "primary", size: "sm" })}</div> | |
| 115 | </form>`, | |
| 116 | { | |
| 117 | head: html`<h2>Model budget</h2> | |
| 118 | <p class="muted">${budgetLine(ctx.app.db, user, new Date())}</p>`, | |
| 119 | }, | |
| 120 | ); | |
| 121 | } | |
| 122 | ||
| 123 | // POST /settings/accounts/:username/model | |
| 124 | export async function grantAct(ctx: Ctx): Promise<Response> { | |
| 125 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 126 | if (!ctx.auth.user.isAdmin) return notFoundPage(ctx); | |
| 127 | const form = await readForm(ctx, "admin"); | |
| 128 | if (form instanceof Response) return form; | |
| 129 | const username = ctx.params.username ?? ""; | |
| 130 | const raw = field(form, "usd").trim().replace(/^\$/, ""); | |
| 131 | const usd = raw === "" || Number(raw) === 0 ? null : /^\d{1,6}(\.\d{1,2})?$/.test(raw) ? Number(raw) : NaN; | |
| 132 | const done = setAccountGrant(ctx.app, ctx.auth.user, username, usd); | |
| 133 | const back = `/settings/accounts/${encodeURIComponent(username)}`; | |
| 134 | if (!done.ok) { | |
| 135 | if (done.error === "not_found") return notFoundPage(ctx); | |
| 136 | return flashTo(ctx, back, { | |
| 137 | tone: "danger", | |
| 138 | message: | |
| 139 | done.error === "invalid_amount" | |
| 140 | ? `A grant is dollars a month, from 0.01 to ${GRANT_MAX_USD}; 0 takes it back.` | |
| 141 | : "You cannot give that to an admin or an agent.", | |
| 142 | }); | |
| 143 | } | |
| 144 | return flashTo(ctx, back, { | |
| 145 | message: | |
| 146 | done.value.usdPerMonth === null | |
| 147 | ? `${username}'s grant is taken back.` | |
| 148 | : `${username} has $${done.value.usdPerMonth.toFixed(2)} a month.`, | |
| 149 | }); | |
| 150 | } |
src/web/pages/origins.ts +7
| @@ -73,6 +73,7 @@ export type AccountSection = | ||
| 73 | 73 | | "password" |
| 74 | 74 | | "tokens" |
| 75 | 75 | | "keys" |
| 76 | | "model" | |
| 76 | 77 | | "passkeys" |
| 77 | 78 | | "origins" |
| 78 | 79 | | "usage" |
| @@ -188,6 +189,12 @@ export function accountSections( | ||
| 188 | 189 | icon: "user", |
| 189 | 190 | current: current === "profile", |
| 190 | 191 | }, |
| 192 | { | |
| 193 | label: "Model", | |
| 194 | href: "/settings/model", | |
| 195 | icon: "key", | |
| 196 | current: current === "model", | |
| 197 | }, | |
| 191 | 198 | { |
| 192 | 199 | label: "Password", |
| 193 | 200 | href: "/settings/password", |
test/model-grant-pages.test.ts added +117
| @@ -0,0 +1,117 @@ | ||
| 1 | /** | |
| 2 | * The pages and the API for a model grant (#1145): a new account's page says | |
| 3 | * zero in one line, an admin sets the grant from the account's page or the | |
| 4 | * API, and no one else may. | |
| 5 | */ | |
| 6 | ||
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { getModelGrant } from "../src/core/model_grant.ts"; | |
| 13 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 14 | import { createToken } from "../src/core/tokens.ts"; | |
| 15 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 16 | import { quietLogs } from "./helpers/globals.ts"; | |
| 17 | ||
| 18 | quietLogs(); | |
| 19 | ||
| 20 | const PASS = "a-long-grant-passphrase"; | |
| 21 | ||
| 22 | describe("a model grant, from the account's page and the API", () => { | |
| 23 | let dataDir = ""; | |
| 24 | let app: App; | |
| 25 | let servers: Servers; | |
| 26 | ||
| 27 | const signIn = async (username: string) => { | |
| 28 | const res = await fetch(`${servers.url}/signin`, { | |
| 29 | method: "POST", | |
| 30 | body: new URLSearchParams({ username, password: PASS }), | |
| 31 | redirect: "manual", | |
| 32 | }); | |
| 33 | return (res.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 34 | }; | |
| 35 | ||
| 36 | beforeAll(async () => { | |
| 37 | dataDir = await mkdtemp(join(tmpdir(), "forge-grant-")); | |
| 38 | app = createApp({ dataDir, port: 0 }); | |
| 39 | servers = await serve(app); | |
| 40 | for (const [username, isAdmin] of [["alice", true], ["bob", false], ["carol", false]] as const) { | |
| 41 | const made = await createUser(app.db, { | |
| 42 | trusted: true, | |
| 43 | username, | |
| 44 | email: `${username}@x.test`, | |
| 45 | password: PASS, | |
| 46 | isAdmin, | |
| 47 | }); | |
| 48 | if (!made.ok) throw new Error(username); | |
| 49 | } | |
| 50 | }, 30_000); | |
| 51 | ||
| 52 | afterAll(async () => { | |
| 53 | servers.stop(); | |
| 54 | app.close(); | |
| 55 | await rm(dataDir, { recursive: true, force: true }); | |
| 56 | }); | |
| 57 | ||
| 58 | test("a new account's page says its budget is zero in one line", async () => { | |
| 59 | const bob = await signIn("bob"); | |
| 60 | const html = await (await fetch(`${servers.url}/settings/model`, { headers: { cookie: bob } })).text(); | |
| 61 | expect(html).toContain("Model budget: $0. Add your own subscription, or ask an admin for a grant."); | |
| 62 | }); | |
| 63 | ||
| 64 | test("an admin sets the grant from the account's page; the page shows it; a person cannot", async () => { | |
| 65 | const bob = await signIn("bob"); | |
| 66 | const refused = await fetch(`${servers.url}/settings/accounts/bob/model`, { | |
| 67 | method: "POST", | |
| 68 | headers: { cookie: bob }, | |
| 69 | body: new URLSearchParams({ usd: "20" }), | |
| 70 | redirect: "manual", | |
| 71 | }); | |
| 72 | expect(refused.status).toBe(404); | |
| 73 | expect(getModelGrant(app.db, getUserByName(app.db, "bob")!.id)).toBeUndefined(); | |
| 74 | ||
| 75 | const admin = await signIn("alice"); | |
| 76 | const set = await fetch(`${servers.url}/settings/accounts/bob/model`, { | |
| 77 | method: "POST", | |
| 78 | headers: { cookie: admin }, | |
| 79 | body: new URLSearchParams({ usd: "20" }), | |
| 80 | redirect: "manual", | |
| 81 | }); | |
| 82 | expect(set.status).toBe(303); | |
| 83 | expect(getModelGrant(app.db, getUserByName(app.db, "bob")!.id)?.usdPerMonth).toBe(20); | |
| 84 | const theirs = await (await fetch(`${servers.url}/settings/model`, { headers: { cookie: bob } })).text(); | |
| 85 | expect(theirs).toContain("a grant of $20.00 a month, $20.00 left"); | |
| 86 | const page = await (await fetch(`${servers.url}/settings/accounts/bob`, { headers: { cookie: admin } })).text(); | |
| 87 | expect(page).toContain("a grant of $20.00 a month"); | |
| 88 | // Nonsense is refused and changes nothing. | |
| 89 | await fetch(`${servers.url}/settings/accounts/bob/model`, { | |
| 90 | method: "POST", | |
| 91 | headers: { cookie: admin }, | |
| 92 | body: new URLSearchParams({ usd: "lots" }), | |
| 93 | redirect: "manual", | |
| 94 | }); | |
| 95 | expect(getModelGrant(app.db, getUserByName(app.db, "bob")!.id)?.usdPerMonth).toBe(20); | |
| 96 | }); | |
| 97 | ||
| 98 | test("the API sets and takes back a grant for an admin token only", async () => { | |
| 99 | const admin = getUserByName(app.db, "alice")!; | |
| 100 | const bobTok = createToken(app.db, getUserByName(app.db, "bob")!.id, "t", "admin"); | |
| 101 | const tok = createToken(app.db, admin.id, "t", "admin"); | |
| 102 | const post = (token: string, usd: unknown) => | |
| 103 | fetch(`${servers.url}/api/v1/admin/accounts/carol/model-grant`, { | |
| 104 | method: "POST", | |
| 105 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 106 | body: JSON.stringify({ usdPerMonth: usd }), | |
| 107 | }); | |
| 108 | expect((await post(bobTok.token, 5)).status).toBe(404); | |
| 109 | expect((await post(tok.token, "5")).status).toBe(422); | |
| 110 | expect((await post(tok.token, -1)).status).toBe(422); | |
| 111 | expect((await post(tok.token, 7.5)).status).toBe(200); | |
| 112 | const carol = getUserByName(app.db, "carol")!; | |
| 113 | expect(getModelGrant(app.db, carol.id)?.usdPerMonth).toBe(7.5); | |
| 114 | expect((await post(tok.token, null)).status).toBe(200); | |
| 115 | expect(getModelGrant(app.db, carol.id)).toBeUndefined(); | |
| 116 | }); | |
| 117 | }); |
test/model-grant.test.ts added +167
| @@ -0,0 +1,167 @@ | ||
| 1 | /** | |
| 2 | * A new account has a model budget of zero; it runs a crew only on its own | |
| 3 | * subscription or on a capped grant an admin gave it (#1145). | |
| 4 | */ | |
| 5 | ||
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { existsSync } from "node:fs"; | |
| 8 | import type { App } from "../src/app.ts"; | |
| 9 | import type { Repo } from "../src/core/repos.ts"; | |
| 10 | import type { User } from "../src/core/users.ts"; | |
| 11 | import { addToCrew } from "../src/actions/crew.ts"; | |
| 12 | import { addOwnModel, setAccountGrant } from "../src/actions/model_grant.ts"; | |
| 13 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 14 | import { assignIssue, openIssue } from "../src/actions/issues.ts"; | |
| 15 | import { createUser } from "../src/core/users.ts"; | |
| 16 | import { recordUsage } from "../src/core/usage.ts"; | |
| 17 | import { budgetLine, grantLeft, monthSpent } from "../src/core/model_grant.ts"; | |
| 18 | import { PLATFORM } from "../src/core/subscriptions.ts"; | |
| 19 | import { readRunLog } from "../src/runs/log.ts"; | |
| 20 | import { | |
| 21 | agentRunSettled, | |
| 22 | startStandInCrew, | |
| 23 | stopStandInCrew, | |
| 24 | type StandInCrew, | |
| 25 | } from "./helpers/crew-standin.ts"; | |
| 26 | ||
| 27 | describe("model budget: zero, an own subscription, a capped grant", () => { | |
| 28 | let standIn: StandInCrew; | |
| 29 | let app: App; | |
| 30 | let admin: User; | |
| 31 | let bot: User; | |
| 32 | let n = 0; | |
| 33 | /** A run that spent nothing, whose ledger line a test may borrow. */ | |
| 34 | let zeroRun = ""; | |
| 35 | ||
| 36 | beforeAll(async () => { | |
| 37 | standIn = await startStandInCrew(); | |
| 38 | ({ app, alice: admin, bot } = standIn); | |
| 39 | process.env.ANTHROPIC_API_KEY = "sk-forge-own-token"; | |
| 40 | }, 30_000); | |
| 41 | ||
| 42 | afterAll(() => { | |
| 43 | delete process.env.ANTHROPIC_API_KEY; | |
| 44 | return stopStandInCrew(standIn); | |
| 45 | }); | |
| 46 | ||
| 47 | async function person(name: string): Promise<{ user: User; repo: Repo }> { | |
| 48 | const made = await createUser(app.db, { | |
| 49 | trusted: true, | |
| 50 | username: name, | |
| 51 | email: `${name}@forge.local`, | |
| 52 | password: "a-good-passphrase", | |
| 53 | }); | |
| 54 | if (!made.ok) throw new Error(made.error); | |
| 55 | const user = made.value; | |
| 56 | const r = await createRepo(app, user, { name: "yard", visibility: "private" }); | |
| 57 | if (!r.ok) throw new Error(String(r.error)); | |
| 58 | const seeded = await commitToBranch(app, user, r.value, { | |
| 59 | message: "Start", | |
| 60 | files: [{ path: "README.md", content: "# yard\n" }], | |
| 61 | }); | |
| 62 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 63 | expect(addToCrew(app, user, r.value, "bot").ok).toBe(true); | |
| 64 | return { user, repo: r.value }; | |
| 65 | } | |
| 66 | ||
| 67 | async function runOn(user: User, repo: Repo) { | |
| 68 | const issue = openIssue(app, user, repo, { title: `Job ${++n}`, body: "Soon." }); | |
| 69 | if (!issue.ok) throw new Error(String(issue.error)); | |
| 70 | expect(assignIssue(app, user, repo, issue.value, bot).ok).toBe(true); | |
| 71 | return agentRunSettled(app, repo, (r) => r.issueId === issue.value.id); | |
| 72 | } | |
| 73 | ||
| 74 | test("a new account has zero, says so, and its run is refused", async () => { | |
| 75 | const { user, repo } = await person("zed"); | |
| 76 | expect(budgetLine(app.db, user, new Date())).toContain("Model budget: $0."); | |
| 77 | const run = await runOn(user, repo); | |
| 78 | expect(run.state).toBe("failed"); | |
| 79 | zeroRun = run.id; | |
| 80 | expect(run.summary).toContain("This repository has no model account"); | |
| 81 | expect(existsSync(standIn.argsFile)).toBe(false); | |
| 82 | }, 60_000); | |
| 83 | ||
| 84 | test("an own subscription runs, for its own repositories only", async () => { | |
| 85 | const { user, repo } = await person("own"); | |
| 86 | const other = await person("else"); | |
| 87 | const added = addOwnModel(app, user, { token: "sk-ant-api03-ownkey" }); | |
| 88 | expect(added.ok).toBe(true); | |
| 89 | expect(budgetLine(app.db, user, new Date())).toContain("own subscription"); | |
| 90 | const run = await runOn(user, repo); | |
| 91 | expect(run.summary).not.toContain("no model account"); | |
| 92 | expect(readRunLog(standIn.dataDir, run.id).lines.join("\n")).toContain( | |
| 93 | "subscription: own-own", | |
| 94 | ); | |
| 95 | // Someone else's repository does not get it. | |
| 96 | const theirs = await runOn(other.user, other.repo); | |
| 97 | expect(theirs.summary).toContain("This repository has no model account"); | |
| 98 | }, 90_000); | |
| 99 | ||
| 100 | test("only a forge admin who is a person gives a grant, and it is audited", async () => { | |
| 101 | const { user } = await person("gina"); | |
| 102 | expect(setAccountGrant(app, user, "gina", 5).ok).toBe(false); | |
| 103 | expect(setAccountGrant(app, admin, "gina", 0).ok).toBe(false); | |
| 104 | expect(setAccountGrant(app, admin, "gina", 99999).ok).toBe(false); | |
| 105 | expect(setAccountGrant(app, admin, bot.username, 5).ok).toBe(false); | |
| 106 | expect(setAccountGrant(app, admin, "gina", 5).ok).toBe(true); | |
| 107 | const event = app.db | |
| 108 | .query<{ payload: string; actor_id: string }, []>( | |
| 109 | "SELECT payload, actor_id FROM event WHERE kind = 'account.model_granted' ORDER BY id DESC LIMIT 1", | |
| 110 | ) | |
| 111 | .get()!; | |
| 112 | expect(event.actor_id).toBe(admin.id); | |
| 113 | expect(JSON.parse(event.payload)).toEqual({ username: "gina", usdPerMonth: 5 }); | |
| 114 | expect(budgetLine(app.db, user, new Date())).toContain("$5.00 a month, $5.00 left"); | |
| 115 | }); | |
| 116 | ||
| 117 | test("a capped grant runs, and stops being offered at the cap", async () => { | |
| 118 | const { user, repo } = await person("cap"); | |
| 119 | expect(setAccountGrant(app, admin, "cap", 5).ok).toBe(true); | |
| 120 | const run = await runOn(user, repo); | |
| 121 | expect(run.summary).not.toContain("no model account"); | |
| 122 | expect(readRunLog(standIn.dataDir, run.id).lines.join("\n")).toContain( | |
| 123 | "model grant: $5.00 left this month", | |
| 124 | ); | |
| 125 | ||
| 126 | // Spend the month's cap on the forge's credential: the next run is refused. | |
| 127 | recordUsage(app.db, { | |
| 128 | runId: run.id, | |
| 129 | repoId: repo.id, | |
| 130 | issueId: null, | |
| 131 | agentId: null, | |
| 132 | subscriptionId: PLATFORM, | |
| 133 | tokensIn: 1, | |
| 134 | tokensOut: 1, | |
| 135 | costUsd: 5, | |
| 136 | wallMs: 1, | |
| 137 | outcome: "ok", | |
| 138 | at: new Date().toISOString(), | |
| 139 | }); | |
| 140 | expect(grantLeft(app.db, user.id, new Date())).toBe(0); | |
| 141 | const refused = await runOn(user, repo); | |
| 142 | expect(refused.state).toBe("failed"); | |
| 143 | expect(refused.summary).toContain("model grant is spent"); | |
| 144 | }, 90_000); | |
| 145 | ||
| 146 | test("the cap is the month's: last month's spend does not count, taking it back ends it", async () => { | |
| 147 | const { user, repo } = await person("mo"); | |
| 148 | setAccountGrant(app, admin, "mo", 2); | |
| 149 | recordUsage(app.db, { | |
| 150 | runId: zeroRun, | |
| 151 | repoId: repo.id, | |
| 152 | issueId: null, | |
| 153 | agentId: null, | |
| 154 | subscriptionId: PLATFORM, | |
| 155 | tokensIn: 1, | |
| 156 | tokensOut: 1, | |
| 157 | costUsd: 9, | |
| 158 | wallMs: 1, | |
| 159 | outcome: "ok", | |
| 160 | at: "2020-01-15T00:00:00.000Z", | |
| 161 | }); | |
| 162 | expect(monthSpent(app.db, user.id, new Date())).toBe(0); | |
| 163 | expect(grantLeft(app.db, user.id, new Date())).toBe(2); | |
| 164 | expect(setAccountGrant(app, admin, "mo", null).ok).toBe(true); | |
| 165 | expect(grantLeft(app.db, user.id, new Date())).toBeUndefined(); | |
| 166 | }); | |
| 167 | }); |
new above
offline