Public: anyone can read this; the crew can change it.

A new account starts with no model budget and cannot spend the forge's own credential #840

Closed opened this in answer to
Closed without merging

scout/forge:scout/656-a-new-account-starts-with-no-model-budge → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +424 −49
docs/APPS.md +6 −2
@@ -916,8 +916,12 @@ that account rests until the time the provider names (now read from
916916 `resets Sep 26 at 9pm (America/Chicago)` as well as `resets 7am (UTC)`), the
917917 next account on the grant takes the run at once, and the pool page shows who
918918 is resting and why, with a button to use it again sooner. Nothing granted
919 anywhere means the forge's own token, as before. Every run remembers the
920 account it spent.
919 anywhere means no model account: the run does not start, spends nothing, and
920 says the repository has none. The forge's own token (`platform (env)`) is
921 granted like any account — to an admin's own scope from the start, to no one
922 else — and a grant may carry a dollar cap and records who made it. Every
923 account (a repository's owner) also has a daily and a per-run ceiling,
924 checked before a run starts. Every run remembers the account it spent.
921925
922926 ### Prompts from Instagram
923927
scripts/gate.ts +1
@@ -60,6 +60,7 @@ export const GATE: readonly string[] = [
6060 "test/apps-busy.test.ts",
6161 "test/apps-token.test.ts",
6262 "test/contain.test.ts",
63 "test/account-budget.test.ts",
6364 "test/subscription-budget.test.ts",
6465 "test/surfaces-adversarial.test.ts",
6566 "test/orgs.test.ts",
src/core/account_ceiling.ts added +69
@@ -0,0 +1,69 @@
1 /**
2 * What one account may spend on the crew, apart from the forge-wide ceiling:
3 * a day's worth and a single run's. Every account has both from the start —
4 * the defaults below, or its own where an admin set one — and an admin's own
5 * account has none unless set. Checked before a run starts, so a run past
6 * either never begins.
7 */
8
9 import type { Database } from "bun:sqlite";
10
11 /** What an account may spend in a UTC day, and in one run, before an admin says otherwise. */
12 export const DEFAULT_DAILY_USD = 5;
13 export const DEFAULT_RUN_USD = 1;
14 const MAX_USD = 100_000;
15
16 export interface Ceilings {
17 /** Dollars per UTC day across the account's repositories; Infinity for none. */
18 readonly dailyUsd: number;
19 /** Dollars in one run; Infinity for none. */
20 readonly runUsd: number;
21 }
22
23 /** The ceilings on an account (a repository's owner), by user id. */
24 export function ceilingsOf(db: Database, ownerId: string): Ceilings {
25 const row = db
26 .query<
27 { is_admin: number; daily: number | null; run: number | null },
28 [string]
29 >(
30 "SELECT is_admin, daily_ceiling_usd AS daily, run_ceiling_usd AS run FROM user WHERE id = ?1",
31 )
32 .get(ownerId);
33 const none = row?.is_admin === 1;
34 return {
35 dailyUsd: row?.daily ?? (none ? Infinity : DEFAULT_DAILY_USD),
36 runUsd: row?.run ?? (none ? Infinity : DEFAULT_RUN_USD),
37 };
38 }
39
40 /** Set an account's ceilings, in dollars; false when one is out of range or the account is unknown. */
41 export function setCeilings(
42 db: Database,
43 ownerId: string,
44 c: { dailyUsd: number; runUsd: number },
45 ): boolean {
46 const ok = (n: number) => Number.isFinite(n) && n >= 0 && n <= MAX_USD;
47 if (!ok(c.dailyUsd) || !ok(c.runUsd)) return false;
48 return (
49 db
50 .query(
51 "UPDATE user SET daily_ceiling_usd = ?2, run_ceiling_usd = ?3 WHERE id = ?1",
52 )
53 .run(ownerId, c.dailyUsd, c.runUsd).changes > 0
54 );
55 }
56
57 /** What the account's repositories have spent on runs since `since` (an ISO instant), reservations included. */
58 export function spentSince(db: Database, ownerId: string, since: string): number {
59 return (
60 db
61 .query<{ spent: number }, [string, string]>(
62 `SELECT COALESCE(SUM(MAX(r.cost_usd,
63 CASE WHEN r.state IN ('queued','running') THEN COALESCE(r.budget_reserved_usd, 0) ELSE 0 END)), 0) AS spent
64 FROM run r JOIN repo p ON p.id = r.repo_id
65 WHERE p.owner_id = ?1 AND r.kind = 'agent' AND r.created_at >= ?2`,
66 )
67 .get(ownerId, since)?.spent ?? 0
68 );
69 }
src/core/schema.ts +17
@@ -1300,4 +1300,21 @@ export const migrations: readonly string[] = [
13001300 );
13011301 CREATE INDEX IF NOT EXISTS app_member_user ON app_member(user_id);
13021302 `,
1303 // 55 — a new account begins with no model budget (#656). A grant records
1304 // who made it and may cap what its scope spends in all; the forge's own
1305 // token is granted like any account, so the admins' own work keeps it and
1306 // nobody else inherits it. An account's daily and per-run ceilings are
1307 // its own to differ from the defaults (`core/account_ceiling.ts`).
1308 `
1309 ALTER TABLE subscription_grant ADD COLUMN cap_usd REAL
1310 CHECK (cap_usd IS NULL OR cap_usd > 0);
1311 ALTER TABLE subscription_grant ADD COLUMN granted_by TEXT;
1312 ALTER TABLE user ADD COLUMN daily_ceiling_usd REAL
1313 CHECK (daily_ceiling_usd IS NULL OR daily_ceiling_usd >= 0);
1314 ALTER TABLE user ADD COLUMN run_ceiling_usd REAL
1315 CHECK (run_ceiling_usd IS NULL OR run_ceiling_usd >= 0);
1316 INSERT OR IGNORE INTO subscription_grant (scope_id, agent_id, subscription_id)
1317 SELECT id, '', 'platform' FROM user WHERE is_admin = 1;
1318 `,
13031319 ];
1320
src/core/subscriptions.ts +91 −26
@@ -6,7 +6,8 @@
66 * organizations each one pays for — down to a single crew member. A run
77 * takes its token from the nearest grant: the repository's, then the
88 * owner's, an agent's own before the crew's. Nothing granted anywhere means
9 * the forge's own token, as before.
9 * no run: a repository has no model account until a grant says so, and the
10 * forge's own token is spent only where it is granted like any other.
1011 *
1112 * When the provider turns an account away, that account rests until the
1213 * provider says it is ready, and the next account on the same grant takes
@@ -18,10 +19,11 @@
1819 *
1920 * The forge's own token is a subscription too: the row `PLATFORM`, shown as
2021 * `platform (env)`, with no sealed token — its credential is the forge's
21 * environment. It is never granted; it is what a run gets when no grant
22 * reaches it, and the ledger and the windows count it like any other. The
23 * grants are each sealed account's scope, an allow-list: an account with
24 * none is never offered to the crew (a person's own plan, kept apart).
22 * environment. It is granted like any other, by an admin, and never by
23 * default; the ledger and the windows count it like any other. The grants
24 * are each account's scope, an allow-list: an account with none is never
25 * offered to the crew (a person's own plan, kept apart). A grant may carry
26 * a cap in dollars, and records who made it.
2527 */
2628
2729 import type { Database } from "bun:sqlite";
@@ -83,6 +85,18 @@ const COMMITTED = `(SELECT COALESCE(SUM(
8385 THEN MAX(COALESCE(r.budget_reserved_usd, 0), r.cost_usd)
8486 ELSE r.cost_usd END), 0)
8587 FROM run r WHERE r.subscription_id = s.id)`;
88 /**
89 * What a grant's scope has committed on its account, like `COMMITTED`: the
90 * runs on this account in the grant's repository, or in any repository its
91 * owner has when the grant is the owner's.
92 */
93 const GRANT_COMMITTED = `(SELECT COALESCE(SUM(
94 CASE WHEN r.state IN ('queued', 'running') AND r.id <> ?4
95 THEN MAX(COALESCE(r.budget_reserved_usd, 0), r.cost_usd)
96 ELSE r.cost_usd END), 0)
97 FROM run r WHERE r.subscription_id = s.id
98 AND (r.repo_id = g.scope_id
99 OR r.repo_id IN (SELECT id FROM repo WHERE owner_id = g.scope_id)))`;
86100 export const BUDGET_MAX_USD = 100_000;
87101
88102 /** An account's whole-life budget and what its runs have spent, in dollars. */
@@ -297,22 +311,36 @@ function touchSubscription(
297311 export interface Grant {
298312 /** A repository id or an owner's (organization's) user id. */
299313 readonly scopeId: string;
314 /** What the grant lets the scope spend in all, in dollars; null is no cap of its own. */
315 readonly capUsd: number | null;
316 /** Who made it; null for one that predates the record. */
317 readonly grantedBy: string | null;
300318 /** An agent's user id, or `EVERYONE`. */
301319 readonly agentId: string;
302320 readonly subscriptionId: string;
303321 }
304322
323 interface GrantRow {
324 scope_id: string;
325 agent_id: string;
326 subscription_id: string;
327 cap_usd: number | null;
328 granted_by: string | null;
329 }
330
305331 export function listGrants(db: Database, scopeId: string): Grant[] {
306332 return db
307333 .query<
308 { scope_id: string; agent_id: string; subscription_id: string },
334 GrantRow,
309335 [string]
310336 >(
311 `SELECT scope_id, agent_id, subscription_id FROM subscription_grant
337 `SELECT scope_id, agent_id, subscription_id, cap_usd, granted_by FROM subscription_grant
312338 WHERE scope_id = ?1 ORDER BY agent_id, subscription_id`,
313339 )
314340 .all(scopeId)
315341 .map((r) => ({
342 capUsd: r.cap_usd,
343 grantedBy: r.granted_by,
316344 scopeId: r.scope_id,
317345 agentId: r.agent_id,
318346 subscriptionId: r.subscription_id,
@@ -322,12 +350,14 @@ export function listGrants(db: Database, scopeId: string): Grant[] {
322350 /** Every grant on this forge, for the page that says where each account goes. */
323351 export function listAllGrants(db: Database): Grant[] {
324352 return db
325 .query<{ scope_id: string; agent_id: string; subscription_id: string }, []>(
326 `SELECT scope_id, agent_id, subscription_id FROM subscription_grant
353 .query<GrantRow, []>(
354 `SELECT scope_id, agent_id, subscription_id, cap_usd, granted_by FROM subscription_grant
327355 ORDER BY subscription_id, scope_id, agent_id`,
328356 )
329357 .all()
330358 .map((r) => ({
359 capUsd: r.cap_usd,
360 grantedBy: r.granted_by,
331361 scopeId: r.scope_id,
332362 agentId: r.agent_id,
333363 subscriptionId: r.subscription_id,
@@ -343,18 +373,38 @@ export function setGrants(
343373 scopeId: string,
344374 agentId: string,
345375 subscriptionIds: readonly string[],
376 /** Recorded on the grants this call adds: who made them, and the cap on them. */
377 made?: { readonly by?: string | undefined; readonly capUsd?: number | undefined },
346378 ): void {
347 const known = new Set(listSubscriptions(db).map((s) => s.id));
379 const known = new Set(listCredentials(db).map((s) => s.id));
348380 const wanted = [...new Set(subscriptionIds)].filter((s) => known.has(s));
381 const cap =
382 made?.capUsd !== undefined && Number.isFinite(made.capUsd) && made.capUsd > 0 && made.capUsd <= BUDGET_MAX_USD
383 ? Math.round(made.capUsd * 100) / 100
384 : null;
349385 db.transaction(() => {
386 // A grant kept through a replace keeps its cap and its maker.
387 const kept = new Map(
388 listGrants(db, scopeId)
389 .filter((g) => g.agentId === agentId)
390 .map((g) => [g.subscriptionId, g] as const),
391 );
350392 db.query(
351393 "DELETE FROM subscription_grant WHERE scope_id = ?1 AND agent_id = ?2",
352394 ).run(scopeId, agentId);
353 for (const subscriptionId of wanted)
395 for (const subscriptionId of wanted) {
396 const was = kept.get(subscriptionId);
354397 db.query(
355 `INSERT INTO subscription_grant (scope_id, agent_id, subscription_id)
356 VALUES (?1, ?2, ?3)`,
357 ).run(scopeId, agentId, subscriptionId);
398 `INSERT INTO subscription_grant (scope_id, agent_id, subscription_id, cap_usd, granted_by)
399 VALUES (?1, ?2, ?3, ?4, ?5)`,
400 ).run(
401 scopeId,
402 agentId,
403 subscriptionId,
404 was ? was.capUsd : cap,
405 was ? was.grantedBy : (made?.by ?? null),
406 );
407 }
358408 })();
359409 }
360410
@@ -434,8 +484,10 @@ function listGrantPlaceRows(
434484 // ---- the pick ----
435485
436486 export type Pick =
437 /** No grant reaches this run: the forge's own token, `PLATFORM`, from its environment. */
438 | { readonly kind: "env" }
487 /** No grant reaches this run: it has no model account and does not start. */
488 | { readonly kind: "none" }
489 /** The forge's own token, `PLATFORM`, granted to this run's repository or owner. */
490 | { readonly kind: "env"; readonly capUsd?: number }
439491 | {
440492 readonly kind: "ready";
441493 readonly subscription: Subscription;
@@ -480,20 +532,22 @@ export function pickSubscription(
480532 token_enc: string;
481533 budget_usd: number | null;
482534 spent_usd: number;
535 cap_usd: number | null;
536 grant_spent_usd: number;
483537 },
484538 [string, string, string, string]
485539 >(
486540 `SELECT g.scope_id, g.agent_id, s.id, s.name, s.kind, s.token_enc, s.resting_until,
487541 s.resting_said, s.last_used_at, s.created_by, s.created_at, s.budget_usd,
488 ${COMMITTED} AS spent_usd
542 ${COMMITTED} AS spent_usd, g.cap_usd, ${GRANT_COMMITTED} AS grant_spent_usd
489543 FROM subscription_grant g JOIN subscription s ON s.id = g.subscription_id
490 WHERE g.scope_id IN (?1, ?2) AND g.agent_id IN (?3, '') AND s.id <> 'platform'
544 WHERE g.scope_id IN (?1, ?2) AND g.agent_id IN (?3, '')
491545 ORDER BY (g.scope_id = ?1) DESC, (g.agent_id = ?3) DESC,
492546 s.last_used_at IS NOT NULL, s.last_used_at, s.name COLLATE NOCASE`,
493547 )
494548 .all(scope.repoId, scope.ownerId, scope.agentId, reserve?.runId ?? "");
495549 const first = rows[0];
496 if (first === undefined) return { kind: "env" };
550 if (first === undefined) return { kind: "none" };
497551 const grant = rows.filter(
498552 (r) => r.scope_id === first.scope_id && r.agent_id === first.agent_id,
499553 );
@@ -502,8 +556,12 @@ export function pickSubscription(
502556 // Spent counts what other runs on it may still spend (their reservation)
503557 // as well as what every run has spent, so runs started together cannot
504558 // each pass a budget that only one of them fits in.
505 const spent = (r: (typeof grant)[number]) =>
506 r.budget_usd !== null && r.budget_usd - r.spent_usd < MIN_RUN_USD;
559 const room = (r: (typeof grant)[number]) =>
560 Math.min(
561 r.budget_usd === null ? Infinity : r.budget_usd - r.spent_usd,
562 r.cap_usd === null ? Infinity : r.cap_usd - r.grant_spent_usd,
563 );
564 const spent = (r: (typeof grant)[number]) => room(r) < MIN_RUN_USD;
507565 const awake = grant.find(
508566 (r) =>
509567 !spent(r) &&
@@ -514,7 +572,10 @@ export function pickSubscription(
514572 return {
515573 kind: "resting",
516574 until: new Date(now.getTime() + BUDGET_RECHECK_MS).toISOString(),
517 said: `its $${first.budget_usd} budget is spent; an admin can raise it`,
575 said:
576 first.budget_usd !== null && first.budget_usd - first.spent_usd < MIN_RUN_USD
577 ? `its $${first.budget_usd} budget is spent; an admin can raise it`
578 : `the $${first.cap_usd} granted here is spent; an admin can raise it`,
518579 names: grant.map((r) => r.name),
519580 };
520581 }
@@ -531,7 +592,10 @@ export function pickSubscription(
531592 names: grant.map((r) => r.name),
532593 };
533594 }
534 const opened = open(dataDir, awake.token_enc, aad(awake.id));
595 const platform = awake.id === PLATFORM;
596 const opened = platform
597 ? ok("")
598 : open(dataDir, awake.token_enc, aad(awake.id));
535599 // A token that will not open (a data directory restored under another
536600 // key) is a resting account with the reason on it, not a run that fails.
537601 if (!opened.ok) {
@@ -549,12 +613,13 @@ export function pickSubscription(
549613 // much is reserved for it now, in the same synchronous step as the
550614 // choice, so the next pick already counts it.
551615 let capUsd: number | undefined;
552 if (awake.budget_usd !== null && reserve !== undefined) {
553 capUsd = Math.max(0, Math.min(reserve.usd, awake.budget_usd - awake.spent_usd));
616 if ((awake.budget_usd !== null || awake.cap_usd !== null) && reserve !== undefined) {
617 capUsd = Math.max(0, Math.min(reserve.usd, room(awake)));
554618 db.query(
555619 "UPDATE run SET subscription_id = ?1, budget_reserved_usd = ?2 WHERE id = ?3",
556620 ).run(awake.id, capUsd, reserve.runId);
557621 }
622 if (platform) return { kind: "env", ...(capUsd === undefined ? {} : { capUsd }) };
558623 return {
559624 kind: "ready",
560625 subscription: { ...subscription, lastUsedAt: now.toISOString() },
@@ -578,7 +643,7 @@ export function grantedAccounts(
578643 .query<{ id: string; name: string; scope_id: string }, [string, string]>(
579644 `SELECT DISTINCT s.id, s.name, g.scope_id
580645 FROM subscription_grant g JOIN subscription s ON s.id = g.subscription_id
581 WHERE g.scope_id IN (?1, ?2) AND s.id <> 'platform'
646 WHERE g.scope_id IN (?1, ?2)
582647 ORDER BY s.name COLLATE NOCASE`,
583648 )
584649 .all(repoId, ownerId);
src/core/users.ts +8 −1
@@ -189,7 +189,14 @@ export async function createUser(
189189 if (input.trusted === true) markVerified(db, userId, new Date().toISOString());
190190 else markUnproven(db, userId);
191191 }
192 return ok(getUserById(db, userId)!);
192 const made = getUserById(db, userId)!;
193 // The forge's own model token is the admin's to spend on their own work;
194 // every other account begins with no model account (`core/subscriptions.ts`).
195 if (made.isAdmin && !agent)
196 db.query(
197 "INSERT OR IGNORE INTO subscription_grant (scope_id, agent_id, subscription_id) VALUES (?1, '', 'platform')",
198 ).run(userId);
199 return ok(made);
193200 }
194201
195202 function isUniqueViolation(error: unknown): boolean {
src/crew/runner.ts +35 −5
@@ -81,6 +81,8 @@ import {
8181 } from "./limits.ts";
8282 import { interruptedSummary } from "./interrupted.ts";
8383 import { noteLimit } from "../core/standing.ts";
84 import { ceilingsOf, spentSince } from "../core/account_ceiling.ts";
85 import { startOfTodayUtc } from "./autonomy.ts";
8486 import { pauseReason } from "./pacing.ts";
8587 import {
8688 pickSubscription,
@@ -771,7 +773,7 @@ async function work(
771773 });
772774
773775 // The account this run works on: the nearest grant's, rotating; the
774 // forge's own token when nothing is granted. A grant whose accounts are
776 // no account at all when nothing is granted. A grant whose accounts are
775777 // all resting holds the run until the first wakes, without a call.
776778 const scope = {
777779 repoId: repo.id,
@@ -780,7 +782,26 @@ async function work(
780782 };
781783 // What this run may spend at most; on a budgeted account the pick
782784 // reserves it (or what is left, if less) against the account's budget.
783 const ownBudget = agent.budgetUsd > 0 ? agent.budgetUsd : options.budgetUsd;
785 // The owner's own ceilings come first, before an account is touched: a
786 // day already spent, or a run allowed less, never reaches the pick.
787 const ceilings = ceilingsOf(app.db, repo.ownerId);
788 const spentDay = spentSince(
789 app.db,
790 repo.ownerId,
791 startOfTodayUtc(new Date()).toISOString(),
792 );
793 if (spentDay >= ceilings.dailyUsd) {
794 write(`account ceiling: $${spentDay.toFixed(2)} of $${ceilings.dailyUsd} today`);
795 return {
796 state: "failed",
797 summary: `the account that owns this repository has reached its daily ceiling of $${ceilings.dailyUsd}; it lifts at UTC midnight`,
798 };
799 }
800 const ownBudget = Math.min(
801 agent.budgetUsd > 0 ? agent.budgetUsd : options.budgetUsd,
802 ceilings.runUsd,
803 ceilings.dailyUsd - spentDay,
804 );
784805 const picked = pickSubscription(
785806 app.db,
786807 app.config.dataDir,
@@ -788,6 +809,14 @@ async function work(
788809 new Date(),
789810 { runId: run.id, usd: ownBudget },
790811 );
812 if (picked.kind === "none") {
813 write("no model account: nothing is granted to this repository or its owner");
814 return {
815 state: "failed",
816 summary:
817 "this repository has no model account: no subscription is granted to it or its owner, so the run did not start and spent nothing",
818 };
819 }
791820 if (picked.kind === "resting") {
792821 const names = picked.names.join(", ");
793822 write(
@@ -834,7 +863,7 @@ async function work(
834863 // agent cut off mid-task otherwise leaves a tree the forge commits blind
835864 // and a pull whose description is the error.
836865 const budget =
837 picked.kind === "ready" && picked.capUsd !== undefined
866 picked.capUsd !== undefined
838867 ? Math.min(ownBudget, picked.capUsd)
839868 : ownBudget;
840869 const reserve = wrapUpReserve(budget);
@@ -1444,11 +1473,12 @@ function redactResult<T extends { result: string }>(r: T): T {
14441473
14451474 /**
14461475 * The credential a run's environment carries: the picked account's token
1447 * under the variable Claude Code reads it from, or — with nothing granted —
1448 * whatever the forge itself was started with.
1476 * under the variable Claude Code reads it from, or — only where the forge's
1477 * own is granted — whatever the forge itself was started with.
14491478 */
14501479 function credentialEnv(picked: Pick): Record<string, string> {
14511480 if (picked.kind === "ready") return { [picked.envName]: picked.token };
1481 if (picked.kind !== "env") return {};
14521482 const own: Record<string, string> = {};
14531483 for (const name of ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"]) {
14541484 const value = process.env[name];
src/web/pages/org.ts +1 −1
@@ -333,7 +333,7 @@ export async function ownerProfile(ctx: Ctx): Promise<Response> {
333333 scopeId: owner.id,
334334 agents: agentsOnForge(ctx),
335335 action: `/${owner.username}/-/subscriptions`,
336 wider: "the forge's own token",
336 wider: "the owner's grant, or no model account",
337337 title: "Subscriptions for every repository here",
338338 })}
339339 </div>`,
src/web/pages/settings.ts +1 −1
@@ -1405,7 +1405,7 @@ export function crewSettingsPage(ctx: Ctx): Response {
14051405 scopeId: repo.id,
14061406 agents: crew,
14071407 action: `${base}/settings/crew/subscriptions`,
1408 wider: "the owner's grant, or the forge's own token",
1408 wider: "the owner's grant, or no model account",
14091409 })}
14101410 </div>`
14111411 : null;
src/web/pages/subscriptions.ts +7 −8
@@ -150,15 +150,15 @@ export function subscriptionsPage(ctx: Ctx): Response {
150150 ? null
151151 : empty({
152152 icon: "key",
153 title: "The crew works on the forge's own token",
154 note: "Add a subscription here and grant it to a repository or an organization; its runs spend that account instead. One granted nowhere is never offered to the crew.",
153 title: "The crew has no model account",
154 note: "Add a subscription here and grant it to a repository or an organization; until then its runs do not start. One granted nowhere is never offered to the crew.",
155155 });
156156 const list =
157157 pool.length === 0
158158 ? empty({
159159 icon: "key",
160 title: "The crew works on the forge's own token",
161 note: "Add a subscription here and grant it to a repository or an organization; its runs spend that account instead. Two on one grant take turns, and one the provider rests hands over to the other.",
160 title: "The crew has no model account",
161 note: "Add a subscription here and grant it to a repository or an organization; until then its runs do not start. Two on one grant take turns, and one the provider rests hands over to the other.",
162162 })
163163 : listCard(
164164 pool.map((s) => {
@@ -506,15 +506,14 @@ export function grantsSection(
506506 title?: string | undefined;
507507 },
508508 ): Html {
509 const pool = listSubscriptions(ctx.app.db);
509 const pool = listCredentials(ctx.app.db);
510510 const head = html`${icon("key")}
511511 <h2>${o.title ?? "Subscriptions"}</h2>`;
512512 if (pool.length === 0)
513513 return card(
514514 html`<p class="muted small">
515 Runs here work on the forge's own token. Add a subscription under
516 <a href="${POOL}">Settings → Subscriptions</a> to spend a particular
517 account here.
515 Runs here have no model account. Add a subscription under
516 <a href="${POOL}">Settings → Subscriptions</a> and grant it here.
518517 </p>`,
519518 { head },
520519 );
test/account-budget.test.ts added +183
@@ -0,0 +1,183 @@
1 /**
2 * A new account begins with no model budget (#656): a repository's runs use
3 * a model credential only from a grant to it or its owner, never the
4 * forge's own token by default. A fresh outsider can create a repository,
5 * add an existing agent, open and assign an issue — and the run does not
6 * start and spends nothing. A capped grant lets it start and bounds it.
7 */
8
9 import { afterAll, beforeAll, expect, test } from "bun:test";
10 import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../src/app.ts";
15 import { addToCrew, createAgent } from "../src/actions/crew.ts";
16 import { assignIssue, openIssue } from "../src/actions/issues.ts";
17 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
18 import { setCeilings } from "../src/core/account_ceiling.ts";
19 import { startCrew, type CrewHandle } from "../src/crew/dispatch.ts";
20 import type { Repo } from "../src/core/repos.ts";
21 import { createRun, listRuns, type Run } from "../src/core/runs.ts";
22 import {
23 EVERYONE,
24 listGrants,
25 PLATFORM,
26 pickSubscription,
27 setGrants,
28 } from "../src/core/subscriptions.ts";
29 import { createUser, type User } from "../src/core/users.ts";
30 import { serve, type Servers } from "../src/http/server.ts";
31
32 let dataDir = "";
33 let app: App;
34 let servers: Servers;
35 let crew: CrewHandle;
36 let alice: User;
37 let carol: User;
38 let bot: User;
39 let repo: Repo;
40 let argsFile = "";
41
42 const seen = new Set<string>();
43
44 /** The next agent run on the repository to end. */
45 async function settled(): Promise<Run> {
46 const deadline = Date.now() + 25_000;
47 while (Date.now() < deadline) {
48 const run = listRuns(app.db, repo.id, { kind: "agent" }).find(
49 (r) => !seen.has(r.id) && ["ok", "failed", "cancelled"].includes(r.state),
50 );
51 if (run) {
52 seen.add(run.id);
53 return run;
54 }
55 await Bun.sleep(100);
56 }
57 throw new Error("run did not settle");
58 }
59
60 async function assign(title: string): Promise<void> {
61 const issue = openIssue(app, carol, repo, { title, body: "Please." });
62 if (!issue.ok) throw new Error("issue");
63 expect(assignIssue(app, carol, repo, issue.value, bot).ok).toBe(true);
64 }
65
66 beforeAll(async () => {
67 dataDir = await mkdtemp(join(tmpdir(), "forge-account-budget-"));
68 app = createApp({ dataDir, port: 0 });
69 servers = await serve(app);
70 argsFile = join(dataDir, "fake.args");
71 const fake = join(dataDir, "fake-claude");
72 writeFileSync(
73 fake,
74 `#!/bin/sh
75 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
76 printf '%s\\n' "$@" > "${argsFile}"
77 IFS= read -r first
78 echo '{"type":"system","subtype":"init","session_id":"fake-1","model":"fake"}'
79 echo "work $(date +%s%N)" >> CREW.md
80 git add -A && git commit -qm "crew work" && git push -q -u origin HEAD
81 echo '{"type":"result","subtype":"success","is_error":false,"result":"Done.","total_cost_usd":0.01,"num_turns":1,"session_id":"fake-1","terminal_reason":"completed"}'
82 `,
83 );
84 chmodSync(fake, 0o755);
85 crew = await startCrew(app, {
86 forgeUrl: servers.url,
87 localUrl: servers.url,
88 binary: fake,
89 concurrency: 1,
90 budgetUsd: 1,
91 runTimeoutMs: 60_000,
92 });
93 const a = await createUser(app.db, {
94 trusted: true,
95 username: "alice",
96 email: "[email protected]",
97 password: "a-good-passphrase",
98 adminIfFirst: true,
99 });
100 const c = await createUser(app.db, {
101 trusted: true,
102 username: "carol",
103 email: "[email protected]",
104 password: "a-good-passphrase",
105 });
106 if (!a.ok || !c.ok) throw new Error("users");
107 alice = a.value;
108 carol = c.value;
109 const made = await createAgent(app, alice, { username: "bot", brief: "Be brief." });
110 if (!made.ok) throw new Error("agent");
111 bot = made.value.user;
112 const created = await createRepo(app, carol, { name: "yard", visibility: "private" });
113 if (!created.ok) throw new Error("repo");
114 repo = created.value;
115 const seeded = await commitToBranch(app, carol, repo, {
116 message: "Start",
117 files: [{ path: "README.md", content: "# yard\n" }],
118 });
119 if (!seeded.ok) throw new Error("seed");
120 expect(addToCrew(app, carol, repo, "bot").ok).toBe(true);
121 }, 30_000);
122
123 afterAll(async () => {
124 await crew.stop();
125 servers.stop();
126 app.close();
127 await rm(dataDir, { recursive: true, force: true });
128 });
129
130 test("only an admin begins with the forge's own token granted", () => {
131 expect(listGrants(app.db, alice.id).map((g) => g.subscriptionId)).toEqual([PLATFORM]);
132 expect(listGrants(app.db, carol.id)).toEqual([]);
133 const scope = { repoId: repo.id, ownerId: carol.id, agentId: bot.id };
134 expect(pickSubscription(app.db, dataDir, scope, new Date()).kind).toBe("none");
135 });
136
137 test("a fresh account's run does not start, and spends nothing", async () => {
138 await assign("Water the beds");
139 const run = await settled();
140 expect(run.state).toBe("failed");
141 expect(run.summary).toContain("has no model account");
142 expect(run.costUsd).toBe(0);
143 expect(existsSync(argsFile)).toBe(false);
144 }, 30_000);
145
146 test("a capped grant lets it start, and the run is held to the cap", async () => {
147 setGrants(app.db, repo.id, EVERYONE, [PLATFORM], { by: alice.id, capUsd: 0.5 });
148 const [grant] = listGrants(app.db, repo.id);
149 expect(grant).toMatchObject({ subscriptionId: PLATFORM, capUsd: 0.5, grantedBy: alice.id });
150 await assign("Mow the lawn");
151 const run = await settled();
152 expect(run.state).toBe("ok");
153 const args = readFileSync(argsFile, "utf8").split("\n");
154 const at = args.indexOf("--max-budget-usd");
155 expect(at).toBeGreaterThan(-1);
156 expect(Number(args[at + 1])).toBeLessThanOrEqual(0.5);
157 }, 30_000);
158
159 test("a grant whose cap is spent offers nothing more", () => {
160 const spent = createRun(app.db, { repoId: repo.id, kind: "agent" });
161 app.db
162 .query("UPDATE run SET state = 'ok', subscription_id = ?1, cost_usd = 0.5 WHERE id = ?2")
163 .run(PLATFORM, spent.id);
164 seen.add(spent.id);
165 const scope = { repoId: repo.id, ownerId: carol.id, agentId: bot.id };
166 const picked = pickSubscription(app.db, dataDir, scope, new Date());
167 expect(picked.kind).toBe("resting");
168 });
169
170 test("an account's daily ceiling stops a run before it starts", async () => {
171 setGrants(app.db, repo.id, EVERYONE, [PLATFORM]);
172 expect(setCeilings(app.db, carol.id, { dailyUsd: 0, runUsd: 1 })).toBe(true);
173 await assign("Prune the roses");
174 const run = await settled();
175 expect(run.state).toBe("failed");
176 expect(run.summary).toContain("daily ceiling");
177 expect(run.costUsd).toBe(0);
178 }, 30_000);
179
180 test("ceilings are validated", () => {
181 expect(setCeilings(app.db, carol.id, { dailyUsd: -1, runUsd: 1 })).toBe(false);
182 expect(setCeilings(app.db, carol.id, { dailyUsd: NaN, runUsd: 1 })).toBe(false);
183 });
test/credentials.test.ts +3 −3
@@ -137,7 +137,7 @@ describe("the platform credential", () => {
137137 expect(listSubscriptions(app.db).map((c) => c.name)).toEqual(["trevato-espo"]);
138138 expect(deleteSubscription(app.db, PLATFORM)).toBe(false);
139139 // Granting it is a no-op: it is what applies when nothing is granted.
140 setGrants(app.db, repo.id, EVERYONE, [PLATFORM]);
140 setGrants(app.db, repo.id, EVERYONE, ["nonesuch"]);
141141 expect(listGrants(app.db, repo.id)).toEqual([]);
142142 expect(standing(app.db, PLATFORM, new Date())).toBeDefined();
143143 });
@@ -148,13 +148,13 @@ describe("a subscription's scope", () => {
148148 const espo = listSubscriptions(app.db)[0]!;
149149 const scope = { repoId: repo.id, ownerId: alice.id, agentId: bot.id };
150150 expect(pickSubscription(app.db, dataDir, scope, new Date()).kind).toBe("env");
151 expect(grantedAccounts(app.db, repo.id, alice.id)).toEqual([]);
151 expect(grantedAccounts(app.db, repo.id, alice.id)).toEqual([{ id: PLATFORM, name: "platform (env)" }]);
152152 expect(scopesOf(app.db).has(espo.id)).toBe(false);
153153
154154 setGrants(app.db, "another-repo", EVERYONE, [espo.id]);
155155 expect(scopesOf(app.db).get(espo.id)).toEqual(["a place that is gone"]);
156156 expect(pickSubscription(app.db, dataDir, scope, new Date()).kind).toBe("env");
157 expect(grantedAccounts(app.db, repo.id, alice.id)).toEqual([]);
157 expect(grantedAccounts(app.db, repo.id, alice.id)).toEqual([{ id: PLATFORM, name: "platform (env)" }]);
158158 setGrants(app.db, "another-repo", EVERYONE, []);
159159
160160 // Granted here, it is picked here — and only then.
test/subscriptions.test.ts +2 −2
@@ -158,7 +158,7 @@ describe("the pool", () => {
158158 // Removing an account removes its grants; the grant falls back.
159159 expect(deleteSubscription(app.db, work.value.id)).toBe(true);
160160 expect(listGrants(app.db, "repo-1")).toEqual([
161 { scopeId: "repo-1", agentId: EVERYONE, subscriptionId: personal.id },
161 { scopeId: "repo-1", agentId: EVERYONE, subscriptionId: personal.id, capUsd: null, grantedBy: null },
162162 ]);
163163 });
164164 });
@@ -510,7 +510,7 @@ describe("the pages", () => {
510510 );
511511 expect(saved.status).toBe(303);
512512 expect(listGrants(app.db, org.value.id)).toEqual([
513 { scopeId: org.value.id, agentId: EVERYONE, subscriptionId: work.id },
513 { scopeId: org.value.id, agentId: EVERYONE, subscriptionId: work.id, capUsd: null, grantedBy: null },
514514 ]);
515515 html = await get("/settings/subscriptions");
516516 expect(html).toContain("@acme");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs