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

infra list opens with one paragraph naming every machine, and show finds a machine by name #16900

Merged opened this

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

Merged

sold/infra-says → main 0 commits

  • Merged. sold/infra-says was merged into main as 09cecc1.

Review

Sign in to review this change.
4 files changed +274 −8
docs/features/infra.md +1 −1
@@ -12,7 +12,7 @@ What runs on your own cloud, what it's for, what it costs, and when it ends; and
1212 - **Web:** `/infra` (`src/web/pages/infra.ts`, routes in `src/http/infra_routes.ts`). Each account's month against its ceiling, one sentence a line ("$13.00 of $50 a month on DigitalOcean"); a line for anything the hourly watch found at a provider that the forge did not make, linking that account's row on Cloud accounts; then each machine that bills, grouped by its experiment's question or by its app, with where it runs in plain words, its monthly cost and when it ends, Keep 7 more days and End now beside it; End now shows only where something exists at the provider (`existsAtProvider` in `src/cloud/billing.ts`, the same test /pinned's Retire uses), so a first deploy that made nothing offers none. What ended in the last 30 days, and anything retired that still bills, stays under a quiet **Ended** disclosure, each in the shared billing sentence with its day: "retired Mon 30 Nov; nothing bills", or "…; its kept disk still bills $1.00 a month" with a link to delete it on Pinned forges; older ones that bill nothing are one line with their count. A dead row (a first deploy that failed and left nothing at its provider) says "nothing exists at DigitalOcean; clear this row", with Clear this row through the confirm (`clearPinned`, event `pinned.cleared`). Build something opens the compose form: an app, a place (the cheapest two in each city, each a row of at least 44px; a filter of city, provider or size words narrows the whole catalog on the server, `/infra/live?part=places`, so the page never carries it; one that cannot be ordered is listed, dimmed, with why), what it is for (a new question, a running experiment, or running the app itself), and when it ends (1, 3, 7 or 30 days; no end only for an app). The plan tray sits at the foot of the form.
1313 - **Terminal:** the Infrastructure screen (`src/tui/screens/infra.ts`, after Cloud accounts in the palette, and `I` on the Cloud accounts screen). What ended is listed after what runs, each in its billing sentence. `n` composes one question at a time and shows the plan with Build; `+` keeps the selected machine 7 more days; `x` ends it now after a confirm (only where something exists at its provider), and `c` clears a dead row after a confirm. A build's steps lead the list as they happen.
1414 - **API:** `GET /api/v1/admin/infra` (`?plan=<id>` adds a build's steps), `POST /api/v1/admin/infra/plan`, `POST /api/v1/admin/infra/apply` (202). Keep is `POST /api/v1/admin/pinned/:name/keep`.
15 - **Agents:** the `infra` MCP tool, in Talk's slot where `experiments` was: `list` (everything `experiments` listed, plus each machine's end and what it bills for, and `ended`: what retired in the last 30 days or still bills, so a question about one is answered from its row; a dead row's `clear` sentence), `show` (an experiment, or a plan id's build), `plan` a `want`, `apply` a plan id (a plan of dead row `names` clears them; Talk offers it, the person allows it), `keep`, `begin`, `attach`, `record_result`. Only `apply` spends money, so the forge asks the person first.
15 - **Agents:** the `infra` MCP tool, in Talk's slot where `experiments` was: `list` (first `says`: one paragraph naming what runs, the dead rows, what ended in the last 30 days with each one's billing sentence, and the total, at most ten names a group then "and N more", so a reader of `says` alone misses no machine; then everything `experiments` listed, plus each machine's end and what it bills for, and `ended`: what retired in the last 30 days or still bills, so a question about one is answered from its row; a dead row's `clear` sentence), `show` (an experiment, a plan id's build, or a machine by name, running or ended, with its billing sentence; a name with no row says "nothing called … has existed here" only when no event ever named it), `plan` a `want`, `apply` a plan id (a plan of dead row `names` clears them; Talk offers it, the person allows it), `keep`, `begin`, `attach`, `record_result`. Only `apply` spends money, so the forge asks the person first.
1616
1717 All four read `infraOf` and plan through `planCompose` in `src/actions/infra.ts`, which plans with `src/cloud/plan.ts`; only a forge admin sees them.
1818
src/actions/infra.ts +63 −3
@@ -25,7 +25,7 @@ import { TARGETS } from "../cloud/targets.ts";
2525 import { lastReading } from "../cloud/watch_read.ts";
2626 import { listApps } from "../core/apps.ts";
2727 import { listCloudAccounts, READ_ONLY } from "../core/cloud_account.ts";
28 import { dnsRecordOf, HOST_NEEDED, listPinned, NAME, placeIdOf, urlOf, lifetimeOf } from "../core/pinned.ts";
28 import { dnsRecordOf, getPinned, HOST_NEEDED, listPinned, NAME, placeIdOf, urlOf, lifetimeOf } from "../core/pinned.ts";
2929 import { getRepoById } from "../core/repos.ts";
3030 import type { User } from "../core/users.ts";
3131 import { resolveOid } from "../git/merge.ts";
@@ -115,7 +115,39 @@ const DAY_MS = 86_400_000;
115115 /** What runs, what it costs and what it is for: the read behind every door. */
116116 export function infraOf(app: App, actor: User | undefined, now = new Date()): Result<InfraView, string> {
117117 const who = admin(actor);
118 if (!who.ok) return who;
118 return who.ok ? ok(reckon(app, now).view) : who;
119 }
120
121 /**
122 * One machine by name, running, ended or a dead row, with its billing sentence: `infra show`'s
123 * answer to "does test1 still cost anything?" when it is asked by name. Undefined when no row of
124 * that name is kept (`goneWords` says whether one ever was).
125 */
126 export function machineOf(app: App, actor: User | undefined, name: string, now = new Date()): Result<Running | undefined, string> {
127 const who = admin(actor);
128 return who.ok ? ok(reckon(app, now).rows.get(name)) : who;
129 }
130
131 /**
132 * What to say of a name with no row: that nothing of that name has existed here, only when no
133 * event ever named it; else when its row went, and that the forge holds nothing of it now.
134 */
135 export function goneWords(app: App, name: string): string {
136 // A machine still being made is the build tray's, with no row yet.
137 if (getPinned(app.db, name) !== undefined) return `${name} is being made, and nothing bills until it is (\`show\` its plan id for the build)`;
138 const last = app.db
139 .query<{ kind: string; at: string }, [string]>(
140 "SELECT kind, created_at AS at FROM event WHERE kind LIKE 'pinned.%' AND json_extract(payload, '$.name') = ?1 ORDER BY created_at DESC LIMIT 1",
141 )
142 .get(name);
143 return last === null
144 ? `nothing called ${name} has existed here: no machine and no experiment of that name`
145 : `${name} is no longer listed: its row went after ${last.kind.replace("pinned.", "")} on ${dayWords(last.at)}, and the forge holds nothing of it`;
146 }
147
148 /** The view, and every machine's row by name, the ones the view counts but does not list among them. */
149 function reckon(app: App, now: Date): { view: InfraView; rows: Map<string, Running> } {
150 const rows = new Map<string, Running>();
119151 const db = app.db;
120152 const x = experiments(db, now);
121153 const places = new Map(keptPlaces(db, keptRate(db, "EUR")).map((p) => [p.id, p]));
@@ -157,6 +189,7 @@ export function infraOf(app: App, actor: User | undefined, now = new Date()): Re
157189 atProvider: existsAtProvider(p),
158190 clear: p.state === "failed" && !existsAtProvider(p) ? `nothing exists at ${isProvider(p.target) ? LABEL[p.target] : p.target}; clear this row` : "",
159191 };
192 rows.set(p.name, r);
160193 if (p.state === "retired") {
161194 // The last month's, and any that still bill, are listed; older ones that bill nothing are counted.
162195 const at = retiredAt.get(p.name);
@@ -210,7 +243,34 @@ export function infraOf(app: App, actor: User | undefined, now = new Date()): Re
210243 return [{ account, says: `At ${LABEL[a.provider]}, not in your infrastructure: ${what}`, href: accountHref(account) }];
211244 });
212245 ended.sort((a, b) => (retiredAt.get(b.name) ?? "").localeCompare(retiredAt.get(a.name) ?? "") || a.name.localeCompare(b.name));
213 return ok({ meters, drift, groups: ordered, ended, endedEarlier, experiments: x });
246 return { view: { meters, drift, groups: ordered, ended, endedEarlier, experiments: x }, rows };
247 }
248
249 /** Most names a group of `infraSays` lists before "and N more". */
250 const SAYS_NAMES = 10;
251 const named = (items: readonly string[]): string =>
252 items.length <= SAYS_NAMES ? items.join(", ") : `${items.slice(0, SAYS_NAMES).join(", ")} and ${items.length - SAYS_NAMES} more`;
253
254 /**
255 * The whole view in one plain paragraph, `infra list`'s `says`: what runs and what it costs, the
256 * dead rows and how to clear them, what ended and what each still bills, what the watch saw that
257 * the forge did not make, and the total. A reader who reads only this misses no machine.
258 */
259 export function infraSays(v: InfraView): string {
260 const machines = v.groups.flatMap((g) => g.machines);
261 const running = machines.filter((m) => m.clear === "");
262 const dead = machines.filter((m) => m.clear !== "");
263 const total = [...machines, ...v.ended].reduce((s, m) => s + m.monthlyCents, 0);
264 return [
265 `Running: ${running.length === 0 ? "none" : named(running.map((m) => `${m.name} (${m.billing})`))}.`,
266 dead.length === 0 ? "" : `Dead rows (nothing exists at the provider): ${named(dead.map((m) => m.name))}; clear them with \`plan\` and their names.`,
267 v.ended.length === 0 ? "" : `Ended in the last ${ENDED_DAYS} days: ${named(v.ended.map((m) => `${m.name} (${m.billing})`))}.`,
268 v.endedEarlier === 0 ? "" : `${plural(v.endedEarlier, "machine")} ended earlier and bill nothing.`,
269 ...v.drift.map((d) => `${d.says}.`),
270 total === 0 ? "Nothing bills." : `All of it bills ${dollars(total)} a month.`,
271 ]
272 .filter((line) => line !== "")
273 .join(" ");
214274 }
215275
216276 /** An app the forge can deploy to a machine: public, so the machine reads its code without a credential. */
src/http/mcp/tools/infra.ts +10 −4
@@ -1,4 +1,4 @@
1 import { buildOf, infraOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts";
1 import { buildOf, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts";
22 import { endsWords, keepPinned } from "../../../actions/pinned.ts";
33 import { EXPERIMENT_WORDS, attachMachine, beginExperiment, findExperiment, recordResult } from "../../../cloud/experiments.ts";
44 import { good, bad, type Tool, str } from "../shared.ts";
@@ -14,7 +14,7 @@ const s = (v: unknown, max: number): string => str(v).slice(0, max);
1414 export const tool: Tool = {
1515 name: "infra",
1616 listedTo: "admin",
17 doc: "`{ action, id?, want?, question?, names?, result? }`: `list`, `plan` a `want` `{app, where, question?, experiment?, days?}` or dead `names`, `apply` its `id`, `keep`, `begin`, `attach`, `record_result`.",
17 doc: "`{ action, id?, want?, question?, names?, result? }`: `list` (its `says` names every machine), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or dead `names`, `apply` its `id`, `keep`, `begin`, `attach`, `record_result`.",
1818 description: "Cloud machines and spend.",
1919 inputSchema: {
2020 type: "object",
@@ -42,15 +42,21 @@ export const tool: Tool = {
4242 const v = infraOf(ctx.app, user);
4343 if (!v.ok) return bad("not_found", "no such tool here");
4444 const { experiments, ...rest } = v.value;
45 return good({ ...experiments, ...rest });
45 // One paragraph that names every machine first, so a reader of the groups alone misses nothing.
46 return good({ says: infraSays(v.value), ...experiments, ...rest });
4647 }
4748 if (action === "show") {
49 if (id === "") return bad("no_id", "show takes an id: a plan's, an experiment's, or a machine's name");
4850 if (id.startsWith("plan-")) {
4951 const b = buildOf(ctx.app, user, id);
5052 return b ? good({ build: b }) : bad("no_build", "No build of that plan has started.");
5153 }
5254 const e = findExperiment(db, id);
53 return e ? good({ experiment: e }) : bad("no_experiment", EXPERIMENT_WORDS.no_experiment);
55 if (e) return good({ experiment: e });
56 // A machine by name, running or ended, with its billing sentence; never "no such experiment" for one.
57 const m = machineOf(ctx.app, user, id);
58 if (!m.ok) return bad("not_found", "no such tool here");
59 return m.value !== undefined ? good({ machine: m.value, says: `${m.value.name} is ${m.value.billing}.` }) : bad("not_found", `${goneWords(ctx.app, id)}.`);
5460 }
5561 if (action === "plan" && args["want"] === undefined && names.length > 0) {
5662 // Dead rows to clear (failed, nothing at their provider): a plan like any other, applied by id.
test/talk-infra-says.test.ts added +200
@@ -0,0 +1,200 @@
1 /**
2 * `infra` names every machine plainly (v0.7.677: Talk read `groups`, missed `ended`, then asked
3 * `show test1` and heard "No such experiment"): `list` opens with `says`, one paragraph naming
4 * what runs, the dead rows, what ended and what each still bills; `show` takes a machine's name and
5 * answers its row with its billing sentence, and says "nothing called … has existed here" only
6 * when that is true. Through a whole Talk turn, a model that reads only `says`, or that asks
7 * `show test1`, answers "test1 is retired <day>; nothing bills."
8 */
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { infraOf, infraSays } from "../src/actions/infra.ts";
15 import { dayWords } from "../src/actions/pinned.ts";
16 import { insertPinned, setRemote } from "../src/core/pinned.ts";
17 import { listTurns, openConversation } from "../src/core/conversations.ts";
18 import { createToken } from "../src/core/tokens.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { useRunner } from "../src/crew/agent_runner.ts";
21 import { say, type ConversationOptions } from "../src/crew/conversation.ts";
22 import { openaiRunner } from "../src/crew/openai_runner.ts";
23 import { serve, type Servers } from "../src/http/server.ts";
24 import { mcpTool } from "./helpers/mcp.ts";
25 import { seedPlaces } from "./helpers/places-fixture.ts";
26
27 type Body = { messages: { role: string; content: string | null }[] };
28
29 let dir: string;
30 let app: App;
31 let servers: Servers;
32 let model: ReturnType<typeof Bun.serve>;
33 let alice: User;
34 let token = "";
35 let retired = "";
36 const kept: Record<string, string | undefined> = {};
37 /** How the canned model asks: `infra list` and only its `says`, or `infra show test1`. */
38 let asks: "says" | "show" = "says";
39 const calls: string[] = [];
40
41 const sse = (chunks: readonly object[]): Response =>
42 new Response(`${chunks.map((c) => `data: ${JSON.stringify(c)}\n\n`).join("")}data: [DONE]\n\n`, {
43 headers: { "content-type": "text/event-stream" },
44 });
45 const usage = { choices: [], usage: { prompt_tokens: 9000, completion_tokens: 10 } };
46
47 function answer(body: Body): Response {
48 const tool = body.messages.find((m) => m.role === "tool")?.content;
49 if (tool === undefined || tool === null) {
50 const args = asks === "says" ? { action: "list" } : { action: "show", id: "test1" };
51 calls.push(JSON.stringify(args));
52 return sse([
53 {
54 choices: [
55 { delta: { tool_calls: [{ index: 0, id: "call_1", function: { name: "mcp__forge__infra", arguments: JSON.stringify(args) } }] } },
56 ],
57 },
58 usage,
59 ]);
60 }
61 // Only the `says` paragraph is read: "… test1 (retired Mon 30 Nov; nothing bills) …", or show's
62 // "test1 is retired Mon 30 Nov; nothing bills.", fenced inside JSON text as every via read is.
63 const says = /"says":"([^"]*)"/.exec(tool)?.[1] ?? "";
64 const found = asks === "says" ? /\btest1 \(([^)]*)\)/.exec(says)?.[1] : /(?:\\n|\s)test1 is ([^\\]*?)\./.exec(says)?.[1];
65 return sse([{ choices: [{ delta: { content: found === undefined ? "I found nothing about test1." : `test1 is ${found}.` } }] }, usage]);
66 }
67
68 const machine = (name: string, state: string, volume = "") => {
69 insertPinned(
70 app.db,
71 {
72 name,
73 target: "digitalocean",
74 account: "main",
75 app: "",
76 source: "",
77 version: "v1",
78 config: {},
79 host: "",
80 claimHash: "",
81 claimExpires: "",
82 datacenter: "nyc3",
83 size: "s-1vcpu-2gb",
84 },
85 alice.id,
86 );
87 setRemote(app.db, name, { remote: "", volume, address: "", state });
88 };
89
90 beforeAll(async () => {
91 dir = await mkdtemp(join(tmpdir(), "forge-talk-infra-says-"));
92 model = Bun.serve({
93 port: 0,
94 async fetch(req) {
95 return answer((await req.json()) as Body);
96 },
97 });
98 for (const k of ["OPENAI_BASE_URL", "OPENAI_MODEL", "OPENAI_API_KEY"]) kept[k] = process.env[k];
99 process.env["OPENAI_BASE_URL"] = `http://127.0.0.1:${String(model.port)}/v1`;
100 process.env["OPENAI_MODEL"] = "local-llama";
101 delete process.env["OPENAI_API_KEY"];
102 useRunner(openaiRunner);
103 app = createApp({ dataDir: dir, port: 0 });
104 servers = await serve(app);
105 const made = await createUser(app.db, {
106 origin: "seed",
107 trusted: true,
108 username: "alice",
109 email: "[email protected]",
110 password: "a-good-passphrase",
111 adminIfFirst: true,
112 });
113 if (!made.ok) throw new Error(made.error);
114 alice = made.value;
115 token = createToken(app.db, alice.id, "admin", "admin").token;
116 await seedPlaces(app.db);
117 app.db.run("INSERT INTO cloud_account (provider, name, summary) VALUES ('digitalocean', 'main', '')");
118 // Production's shape on 30 Nov: two dead rows, two retired machines that bill nothing.
119 machine("canary1", "failed");
120 machine("trevato", "failed");
121 for (const name of ["friend1", "test1"]) {
122 machine(name, "retired");
123 retired = app.bus.append({ kind: "pinned.retired", actorId: alice.id, payload: { name, withData: true } }).createdAt;
124 }
125 // A machine whose row was cleared: an event names it, no row does.
126 app.bus.append({ kind: "pinned.cleared", actorId: alice.id, payload: { name: "gone1" } });
127 });
128
129 afterAll(async () => {
130 useRunner(undefined);
131 for (const [k, v] of Object.entries(kept)) {
132 if (v === undefined) delete process.env[k];
133 else process.env[k] = v;
134 }
135 model.stop(true);
136 servers.stop();
137 app.close();
138 await rm(dir, { recursive: true, force: true });
139 });
140
141 describe("infra says it plainly", () => {
142 test("list opens with one paragraph that names every machine and what it bills", async () => {
143 const said = await mcpTool(servers.url, token, "infra", { action: "list" });
144 const day = dayWords(retired);
145 expect(said.value.says).toBe(
146 "Running: none. Dead rows (nothing exists at the provider): canary1, trevato; clear them with `plan` and their names. " +
147 `Ended in the last 30 days: friend1 (retired ${day}; nothing bills), test1 (retired ${day}; nothing bills). Nothing bills.`,
148 );
149 expect(Object.keys(said.value)[0]).toBe("says");
150 });
151
152 test("each group names at most ten, then how many more", () => {
153 const v = infraOf(app, alice);
154 if (!v.ok) throw new Error(v.error);
155 const dead = v.value.groups.flatMap((g) => g.machines).find((m) => m.name === "canary1")!;
156 const many = Array.from({ length: 13 }, (_, i) => ({ ...dead, name: `dead${i}` }));
157 const says = infraSays({ ...v.value, groups: [{ kind: "app", key: "", title: "", monthlyCents: 0, machines: many }] });
158 expect(says).toContain("dead0, dead1, dead2, dead3, dead4, dead5, dead6, dead7, dead8, dead9 and 3 more; clear them");
159 });
160
161 test("show takes a machine's name: its row and billing sentence; an unknown name is said truly", async () => {
162 const one = await mcpTool(servers.url, token, "infra", { action: "show", id: "test1" });
163 expect(one.value.machine).toMatchObject({ name: "test1", state: "retired", bills: "nothing" });
164 expect(one.value.says).toBe(`test1 is retired ${dayWords(retired)}; nothing bills.`);
165 const dead = await mcpTool(servers.url, token, "infra", { action: "show", id: "canary1" });
166 expect(dead.value.machine.clear).toBe("nothing exists at DigitalOcean; clear this row");
167 expect((await mcpTool(servers.url, token, "infra", { action: "show", id: "nope" })).error).toContain(
168 "nothing called nope has existed here: no machine and no experiment of that name.",
169 );
170 const gone = (await mcpTool(servers.url, token, "infra", { action: "show", id: "gone1" })).error!;
171 expect(gone).toContain("gone1 is no longer listed: its row went after cleared on ");
172 for (const e of [one, dead]) expect(JSON.stringify(e)).not.toContain("No such experiment");
173 });
174 });
175
176 const options = (): ConversationOptions => ({
177 binary: "unused",
178 localUrl: servers.url,
179 budgetUsd: 1,
180 timeoutMs: 30_000,
181 signal: new AbortController().signal,
182 });
183
184 describe("through a whole Talk turn", () => {
185 for (const way of ["says", "show"] as const) {
186 test(`a model that reads ${way === "says" ? "only list's says" : "show test1"} answers that test1 bills nothing`, async () => {
187 asks = way;
188 // Each way in a conversation of its own.
189 app.db.run("DELETE FROM conversation_turn");
190 const said = say(app, options(), alice.id, "does test1 still cost anything?");
191 if (!said.ok) throw new Error(said.error);
192 if (said.value.how === "started") await said.value.done;
193 const turns = listTurns(app.db, alice.id, openConversation(app.db, alice.id).id, { limit: 50 });
194 if (!turns.ok) throw new Error("turns");
195 expect(turns.value.some((t) => t.role === "confirm")).toBe(false);
196 expect(turns.value.at(-1)).toMatchObject({ role: "agent", text: `test1 is retired ${dayWords(retired)}; nothing bills.` });
197 expect(calls.at(-1)).toBe(way === "says" ? '{"action":"list"}' : '{"action":"show","id":"test1"}');
198 });
199 }
200 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs