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

The forge's own credential pays only for the forge's own repositories; anyone else runs on a grant or not at all #950

Closed opened this
Closed without merging

steward/656-no-default-credential → main 4 commits

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
9 files changed +227 −18
src/actions/apps.ts +9 −1
@@ -44,6 +44,7 @@ import {
4444 import { addCrew, getAgentByName } from "../core/agents.ts";
4545 import { listAllAgents } from "./crew.ts";
4646 import { plan, planIssueBody, planningAvailable } from "../crew/plan.ts";
47 import { platformReaches } from "../core/subscriptions.ts";
4748 import type { Issue } from "../core/issues.ts";
4849 import { getPull } from "../core/pulls.ts";
4950 import { canEnterApp, canWrite, getRepo, type Repo } from "../core/repos.ts";
@@ -335,7 +336,14 @@ export async function newApp(
335336 // Off the critical path only in the sense that a slow or absent decider
336337 // costs at most `PLAN_TIMEOUT_MS` and never a wrong answer (crew/plan.ts):
337338 // the repository, the app and production above have already started.
338 if (!agent && input.pickAgent && description !== "") {
339 // The decider runs on the forge's own credential, so only on the forge's
340 // own repositories (#656); anyone else picks their crew member by hand.
341 if (
342 !agent &&
343 input.pickAgent &&
344 description !== "" &&
345 platformReaches(app.db, repo.value.ownerId)
346 ) {
339347 const binary = process.env["FORGE_CLAUDE"] ?? "claude";
340348 if (planningAvailable(binary)) {
341349 const roster = listAllAgents(app, user.value);
src/core/subscriptions.ts +51 −4
@@ -6,7 +6,9 @@
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 * the forge's own token only on the forge's own repositories (an admin's,
10 * or an org an admin owns): anyone else's runs on a grant or not at all
11 * (#656), so a new account can never spend the owner's plan.
1012 *
1113 * When the provider turns an account away, that account rests until the
1214 * provider says it is ready, and the next account on the same grant takes
@@ -18,8 +20,8 @@
1820 *
1921 * The forge's own token is a subscription too: the row `PLATFORM`, shown as
2022 * `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 * environment. It is never granted; it is what a run on the forge's own
24 * repositories gets when no grant reaches it, and the ledger and the windows count it like any other. The
2325 * grants are each sealed account's scope, an allow-list: an account with
2426 * none is never offered to the crew (a person's own plan, kept apart).
2527 */
@@ -28,6 +30,7 @@ import type { Database } from "bun:sqlite";
2830 import { id } from "../kernel/id.ts";
2931 import { err, ok, type Result } from "../kernel/result.ts";
3032 import { open, seal } from "../kernel/secret.ts";
33 import { OWNERS_TEAM } from "./orgs.ts";
3134
3235 export type SubscriptionKind = "oauth" | "api_key";
3336
@@ -439,6 +442,8 @@ function listGrantPlaceRows(
439442 export type Pick =
440443 /** No grant reaches this run: the forge's own token, `PLATFORM`, from its environment. */
441444 | { readonly kind: "env" }
445 /** No grant reaches this run, and the forge's own token is not its owner's to spend. */
446 | { readonly kind: "none" }
442447 | {
443448 readonly kind: "ready";
444449 readonly subscription: Subscription;
@@ -496,7 +501,8 @@ export function pickSubscription(
496501 )
497502 .all(scope.repoId, scope.ownerId, scope.agentId, reserve?.runId ?? "");
498503 const first = rows[0];
499 if (first === undefined) return { kind: "env" };
504 if (first === undefined)
505 return platformReaches(db, scope.ownerId) ? { kind: "env" } : { kind: "none" };
500506 const grant = rows.filter(
501507 (r) => r.scope_id === first.scope_id && r.agent_id === first.agent_id,
502508 );
@@ -589,6 +595,47 @@ export function grantedAccounts(
589595 return (own.length > 0 ? own : rows).map((r) => ({ id: r.id, name: r.name }));
590596 }
591597
598 /**
599 * Whether the forge's own credential may pay for runs on this owner's
600 * repositories: the forge's own, an admin's or an org an admin owns. A
601 * newcomer's repository runs only on a grant an admin gave on purpose.
602 */
603 export function platformReaches(db: Database, ownerId: string): boolean {
604 return (
605 db
606 .query<{ one: number }, [string, string]>(
607 `SELECT 1 AS one FROM user WHERE id = ?1 AND kind = 'user' AND is_admin = 1
608 AND suspended_at IS NULL AND removed_at IS NULL
609 UNION ALL
610 SELECT 1 FROM team t
611 JOIN team_member m ON m.team_id = t.id
612 JOIN user u ON u.id = m.user_id
613 WHERE t.org_id = ?1 AND t.name = ?2 AND u.is_admin = 1
614 AND u.suspended_at IS NULL AND u.removed_at IS NULL
615 LIMIT 1`,
616 )
617 .get(ownerId, OWNERS_TEAM) !== null
618 );
619 }
620
621 /**
622 * Whether anything pays for runs on this owner's repositories: the forge's
623 * own credential (`platformReaches`), or a grant to the owner or to one of
624 * its repositories. A new account has none until an admin grants one.
625 */
626 export function hasModelBudget(db: Database, ownerId: string): boolean {
627 if (platformReaches(db, ownerId)) return true;
628 return (
629 db
630 .query<{ one: number }, [string]>(
631 `SELECT 1 AS one FROM subscription_grant
632 WHERE scope_id = ?1 OR scope_id IN (SELECT id FROM repo WHERE owner_id = ?1)
633 LIMIT 1`,
634 )
635 .get(ownerId) !== null
636 );
637 }
638
592639 /**
593640 * Whether the crew has any model credential to run on: a sealed account,
594641 * or a token or signed-in Claude config in the forge's own environment —
src/crew/runner.ts +14 −2
@@ -856,6 +856,16 @@ async function work(
856856 resumesAt: new Date(picked.until),
857857 };
858858 }
859 // Nothing granted, and the forge's own token is not this repository's
860 // owner's to spend (#656): the run ends here, before any call.
861 if (picked.kind === "none") {
862 write("no model account: nothing is granted to this repository or its owner");
863 return {
864 state: "failed",
865 summary:
866 "this repository has no model account: an admin can grant one in Subscriptions",
867 };
868 }
859869 if (picked.kind === "ready") {
860870 write(`subscription: ${picked.subscription.name}`);
861871 noteRunProgress(app.db, run.id, {
@@ -1508,11 +1518,13 @@ function redactResult<T extends { result: string }>(r: T): T {
15081518
15091519 /**
15101520 * The credential a run's environment carries: the picked account's token
1511 * under the variable Claude Code reads it from, or — with nothing granted —
1512 * whatever the forge itself was started with.
1521 * under the variable Claude Code reads it from, or — with nothing granted,
1522 * on the forge's own repositories — whatever the forge itself was started
1523 * with. Anything else carries none.
15131524 */
15141525 function credentialEnv(picked: Pick): Record<string, string> {
15151526 if (picked.kind === "ready") return { [picked.envName]: picked.token };
1527 if (picked.kind !== "env") return {};
15161528 const own: Record<string, string> = {};
15171529 for (const name of ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"]) {
15181530 const value = process.env[name];
src/web/pages/account.ts +2 −1
@@ -9,6 +9,7 @@
99 * has been read once.
1010 */
1111
12 import { budgetNote } from "../studio/crew.ts";
1213 import { resendVerification } from "../../actions/verify.ts";
1314 import { emailVerified } from "../../core/verify.ts";
1415 import {
@@ -224,7 +225,7 @@ export function accountPage(ctx: Ctx): Response {
224225 ctx,
225226 "profile",
226227 "Settings",
227 html`${everydayLine(ctx, ctx.auth.user)}${profileView(ctx, currentProfile(ctx.auth.user))}${notifyView(ctx)}`,
228 html`${everydayLine(ctx, ctx.auth.user)}${budgetNote(ctx, ctx.auth.user)}${profileView(ctx, currentProfile(ctx.auth.user))}${notifyView(ctx)}`,
228229 );
229230 }
230231
src/web/pages/apps.ts +10 −4
@@ -22,6 +22,7 @@ import {
2222 } from "../../actions/apps.ts";
2323 import { listAllAgents } from "../../actions/crew.ts";
2424 import { planningAvailable } from "../../crew/plan.ts";
25 import { platformReaches } from "../../core/subscriptions.ts";
2526 import { appNameJs, deriveAppName } from "./apps-name.ts";
2627 import { envPull, previewEnv, type EnvName } from "../../apps/data.ts";
2728 import { appsRuntime, type EnvStatus, envsFor } from "../../apps/runtime.ts";
@@ -208,7 +209,10 @@ function newAppForm(ctx: Ctx, values: NewAppValues, error?: string): Html {
208209 const agents = listAllAgents(ctx.app, user);
209210 const crew = agents.ok ? agents.value : [];
210211 const domain = appsRuntime(ctx.app)?.options.domain;
211 const canPlan = planningAvailable(process.env["FORGE_CLAUDE"] ?? "claude");
212 // The decider spends the forge's own credential: offered where that may (#656).
213 const canPlan =
214 planningAvailable(process.env["FORGE_CLAUDE"] ?? "claude") &&
215 platformReaches(ctx.app.db, user.id);
212216
213217 return html`<div class="narrow-wide">
214218 ${pageHead("New app", {
@@ -323,9 +327,11 @@ export function newAppPage(ctx: Ctx): Response {
323327 name: "",
324328 description: "",
325329 visibility: "private",
326 agent: planningAvailable(process.env["FORGE_CLAUDE"] ?? "claude")
327 ? PICK_AGENT
328 : "",
330 agent:
331 planningAvailable(process.env["FORGE_CLAUDE"] ?? "claude") &&
332 platformReaches(ctx.app.db, ctx.auth.user.id)
333 ? PICK_AGENT
334 : "",
329335 }),
330336 scriptJs: appNameJs,
331337 });
src/web/pages/board.ts +2 −1
@@ -14,6 +14,7 @@
1414 * pointer. The old big view (`/big`, every address it had) lands here.
1515 */
1616
17 import { budgetNote } from "../studio/crew.ts";
1718 import { appsForRepos, type AppRecord } from "../../core/apps.ts";
1819 import { askMeasure } from "../../core/ask_ledger.ts";
1920 import { reviewersOf, waitsForPerson } from "../../crew/review.ts";
@@ -228,7 +229,7 @@ export function boardPage(ctx: Ctx): Response {
228229 <time class="board-clock" id="board-clock"></time>
229230 </header>
230231 ${forgeStrip(ctx)} ${declinedStrip(ctx, scope)} ${reviewStrip(ctx, scope)}
231 ${asksStrip(ctx)}
232 ${asksStrip(ctx)} ${budgetNote(ctx, user)}
232233 ${returnsStrip(ctx, scope)}
233234 ${windowsStrip(ctx)}
234235 <div class="board-grid">
src/web/studio/app.ts +1 −1
@@ -447,7 +447,7 @@ export async function studioApp(
447447 })}
448448 ${following === undefined ? "" : followingCard(ctx, repo, following)}
449449 <div id="app-head">${head}</div>
450 ${await policyLine(ctx, repo, record)} ${ownerFacts ? crewKeyNote(ctx) : null}
450 ${await policyLine(ctx, repo, record)} ${ownerFacts ? crewKeyNote(ctx, repo) : null}
451451 ${ownerFacts
452452 ? egressNote(
453453 ctx.app.config.dataDir,
src/web/studio/crew.ts +35 −2
@@ -29,10 +29,16 @@ import { listAllAgents, listCrew } from "../../actions/crew.ts";
2929 import { CREW_ROLES, listCrewRoles, type CrewRole } from "../../core/agents.ts";
3030 import { getAppByRepo } from "../../core/apps.ts";
3131 import { canAdmin, canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
32 import { crewHasCredential } from "../../core/subscriptions.ts";
32 import {
33 crewHasCredential,
34 grantedAccounts,
35 hasModelBudget,
36 platformReaches,
37 } from "../../core/subscriptions.ts";
3338 import { autonomyStatus } from "../../crew/autonomy.ts";
3439 import { crewOffInPreview } from "../../crew/preview.ts";
3540 import type { Ctx } from "../../http/context.ts";
41 import type { User } from "../../core/users.ts";
3642 import { repoBase } from "../chrome.ts";
3743 import { html, raw, type Html } from "../html.ts";
3844 import { icon } from "../icons.ts";
@@ -378,12 +384,39 @@ export function settingsLead(ctx: Ctx, repo: Repo): Html {
378384 </div>`;
379385 }
380386
387 /**
388 * One sentence for an account with no model budget (#656): nothing pays
389 * for its crew yet, and who can change that. Nothing for the forge's own
390 * accounts or one an admin has granted to.
391 */
392 export function budgetNote(ctx: Ctx, user: User): Html | null {
393 if (hasModelBudget(ctx.app.db, user.id)) return null;
394 return html`<p class="small muted" id="budget-note" role="status">
395 ${icon("alert")} You have no model budget yet: the crew cannot run on your
396 repositories until this forge's admin grants an account to you or to one
397 of them.
398 </p>`;
399 }
400
381401 /**
382402 * One sentence when the crew has no model credential, so it cannot start:
383403 * what is missing and where it is added — for the admin, a link to it; for
384404 * anyone else, who can. Nothing when the crew can run.
385405 */
386 export function crewKeyNote(ctx: Ctx): Html | null {
406 export function crewKeyNote(ctx: Ctx, repo?: Repo): Html | null {
407 // A repository that is not the forge's own runs only on a grant (#656).
408 if (
409 repo !== undefined &&
410 !platformReaches(ctx.app.db, repo.ownerId) &&
411 grantedAccounts(ctx.app.db, repo.id, repo.ownerId).length === 0
412 )
413 return html`<p class="small muted" id="crew-key-note" role="status">
414 ${icon("alert")} This repository has no model account yet, so its crew
415 cannot start work: nothing is granted to it or its owner.
416 ${ctx.auth.user?.isAdmin
417 ? html`<a href="/settings/subscriptions">Grant one in Subscriptions</a>.`
418 : "This forge's admin can grant one."}
419 </p>`;
387420 if (crewHasCredential(ctx.app.db)) return null;
388421 return html`<p class="small muted" id="crew-key-note" role="status">
389422 ${icon("alert")} The crew has no model key yet, so it cannot start work.
test/subscriptions.test.ts +103 −2
@@ -5,6 +5,7 @@ import { mkdtemp, rm } from "node:fs/promises";
55 import { tmpdir } from "node:os";
66 import { join } from "node:path";
77 import { createOrg } from "../src/actions/orgs.ts";
8 import { createOrg as foundOrg } from "../src/core/orgs.ts";
89 import { addToCrew, createAgent } from "../src/actions/crew.ts";
910 import { assignIssue, openIssue } from "../src/actions/issues.ts";
1011 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
@@ -21,6 +22,7 @@ import {
2122 listSubscriptions,
2223 pickSubscription,
2324 restSubscription,
25 setBudget,
2426 setGrants,
2527 wakeSubscription,
2628 } from "../src/core/subscriptions.ts";
@@ -82,6 +84,31 @@ describe("the pool", () => {
8284 expect(raw.token_enc).not.toContain(OAT);
8385 });
8486
87 test("with nothing granted, the forge's own token reaches only the forge's own: an admin's, or an org an admin owns (#656)", async () => {
88 const now = new Date("2026-09-28T12:00:00Z");
89 const admin = await createUser(app.db, { trusted: true,
90 username: "maya", email: "[email protected]", isAdmin: true,
91 });
92 const plain = await createUser(app.db, { trusted: true,
93 username: "newbie", email: "[email protected]",
94 });
95 if (!admin.ok || !plain.ok) throw new Error("users");
96 const pick = (ownerId: string) =>
97 pickSubscription(app.db, dataDir, { repoId: "r-own", ownerId, agentId: "b" }, now).kind;
98 expect(pick(admin.value.id)).toBe("env");
99 expect(pick(plain.value.id)).toBe("none");
100 const theirs = foundOrg(app.db, "newbie-co", plain.value.id);
101 const ours = foundOrg(app.db, "harbor", admin.value.id);
102 if (!theirs.ok || !ours.ok) throw new Error("orgs");
103 expect(pick(theirs.value.id)).toBe("none");
104 expect(pick(ours.value.id)).toBe("env");
105 // A suspended admin's repositories are no longer the forge's to pay for.
106 app.db.query("UPDATE user SET suspended_at = 'x' WHERE id = ?1").run(admin.value.id);
107 expect(pick(admin.value.id)).toBe("none");
108 expect(pick(ours.value.id)).toBe("none");
109 app.db.query("UPDATE user SET suspended_at = NULL WHERE id = ?1").run(admin.value.id);
110 });
111
85112 test("picks the nearest grant whole, an agent's before everyone's, and rotates", () => {
86113 const work = addSubscription(app.db, dataDir, { name: "work", token: KEY });
87114 if (!work.ok) throw new Error(work.error);
@@ -91,9 +118,10 @@ describe("the pool", () => {
91118 const scope = { repoId: "repo-1", ownerId: "org-1", agentId: "bot-1" };
92119 const now = new Date("2026-09-28T12:00:00Z");
93120
94 // Nothing granted anywhere: the forge's own token.
121 // Nothing granted anywhere, and the owner is not the forge's: no
122 // credential at all (#656). The forge's own token is the forge's.
95123 expect(pickSubscription(app.db, dataDir, scope, now)).toEqual({
96 kind: "env",
124 kind: "none",
97125 });
98126
99127 // The organization's grant reaches every repository under it.
@@ -358,6 +386,79 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Added CREW
358386 expect(spent.subscription_id).toBe(work.value.id);
359387 }, 60_000);
360388
389 test("an outsider's repository with no grant runs nothing and spends nothing; a capped grant runs it to the cap (#656)", async () => {
390 const o = await createUser(app.db, { trusted: true,
391 username: "olive",
392 email: "[email protected]",
393 password: "an-outsider-passphrase",
394 });
395 if (!o.ok) throw new Error(o.error);
396 const olive = o.value;
397 const made = await createRepo(app, olive, { name: "own", visibility: "private" });
398 if (!made.ok) throw new Error(String(made.error));
399 const own = made.value;
400 const seeded = await commitToBranch(app, olive, own, {
401 message: "Start",
402 files: [{ path: "README.md", content: "# own\n" }],
403 });
404 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
405 expect(addToCrew(app, olive, own, "bot").ok).toBe(true);
406 const before = invocations();
407 const issue = openIssue(app, olive, own, { title: "Spend the owner's plan", body: "" });
408 if (!issue.ok) throw new Error(String(issue.error));
409 expect(assignIssue(app, olive, own, issue.value, bot).ok).toBe(true);
410 const refused = await until(() =>
411 listRuns(app.db, own.id, { kind: "agent" }).find(
412 (r) => r.issueId === issue.value.id && r.state === "failed",
413 ),
414 );
415 expect(refused.summary).toContain("no model account");
416 expect(invocations()).toBe(before);
417 expect(refused.costUsd).toBe(0);
418
419 // Her settings, her board and her repository say so plainly, and who
420 // can change it.
421 const signin = await fetch(`${servers.url}/signin`, {
422 method: "POST",
423 headers: { origin: servers.url },
424 body: new URLSearchParams({ username: "olive", password: "an-outsider-passphrase" }),
425 redirect: "manual",
426 });
427 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
428 const read = async (path: string) =>
429 (await fetch(`${servers.url}${path}`, { headers: { cookie } })).text();
430 for (const path of ["/settings", "/board"])
431 expect(await read(path)).toContain("You have no model budget yet");
432 expect(await read("/alice/garden")).not.toContain("You have no model budget yet");
433
434 // The admin grants a capped account to that repository on purpose.
435 const capped = addSubscription(app.db, dataDir, {
436 name: "olive-cap",
437 token: "sk-ant-api03-a-capped-key-for-olive",
438 });
439 if (!capped.ok) throw new Error(capped.error);
440 expect(setBudget(app.db, capped.value.id, 0.5)).toBe(true);
441 setGrants(app.db, own.id, EVERYONE, [capped.value.id]);
442 const next = openIssue(app, olive, own, { title: "Now on a grant", body: "" });
443 if (!next.ok) throw new Error(String(next.error));
444 expect(assignIssue(app, olive, own, next.value, bot).ok).toBe(true);
445 const ran = await until(() =>
446 listRuns(app.db, own.id, { kind: "agent" }).find(
447 (r) => r.issueId === next.value.id && r.state === "ok",
448 ),
449 );
450 expect(invocations()).toBe(before + 1);
451 expect(envOf(before + 1)).toBe("OAUTH=\nKEY=sk-ant-api03-a-capped-key-for-olive\n");
452 const row = app.db
453 .query<{ subscription_id: string; budget_reserved_usd: number }, [string]>(
454 "SELECT subscription_id, budget_reserved_usd FROM run WHERE id = ?1",
455 )
456 .get(ran.id)!;
457 expect(row.subscription_id).toBe(capped.value.id);
458 expect(row.budget_reserved_usd).toBeLessThanOrEqual(0.5);
459 expect(await read("/settings")).not.toContain("You have no model budget yet");
460 }, 60_000);
461
361462 test("holds a run without a call while every account on the grant rests", async () => {
362463 const work = listSubscriptions(app.db).find((s) => s.name === "work")!;
363464 restSubscription(

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs