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

Crew accounts you can understand: one pool, the account each run spends said plainly, held runs released on any change #16498

opened this

Check · Review · Land · Live — No review yet. Next: reviewer, no review yet.

Ready to land

crew/accounts → main 1 commit

Review

Sign in to review this change.
37 files changed +916 −138
docs/features/crew-accounts.md added +17
@@ -0,0 +1,17 @@
1 ---
2 topic: Bring your own AI
3 row: Which account the crew spends right now, why, and allowing one in a step
4 ---
5 # Crew accounts: which one a run spends
6
7 An account added under Settings → Subscriptions is in the **pool**: the crew uses it by default on every repository a forge admin owns. An account someone who is not an admin adds is used for their own repositories only. Allowing an account at a repository or an owner adds it there; **limiting** it keeps it to the places it is allowed. The server's own token is used only where no account may be.
8
9 A run tries, in order: the accounts allowed at its repository (this agent's before everyone's), then at its owner, then the pool, each the one used longest ago first. It spends the first that is awake and has budget and room in its week.
10
11 - **Settings → Subscriptions**, "Right now": what a run on your repositories spends and why, every account and whether it is used there, and the fix when there is one: "espo-trevato: it is resting until Nov 29; espo-corp has room but is not used here: allow it here", with a one-press Allow.
12 - **Talk and MCP**: `crew_accounts { repo?, owner? }` reads the same sentence; `allow` allows an account there (one confirm), `everywhere` puts one in the pool and `limit` keeps one to where it is allowed (a forge admin's).
13 - **The terminal**: the Subscriptions screen says it on its first lines; `A` allows the fix.
14 - **Held runs**: a run paused for want of an account is released the moment one has room: an account added, allowed, put in the pool, woken, or its budget raised, by any door.
15 - **Who reads what**: a repository's or owner's admin reads its accounts; an account someone else added is named only to a forge admin, else "an account of this forge's"; anyone else is told not found.
16
17 Proof: `test/crew-accounts.test.ts`. The rules are `core/subscriptions.ts` (`pickSubscription`, `scopeAccounts`, `reachWords`) and `actions/crew_accounts.ts`; the release is `crew/recheck_held.ts`.
src/actions/crew_accounts.ts added +274
@@ -0,0 +1,274 @@
1 /**
2 * Which account a crew run spends, said in one place (Settings → Subscriptions, Talk's
3 * `crew_accounts`, the terminal), and the one step that changes it. An account is in the pool,
4 * used by default, unless it is limited to where it is allowed (`core/subscriptions.ts`); the
5 * server's own token is used only where no account may be. Each sentence names the account and,
6 * when another has room but may not be used here, the fix: allow it here.
7 */
8
9 import type { App } from "../app.ts";
10 import { measureFor } from "../core/measure.ts";
11 import { canAdmin, getRepo, type Repo } from "../core/repos.ts";
12 import {
13 allowAt,
14 getSubscriptionByName,
15 listSubscriptions,
16 reachWords,
17 scopeAccounts,
18 setLimited,
19 type ScopeAccount,
20 } from "../core/subscriptions.ts";
21 import { getUserById, getUserByName, type User } from "../core/users.ts";
22 import { weekUse } from "../core/capacity.ts";
23 import { orgAccess, accessAllows } from "../core/orgs.ts";
24 import { err, ok, type Result } from "../kernel/result.ts";
25 import { whenText } from "../crew/limits.ts";
26 import { recheckHeld } from "../crew/recheck_held.ts";
27
28 /** Where crew accounts are read or allowed: one repository, or every repository of an owner. */
29 export interface AccountScope {
30 readonly scopeId: string;
31 readonly repoId: string;
32 readonly ownerId: string;
33 /** `owner/name`, or the owner's name. */
34 readonly name: string;
35 }
36
37 /** One account as the person reads it here. */
38 export interface AccountLine {
39 readonly name: string;
40 /** Whether a run here may use it. */
41 readonly here: boolean;
42 readonly says: string;
43 }
44
45 export interface CrewAccounts {
46 readonly scope: string;
47 /** What a run here spends now, why, and the fix when there is one. */
48 readonly says: string;
49 readonly accounts: readonly AccountLine[];
50 /** An account with room that may not be used here, which the viewer may allow here. */
51 readonly allow?: string;
52 }
53
54 export type AccountsError = "not_found" | "forbidden" | "no_such_account";
55
56 /** "an account of this forge's", for a name the viewer may not read. */
57 const UNNAMED = "an account of this forge's";
58
59 /**
60 * The scope `repo` (owner/name) or `owner` (a username) names, when `viewer` administers it: a site
61 * admin, the repository's admin, the owner, or an admin of the owning organization. Anyone else is
62 * told it is not found, whether it exists or not.
63 */
64 export function accountScope(
65 app: App,
66 viewer: User | undefined,
67 at: { repo?: string; owner?: string },
68 ): Result<AccountScope, "not_found"> {
69 if (viewer === undefined) return err("not_found");
70 if (at.repo !== undefined && at.repo !== "") {
71 const [owner = "", name = ""] = at.repo.split("/");
72 const repo = getRepo(app.db, owner, name);
73 if (repo === undefined || !canAdmin(app.db, repo, viewer))
74 return err("not_found");
75 return ok(repoScope(repo));
76 }
77 const owner =
78 at.owner === undefined || at.owner === ""
79 ? viewer
80 : getUserByName(app.db, at.owner);
81 if (owner === undefined) return err("not_found");
82 const mine =
83 owner.id === viewer.id ||
84 viewer.isAdmin ||
85 (owner.kind === "org" &&
86 accessAllows(orgAccess(app.db, owner.id, viewer), "admin"));
87 return mine
88 ? ok({
89 scopeId: owner.id,
90 repoId: "",
91 ownerId: owner.id,
92 name: owner.username,
93 })
94 : err("not_found");
95 }
96
97 const repoScope = (repo: Repo): AccountScope => ({
98 scopeId: repo.id,
99 repoId: repo.id,
100 ownerId: repo.ownerId,
101 name: `${repo.ownerName}/${repo.name}`,
102 });
103
104 /** Why an account has no room now, in words; undefined when it has room. */
105 function noRoom(
106 app: App,
107 a: Pick<ScopeAccount, "id" | "restingUntil" | "restingSaid" | "budgetSpent">,
108 now: Date,
109 ): string | undefined {
110 if (a.budgetSpent) return "its budget is spent";
111 if (a.restingUntil !== null && a.restingUntil > now.toISOString())
112 return `it is resting until ${whenText(new Date(a.restingUntil))}${a.restingSaid === "" ? "" : ` (${a.restingSaid.replace(/\.$/, "")})`}`;
113 const week = measureFor(app.db, a.id, "week", now);
114 if (week !== null && week.usedPct >= weekUse(app.db))
115 return `its week is full until ${whenText(new Date(week.resetsAt))}`;
116 return undefined;
117 }
118
119 /**
120 * What a crew run at `scope` spends right now and why, the accounts it may not use and why, and
121 * the fix. A name the viewer may not read (an account someone else added, to a viewer who is no
122 * site admin) is said as "an account of this forge's".
123 */
124 export function crewAccountWords(
125 app: App,
126 viewer: User,
127 scope: AccountScope,
128 now: Date = new Date(),
129 ): CrewAccounts {
130 const named = (createdBy: string | null, name: string): string =>
131 viewer.isAdmin || createdBy === viewer.id ? name : UNNAMED;
132 const usable = scopeAccounts(app.db, scope.repoId, scope.ownerId);
133 const reach = reachWords(app.db);
134 const lines: AccountLine[] = usable.map((a) => {
135 const why = noRoom(app, a, now);
136 const how =
137 a.reach === "pool"
138 ? "from the pool"
139 : `allowed at this ${a.reach === "repo" ? "repository" : "owner"}`;
140 return {
141 name: named(a.createdBy, a.name),
142 here: true,
143 says: why === undefined ? `has room (${how})` : `${why} (${how})`,
144 };
145 });
146 const usedIds = new Set(usable.map((a) => a.id));
147 const others = listSubscriptions(app.db)
148 .filter((s) => !usedIds.has(s.id))
149 .map((s) => ({ s, budget: budgetSpentOf(app, s.id) }));
150 for (const { s } of others)
151 lines.push({
152 name: named(s.createdBy, s.name),
153 here: false,
154 says: `not used here: ${reach.get(s.id) ?? "allowed nowhere"}`,
155 });
156 const room = usable.find((a) => noRoom(app, a, now) === undefined);
157 // The fix: another account with room, which this viewer may allow here.
158 const spare = others.find(
159 ({ s, budget }) =>
160 mayAllow(viewer, s.createdBy) &&
161 noRoom(
162 app,
163 {
164 id: s.id,
165 restingUntil: s.restingUntil,
166 restingSaid: s.restingSaid,
167 budgetSpent: budget,
168 },
169 now,
170 ) === undefined,
171 )?.s;
172 const fix =
173 room === undefined && spare !== undefined
174 ? ` ${spare.name} has room but is not used here: allow it here.`
175 : "";
176 const says =
177 room !== undefined
178 ? `Runs for ${scope.name} spend ${named(room.createdBy, room.name)}: it has room this week.`
179 : usable.length === 0
180 ? `No account may be used for ${scope.name}, so runs spend the server's own token${ownerAdmin(app, scope.ownerId) ? "" : ", which is a forge admin's alone: they wait"}.${fix}`
181 : `Runs for ${scope.name} wait: ${usable.map((a) => `${named(a.createdBy, a.name)}: ${noRoom(app, a, now)}`).join("; ")}.${fix}`;
182 return {
183 scope: scope.name,
184 says,
185 accounts: lines,
186 ...(fix === "" || spare === undefined ? {} : { allow: spare.name }),
187 };
188 }
189
190 const ownerAdmin = (app: App, ownerId: string): boolean =>
191 getUserById(app.db, ownerId)?.isAdmin === true;
192
193 const budgetSpentOf = (app: App, id: string): boolean => {
194 const row = app.db
195 .query<
196 { budget_usd: number | null; spent_usd: number },
197 [string]
198 >("SELECT budget_usd, spent_usd FROM subscription WHERE id = ?1")
199 .get(id);
200 return (
201 row !== null &&
202 row.budget_usd !== null &&
203 row.budget_usd - row.spent_usd < 0.25
204 );
205 };
206
207 /** A site admin may allow any account anywhere; anyone else only an account they added. */
208 const mayAllow = (viewer: User, createdBy: string | null): boolean =>
209 viewer.isAdmin || createdBy === viewer.id;
210
211 /**
212 * Allow the account `name` at `scope`, for every crew member, then let runs held for want of an
213 * account try again at once. Someone who is not a site admin allows only an account they added.
214 */
215 export function allowAccount(
216 app: App,
217 viewer: User,
218 scope: AccountScope,
219 name: string,
220 ): Result<{ allowed: boolean; released: number }, AccountsError> {
221 const account = getSubscriptionByName(app.db, name);
222 if (
223 account === undefined ||
224 account.id === "platform" ||
225 !mayAllow(viewer, account.createdBy)
226 )
227 return err("no_such_account");
228 const allowed = allowAt(app.db, scope.scopeId, account.id);
229 if (allowed)
230 app.bus.append({
231 kind: "subscription.allowed",
232 actorId: viewer.id,
233 payload: { account: account.id, scope: scope.name },
234 });
235 return ok({ allowed, released: recheckHeld(app) });
236 }
237
238 /**
239 * Put an account in the pool, used by default (`everywhere`), or limit it to where it is allowed;
240 * a site admin's step. Runs held for want of an account try again at once.
241 */
242 export function poolAccount(
243 app: App,
244 viewer: User,
245 name: string,
246 everywhere: boolean,
247 ): Result<{ released: number }, AccountsError> {
248 if (!viewer.isAdmin) return err("forbidden");
249 const account = getSubscriptionByName(app.db, name);
250 if (account === undefined || !setLimited(app.db, account.id, !everywhere))
251 return err("no_such_account");
252 app.bus.append({
253 kind: everywhere ? "subscription.pooled" : "subscription.limited",
254 actorId: viewer.id,
255 payload: { account: account.id },
256 });
257 return ok({ released: recheckHeld(app) });
258 }
259
260 /** Each refusal in the words every door says. */
261 export const ACCOUNTS_WORDS: Record<AccountsError, string> = {
262 not_found: "no such repository or owner whose crew you run",
263 forbidden: "only a forge admin puts an account in the pool or limits it",
264 no_such_account: "no account by that name that you may allow",
265 };
266
267 /**
268 * The account sentence for a held run's log: what the crew at `repo` spends and the fix, as its
269 * owner would read it (another's account named only to a forge admin).
270 */
271 export function accountsSaid(app: App, repo: Repo, now: Date = new Date()): string {
272 const owner = getUserById(app.db, repo.ownerId);
273 return owner === undefined ? "" : crewAccountWords(app, owner, repoScope(repo), now).says;
274 }
src/core/connections.ts +3
@@ -27,6 +27,7 @@ import {
2727 normalizeToken,
2828 PLATFORM,
2929 setGrants,
30 setLimited,
3031 subscriptionAad,
3132 } from "./subscriptions.ts";
3233
@@ -339,6 +340,8 @@ export function saveConnection(
339340 input.effort ?? "",
340341 input.scope,
341342 );
343 // A person's own connection is theirs alone: limited to their own scope.
344 if (input.scope === "yours") setLimited(db, connectionId, true);
342345 if (input.scope === "yours")
343346 setGrants(db, input.userId, EVERYONE, [
344347 ...listGrants(db, input.userId)
src/core/event_audience.ts +3
@@ -281,6 +281,9 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
281281 // (`actions/invites.ts`).
282282 kind.startsWith("repo.contributor_") ||
283283 kind.startsWith("repo.invite_") ||
284 // Which crew account is allowed where, or pooled, is the forge's own money: its admins'
285 // (`actions/crew_accounts.ts`).
286 kind.startsWith("subscription.") ||
284287 // A repository's monthly spend cap, set or cleared, is its admins' (`actions/wallet.ts`).
285288 kind === "wallet.cap" ||
286289 // A wallet under a tenth of its cap, once a month, is theirs to hear first (`core/wallet.ts`).
src/core/migration-pins/20261125214141-subscription-limited.pin added +1
@@ -0,0 +1,1 @@
1 231dca9c09270f8eae77b9f04effeee775cb796771568de502ad4d762c28c9c3
src/core/migrations/20261125214141-subscription-limited.ts added +7
@@ -0,0 +1,7 @@
1 // A crew account is in the pool, used by default, unless it is limited to where it is allowed
2 // (`core/subscriptions.ts`). An account already allowed somewhere keeps to those places, as it did;
3 // one allowed nowhere joins the pool. Additive.
4 export default `
5 ALTER TABLE subscription ADD COLUMN limited INTEGER NOT NULL DEFAULT 0;
6 UPDATE subscription SET limited = 1 WHERE id IN (SELECT subscription_id FROM subscription_grant);
7 `;
src/core/model_grant.ts +2
@@ -15,6 +15,7 @@ import {
1515 NAME_MAX,
1616 PLATFORM,
1717 setGrants,
18 setLimited,
1819 EVERYONE,
1920 type Subscription,
2021 type SubscriptionError,
@@ -140,6 +141,7 @@ export function addOwnSubscription(
140141 // The account's own: so it stays theirs whatever is granted later (`core/connections.ts`).
141142 db.query("UPDATE subscription SET scope = 'yours' WHERE id = ?1").run(added.value.id);
142143 setGrants(db, user.id, EVERYONE, [added.value.id]);
144 setLimited(db, added.value.id, true);
143145 }
144146 return added;
145147 }
src/core/subscriptions.ts +157 −67
@@ -534,6 +534,39 @@ export function scopesOf(db: Database): Map<string, string[]> {
534534 return out;
535535 }
536536
537 /** The words for the server's own token's reach, wherever an account's reach is listed. */
538 export const SERVER_TOKEN_REACH = "the server's own token: used only where no account may be";
539
540 /**
541 * Where each sealed account is used, in words, by id: a limited one only where it is allowed;
542 * else the pool (a forge admin's repositories) or, for a person's own account, their own, and
543 * wherever it is allowed besides. The one reading the board, Settings and the terminal share.
544 */
545 export function reachWords(db: Database): Map<string, string> {
546 const scopes = scopesOf(db);
547 const rows = db
548 .query<{ id: string; creator: string | null; admin: number | null; limited: number; scope: string }, []>(
549 `SELECT s.id, u.username AS creator, u.is_admin AS admin, s.limited, s.scope FROM subscription s
550 LEFT JOIN user u ON u.id = s.created_by WHERE s.id <> 'platform'`,
551 )
552 .all();
553 return new Map(
554 rows.map((r) => {
555 const at = scopes.get(r.id) ?? [];
556 const own = r.creator !== null && (r.admin !== 1 || r.scope !== "forge");
557 const base =
558 r.limited === 1
559 ? at.length === 0
560 ? "limited, and allowed nowhere: not used"
561 : `only for ${at.join(", ")}`
562 : own
563 ? `for ${r.creator}'s own repositories`
564 : "the pool: every repository a forge admin owns";
565 return [r.id, r.limited === 0 && at.length > 0 ? `${base}, and ${at.join(", ")}` : base];
566 }),
567 );
568 }
569
537570 export interface GrantPlace {
538571 readonly subscription: string;
539572 /** `owner/name` for a repository, `@org` for an organization. */
@@ -593,12 +626,20 @@ function listGrantPlaceRows(
593626 }));
594627 }
595628
629 /**
630 * Limit an account to where it is allowed (`true`), or put it in the pool, used by default
631 * (`false`). False when no such account.
632 */
633 export function setLimited(db: Database, subscriptionId: string, limited: boolean): boolean {
634 return db.query("UPDATE subscription SET limited = ?2 WHERE id = ?1 AND id <> 'platform'").run(subscriptionId, limited ? 1 : 0).changes === 1;
635 }
636
596637 // ---- the pick ----
597638
598639 export type Pick =
599 /** No grant reaches this run: the forge's own token, `PLATFORM`, from its environment. */
640 /** No account may be used here and the scope's owner is a forge admin: the server's own token. */
600641 | { readonly kind: "env" }
601 /** No grant reaches this run and its owner is not a forge admin: the forge's token is not theirs to spend. */
642 /** No account may be used here and the scope's owner is not a forge admin: nothing to spend. */
602643 | { readonly kind: "none" }
603644 | {
604645 readonly kind: "ready";
@@ -610,7 +651,7 @@ export type Pick =
610651 /** On a budgeted account: the most this run may spend, reserved for it. */
611652 readonly capUsd?: number;
612653 }
613 /** Every account on the nearest grant is resting; the earliest to wake. */
654 /** Every account that may be used here is resting or spent; the earliest to wake. */
614655 | {
615656 readonly kind: "resting";
616657 readonly until: string;
@@ -624,12 +665,64 @@ export interface PickScope {
624665 readonly agentId: string;
625666 }
626667
668 /** Why an account may be used at a scope: allowed there (a grant), or the pool's default. */
669 export type Reach = "repo" | "owner" | "pool";
670
671 type CandidateRow = Row & {
672 token_enc: string;
673 budget_usd: number | null;
674 spent_usd: number;
675 reach: Reach;
676 };
677
627678 /**
628 * The account a run works on. The nearest grant wins whole: a repository's
629 * before its owner's, this agent's before everyone's — and a grant whose
630 * accounts are all resting does not fall through to a wider one, because a
631 * work repository must not quietly spend the personal plan. Within the
632 * grant, the account used longest ago goes first.
679 * The accounts a run at `scope` may use, in the order they are tried: those allowed here (a
680 * grant), the repository's before its owner's and this agent's before everyone's; then the pool.
681 * An account is in the pool, used by default, unless it is limited (`limited`) to where it is
682 * allowed. The pool is a forge admin's accounts for a forge admin's scopes, and anyone's own
683 * accounts for their own: a person's run never spends an account that is not theirs or allowed to
684 * them. Within each, the account used longest ago first.
685 */
686 function candidates(db: Database, scope: PickScope, runId: string): CandidateRow[] {
687 const rows = db
688 .query<CandidateRow & { tier: number }, [string, string, string, string]>(
689 `SELECT * FROM (
690 SELECT s.id, s.name, s.kind, s.token_enc, s.api_base, s.resting_until, s.resting_said,
691 s.last_used_at, s.created_by, s.created_at, s.budget_usd, ${COMMITTED} AS spent_usd,
692 CASE WHEN g.scope_id = ?1 THEN 'repo' ELSE 'owner' END AS reach,
693 (CASE WHEN g.scope_id = ?1 THEN 0 ELSE 2 END) + (CASE WHEN g.agent_id = ?3 THEN 0 ELSE 1 END) AS tier
694 FROM subscription_grant g JOIN subscription s ON s.id = g.subscription_id
695 WHERE g.scope_id IN (?1, ?2) AND g.agent_id IN (?3, '') AND s.id <> 'platform'
696 -- A crew run speaks Anthropic's protocol; another connection is Talk's (core/connections.ts).
697 AND s.protocol = 'anthropic'
698 UNION ALL
699 SELECT s.id, s.name, s.kind, s.token_enc, s.api_base, s.resting_until, s.resting_said,
700 s.last_used_at, s.created_by, s.created_at, s.budget_usd, ${COMMITTED} AS spent_usd,
701 'pool' AS reach, 4 AS tier
702 FROM subscription s
703 WHERE s.id <> 'platform' AND s.protocol = 'anthropic'
704 AND s.limited = 0
705 AND (s.created_by = ?2
706 OR (s.scope = 'forge'
707 AND (s.created_by IS NULL OR EXISTS (SELECT 1 FROM user c WHERE c.id = s.created_by AND c.is_admin = 1))
708 AND EXISTS (SELECT 1 FROM user o WHERE o.id = ?2 AND o.is_admin = 1)))
709 )
710 ORDER BY tier, last_used_at IS NOT NULL, last_used_at, name COLLATE NOCASE`,
711 )
712 .all(scope.repoId, scope.ownerId, scope.agentId, runId)
713 .filter((r) => gatewayUsable(r.api_base));
714 const seen = new Set<string>();
715 return rows.filter((r) => !seen.has(r.id) && seen.add(r.id) !== undefined);
716 }
717
718 /** Less than `MIN_RUN_USD` left on its whole-life budget. */
719 const budgetSpent = (r: { budget_usd: number | null; spent_usd: number }): boolean =>
720 r.budget_usd !== null && r.budget_usd - r.spent_usd < MIN_RUN_USD;
721
722 /**
723 * The account a run works on: the first of `candidates` that is awake and has budget. When every
724 * one is resting or spent the run waits for the soonest to wake. The server's own token is used
725 * only when no account may be used here at all, and only for a forge admin's scope.
633726 */
634727 export function pickSubscription(
635728 db: Database,
@@ -638,71 +731,36 @@ export function pickSubscription(
638731 now: Date,
639732 reserve?: { readonly runId: string; readonly usd: number },
640733 ): Pick {
641 const rows = db
642 .query<
643 Row & {
644 scope_id: string;
645 agent_id: string;
646 token_enc: string;
647 budget_usd: number | null;
648 spent_usd: number;
649 },
650 [string, string, string, string]
651 >(
652 `SELECT g.scope_id, g.agent_id, s.id, s.name, s.kind, s.token_enc, s.api_base, s.resting_until,
653 s.resting_said, s.last_used_at, s.created_by, s.created_at, s.budget_usd,
654 ${COMMITTED} AS spent_usd
655 FROM subscription_grant g JOIN subscription s ON s.id = g.subscription_id
656 WHERE g.scope_id IN (?1, ?2) AND g.agent_id IN (?3, '') AND s.id <> 'platform'
657 -- A crew run speaks Anthropic's protocol; another connection is Talk's (core/connections.ts).
658 AND s.protocol = 'anthropic'
659 ORDER BY (g.scope_id = ?1) DESC, (g.agent_id = ?3) DESC,
660 s.last_used_at IS NOT NULL, s.last_used_at, s.name COLLATE NOCASE`,
661 )
662 .all(scope.repoId, scope.ownerId, scope.agentId, reserve?.runId ?? "")
663 .filter((r) => gatewayUsable(r.api_base));
664 const first = rows[0];
665 if (first === undefined) {
666 const owner = db
667 .query<{ is_admin: number }, [string]>("SELECT is_admin FROM user WHERE id = ?1")
668 .get(scope.ownerId);
669 return owner?.is_admin === 1 ? { kind: "env" } : { kind: "none" };
670 }
671 const grant = rows.filter(
672 (r) => r.scope_id === first.scope_id && r.agent_id === first.agent_id,
673 );
734 const rows = candidates(db, scope, reserve?.runId ?? "");
735 if (rows.length === 0) return ownerIsAdmin(db, scope.ownerId) ? { kind: "env" } : { kind: "none" };
674736 // An account whose whole-life budget is spent is not offered again until
675737 // an admin raises it; looked at again within the hour, so a raise is felt.
676738 // Spent counts what other runs on it may still spend (their reservation)
677739 // as well as what every run has spent, so runs started together cannot
678740 // each pass a budget that only one of them fits in.
679 const spent = (r: (typeof grant)[number]) =>
680 r.budget_usd !== null && r.budget_usd - r.spent_usd < MIN_RUN_USD;
681 const awake = grant.find(
682 (r) =>
683 !spent(r) &&
684 (r.resting_until === null || r.resting_until <= now.toISOString()),
741 const awake = rows.find(
742 (r) => !budgetSpent(r) && (r.resting_until === null || r.resting_until <= now.toISOString()),
685743 );
686 if (awake === undefined && grant.every(spent)) {
687 const first = grant[0]!;
744 if (awake === undefined && rows.every(budgetSpent)) {
745 const first = rows[0]!;
688746 return {
689747 kind: "resting",
690748 until: new Date(now.getTime() + BUDGET_RECHECK_MS).toISOString(),
691749 said: storedText(`its $${first.budget_usd} budget is spent.`, "an admin of this forge", "raise it"),
692 names: grant.map((r) => r.name),
750 names: rows.map((r) => r.name),
693751 };
694752 }
695753 if (awake === undefined) {
696 const soonest = grant
697 .filter((r) => !spent(r) && r.resting_until !== null)
754 const soonest = rows
755 .filter((r) => !budgetSpent(r) && r.resting_until !== null)
698756 .map((r) => r.resting_until!)
699757 .sort()
700758 .at(0)!;
701759 return {
702760 kind: "resting",
703761 until: soonest,
704 said: grant.find((r) => r.resting_until === soonest)!.resting_said,
705 names: grant.map((r) => r.name),
762 said: rows.find((r) => r.resting_until === soonest)!.resting_said,
763 names: rows.map((r) => r.name),
706764 };
707765 }
708766 const opened = open(dataDir, awake.token_enc, aad(awake.id));
@@ -747,26 +805,58 @@ export function pickSubscription(
747805 };
748806 }
749807
808 const ownerIsAdmin = (db: Database, ownerId: string): boolean =>
809 db.query<{ is_admin: number }, [string]>("SELECT is_admin FROM user WHERE id = ?1").get(ownerId)?.is_admin === 1;
810
811 /** One account a scope's crew may draw on, as `crewAccountWords` and the week's meter read it. */
812 export interface ScopeAccount {
813 readonly id: string;
814 readonly name: string;
815 readonly reach: Reach;
816 readonly createdBy: string | null;
817 readonly restingUntil: string | null;
818 readonly restingSaid: string;
819 readonly budgetSpent: boolean;
820 }
821
750822 /**
751 * The accounts the crew on a repository works on, for pacing: the
752 * repository's own grants if it has any, else its owner's — whichever
753 * agent they name. Empty when none is granted (the forge's own token).
823 * The accounts the crew at a repository (its owner's scope, any agent) may draw on, in the order a
824 * pick tries them. Empty when none may: the server's own token, for a forge admin's scope.
825 */
826 export function scopeAccounts(db: Database, repoId: string, ownerId: string): ScopeAccount[] {
827 return candidates(db, { repoId, ownerId, agentId: "" }, "").map((r) => ({
828 id: r.id,
829 name: r.name,
830 reach: r.reach,
831 createdBy: r.created_by,
832 restingUntil: r.resting_until,
833 restingSaid: r.resting_said,
834 budgetSpent: budgetSpent(r),
835 }));
836 }
837
838 /**
839 * The accounts the crew on a repository works on, for pacing: every one a pick may try there.
840 * Empty when none may (the server's own token).
754841 */
755842 export function grantedAccounts(
756843 db: Database,
757844 repoId: string,
758845 ownerId: string,
759846 ): { id: string; name: string }[] {
760 const rows = db
761 .query<{ id: string; name: string; scope_id: string }, [string, string]>(
762 `SELECT DISTINCT s.id, s.name, g.scope_id
763 FROM subscription_grant g JOIN subscription s ON s.id = g.subscription_id
764 WHERE g.scope_id IN (?1, ?2) AND s.id <> 'platform'
765 ORDER BY s.name COLLATE NOCASE`,
766 )
767 .all(repoId, ownerId);
768 const own = rows.filter((r) => r.scope_id === repoId);
769 return (own.length > 0 ? own : rows).map((r) => ({ id: r.id, name: r.name }));
847 return scopeAccounts(db, repoId, ownerId).map((a) => ({ id: a.id, name: a.name }));
848 }
849
850 /**
851 * Allow an account at one scope (a repository or an owner), for every crew member, beside what is
852 * allowed there already; false when it already was. Whether it is used elsewhere is its `limited`.
853 */
854 export function allowAt(db: Database, scopeId: string, subscriptionId: string): boolean {
855 return (
856 db
857 .query("INSERT OR IGNORE INTO subscription_grant (scope_id, agent_id, subscription_id) VALUES (?1, '', ?2)")
858 .run(scopeId, subscriptionId).changes === 1
859 );
770860 }
771861
772862 /**
src/crew/conversation_ask.ts +8
@@ -300,6 +300,14 @@ export const ASKED_AS: Readonly<Record<string, Form>> = {
300300 return verbs[String(a["verb"])] ?? `Change ${which}`;
301301 },
302302 pinned_forge: (a) => pinnedForge(a),
303 crew_accounts: (a) => {
304 const where = val(a, "repo") || val(a, "owner") || "your repositories";
305 return val(a, "allow") !== ""
306 ? `Let the crew's runs for ${where} spend the account ${val(a, "allow")}`
307 : val(a, "everywhere") !== ""
308 ? `Put the account ${val(a, "everywhere")} in the pool, so the crew uses it by default on every repository a forge admin owns`
309 : `Keep the account ${val(a, "limit")} to where it is allowed`;
310 },
303311 invite: (a) =>
304312 a["link"] === true
305313 ? `Make a one-use link to work on ${repo(a)}: ${linkOpens(repo(a))}; they cannot merge or change settings`
src/crew/conversation_confirm.ts +2
@@ -108,6 +108,8 @@ export const ASKING: Readonly<Record<string, Asking>> = {
108108 land_past_gate: {},
109109 share: {},
110110 invites: { asks: (a) => a["action"] !== "list" },
111 // Which account the crew spends is money: allowing, pooling or limiting one asks first.
112 crew_accounts: { asks: (a) => ["allow", "everywhere", "limit"].some((k) => typeof a[k] === "string" && a[k] !== "") },
111113 invite: {
112114 asks: (a) => (typeof a["who"] === "string" && a["who"] !== "") || a["link"] === true || (typeof a["revoke"] === "string" && a["revoke"] !== ""),
113115 once: "The invite link was shown once, to you, and is not kept here.",
src/crew/dispatch.ts +6 −1
@@ -18,6 +18,8 @@ import { betCapHold } from "./bet_cap_hold.ts";
1818 import { weekHold } from "./week_hold.ts";
1919 import { personActing } from "../core/acting_via.ts";
2020 import { weekFor, weekSpent } from "./week_read.ts";
21 import { recheckOnChange } from "./recheck_held.ts";
22 import { accountsSaid } from "../actions/crew_accounts.ts";
2123 import { redStreak } from "./red_thrice.ts";
2224 import { twinNote, twinOf, type Twin } from "./twin.ts";
2325 import { NO_MERGE } from "../checks/merged.ts";
@@ -343,6 +345,8 @@ export async function startCrew(
343345 log.error("usage check failed", { error: String(error) }),
344346 ));
345347 }
348 // An account added, allowed, woken or raised: runs paused for one are looked at again.
349 recheckOnChange(app);
346350 pump(app, ready, inFlight);
347351 }, undefined, app);
348352 } catch (error) {
@@ -1827,7 +1831,8 @@ export function pump(
18271831 held.set(fresh.id, "pace");
18281832 if (!noted.has(fresh.id)) {
18291833 noted.add(fresh.id);
1830 appendRunLog(app.config.dataDir, fresh.id, paced);
1834 // Which account is full, and the fix when another has room (`actions/crew_accounts.ts`).
1835 appendRunLog(app.config.dataDir, fresh.id, `${paced} ${accountsSaid(app, home)}`);
18311836 }
18321837 continue;
18331838 }
src/crew/recheck_held.ts added +74
@@ -0,0 +1,74 @@
1 /**
2 * A run paused for want of an account (every one it may use resting, spent or full) waits for the
3 * moment the provider named. When the accounts change (one added, allowed, put in the pool, woken,
4 * or its budget raised) such a run is looked at again at once: one whose scope now has an account
5 * with room is released now, not at the old moment. One that would only pause again is left, so a
6 * recheck never spends a run's pauses.
7 */
8
9 import type { App } from "../app.ts";
10 import { scopeAccounts } from "../core/subscriptions.ts";
11 import { forgetWeek } from "./week_read.ts";
12
13 /** Release the account-paused runs whose scope now has an account with room; how many. */
14 export function recheckHeld(app: App, now: Date = new Date()): number {
15 forgetWeek();
16 const held = app.db
17 .query<{ id: string; repo_id: string; owner_id: string }, [string]>(
18 `SELECT r.id, r.repo_id, repo.owner_id FROM run r JOIN repo ON repo.id = r.repo_id
19 WHERE r.kind = 'agent' AND r.state = 'queued' AND r.not_before > ?1
20 AND r.summary LIKE 'paused%' AND r.summary NOT LIKE 'paused: network%'`,
21 )
22 .all(now.toISOString());
23 const at = now.toISOString();
24 const roomy = new Map<string, boolean>();
25 let released = 0;
26 for (const run of held) {
27 const key = `${run.repo_id}\0${run.owner_id}`;
28 if (!roomy.has(key))
29 roomy.set(
30 key,
31 scopeAccounts(app.db, run.repo_id, run.owner_id).some(
32 (a) =>
33 !a.budgetSpent && (a.restingUntil === null || a.restingUntil <= at),
34 ),
35 );
36 if (!roomy.get(key)) continue;
37 released += app.db
38 .query(
39 "UPDATE run SET not_before = NULL WHERE id = ?1 AND state = 'queued'",
40 )
41 .run(run.id).changes;
42 }
43 if (released > 0)
44 app.log.info("runs paused for an account released: an account has room now", {
45 released,
46 });
47 return released;
48 }
49
50 /** What the accounts look like, cheaply: a change between two crew ticks means look again. */
51 function accountsPrint(app: App): string {
52 return (
53 app.db
54 .query<{ print: string | null }, []>(
55 `SELECT (SELECT COUNT(*) FROM subscription_grant) || '|' ||
56 COALESCE(group_concat(id || ',' || limited || ',' || COALESCE(resting_until, '') || ',' || COALESCE(budget_usd, ''), ';'), '') AS print
57 FROM subscription`,
58 )
59 .get()?.print ?? ""
60 );
61 }
62
63 const printed = new WeakMap<App, string>();
64
65 /**
66 * On each crew tick: when the accounts changed since the last one, by any door (Settings, MCP, the
67 * terminal, a key added for the crew), release what an account with room now serves.
68 */
69 export function recheckOnChange(app: App, now: Date = new Date()): number {
70 const print = accountsPrint(app);
71 const before = printed.get(app);
72 printed.set(app, print);
73 return before === undefined || before === print ? 0 : recheckHeld(app, now);
74 }
src/crew/runner.ts +2 −1
@@ -11,6 +11,7 @@
1111 * what the forge has.
1212 */
1313
14 import { accountsSaid } from "../actions/crew_accounts.ts";
1415 import { storedText } from "../kernel/blocked.ts";
1516 import { failureBrief } from "./failure_brief.ts";
1617 import { holdsNaming } from "./desk_posts.ts";
@@ -1546,7 +1547,7 @@ async function work(
15461547 if (picked.kind === "resting") {
15471548 const names = picked.names.join(", ");
15481549 write(
1549 `${names}: resting (${picked.said}) until ${whenText(new Date(picked.until))}`,
1550 `${names}: resting (${picked.said}) until ${whenText(new Date(picked.until))}. ${accountsSaid(app, repo)}`,
15501551 );
15511552 if (run.attempt < MAX_PAUSES)
15521553 return {
src/crew/week_read.ts +6 −4
@@ -46,8 +46,8 @@ function weekOf(app: Reads, repo: Repo, now: Date): Week {
4646
4747 /** The accounts a repository's crew draws on. */
4848 function accountsOf(app: Reads, repo: Repo): string[] {
49 // A crew with no grant runs on the forge's own token: the account `usage`
50 // prints as `platform`. It is metered too, never skipped (#8873).
49 // A crew no account may serve runs on the server's own token: the account `usage` prints as
50 // `platform`. It is metered too, never skipped (#8873).
5151 const granted = grantedAccounts(app.db, repo.id, repo.ownerId).map((a) => a.id);
5252 return granted.length > 0 ? granted : [PLATFORM];
5353 }
@@ -71,8 +71,10 @@ function readWeek(app: Reads, repo: Repo, now: Date): Week {
7171 if (resetsAt === null || at < resetsAt) resetsAt = at;
7272 observedAt = Math.min(observedAt, Date.parse(m.observedAt));
7373 }
74 // No measurement is an unmeasured week: nothing holds the crew but the provider.
75 if (resetsAt === null) return { meter: null, observedAt: now.getTime() };
74 // No measurement is an unmeasured week: nothing holds the crew but the provider. Nor does one
75 // account not yet measured: it has room until a run's reply says otherwise, so an account just
76 // added is used at once, not held behind the week of the ones beside it.
77 if (resetsAt === null || known.length < accounts.length) return { meter: null, observedAt: now.getTime() };
7678 return { meter: { freePct: 100 - usedPct / known.length, keptPct: keptPct / known.length, resetsAt: new Date(resetsAt) }, observedAt };
7779 }
7880
src/http/marks/settings.json +1
@@ -48,6 +48,7 @@
4848 "/settings/crew/key": "admin",
4949 "/settings/crew/budgets": "admin",
5050 "/settings/subscriptions/:id/delete": "admin",
51 "/settings/subscriptions/allow": "admin",
5152 "/settings/subscriptions/:id/wake": "admin",
5253 "/settings/subscriptions/:id/headroom": "admin",
5354 "/settings/subscriptions/:id/budget": "admin",
src/http/mcp/catalog.ts +1 −1
@@ -47,7 +47,7 @@ export const DEFAULT_TOOLS: readonly string[] = [
4747 export const TALK_TOOLS: readonly string[] = [
4848 ...DEFAULT_TOOLS,
4949 "issue", "issues", "pull", "pulls", "commits", "threads", "search", "read_file", "repo", "run_log",
50 "preview", "assigned", "health", "releases", "person", "whoami_can", "show", "pane", "origins", "invite", "wall",
50 "preview", "assigned", "health", "releases", "person", "whoami_can", "show", "pane", "origins", "invite", "wall", "crew_accounts",
5151 "close", "assign", "labels", "edit", "review", "merge", "keep_plan", "steer", "stop",
5252 "write_file", "branches", "open_pull", "new_app", "fetch_url", "bring", "propose_upstream",
5353 ];
src/http/mcp/tools/crew_accounts.ts added +42
@@ -0,0 +1,42 @@
1 import { accountScope, ACCOUNTS_WORDS, allowAccount, crewAccountWords, poolAccount } from "../../../actions/crew_accounts.ts";
2 import { bad, good, str, type Tool } from "../shared.ts";
3
4 /** Only a read: nothing to allow, pool or limit. */
5 const reads = (args: Record<string, unknown>): boolean => str(args["allow"]) === "" && str(args["everywhere"]) === "" && str(args["limit"]) === "";
6
7 export const tool: Tool = {
8 name: "crew_accounts",
9 doc: "`{ repo?, owner?, allow?, everywhere?, limit? }`: which account the crew's runs spend right now at a repository (owner/name) or an owner (default: yours) and why, every account and whether it is used there, and the fix (`allow`: an account with room that is not used there); `allow` an account there (one confirm), `everywhere` puts one in the pool and `limit` keeps one to where it is allowed (a forge admin's). The repository's or owner's admin only",
10 description: "Which account crew runs spend and why; allow one where it is needed.",
11 inputSchema: {
12 type: "object",
13 properties: {
14 repo: { type: "string" },
15 owner: { type: "string" },
16 allow: { type: "string" },
17 everywhere: { type: "string" },
18 limit: { type: "string" },
19 },
20 },
21 writes: true,
22 readsWithout: ["allow", "everywhere", "limit"],
23 heldNotWhen: reads,
24 run(ctx, user, args) {
25 if (user === undefined) return bad("unauthorized", "sign in");
26 const scope = accountScope(ctx.app, user, { repo: str(args["repo"]), owner: str(args["owner"]) });
27 if (!scope.ok) return bad("not_found", ACCOUNTS_WORDS.not_found);
28 const allow = str(args["allow"]);
29 if (allow !== "") {
30 const done = allowAccount(ctx.app, user, scope.value, allow);
31 if (!done.ok) return bad(done.error, ACCOUNTS_WORDS[done.error]);
32 return good({ ...crewAccountWords(ctx.app, user, scope.value), released: done.value.released });
33 }
34 const pooled = str(args["everywhere"]) || str(args["limit"]);
35 if (pooled !== "") {
36 const done = poolAccount(ctx.app, user, pooled, str(args["everywhere"]) !== "");
37 if (!done.ok) return bad(done.error, ACCOUNTS_WORDS[done.error]);
38 return good({ ...crewAccountWords(ctx.app, user, scope.value), released: done.value.released });
39 }
40 return good(crewAccountWords(ctx.app, user, scope.value));
41 },
42 };
src/http/mcp/tools/index.ts +1
@@ -50,6 +50,7 @@ export { tool as confirm_wait } from "./confirm_wait.ts";
5050 export { tool as contribute } from "./contribute.ts";
5151 export { tool as converge } from "./converge.ts";
5252 export { tool as crew } from "./crew.ts";
53 export { tool as crew_accounts } from "./crew_accounts.ts";
5354 export { tool as data } from "./data.ts";
5455 export { tool as decisions_by } from "./decisions_by.ts";
5556 export { tool as desk } from "./desk.ts";
src/http/settings_routes.ts +2
@@ -83,6 +83,7 @@ import {
8383 subscriptionBudget,
8484 subscriptionHeadroom,
8585 subscriptionWake,
86 subscriptionAllow,
8687 } from "../web/pages/subscriptions.ts";
8788 import { peoplePage, roleAct } from "../web/pages/people.ts";
8889 import { ceilingAct, grantAct, modelAdd, modelPage } from "../web/pages/model.ts";
@@ -216,6 +217,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
216217 router.add("POST", "/settings/crew/key", crewKeyAdd);
217218 router.add("POST", "/settings/crew/budgets", crewBudgetsSave);
218219 router.add("POST", "/settings/subscriptions/:id/delete", subscriptionDelete);
220 router.add("POST", "/settings/subscriptions/allow", subscriptionAllow);
219221 router.add("POST", "/settings/subscriptions/:id/wake", subscriptionWake);
220222 router.add(
221223 "POST",
src/spawn/preview-seed.ts +7 −3
@@ -57,7 +57,7 @@ import { addDependency } from "../core/dependencies.ts";
5757 import { claimRun, createPullRun, createRun, finishRun } from "../core/runs.ts";
5858 import { setMember } from "../core/roles.ts";
5959 import { noteLimit } from "../core/standing.ts";
60 import { addSubscription, listSubscriptions } from "../core/subscriptions.ts";
60 import { addSubscription, listSubscriptions, setLimited } from "../core/subscriptions.ts";
6161 import { createAgent } from "../actions/crew.ts";
6262 import { getAgentByName } from "../core/agents.ts";
6363 import { createSession, destroySession } from "../core/sessions.ts";
@@ -583,6 +583,8 @@ async function seedSettingsPages(app: App, admin: User): Promise<Result<void, st
583583 token: "sk-ant-oat01-preview-sample-not-a-credential",
584584 });
585585 if (!added.ok) return err(`the sample account: ${added.error}`);
586 // Limited, and allowed nowhere: its token is no credential, so no run is ever handed it.
587 setLimited(app.db, added.value.id, true);
586588 }
587589 if (!listRunners(app.db).some((r) => r.name === PREVIEW_RUNNER)) enrolRunner(app.db, PREVIEW_RUNNER, admin.id);
588590 const http = forgeHttp(app);
@@ -818,8 +820,8 @@ async function seedLanding(app: App, admin: User, repo: Repo): Promise<Result<vo
818820 * ones, and a weekly capacity it can cut the list by: an inert account
819821 * that the provider refused at $8 last week and that has spent a little
820822 * since. Its token is no credential, only the shape one has, and it is
821 * granted to no repository or owner, so `pickSubscription` (which joins
822 * on grants) never offers it to a run or a conversation.
823 * limited and allowed nowhere, so `pickSubscription` never offers it to a
824 * run or a conversation.
823825 */
824826 function seedPrices(app: App, admin: User, repo: Repo): Result<Issue[], string> {
825827 const finished: Issue[] = [];
@@ -847,6 +849,8 @@ function seedPrices(app: App, admin: User, repo: Repo): Result<Issue[], string>
847849 token: "sk-ant-oat01-preview-sample-not-a-credential",
848850 });
849851 if (!added.ok) return err(`the sample account: ${added.error}`);
852 // Limited, and allowed nowhere: its token is no credential, so no run is ever handed it.
853 setLimited(app.db, added.value.id, true);
850854 const spend = (usd: number, at: Date) => {
851855 const run = createRun(app.db, { repoId: repo.id, kind: "agent", actorId: admin.id, reason: "seed" });
852856 claimRun(app.db, run.id);
src/tui/screens/subscriptions.ts +34 −9
@@ -17,7 +17,7 @@ import {
1717 getSubscription,
1818 isSubscriptionName,
1919 listSubscriptions,
20 scopesOf,
20 reachWords,
2121 setBudget,
2222 wakeSubscription,
2323 type Subscription,
@@ -28,7 +28,8 @@ import { SUBSCRIPTION_WORDS, addRefusal } from "../../core/subscriptions_words.t
2828 import type { Ctx, Screen } from "../app/app.ts";
2929 import { binding } from "../app/keys.ts";
3030 import { style } from "../term/style.ts";
31 import { truncate } from "../term/width.ts";
31 import { truncate, wrap } from "../term/width.ts";
32 import { ACCOUNTS_WORDS, allowAccount, crewAccountWords, type CrewAccounts } from "../../actions/crew_accounts.ts";
3233 import type { Session } from "../session.ts";
3334 import { fill, len, split } from "../ui/layout.ts";
3435 import { ListState, confirmScreen, drawList, later, promptScreen, type ListRow } from "./common.ts";
@@ -44,22 +45,25 @@ export function subscriptionsScreen(f: Session, ctx: Ctx): Screen {
4445 // What the screen shows, read once on open and again after each change it
4546 // makes, so a keypress redraws from memory and never queries the database.
4647 let all: Subscription[] = [];
48 let rightNow: CrewAccounts | undefined;
4749 let listed: ListRow[] = [];
4850 const load = (): void => {
4951 all = admitted() ? listSubscriptions(f.app.db) : [];
5052 const budgets = budgetsOf(f.app.db);
51 const scopes = scopesOf(f.app.db);
53 const reach = reachWords(f.app.db);
54 // What a crew run on this admin's own repositories spends right now, and the fix.
55 rightNow = f.user !== undefined && admitted() ? crewAccountWords(f.app, f.user, { scopeId: f.user.id, repoId: "", ownerId: f.user.id, name: f.user.username }) : undefined;
5256 const seen = standings(f.app.db, all.map((a) => a.id), new Date());
5357 const now = Date.now();
5458 listed = all.map((s) => {
5559 const b = budgets.get(s.id);
5660 const resting = s.restingUntil !== null && Date.parse(s.restingUntil) > now;
57 const pays = (scopes.get(s.id) ?? []).join(", ");
61 const pays = reach.get(s.id) ?? "";
5862 const st = seen.get(s.id);
5963 return {
6064 title: s.name,
6165 tone: resting ? "attn" : "success",
62 secondary: `${s.kind} ${pays === "" ? "pays for nothing" : `pays for ${pays}`}`,
66 secondary: `${s.kind} ${pays}`,
6367 meta:
6468 `${b?.budgetUsd == null ? "no budget" : `budget ${money(b.budgetUsd)}`} spent ${money(b?.spentUsd ?? 0)} ` +
6569 (resting ? `resting until ${s.restingUntil}` : "awake"),
@@ -119,12 +123,13 @@ export function subscriptionsScreen(f: Session, ctx: Ctx): Screen {
119123
120124 const screen: Screen = {
121125 title: "Crew subscriptions",
122 keys: [binding(["j", "k"], "move cursor"), binding(["w"], "wake"), binding(["b"], "set budget"), binding(["a"], "add"), binding(["D"], "remove"), binding(["esc"], "back")],
126 keys: [binding(["j", "k"], "move cursor"), binding(["A"], "allow the fix here"), binding(["w"], "wake"), binding(["b"], "set budget"), binding(["a"], "add"), binding(["D"], "remove"), binding(["esc"], "back")],
123127 render(area, s) {
124128 const c = ctx.theme.c;
125 const [head, body] = split(area, "v", [len(1), fill(1)]);
126 const text = note !== "" ? note : all.length === 0 ? "No subscription yet. a adds one." : "w wakes a resting one, b sets its budget, a adds, D removes.";
127 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
129 const help = all.length === 0 ? "No subscription yet. a adds one." : `w wakes a resting one, b sets its budget, a adds, D removes${rightNow?.allow === undefined ? "" : `, A allows ${rightNow.allow} here`}.`;
130 const said = wrap(note !== "" ? note : `${rightNow?.says ?? ""} ${help}`.trim(), Math.max(1, area.w)).slice(0, 3);
131 const [head, body] = split(area, "v", [len(said.length), fill(1)]);
132 said.forEach((line, i) => s.text(head!.x, head!.y + i, truncate(line, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w));
128133 drawList(s, body!, c, state, listed);
129134 },
130135 key(e) {
@@ -132,6 +137,26 @@ export function subscriptionsScreen(f: Session, ctx: Ctx): Screen {
132137 if (state.key(e, all.length)) return true;
133138 if (e.ctrl || e.alt || !admitted()) return false;
134139 const sub = all[state.index];
140 const spare = rightNow?.allow;
141 if (e.key === "A" && spare !== undefined && f.user !== undefined) {
142 const user = f.user;
143 void later(ctx, () =>
144 confirmScreen(ctx, screen, {
145 title: "Allow here",
146 body: [`Let the crew's runs for ${user.username} spend ${spare}.`],
147 actions: [{ label: "Cancel", variant: "ghost" }, { label: "Allow" }],
148 selected: 1,
149 onChoose: (i) => {
150 if (i !== 1) return;
151 const done = allowAccount(f.app, user, { scopeId: user.id, repoId: "", ownerId: user.id, name: user.username }, spare);
152 note = done.ok ? `${spare} is allowed here${done.value.released === 0 ? "" : `; ${done.value.released} held runs start now`}.` : ACCOUNTS_WORDS[done.error];
153 load();
154 ctx.invalidate();
155 },
156 }),
157 );
158 return true;
159 }
135160 if (e.key === "w" && sub !== undefined) {
136161 const now = getSubscription(f.app.db, sub.id);
137162 if (now === undefined) note = "No such subscription.";
src/web/pages/board.ts +9 −16
@@ -49,7 +49,8 @@ import { standings, WINDOW_MS } from "../../core/standing.ts";
4949 import {
5050 listCredentials,
5151 PLATFORM,
52 scopesOf,
52 reachWords,
53 SERVER_TOKEN_REACH,
5354 type Subscription,
5455 } from "../../core/subscriptions.ts";
5556 import { readSpend } from "../../actions/spend.ts";
@@ -638,11 +639,9 @@ function figures(parts: readonly FigureWords[]): Html {
638639 /**
639640 * Each credential's 5-hour and weekly window — used, left, resets — and the
640641 * crew's spend broken down, for a site admin only: the pool is theirs
641 * (`/settings/subscriptions`). The platform's token leads: it is the crew's.
642 * Then the accounts with a scope, then those with none — a person's own
643 * plan, never offered to the crew, its numbers kept apart so they never
644 * read as idle crew capacity. A fixed number of statements however many
645 * accounts (`standings`, `scopesOf`). A live region of its own.
642 * (`/settings/subscriptions`). The server's own token leads, then every account, each with where
643 * it is used (`reachWords`). A fixed number of statements however many accounts. A live region of
644 * its own.
646645 */
647646 function windowsStrip(ctx: Ctx): Html | null {
648647 if (!ctx.auth.user?.isAdmin) return null;
@@ -655,11 +654,8 @@ function windowsStrip(ctx: Ctx): Html | null {
655654 pool.map((s) => s.id),
656655 now,
657656 );
658 const scopes = scopesOf(db);
659 const scopeWords = (id: string): string =>
660 id === PLATFORM
661 ? "every app no subscription is granted to"
662 : (scopes.get(id) ?? []).join(", ");
657 const reach = reachWords(db);
658 const scopeWords = (id: string): string => (id === PLATFORM ? SERVER_TOKEN_REACH : (reach.get(id) ?? ""));
663659 const row = (s: Subscription): Html | null => {
664660 const st = all.get(s.id);
665661 if (st === undefined) return null;
@@ -690,11 +686,9 @@ function windowsStrip(ctx: Ctx): Html | null {
690686 ></span
691687 >`;
692688 })}
693 ${when(scopeWords(s.id) !== "", () => html`<span>for ${scopeWords(s.id)}</span>`)}
689 ${when(scopeWords(s.id) !== "", () => html`<span>${scopeWords(s.id)}</span>`)}
694690 </a>`;
695691 };
696 const crew = pool.filter((s) => s.id === PLATFORM || scopes.has(s.id));
697 const apart = pool.filter((s) => s.id !== PLATFORM && !scopes.has(s.id));
698692 const group = (name: string, key: string, subs: readonly Subscription[]): Html =>
699693 html`<div class="stack stack-tight" data-group="${key}">
700694 <span class="muted small">${name}</span>${subs.map(row)}
@@ -705,8 +699,7 @@ function windowsStrip(ctx: Ctx): Html | null {
705699 data-live="run.queued,run.started,run.finished,usage.*"
706700 aria-label="Subscription windows"
707701 >
708 ${group("The crew's", "crew", crew)}
709 ${when(apart.length > 0, () => group("Not offered to the crew", "apart", apart))}
702 ${group("The crew's", "crew", pool)}
710703 <details id="spend-detail">
711704 <summary class="muted small">Spend by credential, app, agent, issue and kind</summary>
712705 ${spendView(readSpend(ctx.app, now))}
src/web/pages/subscriptions.ts +32 −9
@@ -5,6 +5,7 @@
55 * for. A token is typed once and never shown again.
66 */
77
8 import { ACCOUNTS_WORDS, allowAccount, crewAccountWords } from "../../actions/crew_accounts.ts";
89 import { sshOn } from "../../settings/ssh.ts";
910 import { listAgents, type Agent } from "../../core/agents.ts";
1011 import {
@@ -19,7 +20,8 @@ import {
1920 listSubscriptions,
2021 NAME_MAX,
2122 PLATFORM,
22 scopesOf,
23 reachWords,
24 SERVER_TOKEN_REACH,
2325 setBudget,
2426 setGrants,
2527 wakeSubscription,
@@ -120,13 +122,8 @@ export function subscriptionsPage(ctx: Ctx): Response {
120122 const places = timePhase(ctx.request, "places", () =>
121123 listGrantPlaces(ctx.app.db),
122124 );
123 const scopes = timePhase(ctx.request, "scopes", () => scopesOf(ctx.app.db));
124 const scopeText = (s: Subscription): string =>
125 s.id === PLATFORM
126 ? "the crew's: every app no subscription is granted to"
127 : scopes.has(s.id)
128 ? `for ${scopes.get(s.id)!.join(", ")}`
129 : "not offered to the crew — granted nowhere";
125 const reach = timePhase(ctx.request, "scopes", () => reachWords(ctx.app.db));
126 const scopeText = (s: Subscription): string => (s.id === PLATFORM ? SERVER_TOKEN_REACH : (reach.get(s.id) ?? ""));
130127 const budgets = timePhase(ctx.request, "budgets", () =>
131128 budgetsOf(ctx.app.db),
132129 );
@@ -345,9 +342,22 @@ export function subscriptionsPage(ctx: Ctx): Response {
345342 )}
346343 </dl></section>`;
347344
345 // What a crew run on the admin's own repositories spends right now, why, and the one-step fix.
346 const user = ctx.auth.user!;
347 const words = crewAccountWords(ctx.app, user, { scopeId: user.id, repoId: "", ownerId: user.id, name: user.username }, now);
348 const rightNow = html`<section class="settings-block" data-crew-accounts><h2>Right now</h2>
349 <p>${words.says}</p>
350 ${words.allow === undefined
351 ? null
352 : html`<form method="post" action="${POOL}/allow" class="inline-form">
353 <input type="hidden" name="account" value="${words.allow}" />
354 ${btn(`Allow ${words.allow} here`, { variant: "primary", size: "sm" })}
355 </form>`}
356 <ul class="small muted">${words.accounts.map((a) => html`<li><b>${a.name}</b> ${a.says}</li>`)}</ul>
357 </section>`;
348358 const response = shell(
349359 ctx,
350 html`${lent} ${own} ${isHostedForge(ctx.app) && sealed.length === 0 ? null : list} ${none === null || isHostedForge(ctx.app) ? null : html`<div class="mt">${none}</div>`}
360 html`${rightNow} ${lent} ${own} ${isHostedForge(ctx.app) && sealed.length === 0 ? null : list} ${none === null || isHostedForge(ctx.app) ? null : html`<div class="mt">${none}</div>`}
351361 <p class="mt muted small">What they spent: <a href="/settings/spend">Usage → Spend</a>.</p>
352362 <div class="mt">${add}</div>
353363 ${used === null ? null : html`<div class="mt">${used}</div>`}`,
@@ -356,6 +366,19 @@ export function subscriptionsPage(ctx: Ctx): Response {
356366 return response;
357367 }
358368
369 // POST /settings/subscriptions/allow — allow an account for the admin's own repositories, the
370 // fix "Right now" names; runs held for want of an account try again at once.
371 export async function subscriptionAllow(ctx: Ctx): Promise<Response> {
372 const denied = requireAdmin(ctx);
373 if (denied) return denied;
374 const form = await readForm(ctx, "admin");
375 if (form instanceof Response) return form;
376 const user = ctx.auth.user!;
377 const done = allowAccount(ctx.app, user, { scopeId: user.id, repoId: "", ownerId: user.id, name: user.username }, field(form, "account"));
378 if (!done.ok) return flashTo(ctx, POOL, { tone: "danger", message: ACCOUNTS_WORDS[done.error] });
379 return flashTo(ctx, POOL, { message: done.value.released === 0 ? "Allowed here." : `Allowed here; ${done.value.released} held runs start now.` });
380 }
381
359382 // POST /settings/subscriptions
360383 export async function subscriptionAdd(ctx: Ctx): Promise<Response> {
361384 const denied = requireAdmin(ctx);
test/board-windows.test.ts +4 −2
@@ -312,8 +312,10 @@ describe("efficiency and standing, grouped", () => {
312312 const strip = page.slice(page.indexOf('id="windows"'), page.indexOf('id="spend-detail"'));
313313 expect(strip).not.toContain('class="card');
314314 expect(strip).toContain('data-group="crew"');
315 // A credential no app is scoped to sits in its own group.
316 expect(strip).toContain('data-group="apart"');
315 // Every credential is the crew's, each saying where it is used: an account allowed nowhere is
316 // the pool's, never set apart as unused.
317 expect(strip).not.toContain('data-group="apart"');
318 expect(strip).toContain("the pool: every repository a forge admin owns");
317319 expect(strip).toContain('data-key="sub:');
318320 expect(strip).toContain('data-window="5h"');
319321 expect(strip).toContain('data-window="week"');
test/conversation-ask.test.ts +3
@@ -492,6 +492,9 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [
492492 ["invite", { repo: "marin/cakes", who: "ben", remove: true }, "Take ben off marin/cakes: they can no longer open it, its app or ask its crew."],
493493 ["wall", { repo: "marin/cakes", number: 2, answer: "allow" }, "Allow pull #2 in marin/cakes at the access wall and merge it."],
494494 ["wall", { repo: "marin/cakes", number: 2, answer: "send_back" }, "Send pull #2 in marin/cakes back at the access wall."],
495 ["crew_accounts", { repo: "marin/cakes", allow: "espo-corp" }, "Let the crew's runs for marin/cakes spend the account espo-corp."],
496 ["crew_accounts", { everywhere: "espo-corp" }, "Put the account espo-corp in the pool, so the crew uses it by default on every repository a forge admin owns."],
497 ["crew_accounts", { limit: "espo-corp" }, "Keep the account espo-corp to where it is allowed."],
495498 [
496499 "pinned_forge",
497500 { verb: "deploy", name: "shop", target: "hetzner" },
test/conversation-turn.test.ts +3 −1
@@ -15,7 +15,7 @@ import { clearAccountCeiling, daySpent, setAccountCeiling } from "../src/core/ac
1515 import { claimDone, completeWrite, recordWrite } from "../src/core/conversation_writes.ts";
1616 import { listTurns, newConversation, openConversation } from "../src/core/conversations.ts";
1717 import { monthSpent } from "../src/core/model_grant.ts";
18 import { addSubscription, getSubscription, PLATFORM, restSubscription, setGrants, wakeSubscription } from "../src/core/subscriptions.ts";
18 import { addSubscription, getSubscription, PLATFORM, restSubscription, setGrants, setLimited, wakeSubscription } from "../src/core/subscriptions.ts";
1919 import { verifyToken } from "../src/core/tokens.ts";
2020 import { createUser, type User } from "../src/core/users.ts";
2121 import { createSession } from "../src/core/sessions.ts";
@@ -398,6 +398,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Back.","to
398398 const sub = addSubscription(app.db, dir, { name: "lent", token: "sk-ant-api-test-lent" });
399399 if (!sub.ok) throw new Error("subscription");
400400 setGrants(app.db, alice.id, "", [sub.value.id]);
401 setLimited(app.db, sub.value.id, true);
401402 const until = new Date(Date.now() + 15 * 60_000).toISOString();
402403 restSubscription(app.db, sub.value.id, until, "window full");
403404 const said = say(app, options(stub("rested", "s", "answer")), alice.id, "what is happening on voxel?");
@@ -460,6 +461,7 @@ echo '{"type":"result","subtype":"success","is_error":true,"result":"You have hi
460461 const account = addSubscription(app.db, dir, { name: "home", token: "sk-ant-api-test-home" });
461462 if (!account.ok) throw new Error("account");
462463 setGrants(app.db, alice.id, "", [account.value.id]);
464 setLimited(app.db, account.value.id, true);
463465 try {
464466 const said = say(app, options(limitedStub("limited")), alice.id, "hello?");
465467 expect(said.ok).toBe(true);
test/credentials.test.ts +33 −14
@@ -31,6 +31,8 @@ import {
3131 listSubscriptions,
3232 pickSubscription,
3333 PLATFORM,
34 SERVER_TOKEN_REACH,
35 setLimited,
3436 scopesOf,
3537 setGrants,
3638 } from "../src/core/subscriptions.ts";
@@ -148,16 +150,21 @@ describe("the platform credential", () => {
148150 });
149151
150152 describe("a subscription's scope", () => {
151 test("one granted nowhere is never picked; one granted elsewhere is not picked here", () => {
152 // Invariant: a subscription is picked for a repository only when granted there; elsewhere the pick falls back to env.
153 test("one allowed nowhere is the pool, used by default; one allowed elsewhere is not picked here", () => {
154 // Invariant: an account no grant limits is used on an admin's repository by default (the
155 // server's own token only when there is none); one allowed elsewhere is used only there.
153156 const espo = listSubscriptions(app.db)[0]!;
154157 const scope = { repoId: repo.id, ownerId: alice.id, agentId: bot.id };
155 expect(pickSubscription(app.db, dataDir, scope, new Date()).kind).toBe("env");
156 expect(grantedAccounts(app.db, repo.id, alice.id)).toEqual([]);
158 const pooled = pickSubscription(app.db, dataDir, scope, new Date());
159 expect(pooled.kind === "ready" && pooled.subscription.id).toBe(espo.id);
160 expect(grantedAccounts(app.db, repo.id, alice.id)).toEqual([{ id: espo.id, name: espo.name }]);
157161 expect(scopesOf(app.db).has(espo.id)).toBe(false);
158162
163 // Allowed elsewhere it is still the pool's; limited, it is used only where it is allowed.
159164 setGrants(app.db, "another-repo", EVERYONE, [espo.id]);
160165 expect(scopesOf(app.db).get(espo.id)).toEqual(["a place that is gone"]);
166 expect(pickSubscription(app.db, dataDir, scope, new Date()).kind).toBe("ready");
167 setLimited(app.db, espo.id, true);
161168 expect(pickSubscription(app.db, dataDir, scope, new Date()).kind).toBe("env");
162169 expect(grantedAccounts(app.db, repo.id, alice.id)).toEqual([]);
163170 setGrants(app.db, "another-repo", EVERYONE, []);
@@ -168,12 +175,15 @@ describe("a subscription's scope", () => {
168175 expect(picked.kind === "ready" && picked.subscription.id).toBe(espo.id);
169176 expect(scopesOf(app.db).get(espo.id)).toEqual(["alice/garden"]);
170177 setGrants(app.db, repo.id, EVERYONE, []);
178 setLimited(app.db, espo.id, false);
171179 });
172180 });
173181
174182 describe("a repository whose owner is not a forge admin", () => {
175 test("gets none without a grant and the subscription once granted; an admin's still gets env", async () => {
176 // Invariant: a non-admin owner's repository gets no credential without a grant, the subscription with one; an admin's gets env.
183 test("gets none without a grant and the subscription once granted; an admin's gets the pool, else env", async () => {
184 // Invariant: a non-admin owner's repository gets no credential without a grant, the
185 // subscription with one; an admin's gets the pool, and the server's own token once the pool
186 // is empty.
177187 const b = await createUser(app.db, {
178188 origin: "seed",
179189 trusted: true,
@@ -188,9 +198,17 @@ describe("a repository whose owner is not a forge admin", () => {
188198 setGrants(app.db, "bobs-repo", EVERYONE, [espo.id]);
189199 const picked = pickSubscription(app.db, dataDir, outsider, new Date());
190200 expect(picked.kind === "ready" && picked.subscription.id).toBe(espo.id);
191 setGrants(app.db, "bobs-repo", EVERYONE, []);
201 // Limited to bob's repository, espo is not alice's: hers falls back to the server's token.
192202 const admin = { repoId: "admins-repo", ownerId: alice.id, agentId: bot.id };
203 setLimited(app.db, espo.id, true);
193204 expect(pickSubscription(app.db, dataDir, admin, new Date()).kind).toBe("env");
205 setLimited(app.db, espo.id, false);
206 setGrants(app.db, "bobs-repo", EVERYONE, []);
207 const pooled = pickSubscription(app.db, dataDir, admin, new Date());
208 expect(pooled.kind === "ready" && pooled.subscription.id).toBe(espo.id);
209 // The next test runs on the server's own token: espo stays limited to bob's.
210 setGrants(app.db, "bobs-repo", EVERYONE, [espo.id]);
211 setLimited(app.db, espo.id, true);
194212 });
195213 });
196214
@@ -315,7 +333,7 @@ describe("the breakdown", () => {
315333 });
316334
317335 describe("the board", () => {
318 test("puts the crew's credentials first and the unscoped account apart, with the spend", async () => {
336 test("puts the crew's credentials first, each with where it is used, with the spend", async () => {
319337 // Invariant: the board and settings pages show the crew's credentials apart from the unscoped account, with the spend views.
320338 const cookie = (
321339 (
@@ -327,13 +345,14 @@ describe("the board", () => {
327345 ).headers.get("set-cookie") ?? ""
328346 ).split(";")[0]!;
329347 const page = await (await fetch(`${servers.url}/board`, { headers: { cookie } })).text();
348 // Every account is the crew's now, each with where it is used (an account is the pool until
349 // it is limited); none is kept apart as not offered.
330350 const crewAt = page.indexOf('data-group="crew"');
331 const apartAt = page.indexOf('data-group="apart"');
332351 expect(crewAt).toBeGreaterThan(-1);
333 expect(apartAt).toBeGreaterThan(crewAt);
334 expect(page.slice(crewAt, apartAt)).toContain("platform (env)");
335 expect(page.slice(crewAt, apartAt)).not.toContain("trevato-espo");
336 expect(page.slice(apartAt)).toContain("trevato-espo");
352 expect(page).not.toContain('data-group="apart"');
353 expect(page.slice(crewAt)).toContain("platform (env)");
354 expect(page.slice(crewAt)).toContain("trevato-espo");
355 expect(page.slice(crewAt)).toContain(SERVER_TOKEN_REACH.replace("'", "&#39;"));
337356 expect(page).toContain('data-live="run.queued,run.started,run.finished,usage.*"');
338357 expect(page).toContain('data-by="byKind"');
339358 expect(page).toContain("The 10 costliest runs");
@@ -342,7 +361,7 @@ describe("the board", () => {
342361 await fetch(`${servers.url}/settings/subscriptions`, { headers: { cookie } })
343362 ).text();
344363 expect(subs).toContain("platform (env)");
345 expect(subs).toContain("not offered to the crew");
364 expect(subs).toContain(SERVER_TOKEN_REACH.replace("'", "&#39;"));
346365 expect(subs).toContain('href="/settings/spend"');
347366
348367 const spend = await (await fetch(`${servers.url}/settings/spend`, { headers: { cookie } })).text();
test/crew-accounts.test.ts added +156
@@ -0,0 +1,156 @@
1 /**
2 * Which account a crew run spends, in one place, and the one step that changes it (the owner,
3 * 2026-11-25: "this whole configuration feels confusing"). An account is in the pool, used by
4 * default, unless it is limited to where it is allowed; the server's own token is used only where
5 * no account may be; a run paused for want of an account is released the moment one has room.
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 { accountScope, crewAccountWords } from "../src/actions/crew_accounts.ts";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import type { Repo } from "../src/core/repos.ts";
15 import { createRun, getRun } from "../src/core/runs.ts";
16 import { createSession } from "../src/core/sessions.ts";
17 import { addSubscription, pickSubscription, restSubscription, setGrants, setLimited, EVERYONE } from "../src/core/subscriptions.ts";
18 import { createToken } from "../src/core/tokens.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { mintViaToken } from "../src/core/via_token.ts";
21 import { recheckOnChange } from "../src/crew/recheck_held.ts";
22 import { serve, type Servers } from "../src/http/server.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24 import { promote } from "./helpers/members.ts";
25
26 quietLogs();
27 let dir: string, app: App, servers: Servers;
28 let trevato: User, bob: User, carol: User, forge: Repo, bobs: Repo;
29 const NOV29 = "2026-11-29T02:01:00.000Z";
30 const NOW = new Date("2026-11-25T21:00:00.000Z");
31 let id = 1;
32
33 const person = async (username: string, isAdmin = false): Promise<User> => {
34 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.test`, password: "a-good-passphrase", isAdmin });
35 if (!made.ok) throw new Error(made.error);
36 promote(app.db, made.value);
37 return made.value;
38 };
39 const account = (name: string, by: User): string => {
40 const made = addSubscription(app.db, dir, { name, token: `sk-ant-oat01-${name}-token-for-the-test`, createdBy: by.id });
41 if (!made.ok) throw new Error(made.error);
42 return made.value.id;
43 };
44 const pick = (repo: Repo) => pickSubscription(app.db, dir, { repoId: repo.id, ownerId: repo.ownerId, agentId: "" }, NOW);
45 const named = (p: ReturnType<typeof pick>) => (p.kind === "ready" ? p.subscription.name : p.kind);
46 const mcp = async (token: string, args: Record<string, unknown>): Promise<string> => {
47 const res = await fetch(`${servers.url}/mcp`, {
48 method: "POST",
49 headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
50 body: JSON.stringify({ jsonrpc: "2.0", id: id++, method: "tools/call", params: { name: "crew_accounts", arguments: args } }),
51 });
52 return ((await res.json()) as { result: { content: { text: string }[] } }).result.content.map((c) => c.text).join("\n");
53 };
54
55 beforeAll(async () => {
56 dir = await mkdtemp(join(tmpdir(), "forge-crew-accounts-"));
57 app = createApp({ dataDir: dir, port: 0 });
58 trevato = await person("trevato", true);
59 bob = await person("bob");
60 carol = await person("carol");
61 const f = await createRepo(app, trevato, { name: "forge", visibility: "public" });
62 const b = await createRepo(app, bob, { name: "shop", visibility: "private" });
63 if (!f.ok || !b.ok) throw new Error("repos");
64 [forge, bobs] = [f.value, b.value];
65 servers = await serve(app);
66 });
67 afterAll(async () => {
68 await servers.stop();
69 app.close();
70 await rm(dir, { recursive: true, force: true });
71 });
72
73 describe("today's case: the account in use is full until Nov 29, and another is added", () => {
74 test("the pause names the account and the fix; adding the new one releases the held run at once", () => {
75 // espo-trevato is limited to trevato's repositories, and its week is full until Nov 29.
76 const full = account("espo-trevato", trevato);
77 setGrants(app.db, trevato.id, EVERYONE, [full]);
78 setLimited(app.db, full, true);
79 restSubscription(app.db, full, NOV29, "You've hit your weekly limit");
80 expect(pick(forge)).toMatchObject({ kind: "resting", until: NOV29 });
81 // A run paused on it, to resume on Nov 29.
82 const run = createRun(app.db, { repoId: forge.id, kind: "agent", notBefore: NOV29, summary: `paused: espo-trevato resting — weekly; resumes ${NOV29}` });
83 recheckOnChange(app, NOW);
84 const scope = { scopeId: trevato.id, repoId: "", ownerId: trevato.id, name: "trevato" };
85 expect(crewAccountWords(app, trevato, scope, NOW).says).toStartWith("Runs for trevato wait: espo-trevato: it is resting until");
86
87 // An account kept to another place is named as the fix, and releases nothing.
88 const acme = account("espo-acme", trevato);
89 setGrants(app.db, "acme", EVERYONE, [acme]);
90 setLimited(app.db, acme, true);
91 const words = crewAccountWords(app, trevato, scope, NOW);
92 expect(words.says).toContain("espo-acme has room but is not used here: allow it here.");
93 expect(words.allow).toBe("espo-acme");
94 expect(recheckOnChange(app, NOW)).toBe(0);
95 expect(getRun(app.db, run.id)!.notBefore).toBe(NOV29);
96
97 // espo-corp is added, ungranted, as tonight: in the pool by default, the run is released at
98 // once, and spends it.
99 account("espo-corp", trevato);
100 expect(recheckOnChange(app, NOW)).toBe(1);
101 expect(getRun(app.db, run.id)!.notBefore).toBeNull();
102 expect(named(pick(forge))).toBe("espo-corp");
103 expect(crewAccountWords(app, trevato, scope, NOW).says).toBe("Runs for trevato spend espo-corp: it has room this week.");
104 });
105
106 test("Settings says it and allows the fix in one step; Talk's allow asks first", async () => {
107 const corp = app.db.query<{ id: string }, []>("SELECT id FROM subscription WHERE name = 'espo-corp'").get()!.id;
108 setLimited(app.db, corp, true);
109 const cookie = `forge_session=${createSession(app.db, trevato.id).token}`;
110 const page = await (await fetch(`${servers.url}/settings/subscriptions`, { headers: { cookie } })).text();
111 expect(page).toContain("data-crew-accounts");
112 expect(page).toContain("allow it here.");
113 expect(page).toContain('name="account" value="espo-acme"');
114 // Through a conversation, allowing is held for the person's yes.
115 const via = mintViaToken(app.db, trevato.id, "conversation:c1", "", new Date(Date.now() + 600_000).toISOString());
116 if (!via.ok) throw new Error(via.error);
117 expect(await mcp(via.value.token, { allow: "espo-acme" })).toContain('"needs_confirm"');
118 // The page's one press allows it here.
119 const posted = await fetch(`${servers.url}/settings/subscriptions/allow`, {
120 method: "POST",
121 redirect: "manual",
122 headers: { cookie, origin: servers.url, "content-type": "application/x-www-form-urlencoded" },
123 body: new URLSearchParams({ account: "espo-acme" }),
124 });
125 expect(posted.status).toBe(303);
126 expect(named(pick(forge))).toBe("espo-acme");
127 });
128 });
129
130 describe("whose accounts reach where", () => {
131 test("an account a non-admin adds is used only for their own repositories, never an admin's or another's", () => {
132 // Every other account is kept to where it is allowed, so only bob's is in play.
133 app.db.query("UPDATE subscription SET limited = 1").run();
134 expect(named(pick(bobs))).toBe("none");
135 account("bobs-own", bob);
136 expect(named(pick(bobs))).toBe("bobs-own");
137 expect(named(pick(forge))).not.toBe("bobs-own");
138 const carols = { ...bobs, id: "carols-repo", ownerId: carol.id };
139 expect(named(pick(carols))).toBe("none");
140 });
141
142 test("a stranger is told nothing, and reads no account's name it did not add", async () => {
143 const carolToken = createToken(app.db, carol.id, "t", "ro").token;
144 const told = await mcp(carolToken, { repo: "trevato/forge" });
145 expect(told).toStartWith("not_found:");
146 expect(accountScope(app, carol, { repo: "bob/shop" }).ok).toBe(false);
147 // Her own scope: accounts she did not add are never named.
148 const own = await mcp(carolToken, {});
149 for (const name of ["espo-trevato", "espo-corp", "bobs-own"]) expect(own).not.toContain(name);
150 expect(own).toContain("an account of this forge's");
151 // Bob reads his own by name, and the admin's not.
152 const bobs = await mcp(createToken(app.db, bob.id, "t", "ro").token, {});
153 expect(bobs).toContain("bobs-own");
154 expect(bobs).not.toContain("espo-corp");
155 });
156 });
test/idle-reason.test.ts +3 −1
@@ -17,7 +17,7 @@ import { createRun } from "../src/core/runs.ts";
1717 import { noteMeasure } from "../src/core/measure.ts";
1818 import { forgetWeek } from "../src/crew/week_read.ts";
1919 import { noteLimit } from "../src/core/standing.ts";
20 import { addSubscription, PLATFORM, setGrants } from "../src/core/subscriptions.ts";
20 import { addSubscription, PLATFORM, setGrants, setLimited } from "../src/core/subscriptions.ts";
2121 import { createUser, getUserByName, type User } from "../src/core/users.ts";
2222 import { idleLine, idleReason } from "../src/crew/idle_reason.ts";
2323
@@ -113,6 +113,8 @@ describe("idleReason", () => {
113113 const added = addSubscription(app.db, dataDir, { name: `acct${n}`, token: "sk-ant-api03-idle-reason-test-key" });
114114 if (!added.ok) throw new Error(String(added.error));
115115 setGrants(app.db, repo.id, "", [added.value.id]);
116 // This repository's alone: limited, so the tests after it run on the server's own token.
117 setLimited(app.db, added.value.id, true);
116118 noteLimit(app.db, added.value.id, {
117119 window: "5h",
118120 resetsAt: "2026-10-02T14:00:00.000Z",
test/invite-contributors.test.ts +2 −1
@@ -193,8 +193,9 @@ beforeAll(async () => {
193193 throw new Error("hook");
194194 const sub = addSubscription(app.db, standIn.dataDir, { name: SUB, token: "sk-ant-oat01-zqx-owner-only" });
195195 if (!sub.ok) throw new Error(sub.error);
196 // Granted to the other repository, so the money test's own grant on the app stays its alone.
196 // Limited to the other repository, so the money test's own grant on the app stays its alone.
197197 app.db.query("INSERT INTO subscription_grant (scope_id, agent_id, subscription_id) VALUES (?1, '', ?2)").run(vault.value.id, sub.value.id);
198 app.db.query("UPDATE subscription SET limited = 1 WHERE id = ?1").run(sub.value.id);
198199 }, 30_000);
199200 afterAll(() => stopStandInCrew(standIn), 30_000);
200201
test/looks-owner.test.ts +3 −3
@@ -138,9 +138,9 @@ describe("the preview seed", () => {
138138 ["Make every long and winding bet name wrap instead of pushing the page sideways", "proposed", 20],
139139 ]);
140140
141 // The sample account that prices the week has no grant, so no run or
142 // conversation in a preview can be handed its inert token: the admin
143 // falls through to the platform's own credential.
141 // The sample account that prices the week is limited and allowed nowhere, so no run or
142 // conversation in a preview can be handed its inert token: the admin falls through to the
143 // platform's own credential.
144144 expect(app.db.query("SELECT COUNT(*) AS n FROM subscription WHERE name = 'preview sample'").get()).toEqual({ n: 1 });
145145 const picked = pickSubscription(app.db, app.config.dataDir, { repoId: repo.id, ownerId: admin.id, agentId: "" }, new Date());
146146 expect(picked.kind).toBe("env");
test/mcp-forge-protocol.test.ts +1
@@ -217,6 +217,7 @@ describe("the forge over MCP: protocol", () => {
217217 "forge_proposals",
218218 "converge",
219219 "crew",
220 "crew_accounts",
220221 "family",
221222 "features",
222223 "next_steps",
test/mcp-talk-tools.test.ts +1
@@ -293,6 +293,7 @@ describe("every write Talk's agent is newly listed is held after it reads someon
293293 edit: { repo: "alice/hostile", number: 1, title: "pwned" },
294294 invite: { repo: "alice/hostile", who: "mallory" },
295295 wall: { repo: "alice/hostile", number: 2, answer: "allow" },
296 crew_accounts: { repo: "alice/hostile", allow: "mallory-key" },
296297 keep_plan: { repo: "alice/hostile", number: 1, items: ["pwned"] },
297298 labels: { repo: "alice/hostile", number: 1, labels: ["pwned"] },
298299 merge: { repo: "alice/hostile", number: 2, dryRun: false },
test/runner-measure.test.ts +5 −2
@@ -11,7 +11,7 @@ import { createApp, type App } from "../src/app.ts";
1111 import { measureFor } from "../src/core/measure.ts";
1212 import type { Repo } from "../src/core/repos.ts";
1313 import { listRuns } from "../src/core/runs.ts";
14 import { addSubscription, PLATFORM, setGrants } from "../src/core/subscriptions.ts";
14 import { addSubscription, PLATFORM, setGrants, setLimited } from "../src/core/subscriptions.ts";
1515 import { createUser, type User } from "../src/core/users.ts";
1616 import { startCrew, type CrewHandle } from "../src/crew/dispatch.ts";
1717 import { serve, type Servers } from "../src/http/server.ts";
@@ -78,10 +78,13 @@ afterAll(async () => {
7878 await rm(dataDir, { recursive: true, force: true });
7979 });
8080
81 test("a run with no grant stores the measure against platform; with a grant, against that subscription", async () => {
81 test("a run no account may serve stores the measure against platform; with one allowed, against that subscription", async () => {
8282 const added = addSubscription(app.db, dataDir, { name: "main", token: "sk-ant-oat01-runner-1" });
8383 if (!added.ok) throw new Error(added.error);
8484 const sub = added.value.id;
85 // Limited to where it is allowed, and allowed nowhere yet: the first run is on the server's
86 // token.
87 setLimited(app.db, sub, true);
8588 const now = new Date();
8689 await runOnce("first");
8790 expect(measureFor(app.db, PLATFORM, "week", now)?.usedPct).toBe(50);
test/subscription-budget.test.ts +3
@@ -233,6 +233,9 @@ describe("an account's whole-life budget", () => {
233233 const id = made.value.id;
234234 const r = repo;
235235 setGrants(app.db, r.id, EVERYONE, [id]);
236 // The other accounts are limited to where they are allowed, so a spent one has no pool to fall
237 // to.
238 app.db.query("UPDATE subscription SET limited = 1 WHERE id <> ?1").run(id);
236239 lockBudget(app.db, id, 8);
237240 const a = createRun(app.db, { repoId: r.id, kind: "agent" });
238241 const b = createRun(app.db, { repoId: r.id, kind: "agent" });
test/week-doors.test.ts +3
@@ -133,6 +133,9 @@ describe("the week's doors", () => {
133133 // Capacity: the provider refused at $20 a week ago; the next window is open and unspent.
134134 const sub = addSubscription(forge.db, dataDir, { name: "acct", token: "sk-ant-oat01-doors-test-1" });
135135 if (!sub.ok) throw new Error(sub.error);
136 // Limited to another repository: the crew here runs on the server's own token.
137 forge.db.query("INSERT INTO subscription_grant (scope_id, agent_id, subscription_id) VALUES ('elsewhere', '', ?1)").run(sub.value.id);
138 forge.db.query("UPDATE subscription SET limited = 1 WHERE id = ?1").run(sub.value.id);
136139 recordUsage(forge.db, {
137140 runId: createRun(forge.db, { repoId: repo.id, kind: "agent" }).id, repoId: repo.id, issueId: null, agentId: null,
138141 subscriptionId: sub.value.id, tokensIn: 1, tokensOut: 1, costUsd: 20, wallMs: 1000, outcome: "ok",
test/week-wiring.test.ts +5 −3
@@ -180,8 +180,10 @@ test("with no measurement of the week nothing holds the crew and home says nothi
180180 });
181181
182182 test("a crew on the forge's own token is metered: the provider's measure stops it at the budget", () => {
183 // The cause of #8873: no grant meant no account, no week.
184 app.db.query("DELETE FROM subscription_grant").run();
183 // The cause of #8873: no grant meant no account, no week. The one account is limited to
184 // another repository, so this crew has none and runs on the server's own token.
185 app.db.query("UPDATE subscription_grant SET scope_id = 'elsewhere'").run();
186 app.db.query("UPDATE subscription SET limited = 1").run();
185187 app.db.query("DELETE FROM usage").run();
186188 setCapacity(app.db, "week.use", "50", alice.id);
187189 try {
@@ -191,7 +193,7 @@ test("a crew on the forge's own token is metered: the provider's measure stops i
191193 expect(weekWords(app, NOW)).toContain("54% of the week used");
192194 } finally {
193195 setCapacity(app.db, "week.use", "90", alice.id);
194 app.db.query("INSERT INTO subscription_grant (scope_id, agent_id, subscription_id) VALUES (?1, '', ?2)").run(repo.id, sub);
196 app.db.query("UPDATE subscription_grant SET scope_id = ?1").run(repo.id);
195197 }
196198 });
197199

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs