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

Talk's agent can chart compute and shipping: an admin's Talk reads the machine's history, and both series come small #16320

Merged opened this

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

Merged

talk/data-series → main 0 commits

  • Merged. talk/data-series was merged into main as 334c109.

Review

Sign in to review this change.
10 files changed +155 −14
src/core/pulls.ts +26
@@ -1642,3 +1642,29 @@ export function pullSummary(body: string, checkState: string): string {
16421642 const changed = changedSentences(body);
16431643 return changed === "" ? verifiedSentence(checkState) : `${changed} ${verifiedSentence(checkState)}`;
16441644 }
1645
1646 /** The most days `mergedPerDay` counts back. */
1647 export const MERGED_DAYS_MAX = 90;
1648
1649 /**
1650 * Pulls merged into `repoId` each UTC day, the last `days` with today, oldest first: the series a
1651 * chart of shipping draws from (`pulls` with `brief`). Read through `pull_merged` (a range on
1652 * `merged_at`), days counted in code. A sealed pull is not counted.
1653 */
1654 export function mergedPerDay(db: Database, repoId: string, days: number, now: number = Date.now()): { days: string[]; merged: number[] } {
1655 const today = Math.floor(now / 86_400_000);
1656 const labels = Array.from({ length: days }, (_, i) => new Date((today - days + 1 + i) * 86_400_000).toISOString().slice(0, 10));
1657 const counts = new Map(labels.map((d) => [d, 0]));
1658 const rows = db
1659 .query<{ at: string }, [string, string]>(
1660 `SELECT p.merged_at AS at FROM pull p INDEXED BY pull_merged JOIN issue i ON i.id = p.issue_id
1661 WHERE p.merged_at >= ?2 AND i.repo_id = ?1 AND i.sealed = 0`,
1662 )
1663 .all(repoId, `${labels[0]!}T00:00:00.000Z`);
1664 for (const r of rows) {
1665 const day = r.at.slice(0, 10);
1666 const n = counts.get(day);
1667 if (n !== undefined) counts.set(day, n + 1);
1668 }
1669 return { days: labels, merged: labels.map((d) => counts.get(d)!) };
1670 }
src/http/mcp.ts +2 −2
@@ -54,7 +54,7 @@ import { stepOf } from "../core/talk_steps.ts";
5454 import { TOOLS } from "./mcp/tools.ts";
5555 import { runMcpRefusal } from "./run_gate.ts";
5656 import { NO_TOOL_HINT, READ_ONLY_REFUSAL, hintOf, hintOfText, noToolNamed, withNextStep } from "./mcp/hints.ts";
57 import { DEFAULT_TOOLS, GUEST_TOOLS, TALK_TOOLS, wantsAll } from "./mcp/catalog.ts";
57 import { DEFAULT_TOOLS, GUEST_TOOLS, talkLists, wantsAll } from "./mcp/catalog.ts";
5858 import { roleOf, type Role } from "../core/roles.ts";
5959 import { OFFER_TOOL, offerAnswer } from "./mcp/offer.ts";
6060 import { OFFER_REQUEST_MAX } from "../actions/offer.ts";
@@ -207,7 +207,7 @@ function rpcOne(
207207 ? listed
208208 : role === "guest"
209209 ? listed.filter((t) => GUEST_TOOLS.includes(t.name))
210 : listed.filter((t) => (ctx.auth.through === undefined ? DEFAULT_TOOLS : TALK_TOOLS).includes(t.name));
210 : listed.filter((t) => (ctx.auth.through === undefined ? DEFAULT_TOOLS.includes(t.name) : talkLists(t.name, user.isAdmin)));
211211 // The cursor is the name of the last tool of the page before, so a tool
212212 // added between two requests moves nothing.
213213 const cursor = params["cursor"];
src/http/mcp/catalog.ts +13
@@ -49,6 +49,19 @@ export const TALK_TOOLS: readonly string[] = [
4949 "write_file", "branches", "open_pull", "new_app",
5050 ];
5151
52 /**
53 * What Talk's agent is also listed when the person is a forge admin: the machine's history
54 * (`telemetry_history`, a read; `brief` charts it). An everyday account's agent is not listed it,
55 * since the tool would only refuse them.
56 */
57 export const TALK_ADMIN_TOOLS: readonly string[] = ["telemetry_history"];
58
59 /**
60 * Whether Talk's agent is listed this tool for this person: the only tools its harness can call,
61 * so `find_tool` offers it nothing else.
62 */
63 export const talkLists = (name: string, isAdmin: boolean): boolean => TALK_TOOLS.includes(name) || (isAdmin && TALK_ADMIN_TOOLS.includes(name));
64
5265 /**
5366 * What a guest's manifest lists (#13461): the two doors an outsider is given, a report and an
5467 * offer. Every other tool still answers by name (`find_tool` shows its schema); it is not listed to
src/http/mcp/tools/find_tool.ts +6 −3
@@ -1,9 +1,9 @@
11 import { bad, good, str, type Tool } from "../shared.ts";
2 import { FIND_MAX, matching, QUERY_MAX } from "../catalog.ts";
2 import { FIND_MAX, matching, QUERY_MAX, talkLists } from "../catalog.ts";
33
44 export const tool: Tool = {
55 name: "find_tool",
6 doc: "`{ query }`: the tools whose name, description or plain-word keywords match every word (else the most words); filler words are ignored, with their one-line description and schema; a tool found is callable at once, listed or not. `tools/list` with `{\"all\": true}` is the full list",
6 doc: "`{ query }`: the tools whose name, description or plain-word keywords match every word (else the most words); filler words are ignored, with their one-line description and schema; a tool found is callable at once, listed or not; Talk's own agent, which can call only what it is listed, is found only those. `tools/list` with `{\"all\": true}` is the full list",
77 description: "Find a tool by what it does; returns name, description and schema. Any tool is callable by name.",
88 inputSchema: {
99 type: "object",
@@ -17,7 +17,10 @@ export const tool: Tool = {
1717 // Lazy: mcp.ts imports the tool table, which holds this tool.
1818 const { entriesFor } = await import("../../mcp.ts");
1919 const found = matching(
20 entriesFor(ctx, user).map(({ name, description, inputSchema }) => ({ name, description, inputSchema })),
20 // Talk's agent calls only what it is listed: it is never offered a tool it cannot call.
21 entriesFor(ctx, user)
22 .filter((t) => ctx.auth.through === undefined || talkLists(t.name, user.isAdmin))
23 .map(({ name, description, inputSchema }) => ({ name, description, inputSchema })),
2124 query,
2225 );
2326 return good({
src/http/mcp/tools/pulls.ts +14 −2
@@ -3,7 +3,7 @@ import { canRead, getReposByIds } from "../../../core/repos.ts";
33 import { mayView, sealedScope } from "../../../core/sealed.ts";
44 import { listReviewsFor, reviewSummariesFor } from "../../../core/reviews.ts";
55 import { movedSinceApproval } from "../../../core/approval_at.ts";
6 import { listPulls, openPullPileRows, pullDir, pullMergeStates, pullsByIssueIds } from "../../../core/pulls.ts";
6 import { listPulls, mergedPerDay, MERGED_DAYS_MAX, openPullPileRows, pullDir, pullMergeStates, pullsByIssueIds } from "../../../core/pulls.ts";
77 import { checkSummary } from "../../../core/runs.ts";
88 import type { Ctx } from "../../context.ts";
99 import type { User } from "../../../core/users.ts";
@@ -14,7 +14,7 @@ import { good, bad, limitArg, type Args, type Answer, type Tool, REPO_ARG, repoA
1414
1515 export const tool: Tool = {
1616 name: "pulls",
17 doc: "`{ repo?, state?, limit?, cursor? }`: without `repo`, every open pull you may read, oldest first, as `{ pulls, next_cursor }` (limit 1-200, default 50): `repo`, `number`, `title`, `check`, `verdict` (approved, changes_requested or none) and `gate` (what holds it, or null; the `why` module's cause); with `repo`, a repository's pulls, newest first, one brief line each: `number`, `title`, `author`, `head`, `check` (state), `approvals`, `movedSinceApproval` (the approval was given for a head or base that has since moved), `changesRequested`, `mergeable` (null once closed), `waitsFor` (`pull`'s `line`, or null); `state` open (default) or closed, `limit` 1-50 (default 20); no bodies, no diffs",
17 doc: "`{ repo?, state?, limit?, cursor? }`: without `repo`, every open pull you may read, oldest first, as `{ pulls, next_cursor }` (limit 1-200, default 50): `repo`, `number`, `title`, `check`, `verdict` (approved, changes_requested or none) and `gate` (what holds it, or null; the `why` module's cause); with `repo`, a repository's pulls, newest first, one brief line each: `number`, `title`, `author`, `head`, `check` (state), `approvals`, `movedSinceApproval` (the approval was given for a head or base that has since moved), `changesRequested`, `mergeable` (null once closed), `waitsFor` (`pull`'s `line`, or null); `state` open (default) or closed, `limit` 1-50 (default 20); no bodies, no diffs. `{ repo, brief: true, days? }` (1-90, default 14): pulls merged each UTC day, `{ repo, days: [YYYY-MM-DD], merged: [n] }`, oldest first, to chart shipping",
1818 description:
1919 "A repository's pulls, newest first; no `repo`: all open pulls you may read, oldest first.",
2020 inputSchema: {
@@ -24,10 +24,22 @@ export const tool: Tool = {
2424 state: { type: "string", enum: ["open", "closed"] },
2525 limit: { type: "integer", minimum: 1, maximum: 50, description: "with repo; 200 without" },
2626 cursor: { type: "string" },
27 brief: { type: "boolean" },
28 days: { type: "integer", minimum: 1, maximum: MERGED_DAYS_MAX },
2729 },
2830 },
2931 writes: false,
3032 async run(ctx, user, args) {
33 if (args["brief"] !== undefined && typeof args["brief"] !== "boolean") return bad("invalid_brief", "brief is true or false");
34 if (args["brief"] === true) {
35 if (args["repo"] === undefined) return bad("invalid", "brief counts one repository's merged pulls: name `repo`");
36 const repo = repoArg(ctx, user, args);
37 if (isAnswer(repo)) return repo;
38 const days = args["days"] ?? 14;
39 if (typeof days !== "number" || !Number.isInteger(days) || days < 1 || days > MERGED_DAYS_MAX)
40 return bad("invalid", `days is a whole number from 1 to ${MERGED_DAYS_MAX}`);
41 return good({ repo: `${repo.ownerName}/${repo.name}`, ...mergedPerDay(ctx.app.db, repo.id, days) });
42 }
3143 if (args["repo"] === undefined) return pile(ctx, user, args);
3244 const repo = repoArg(ctx, user, args);
3345 if (isAnswer(repo)) return repo;
src/http/mcp/tools/telemetry_history.ts +6 −5
@@ -1,26 +1,27 @@
11 import { noteRead, telemetryReader } from "../../../actions/telemetry.ts";
22 import { badBlocked } from "../shared.ts";
33 import { noTelemetryBlocked } from "../../../actions/blocked_words.ts";
4 import { historyOver } from "../../../system/telemetry.ts";
4 import { historyBrief, historyOver } from "../../../system/telemetry.ts";
55 import { good, bad, type Tool } from "../shared.ts";
66
77 export const tool: Tool = {
88 name: "telemetry_history",
9 doc: "`{ hours? }` (1–72, default 6): the node's and the forge's CPU cores, memory and load over the window, `{ hours, points: [{ target, at, cpuCores, cpuCoresMax (the bucket's peak), memoryBytes, load }] }`, at most 300 points a series (15-s samples to 24 h, 5-min beyond, averaged down); a forge admin or `telemetry:read`, as `system`; the machine records no disk history",
10 description: "Machine CPU, memory, load over `hours` (1–72, default 6).",
9 doc: "`{ hours? }` (1–72, default 6): the node's and the forge's CPU cores, memory and load over the window, `{ hours, points: [{ target, at, cpuCores, cpuCoresMax (the bucket's peak), memoryBytes, load }] }`, at most 300 points a series (15-s samples to 24 h, 5-min beyond, averaged down); a forge admin or `telemetry:read`, as `system`; the machine records no disk history. `brief: true`: one value an hour to chart from, `{ hours, at: [YYYY-MM-DDTHH], node, forge }`, each `{ cpuCores, memoryGiB, load }` as arrays, a few hundred bytes a day",
10 description: "Machine CPU, memory, load over `hours` (1–72, default 6); brief: hourly series to chart.",
1111 inputSchema: {
1212 type: "object",
13 properties: { hours: { type: "integer", minimum: 1, maximum: 72 } },
13 properties: { hours: { type: "integer", minimum: 1, maximum: 72 }, brief: { type: "boolean" } },
1414 },
1515 writes: false,
1616 run(ctx, user, args) {
1717 const hours = args.hours === undefined ? 6 : args.hours;
1818 if (typeof hours !== "number" || !Number.isInteger(hours) || hours < 1 || hours > 72)
1919 return bad("invalid", "hours is a whole number from 1 to 72");
20 if (args["brief"] !== undefined && typeof args["brief"] !== "boolean") return bad("invalid_brief", "brief is true or false");
2021 const reader = telemetryReader(ctx.app, user);
2122 if (!reader)
2223 return badBlocked("forbidden", noTelemetryBlocked(ctx.app, user, "Reading this forge's machine figures takes the telemetry:read grant."));
2324 noteRead(ctx.app, user, reader, "history");
24 return good({ hours, points: historyOver(ctx.app, hours) });
25 return good(args["brief"] === true ? historyBrief(ctx.app, hours) : { hours, points: historyOver(ctx.app, hours) });
2526 },
2627 };
src/system/telemetry.ts +29
@@ -235,6 +235,35 @@ export function historyOver(app: App, hours: number) {
235235 return out.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : a.target < b.target ? -1 : 1));
236236 }
237237
238 /** One target's hourly series in `historyBrief`, rounded for reading: cores, GiB and load. */
239 type BriefSeries = { cpuCores: (number | null)[]; memoryGiB: (number | null)[]; load: (number | null)[] };
240
241 /**
242 * The same machine history as one value an hour, small enough to chart from: the UTC hours (`at`,
243 * `YYYY-MM-DDTHH`) and, for the node and the forge, the hour's mean cores, memory in GiB and load,
244 * two decimals, null for an hour with no sample. About 30 bytes an hour a target, where the points
245 * are about 150 a point.
246 */
247 export function historyBrief(app: App, hours: number): { hours: number; at: string[]; node: BriefSeries; forge: BriefSeries } {
248 const points = historyOver(app, hours);
249 const at = [...new Set(points.map((p) => p.at.slice(0, 13)))].sort();
250 const slot = new Map(at.map((h, i) => [h, i]));
251 const round = (v: number | null): number | null => (v === null ? null : Math.round(v * 100) / 100);
252 const series = (target: string): BriefSeries => {
253 const sums = at.map(() => ({ cpu: [] as number[], mem: [] as number[], load: [] as number[] }));
254 for (const p of points) {
255 if (p.target !== target) continue;
256 const s = sums[slot.get(p.at.slice(0, 13))!]!;
257 if (p.cpuCores !== null) s.cpu.push(p.cpuCores);
258 if (p.memoryBytes !== null) s.mem.push(p.memoryBytes / 2 ** 30);
259 if (p.load !== null) s.load.push(p.load);
260 }
261 const mean = (xs: number[]): number | null => (xs.length === 0 ? null : round(xs.reduce((a, b) => a + b, 0) / xs.length));
262 return { cpuCores: sums.map((s) => mean(s.cpu)), memoryGiB: sums.map((s) => mean(s.mem)), load: sums.map((s) => mean(s.load)) };
263 };
264 return { hours, at, node: series("node"), forge: series("forge") };
265 }
266
238267 export const WELCOME_LABEL = "help wanted";
239268
240269 /** What an agent that arrives should know: what this is, where it hurts, what welcomes it, how to propose. */
test/mcp-pulls.test.ts +19
@@ -190,3 +190,22 @@ test("an approval given for a base that has since moved says so", async () => {
190190 expect(after.movedSinceApproval).toBe(true);
191191 expect((await labPulls("rita")).find((p) => p.head === "asked").movedSinceApproval).toBe(false);
192192 });
193
194 test("brief counts the pulls merged each day, small enough to chart, and refuses without a repo", async () => {
195 // Two of svc's pulls merged, one today and one two days ago; the third day has none.
196 const day = 86_400_000;
197 const ids = app.db.query<{ id: string }, []>("SELECT i.id FROM issue i JOIN repo r ON r.id = i.repo_id WHERE r.name = 'svc' AND i.kind = 'pull' ORDER BY i.number").all();
198 app.db.query("UPDATE pull SET merged_at = ?2 WHERE issue_id = ?1").run(ids[0]!.id, new Date().toISOString());
199 app.db.query("UPDATE pull SET merged_at = ?2 WHERE issue_id = ?1").run(ids[1]!.id, new Date(Date.now() - 2 * day).toISOString());
200 const r = await pulls(tok["ada"]!, { repo: "ada/svc", brief: true, days: 3 });
201 expect(r.value.repo).toBe("ada/svc");
202 expect(r.value.days).toHaveLength(3);
203 expect(r.value.days.at(-1)).toBe(new Date().toISOString().slice(0, 10));
204 expect(r.value.merged).toEqual([1, 0, 1]);
205 // Two weeks is a few hundred bytes, where the pulls themselves run to tens of kilobytes.
206 const weeks = await pulls(tok["ada"]!, { repo: "ada/svc", brief: true });
207 expect(weeks.value.days).toHaveLength(14);
208 expect(Buffer.byteLength(JSON.stringify(weeks.value))).toBeLessThan(400);
209 expect((await pulls(tok["ada"]!, { brief: true })).error).toContain("repo");
210 expect((await pulls(tok["ada"]!, { repo: "ada/svc", brief: true, days: 91 })).error).toBeTruthy();
211 });
test/mcp-talk-tools.test.ts +25 −2
@@ -19,7 +19,7 @@ import { createIssue } from "../src/core/issues.ts";
1919 import { createToken } from "../src/core/tokens.ts";
2020 import { createUser, type User } from "../src/core/users.ts";
2121 import { mintViaToken } from "../src/core/via_token.ts";
22 import { DEFAULT_TOOLS, TALK_TOOLS } from "../src/http/mcp/catalog.ts";
22 import { DEFAULT_TOOLS, TALK_ADMIN_TOOLS, TALK_TOOLS, talkLists } from "../src/http/mcp/catalog.ts";
2323 import * as tools from "../src/http/mcp/tools/index.ts";
2424 import { serve, type Servers } from "../src/http/server.ts";
2525 import { promote } from "./helpers/members.ts";
@@ -144,10 +144,33 @@ describe("the Talk list", () => {
144144 expect(cursor).toBeUndefined();
145145 if (bytes >= TALK_CEILING) throw new Error(OVER(bytes));
146146 // Nothing outside the Talk list is offered.
147 for (const n of names) expect(TALK_TOOLS).toContain(n);
147 for (const n of names) expect(talkLists(n, u.isAdmin)).toBe(true);
148148 }
149149 });
150150
151 test("an admin's agent reads the machine's history; an everyday account's is not listed it, and find_tool offers neither a tool it cannot call", async () => {
152 const admin = await list(via(alice, "how is the server doing?").token);
153 for (const n of TALK_ADMIN_TOOLS) expect(admin.names).toContain(n);
154 const member = await list(via(bob, "how is the server doing?").token);
155 for (const n of TALK_ADMIN_TOOLS) expect(member.names).not.toContain(n);
156 const find = async (u: User) => {
157 const r = (await post(via(u, "graphs").token, "tools/call", { name: "find_tool", arguments: { query: "cpu memory" } })).result!;
158 const text = (r["content"] as { text: string }[])[0]!.text;
159 // Strings a via token reads come fenced (`[[data …]]`): the name is inside.
160 return ((JSON.parse(text) as { tools: { name: string }[] }).tools ?? []).map((t) => t.name.replace(/\[\[\/?data [0-9a-f]+\]\]/g, "").trim());
161 };
162 // Found tools are the agent's own list, for each person: `system` (now) is never offered to it.
163 const forAdmin = await find(alice);
164 expect(forAdmin).toContain("telemetry_history");
165 for (const n of forAdmin) expect(admin.names).toContain(n);
166 const forMember = await find(bob);
167 expect(forMember).not.toContain("telemetry_history");
168 for (const n of forMember) expect(member.names).toContain(n);
169 // A plain token still finds every tool it may call, Talk's rule aside.
170 const r = (await post(plain(alice, "admin"), "tools/call", { name: "find_tool", arguments: { query: "cpu memory" } })).result!;
171 expect((r["content"] as { text: string }[])[0]!.text).toContain("\"system\"");
172 });
173
151174 test("a tool visible hides from this person is never listed to their agent", async () => {
152175 // What a full list shows this member's plain token is what visible lets them use.
153176 const all: string[] = [];
test/mcp-telemetry-history.test.ts +15
@@ -97,6 +97,21 @@ describe("telemetry_history over MCP", () => {
9797 expect(Math.max(...pts.map((p) => p.cpuCores))).toBeLessThan(9);
9898 });
9999
100 test("brief is one value an hour a target, small enough to chart", async () => {
101 const r = await tool(admin, { hours: 24, brief: true });
102 expect(r.value.hours).toBe(24);
103 expect(r.value.at.length).toBeGreaterThan(0);
104 expect(r.value.at.length).toBeLessThanOrEqual(25);
105 expect(r.value.at[0]).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}$/);
106 expect(r.value.node.cpuCores).toHaveLength(r.value.at.length);
107 expect(r.value.node.memoryGiB).toHaveLength(r.value.at.length);
108 expect(r.value.forge.load.every((v: number | null) => v === null)).toBe(true);
109 // A day is about a kilobyte, where its points run to tens of kilobytes.
110 expect(Buffer.byteLength(JSON.stringify(r.value))).toBeLessThan(2_500);
111 expect(Buffer.byteLength(JSON.stringify((await tool(admin, { hours: 24 })).value))).toBeGreaterThan(20_000);
112 expect((await tool(admin, { hours: 1, brief: "yes" })).error).toBeTruthy();
113 });
114
100115 test("hours outside 1 to 72 is refused", async () => {
101116 for (const hours of [0, 73, -1, 1.5, "6"]) {
102117 expect((await tool(admin, { hours })).error).toBeTruthy();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs