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

A repository's wallet is readable through the MCP with the page's numbers #13616

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/13590-a-repository-s-wallet-is-readable-throug → main 3 commits fork 4 threads · 4 unresolved

  • Merged. scout/13590-a-repository-s-wallet-is-readable-throug was merged into main as c0c2891.

Review

Sign in to review this change.
8 files changed +228 −12
docs/MCP.md +8 −1
@@ -239,7 +239,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
239239 | `tokens` | — | Your API tokens, no secrets | 146 |
240240 | `trail` | — | A migrated repository's source and forks; `shown` shows or hides them (admin) | 258 |
241241 | `upstream` | — | Read, set (`enabled`) or `check` the upstream a repository follows | 361 |
242 | `usage` | — | Crew spend: with `repo`, `days` (1–90) by agent, issue; without, today, last24h, headroom % | 388 |
242 | `usage` | — | Crew spend by `repo` and `days`, or its wallet with `kind: wallet` | 386 |
243243 | `valves` | — | The week's pipes and valves; with `repo` and `level`, turns a valve (plans first) | 269 |
244244 | `variant` | — | Like or dislike a pull among its variants; a later vote replaces; dislike closes it | 349 |
245245 | `vision` | — | VISION.md: purpose, order, rules | 235 |
@@ -721,3 +721,10 @@ Every 401, 403, 404, 409 and 422 JSON answer from `/api/v1` is `{ error, message
721721 Every refused `tools/call` text ends in `Next: …`, one step: which argument to fix, which sign-in to use, which tool to call first. A tool that has its own `Next:` keeps it; otherwise `withNextStep` (`src/http/mcp/hints.ts`) adds one from the error code and the tool's own schema, so a new tool is covered without editing. It never echoes arguments, tokens or another person's data. `test/mcp-refusal-hints.test.ts` calls every tool in `tools/list` (`all: true`, paged) with empty and bad arguments, as a member and as an admin, and the stranger's 401 and `report`/`start`.
722722
723723 A guest token (a person who is neither member nor admin) is listed only `report` and `offer` by default; `all: true` still pages every tool. Its `tools/list` and `initialize` name the role; the role is read on every request, so a promotion shows at once. Every other tool still answers by name, and `find_tool` shows its schema.
724
725 `usage` with `{ repo, kind: "wallet" }` is a repository's wallet (#13590):
726 `{ app, capUsd, spent, left, balance, lastSpend, latest }`, the three latest

Non-blocking: lastSpend was removed from the answer, so drop it from this shape. It is now { app, capUsd, spent, left, balance, latest }.

727 spends in the wallet page's words. Dollars come from `money` and the balance
728 from `balanceWords` (`src/core/wallet.ts`), the same the page and terminal use;
729 `readWalletSummary` (`src/actions/wallet.ts`) gives a writer's gate, and anyone
730 else the page's own `not_found`.
docs/features/wallet.md +6 −2
@@ -15,5 +15,9 @@ did not end well says so beside what it paid for.
1515 - **Speed:** the read walks `usage_repo (repo_id, at)` for twenty rows, no
1616 scan and no sort, so it does not grow with the ledger
1717 (`test/wallet.test.ts` counts its statements at 10,000 rows and reads the plan).
18 - **Left out:** paging beyond 20, and a JSON form; `GET /api/v1/repos/:owner/:name/usage`
19 already gives the recent lines.
18 - **Left out:** paging beyond 20; the MCP (below) gives the summary, and `GET /api/v1/repos/:owner/:name/usage`
outdated

Now contradicts the new MCP section: a JSON form of the wallet exists. Update this Left out line.

19 gives the recent lines as JSON.
20
21 ## MCP
22
23 `usage` with `{ repo, kind: "wallet" }` answers the balance and the three latest spends, amounts and balance written by the page's own `money` and `balanceWords`; a reader who may not see the wallet gets the page's not-found.
src/actions/wallet.ts +43 −1
@@ -16,7 +16,7 @@ import { getIssuesByIds } from "../core/issues.ts";
1616 import { canAdmin, canSeeOwnerFacts, type Repo } from "../core/repos.ts";
1717 import type { UsageKind, UsageOutcome } from "../core/usage.ts";
1818 import type { User } from "../core/users.ts";
19 import { monthCap, setMonthCap, validCap, WALLET_CAP_MAX_USD } from "../core/wallet.ts";
19 import { balanceWords, money, monthCap, monthSpent, setMonthCap, validCap, WALLET_CAP_MAX_USD } from "../core/wallet.ts";
2020 import { err, ok, type Result } from "../kernel/result.ts";
2121
2222 export const WALLET_ROWS = 20;
@@ -84,6 +84,48 @@ export function readWallet(app: App, actor: User | undefined, repo: Repo): Resul
8484 }
8585
8686
87 export const SUMMARY_SPENDS = 3;
88
89 export interface WalletSummary {
90 readonly app: string;
91 /** The monthly cap in whole dollars, or null. */
92 readonly capUsd: number | null;
93 /** Dollars spent this UTC month, as the page writes them: `$1.50`. */
94 readonly spent: string;
95 /** What is left under the cap, as `$8.50`, or null with no cap. */
96 readonly left: string | null;
97 /** The wallet line's words. */
98 readonly balance: string;
99 /**
100 * The three newest spends, newest first: date, dollars, what it paid for, `(outcome)` if not ok.
101 */
102 readonly latest: readonly string[];
103 }
104
105 /** One spend as a line of text (the page lays the same parts out as a table row, with `money`). */
106 export const spendWords = (s: WalletSpend): string =>
107 `${s.date} ${money(s.costUsd)} ${s.paidFor}${s.outcome === "ok" ? "" : ` (${s.outcome})`}`;
108
109 /**
110 * Balance, last spend and the three latest, for the MCP: the page's gate and its refusal
111 * (`not_found`).
112 */
113 export function readWalletSummary(app: App, actor: User | undefined, repo: Repo, now: Date): Result<WalletSummary, "not_found"> {
114 const read = readWallet(app, actor, repo);
115 if (!read.ok) return read;
116 const cap = monthCap(app.db, repo.id);
117 const spent = monthSpent(app.db, repo.id, now);
118 const latest = read.value.spends.slice(0, SUMMARY_SPENDS).map(spendWords);
119 return ok({
120 app: read.value.app,
121 capUsd: cap ?? null,
122 spent: money(spent),
123 left: cap === undefined ? null : money(Math.max(0, cap - spent)),
124 balance: balanceWords(cap, spent, now),
125 latest,
126 });
127 }
128
87129 export type WalletError = "not_found" | "invalid_amount";
88130
89131 /** `text` is what was typed: empty clears the cap, otherwise whole dollars. */
src/core/wallet.ts +21 −2
@@ -48,6 +48,25 @@ export const resetDate = (now: Date): string => new Date(Date.UTC(now.getUTCFull
4848 * cap or there is none. A caller that has read the cap passes it, so it is not read twice.
4949 */
5050 export function capReached(db: Database, repoId: string, now: Date, cap: number | undefined = monthCap(db, repoId)): string | undefined {
51 if (cap === undefined || monthSpent(db, repoId, now) < cap) return undefined;
52 return `This repository's monthly cap of $${cap} is reached; its crew starts no new runs until ${resetDate(now)} (UTC) or the cap is raised.`;
51 if (cap === undefined) return undefined;
52 const spent = monthSpent(db, repoId, now);
53 return spent < cap ? undefined : balanceWords(cap, spent, now);
54 }
55
56 /**
57 * Dollars as every door writes them: `$12.50`. The one formatter for the page, the terminal and the
58 * MCP.
59 */
60 export const money = (usd: number): string => `$${usd.toFixed(2)}`;
61
62 /**
63 * The wallet's standing in words: the sentence a refused run reads, or what is left, or that there
64 * is no cap.
65 */
66 export function balanceWords(cap: number | undefined, spent: number, now: Date): string {
67 if (cap === undefined) return `No monthly cap; ${money(spent)} spent this month.`;
68 if (spent >= cap) {
69 return `This repository's monthly cap of $${cap} is reached; its crew starts no new runs until ${resetDate(now)} (UTC) or the cap is raised.`;
70 }
71 return `${money(cap - spent)} of the $${cap} monthly cap is left; it resets ${resetDate(now)} (UTC).`;
5372 }
src/http/mcp/tools/usage.ts +13 −2
@@ -1,20 +1,31 @@
11 import { readForgeUsage, readUsage, usageDays, USAGE_DAYS_DEFAULT, USAGE_DAYS_MAX } from "../../../actions/usage.ts";
2 import { readWalletSummary } from "../../../actions/wallet.ts";
23 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
34
45 export const tool: Tool = {
56 name: "usage",
6 doc: "`{ repo?, days? }`: no repo, the forge's spend today and last24h and each account's headroom %; else what the crew's runs spent — tokens, cost, wall time — by subscription, agent, issue, and each account's 5-hour and weekly standing; a writer's",
7 doc: "`{ repo?, days?, kind? }`: `kind: wallet` with a repo is its balance and three latest spends, as the wallet page says them; no repo, the forge's spend today and last24h and each account's headroom %; else what the crew's runs spent — tokens, cost, wall time — by subscription, agent, issue, and each account's 5-hour and weekly standing; a writer's",
78 description:
8 "Crew spend: with `repo`, `days` (1–90) by agent, issue; without, today, last24h, headroom %. Writers.",
9 "Crew spend by `repo` and `days`, or its wallet with `kind: wallet`. Writers.",
outdated

Principle 8: "kind: wallet balance; none: today" is not plain words. Reword it, or make room properly rather than cutting the sentence.

910 inputSchema: {
1011 type: "object",
1112 properties: {
1213 repo: REPO_ARG,
1314 days: { type: "integer", minimum: 1, maximum: USAGE_DAYS_MAX },
15 kind: { type: "string" },
1416 },
1517 },
1618 writes: false,
1719 run(ctx, user, args) {
20 const kind = args["kind"];
21 if (kind !== undefined && kind !== "wallet") return bad("invalid_kind", "kind is `wallet`, or leave it out");
22 if (kind === "wallet") {
23 if (args["days"] !== undefined) return bad("invalid_days", "wallet has no days");
24 const found = repoArg(ctx, user, args);
25 if (isAnswer(found)) return found;
26 const wallet = readWalletSummary(ctx.app, user, found, new Date());
27 return wallet.ok ? good(wallet.value) : bad("not_found", "no such app or repository (owner/name)");
28 }
1829 if (args["repo"] === undefined) {
1930 if (args["days"] !== undefined)
2031 return bad("invalid_days", "days needs a repo; without one the answer is today and last24h");
src/tui/screens/money.ts +2 −1
@@ -12,6 +12,7 @@
1212 */
1313
1414 import { mayReadStatement } from "../../actions/statement.ts";
15 import { money } from "../../core/wallet.ts";
1516 import { readWallet, type WalletSpend } from "../../actions/wallet.ts";
1617 import { readAppMoney, readForgeMoney, type AppMoney, type ForgeMoney, type MoneyLine } from "../../actions/money.ts";
1718 import { canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
@@ -115,7 +116,7 @@ export function moneyCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Com
115116 export function walletRows(spends: readonly WalletSpend[]): ListRow[] {
116117 return spends.map((s) => ({
117118 title: s.paidFor,
118 meta: `${s.date} · $${s.costUsd.toFixed(2)} · run ${s.runId.slice(-8)}`,
119 meta: `${s.date} · ${money(s.costUsd)} · run ${s.runId.slice(-8)}`,
119120 }));
120121 }
121122
src/web/pages/wallet.ts +3 −3
@@ -9,7 +9,7 @@
99 import { capInvalidWords, capSavedWords, readWallet, saveCap } from "../../actions/wallet.ts";
1010 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1111 import { canAdmin } from "../../core/repos.ts";
12 import { capReached, monthCap, monthSpent, WALLET_CAP_MAX_USD } from "../../core/wallet.ts";
12 import { capReached, money, monthCap, monthSpent, WALLET_CAP_MAX_USD } from "../../core/wallet.ts";
1313 import type { Ctx } from "../../http/context.ts";
1414 import { adminForm } from "../admin_form.ts";
1515 import { loadRepo, repoBase, repoNotFound } from "../chrome.ts";
@@ -35,7 +35,7 @@ export function walletPage(ctx: Ctx): Response {
3535 const cap = monthCap(ctx.app.db, repo.id);
3636 const spent = monthSpent(ctx.app.db, repo.id, now);
3737 const paused = capReached(ctx.app.db, repo.id, now, cap);
38 capBlock = html`<p id="wallet-spend">Spent this month: <strong class="num">$${spent.toFixed(2)}</strong>.</p>
38 capBlock = html`<p id="wallet-spend">Spent this month: <strong class="num">${money(spent)}</strong>.</p>
3939 ${paused === undefined ? null : html`<p id="wallet-paused">${paused}</p>`}
4040 <form method="post" action="${base}/wallet" class="mt">
4141 ${formField({
@@ -65,7 +65,7 @@ export function walletPage(ctx: Ctx): Response {
6565 ${w.spends.map(
6666 (s) => html`<tr>
6767 <td class="mono">${s.date}</td>
68 <td class="num mono">$${s.costUsd.toFixed(2)}</td>
68 <td class="num mono">${money(s.costUsd)}</td>
6969 <td>${s.paidFor}${s.outcome === "ok" ? "" : html` <span class="small">(${s.outcome})</span>`}</td>
7070 <td><a href="${s.runPath}">${s.runId.slice(-8)}</a></td>
7171 </tr>`,
test/mcp-wallet.test.ts added +132
@@ -0,0 +1,132 @@
1 /**
2 * `usage` with `kind: wallet` (#13590): balance, last spend and three latest, in the wallet page's
3 * words: one formatter (`money`, `balanceWords`) for amounts and balance.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { readWallet } from "../src/actions/wallet.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { getRepo } from "../src/core/repos.ts";
13 import { createRun } from "../src/core/runs.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { balanceWords, capReached, money, setMonthCap } from "../src/core/wallet.ts";
16 import { tool } from "../src/http/mcp/tools/usage.ts";
17 import type { Ctx } from "../src/http/context.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22
23 let dir = "";
24 let app: App;
25 let servers: Servers;
26 let owner: User;
27 let stranger: User;
28 let repoId = "";
29 let cookie = "";
30
31 beforeAll(async () => {
32 dir = await mkdtemp(join(tmpdir(), "forge-mcp-wallet-"));
33 app = createApp({ dataDir: dir, port: 0 });
34 servers = await serve(app);
35 const mk = async (username: string, first: boolean) => {
36 const r = await createUser(app.db, {
37 origin: "seed", trusted: true, username, email: `${username}@forge.local`,
38 password: "a-good-passphrase", adminIfFirst: first,
39 });
40 if (!r.ok) throw new Error(r.error);
41 return r.value;
42 };
43 owner = await mk("trevato", true);
44 stranger = await mk("stranger", false);
45 const made = await createRepo(app, owner, { name: "garden", visibility: "public" });
46 if (!made.ok) throw new Error("repo");
47 repoId = made.value.id;
48 const res = await fetch(servers.url + "/signin", {
49 method: "POST", redirect: "manual",
50 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
51 body: new URLSearchParams({ username: "trevato", password: "a-good-passphrase" }),
52 });
53 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
54 const at = new Date().toISOString();
55 for (const usd of [1.005, 2, 0.5, 4.25]) {
56 const run = createRun(app.db, { repoId, kind: "agent" });
57 app.db
58 .query(`INSERT INTO usage (run_id, repo_id, kind, cost_usd, outcome, at) VALUES (?1, ?2, 'build', ?3, 'ok', ?4)`)
59 .run(run.id, repoId, usd, at);
60 }
61 });
62 afterAll(async () => {
63 servers.stop();
64 app.close();
65 await rm(dir, { recursive: true, force: true });
66 });
67
68 const ctxFor = (user: User | undefined): Ctx => ({
69 app,
70 request: new Request(servers.url + "/mcp"),
71 url: new URL(servers.url + "/mcp"),
72 params: {},
73 auth: { user, scope: undefined, via: "session" },
74 theme: undefined,
75 });
76 const ask = (user: User, args: Record<string, unknown>) =>
77 tool.run(ctxFor(user), user, { repo: "trevato/garden", kind: "wallet", ...args }) as { ok: boolean; value?: any; error?: any };
78
79 test("no cap: the balance says so, the last spend and the three latest are the page's rows", async () => {
80 const r = ask(owner, {});
81 expect(r.ok).toBe(true);
82 const v = r.value;
83 expect(v.capUsd).toBeNull();
84 expect(v.left).toBeNull();
85 expect(v.spent).toBe(money(1.005 + 2 + 0.5 + 4.25));
86 expect(v.balance).toBe(`No monthly cap; ${v.spent} spent this month.`);
87 expect(v.latest).toHaveLength(3);
88 expect(v.lastSpend).toBeUndefined();
89 expect(v.latest[0]).toMatch(/^\d{4}-\d{2}-\d{2} \$\d+\.\d\d build/);
90 const page = await (await fetch(servers.url + "/trevato/garden/wallet", { headers: { cookie } })).text();
91 // The same amounts, formatted by the one formatter, appear on the page.
92 for (const w of (readWallet(app, owner, getRepo(app.db, "trevato", "garden")!) as unknown as { value: { spends: { costUsd: number }[] } }).value.spends.slice(0, 3)) {
93 expect(page).toContain(money(w.costUsd));
94 }
95 expect(page).toContain(`<strong class="num">${v.spent}</strong>`);
96 });
97
98 test("under a cap the balance says what is left; at the cap it is the sentence the page and a refused run read", async () => {
99 setMonthCap(app.db, repoId, 100, owner.id, new Date());
100 const under = ask(owner, {}).value;
101 expect(under.left).toBe(money(100 - (1.005 + 2 + 0.5 + 4.25)));
102 expect(under.balance).toBe(balanceWords(100, 1.005 + 2 + 0.5 + 4.25, new Date()));
103 expect(under.balance).toContain("is left");
104 setMonthCap(app.db, repoId, 5, owner.id, new Date());
105 const at = ask(owner, {}).value;
106 expect(at.left).toBe("$0.00");
107 expect(at.balance).toBe(capReached(app.db, repoId, new Date()));
108 const page = await (await fetch(servers.url + "/trevato/garden/wallet", { headers: { cookie } })).text();
109 expect(page).toContain(at.balance.replace(/'/g, "&#39;"));
110 });
111
112 test("a non-ok spend carries its outcome; an ok one does not", () => {
113 const run = createRun(app.db, { repoId, kind: "agent" });
outdated

Vacuous: error ?? ask(...) is always defined. Assert the exact not_found answer, and add the real visitor case (user undefined). Also assert latest contents and the (outcome) suffix for a non-ok spend.

114 app.db
115 .query(`INSERT INTO usage (run_id, repo_id, kind, cost_usd, outcome, at) VALUES (?1, ?2, 'build', 9, 'failed', ?3)`)
116 .run(run.id, repoId, new Date(Date.now() + 1000).toISOString());
117 const latest = ask(owner, {}).value.latest as string[];
118 expect(latest).toHaveLength(3);
119 expect(latest[0]).toMatch(/^\d{4}-\d{2}-\d{2} \$9\.00 build.* \(failed\)$/);
120 expect(latest[1]).not.toContain("(");
121 });
122
123 test("a stranger and a visitor get the not-found the page gives; bad arguments are named", () => {
124 for (const who of [stranger, undefined]) {
125 const r = tool.run(ctxFor(who), who as User, { repo: "trevato/garden", kind: "wallet" }) as any;
126 expect(JSON.stringify(r)).toContain("not_found");
127 expect(JSON.stringify(r)).not.toContain("latest");
128 }
129 expect(JSON.stringify(ask(owner, { repo: "trevato/none" }))).toContain("not_found");
130 expect(JSON.stringify(ask(owner, { kind: "other" }))).toContain("invalid_kind");
131 expect(JSON.stringify(ask(owner, { days: 3 }))).toContain("invalid_days");
132 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs