Public: anyone can read this; the crew can change it.
telemetry_history and forges answer in a summary by default, with detail on request #16893
Check · Review · Land · Live done — Landed and live in production.
sold/tools-compact → main 0 commits
21 files
changed +423
−127
- docs/features/forges-side-by-side.md
- docs/features/sandbox-move.md
- docs/features/system.md
- src/http/mcp/tools/forges.ts
- src/http/mcp/tools/telemetry_history.ts
- src/spawn/client_words.ts
- src/spawn/clients.ts
- src/system/telemetry.ts
- src/web/studio/cards.ts
- test/client-list.test.ts
- test/client-states.test.ts
- test/family-heartbeat.test.ts
- test/forges-compact.test.ts
- test/forges-kept.test.ts
- test/forges-month-ledger.test.ts
- test/mcp-forges-card.test.ts
- test/mcp-forges-usage.test.ts
- test/mcp-telemetry-history.test.ts
- test/spawn-in-process-visible.test.ts
- test/spawn-reach-door.test.ts
- test/spawn-template-record.test.ts
docs/features/forges-side-by-side.md +9 −1
| @@ -16,4 +16,12 @@ The table is for comparing; the list below it stays for what needs doing (claim | ||
| 16 | 16 | |
| 17 | 17 | ## This month's cost (#12275) |
| 18 | 18 | |
| 19 | Each forge's line on `/forges`, in the terminal's "Forges you sent" card and in the `forges` MCP tool's `month` field says what the child spent this month, from the child's own ledger: "this month $3.75 · 2 min · 100 tokens in, 10 out". The month is the UTC calendar month, read from each entry's end time; a part no entry carried is left out, and a child with no ledger shows nothing. The ledger's hash chain is checked first: a chain that does not verify reads "ledger broken at 2026-11.jsonl:3" (as a warning badge on the page) and is never summed; a ledger that cannot be read reads "ledger unreadable", and one over 8 MiB "ledger too large to check". The ledger is never read while a page or tool request waits: the last value is served, and a read is queued (one child at a time) when it is more than five minutes old, so a child's first figure appears on the pass after the one that first lists it. | |
| 19 | Each forge's line on `/forges`, in the terminal's "Forges you sent" card and in the `forges` MCP tool (each line's billing, "$3.75 this month", and `month` in the row `{ name }` reads) says what the child spent this month, from the child's own ledger: "this month $3.75 · 2 min · 100 tokens in, 10 out". The month is the UTC calendar month, read from each entry's end time; a part no entry carried is left out, and a child with no ledger shows nothing. The ledger's hash chain is checked first: a chain that does not verify reads "ledger broken at 2026-11.jsonl:3" (as a warning badge on the page) and is never summed; a ledger that cannot be read reads "ledger unreadable", and one over 8 MiB "ledger too large to check". The ledger is never read while a page or tool request waits: the last value is served, and a read is queued (one child at a time) when it is more than five minutes old, so a child's first figure appears on the pass after the one that first lists it. | |
| 20 | ||
| 21 | ## Over MCP | |
| 22 | ||
| 23 | The `forges` tool lists a line a forge, `name | state | version | billing` ("-" where a forge has | |
| 24 | not said), unopened links first, with the address once as a pattern (`url`, `<name>` in it): a | |
| 25 | hundred forges stay under 6 KB, so an agent reads the whole list. `{ name }` returns that forge's | |
| 26 | whole row, everything `/forges` shows. The page, the terminal and `GET /api/v1/forges` read the | |
| 27 | whole rows (`clientRows`). |
docs/features/sandbox-move.md +2 −2
| @@ -22,8 +22,8 @@ leave it. | ||
| 22 | 22 | - **/system**: "Forges inside this process, last hour": for each, its |
| 23 | 23 | requests and how long they were open, how long its timers held the thread, |
| 24 | 24 | and the stalls named for it. The stall log itself names `child:<name>`. |
| 25 | - `GET /api/v1/forges`, the MCP `forges` and `family` tools: `placement`, and | |
| 26 | `where` in words. | |
| 25 | - `GET /api/v1/forges`, the MCP `forges` tool's row (`{ name }`) and the `family` tool: | |
| 26 | `placement`, and `where` in words. | |
| 27 | 27 | |
| 28 | 28 | ## Moving one |
| 29 | 29 |
docs/features/system.md +9
| @@ -42,3 +42,12 @@ the host's CPU count even when its quota is lower. | ||
| 42 | 42 | |
| 43 | 43 | When no limit is set below the host, none of these say "cgroup", and |
| 44 | 44 | `limitedBy` is `"host"`. |
| 45 | ||
| 46 | ## History for agents | |
| 47 | ||
| 48 | The MCP `telemetry_history` tool answers in a few kilobytes by default: the window and, for the | |
| 49 | node and the forge, the sample count, each measure's last, least, most and 95th percentile (from | |
| 50 | the raw samples, so a spike shows in `max` and `cpuCoresPeak`), and 12 averaged points as columns. | |
| 51 | `series` (`node` or `forge`) returns that series' points, at most 150, and says how many samples | |
| 52 | each stands for. `brief: true` stays one value an hour, to chart. The terminal's System screen and | |
| 53 | the hourly brief read the whole history (`historyOver`), not the tool. |
src/http/mcp/tools/forges.ts +11 −8
| @@ -3,7 +3,7 @@ import { CODE_ERRORS, makeCode, planCode, readCodes, revoke } from "../../../act | ||
| 3 | 3 | import { REFUSED_SHOWN, listRefusals, mayReadRefusals } from "../../../core/first_ask_refusals.ts"; |
| 4 | 4 | import { publicOrigin } from "../../../core/public_origin.ts"; |
| 5 | 5 | import { scopeAllows } from "../../../core/tokens.ts"; |
| 6 | import { clientLines } from "../../../spawn/client_words.ts"; | |
| 6 | import { clientLines, sentLines } from "../../../spawn/client_words.ts"; | |
| 7 | 7 | import { clientRows, listedKept } from "../../../spawn/clients.ts"; |
| 8 | 8 | import { archiveForge, archivedForges, restoreForge } from "../../../spawn/archive.ts"; |
| 9 | 9 | import { CHILD_NAME } from "../../../spawn/placement.ts"; |
| @@ -18,10 +18,10 @@ const sentSays = (n: number) => (n === 0 ? "This forge has sent no forges yet." | ||
| 18 | 18 | export const tool: Tool = { |
| 19 | 19 | name: "forges", |
| 20 | 20 | listedTo: "admin", |
| 21 | doc: "the forges sent from here: name, address, whom for, apps, claimed, stage (link not opened/opened/signed in/crew working/last tell, with stageAt; resend true when unopened 3 days: claim_link), last activity (a person or the crew, never a heartbeat), who claimed it and when, kept (its newest backup's age, or never kept), keep cost, archive reason, reachable, size, use, madeFrom; `{ forge, plan?, dryRun? }` reads a forge's plan (small|medium|large); `plan` grants it by hand; `size` workshop raises a forge; `{ forge, sandbox: true }` reads what moving a forge into a sandbox would meet (hooks, command-running keys, size) and with `dryRun: false` moves it, proven, put back on failure (`acknowledge: true` when it was held for what its repositories hold); each forge carries `placement` and `where`; gift codes: `codes` true lists, `code` {plan, uses?, note?, expires?} makes (shown once), `revoke` id; planned unless `dryRun` is false; `archive` a name or names stops each, writes its data and ledger as one file to the backup destination, then removes it; `restore` a name brings an archived one back; `kind` refused: the last 20 refused first asks; `kind` clients lists each client in the page's words, with runs, pulls, tellAt while working; `action` resend + `forge`: previews, with `dryRun: false` replaces its link", | |
| 21 | doc: "the forges sent from here, one line each: \"name | state | version | billing\" (unopened links first), with `url` once as a pattern; `name`: that forge's whole row (address, whom for, apps, claimed, stage with stageAt and resend, last activity, claimed by and when, kept, archive reason, reachable, size, use, madeFrom, placement, where); `{ forge, plan?, dryRun? }` reads a forge's plan (small|medium|large); `plan` grants it by hand; `size` workshop raises a forge; `{ forge, sandbox: true }` reads what moving a forge into a sandbox would meet (hooks, command-running keys, size) and with `dryRun: false` moves it, proven, put back on failure (`acknowledge: true` when it was held for what its repositories hold); gift codes: `codes` true lists, `code` {plan, uses?, note?, expires?} makes (shown once), `revoke` id; planned unless `dryRun` is false; `archive` a name or names stops each, writes its data and ledger as one file to the backup destination, then removes it; `restore` a name brings an archived one back; `kind` refused: the last 20 refused first asks; `kind` clients lists each client in the page's words, with runs, pulls, tellAt while working; `action` resend + `forge`: previews, with `dryRun: false` replaces its link", | |
| 22 | 22 | description: |
| 23 | "Forges sent from here (admin): clients, plans, sizes.", | |
| 24 | inputSchema: { type: "object", properties: { kind: { type: "string", enum: ["refused", "clients"] }, action: { enum: ["resend"] }, forge: { type: "string" }, plan: { type: "string" }, codes: { type: "boolean" }, code: { type: "object" }, revoke: { type: "string" }, archive: { type: ["string", "array"], items: { type: "string" } }, restore: { type: "string" }, sandbox: { type: "boolean" }, size: { type: "string" }, acknowledge: { type: "boolean" }, dryRun: { type: "boolean" } } }, | |
| 23 | "Forges sent from here (admin).", | |
| 24 | inputSchema: { type: "object", properties: { name: { type: "string" }, kind: { type: "string", enum: ["refused", "clients"] }, action: { enum: ["resend"] }, forge: { type: "string" }, plan: { type: "string" }, codes: { type: "boolean" }, code: { type: "object" }, revoke: { type: "string" }, archive: { type: ["string", "array"], items: { type: "string" } }, restore: { type: "string" }, sandbox: { type: "boolean" }, size: { type: "string" }, acknowledge: { type: "boolean" }, dryRun: { type: "boolean" } } }, | |
| 25 | 25 | writes: true, |
| 26 | 26 | tier: "delete", |
| 27 | 27 | deletes: (args) => args["archive"] !== undefined, |
| @@ -121,9 +121,12 @@ export const tool: Tool = { | ||
| 121 | 121 | return set.ok ? good(set.value) : refuse(set.error); |
| 122 | 122 | } |
| 123 | 123 | const forges = await clientRows(ctx.app); |
| 124 | return good({ | |
| 125 | says: sentSays(forges.length), | |
| 126 | forges: listedKept(ctx.app, forges), | |
| 127 | }); | |
| 124 | // One forge's whole row by name; the list is a line each, since the rows of two dozen forges | |
| 125 | // were 54 KB, more than an agent reads of one answer. | |
| 126 | if (args["name"] !== undefined) { | |
| 127 | const one = forges.find((f) => f.name === args["name"]); | |
| 128 | return one === undefined ? bad("not_found", "No forge of that name was sent from here.") : good(listedKept(ctx.app, [one])[0]); | |
| 129 | } | |
| 130 | return good({ says: sentSays(forges.length), ...sentLines(forges), detail: "name: one forge's whole row" }); | |
| 128 | 131 | }, |
| 129 | 132 | }; |
src/http/mcp/tools/telemetry_history.ts +14 −5
| @@ -1,16 +1,20 @@ | ||
| 1 | 1 | import { noteRead, telemetryReader } from "../../../actions/telemetry.ts"; |
| 2 | 2 | import { badBlocked } from "../shared.ts"; |
| 3 | 3 | import { noTelemetryBlocked } from "../../../actions/blocked_words.ts"; |
| 4 | import { historyBrief, historyOver } from "../../../system/telemetry.ts"; | |
| 4 | import { DETAIL_POINTS, HISTORY_SERIES, SUMMARY_POINTS, historyBrief, historyDetail, historySummary } from "../../../system/telemetry.ts"; | |
| 5 | 5 | import { good, bad, type Tool } from "../shared.ts"; |
| 6 | 6 | |
| 7 | 7 | export const tool: Tool = { |
| 8 | 8 | 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. `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: "CPU, memory, load over `hours` (1–72); brief: hourly.", | |
| 9 | doc: `\`{ hours?, series?, brief? }\` (hours 1–72, default 6): the node's and the forge's CPU cores, memory and load as a summary: per series \`samples\`, { last, min, max, p95 } of \`cpuCores\`, \`memoryGiB\` and \`load\`, \`cpuCoresPeak\`, and ${SUMMARY_POINTS} \`points\` as columns. \`series\` (node or forge): its points, at most ${DETAIL_POINTS} (\`says\` how averaged). \`brief: true\`: hourly arrays to chart. Admin or \`telemetry:read\`; no disk history`, | |
| 10 | description: "CPU, memory, load.", | |
| 11 | 11 | inputSchema: { |
| 12 | 12 | type: "object", |
| 13 | properties: { hours: { type: "integer", minimum: 1, maximum: 72 }, brief: { type: "boolean" } }, | |
| 13 | properties: { | |
| 14 | hours: { type: "integer", minimum: 1, maximum: 72 }, | |
| 15 | series: { type: "string" }, | |
| 16 | brief: { type: "boolean" }, | |
| 17 | }, | |
| 14 | 18 | }, |
| 15 | 19 | writes: false, |
| 16 | 20 | run(ctx, user, args) { |
| @@ -18,10 +22,15 @@ export const tool: Tool = { | ||
| 18 | 22 | if (typeof hours !== "number" || !Number.isInteger(hours) || hours < 1 || hours > 72) |
| 19 | 23 | return bad("invalid", "hours is a whole number from 1 to 72"); |
| 20 | 24 | if (args["brief"] !== undefined && typeof args["brief"] !== "boolean") return bad("invalid_brief", "brief is true or false"); |
| 25 | const series = args["series"]; | |
| 26 | if (series !== undefined && !HISTORY_SERIES.includes(series as (typeof HISTORY_SERIES)[number])) return bad("invalid_series", "series is node or forge"); | |
| 21 | 27 | const reader = telemetryReader(ctx.app, user); |
| 22 | 28 | if (!reader) |
| 23 | 29 | return badBlocked("forbidden", noTelemetryBlocked(ctx.app, user, "Reading this forge's machine figures takes the telemetry:read grant.")); |
| 24 | 30 | noteRead(ctx.app, user, reader, "history"); |
| 25 | return good(args["brief"] === true ? historyBrief(ctx.app, hours) : { hours, points: historyOver(ctx.app, hours) }); | |
| 31 | // A summary unless one series' points are asked for by name: the points of both series over six | |
| 32 | // hours were 87 KB, more than an agent reads of one answer. | |
| 33 | if (args["brief"] === true) return good(historyBrief(ctx.app, hours)); | |
| 34 | return good(series !== undefined ? historyDetail(ctx.app, hours, series as (typeof HISTORY_SERIES)[number]) : historySummary(ctx.app, hours)); | |
| 26 | 35 | }, |
| 27 | 36 | }; |
src/spawn/client_words.ts +32
| @@ -93,3 +93,35 @@ export function sentWords(r: Pick<ClientRow, "made" | "apps" | "sentAt">, now: n | ||
| 93 | 93 | const when = days <= 0 ? "today" : days === 1 ? "yesterday" : `${days} days ago`; |
| 94 | 94 | return `Sent ${what}, ${when}`; |
| 95 | 95 | } |
| 96 | ||
| 97 | /** What a sent forge costs this month, in a few words: its crew's spend against its cap, and what this forge lends it; "-" when it has not said. */ | |
| 98 | export function forgeBilling(r: Pick<ClientRow, "month" | "ceilingUsd" | "creditCapUsd" | "creditSpentUsd">): string { | |
| 99 | const usd = (n: number) => `$${n.toFixed(2)}`; | |
| 100 | const lent = r.creditCapUsd === null || r.creditCapUsd === undefined ? "" : `; lent ${usd(r.creditSpentUsd ?? 0)} of ${usd(r.creditCapUsd)}`; | |
| 101 | if (r.month === null || r.month === undefined) return lent === "" ? "-" : lent.slice(2); | |
| 102 | if (!r.month.ok) return `its ledger is broken (${r.month.why})${lent}`; | |
| 103 | return `${usd(r.month.usd_tokens ?? 0)} this month${r.ceilingUsd === null ? "" : ` of a ${usd(r.ceilingUsd)} cap`}${lent}`; | |
| 104 | } | |
| 105 | ||
| 106 | /** The columns of a `sentLines` line. */ | |
| 107 | export const FORGE_COLUMNS = "name | state | version | billing"; | |
| 108 | ||
| 109 | /** | |
| 110 | * The sent forges as `forges` answers by default: one line each in `FORGE_COLUMNS` ("-" where a | |
| 111 | * forge has not said), unopened links first, and the address once as a pattern (`<name>` in it), | |
| 112 | * with a line's own address after it only where it differs. A hundred forges are about 6 KB; | |
| 113 | * `name` reads one whole row. | |
| 114 | */ | |
| 115 | export function sentLines(rows: readonly ClientRow[]): { columns: string; url: string; forges: string[] } { | |
| 116 | const first = rows[0]; | |
| 117 | const url = first === undefined ? "" : first.url.split(first.name).join("<name>"); | |
| 118 | const ordered = [...rows.filter((r) => r.stage?.resend === true), ...rows.filter((r) => r.stage?.resend !== true)]; | |
| 119 | const forges = ordered.map((r) => { | |
| 120 | // "Unclaimed" is what an unopened link already says; not reporting and app down are not. | |
| 121 | const alarm = r.attention === null || r.attention === "unclaimed" ? "" : ATTENTION_WORDS[r.attention].toLowerCase(); | |
| 122 | const state = !r.made ? "being made" : [r.stage?.words ?? "no answer", alarm].filter((w) => w !== "").join(", "); | |
| 123 | const own = url.split("<name>").join(r.name) === r.url ? [] : [r.url]; | |
| 124 | return [r.name, state, r.version ?? "-", forgeBilling(r), ...own].join(" | "); | |
| 125 | }); | |
| 126 | return { columns: FORGE_COLUMNS, url, forges }; | |
| 127 | } |
src/spawn/clients.ts +3
| @@ -160,6 +160,8 @@ export interface ClientRow { | ||
| 160 | 160 | readonly disk: ChildDisk; |
| 161 | 161 | /** When its last heartbeat reached this forge, ISO; null when none has. */ |
| 162 | 162 | readonly lastHeartbeatAt: string | null; |
| 163 | /** The version its last heartbeat named; null (or absent) when none has. */ | |
| 164 | readonly version?: string | null; | |
| 163 | 165 | /** Epoch ms its grace for a late payment ends; absent when it is not in grace. */ |
| 164 | 166 | readonly graceUntil?: number; |
| 165 | 167 | /** The first step its person has not taken, read from the child's heartbeat. */ |
| @@ -460,6 +462,7 @@ export async function clientRows(app: App, options: { probe?: boolean } = {}): P | ||
| 460 | 462 | use: forgeUse(c, childDirOf(app, c.bodyId)), |
| 461 | 463 | disk: liveChildDisk(app.config.dataDir, c.bodyId, mountinfo), |
| 462 | 464 | lastHeartbeatAt: beats[i] === undefined ? null : new Date(beats[i]!.receivedAt).toISOString(), |
| 465 | version: beats[i]?.beat.version ?? null, | |
| 463 | 466 | link: states[i]?.link ?? null, |
| 464 | 467 | replacedAt: replaced.get(c.name) ?? null, |
| 465 | 468 | // Read from the record this forge wrote when it made the child, never from the child's word. |
src/system/telemetry.ts +112 −20
| @@ -188,11 +188,10 @@ type HistoryPoint = { | ||
| 188 | 188 | load: number | null; |
| 189 | 189 | }; |
| 190 | 190 | |
| 191 | /** | |
| 192 | * The same points over the last `hours` (15-s steps inside the day, 5-min beyond it), each target | |
| 193 | * averaged down to at most `HISTORY_POINTS`, so the answer is bounded however long the window. | |
| 194 | */ | |
| 195 | export function historyOver(app: App, hours: number) { | |
| 191 | type Sample = Omit<HistoryPoint, "target"> & { target: string }; | |
| 192 | ||
| 193 | /** The raw samples over the last `hours`: 15-s steps inside the day, 5-min beyond it. */ | |
| 194 | function samplesOver(app: App, hours: number): { step: number; rows: Sample[] } { | |
| 196 | 195 | const step = hours <= 24 ? 15 : 300; |
| 197 | 196 | const rows = app.db |
| 198 | 197 | .query< |
| @@ -212,27 +211,120 @@ export function historyOver(app: App, hours: number) { | ||
| 212 | 211 | memoryBytes: r.memory_bytes, |
| 213 | 212 | load: r.load, |
| 214 | 213 | })); |
| 214 | return { step, rows }; | |
| 215 | } | |
| 216 | ||
| 217 | /** One target's samples averaged into at most `most` buckets, each keeping its busiest sample. */ | |
| 218 | function bucketed(rows: readonly Sample[], target: string, most: number): HistoryPoint[] { | |
| 215 | 219 | const mean = (xs: (number | null)[]) => { |
| 216 | 220 | const v = xs.filter((x): x is number => x !== null); |
| 217 | 221 | return v.length ? v.reduce((a, b) => a + b, 0) / v.length : null; |
| 218 | 222 | }; |
| 223 | const own = rows.filter((r) => r.target === target); | |
| 224 | const size = Math.ceil(own.length / most) || 1; | |
| 219 | 225 | const out: HistoryPoint[] = []; |
| 220 | for (const target of ["node", "forge"]) { | |
| 221 | const own = rows.filter((r) => r.target === target); | |
| 222 | const size = Math.ceil(own.length / HISTORY_POINTS) || 1; | |
| 223 | for (let i = 0; i < own.length; i += size) { | |
| 224 | const g = own.slice(i, i + size); | |
| 225 | out.push({ | |
| 226 | target, | |
| 227 | at: g[0]!.at, | |
| 228 | cpuCores: mean(g.map((r) => r.cpuCores)), | |
| 229 | cpuCoresMax: g.reduce<number | null>((m, r) => (r.cpuCoresMax === null ? m : Math.max(m ?? -Infinity, r.cpuCoresMax)), null), | |
| 230 | memoryBytes: mean(g.map((r) => r.memoryBytes)), | |
| 231 | load: mean(g.map((r) => r.load)), | |
| 232 | }); | |
| 233 | } | |
| 226 | for (let i = 0; i < own.length; i += size) { | |
| 227 | const g = own.slice(i, i + size); | |
| 228 | out.push({ | |
| 229 | target, | |
| 230 | at: g[0]!.at, | |
| 231 | cpuCores: mean(g.map((r) => r.cpuCores)), | |
| 232 | cpuCoresMax: g.reduce<number | null>((m, r) => (r.cpuCoresMax === null ? m : Math.max(m ?? -Infinity, r.cpuCoresMax)), null), | |
| 233 | memoryBytes: mean(g.map((r) => r.memoryBytes)), | |
| 234 | load: mean(g.map((r) => r.load)), | |
| 235 | }); | |
| 234 | 236 | } |
| 235 | return out.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : a.target < b.target ? -1 : 1)); | |
| 237 | return out; | |
| 238 | } | |
| 239 | ||
| 240 | /** | |
| 241 | * The same points over the last `hours` (15-s steps inside the day, 5-min beyond it), each target | |
| 242 | * averaged down to at most `HISTORY_POINTS`, so the answer is bounded however long the window. | |
| 243 | * The terminal's System screen and the hourly brief read it; MCP answers from `historySummary`. | |
| 244 | */ | |
| 245 | export function historyOver(app: App, hours: number) { | |
| 246 | const { rows } = samplesOver(app, hours); | |
| 247 | return [...bucketed(rows, "node", HISTORY_POINTS), ...bucketed(rows, "forge", HISTORY_POINTS)].sort((a, b) => | |
| 248 | a.at < b.at ? -1 : a.at > b.at ? 1 : a.target < b.target ? -1 : 1, | |
| 249 | ); | |
| 250 | } | |
| 251 | ||
| 252 | /** The two machine series `telemetry_history` names. */ | |
| 253 | export const HISTORY_SERIES = ["node", "forge"] as const; | |
| 254 | /** Points a series' summary carries to show its shape. */ | |
| 255 | export const SUMMARY_POINTS = 12; | |
| 256 | /** Most points `historyDetail` returns for one series; a longer window is averaged down to it. */ | |
| 257 | export const DETAIL_POINTS = 150; | |
| 258 | ||
| 259 | const two = (v: number | null): number | null => (v === null ? null : Math.round(v * 100) / 100); | |
| 260 | const gib = (b: number | null): number | null => (b === null ? null : b / 2 ** 30); | |
| 261 | ||
| 262 | /** The last value, the least, the most and the 95th percentile of one measure, two decimals; null with no sample. */ | |
| 263 | function spread(xs: readonly (number | null)[]): { last: number | null; min: number | null; max: number | null; p95: number | null } { | |
| 264 | const v = xs.filter((x): x is number => x !== null); | |
| 265 | if (v.length === 0) return { last: null, min: null, max: null, p95: null }; | |
| 266 | const sorted = [...v].sort((a, b) => a - b); | |
| 267 | return { last: two(v.at(-1)!), min: two(sorted[0]!), max: two(sorted.at(-1)!), p95: two(sorted[Math.min(sorted.length, Math.max(1, Math.ceil(0.95 * sorted.length))) - 1]!) }; | |
| 268 | } | |
| 269 | ||
| 270 | /** A series' points as columns, two decimals, memory in GiB: what a chart or a reader needs, a fraction of the objects' size. */ | |
| 271 | function columns(points: readonly HistoryPoint[]) { | |
| 272 | return { | |
| 273 | at: points.map((p) => p.at.slice(0, 19)), | |
| 274 | cpuCores: points.map((p) => two(p.cpuCores)), | |
| 275 | cpuCoresMax: points.map((p) => two(p.cpuCoresMax)), | |
| 276 | memoryGiB: points.map((p) => two(gib(p.memoryBytes))), | |
| 277 | load: points.map((p) => two(p.load)), | |
| 278 | }; | |
| 279 | } | |
| 280 | ||
| 281 | /** | |
| 282 | * The machine history in a few kilobytes, `telemetry_history`'s default: the window, and for the | |
| 283 | * node and the forge the sample count, each measure's last, least, most and 95th percentile (from | |
| 284 | * the raw samples, so a spike shows in `max`), and `SUMMARY_POINTS` averaged points for its shape. | |
| 285 | */ | |
| 286 | export function historySummary(app: App, hours: number) { | |
| 287 | const { step, rows } = samplesOver(app, hours); | |
| 288 | const series = Object.fromEntries( | |
| 289 | HISTORY_SERIES.map((target) => { | |
| 290 | const own = rows.filter((r) => r.target === target); | |
| 291 | return [ | |
| 292 | target, | |
| 293 | { | |
| 294 | samples: own.length, | |
| 295 | cpuCores: spread(own.map((r) => r.cpuCores)), | |
| 296 | cpuCoresPeak: spread(own.map((r) => r.cpuCoresMax)).max, | |
| 297 | memoryGiB: spread(own.map((r) => gib(r.memoryBytes))), | |
| 298 | load: spread(own.map((r) => r.load)), | |
| 299 | points: columns(bucketed(rows, target, SUMMARY_POINTS)), | |
| 300 | }, | |
| 301 | ]; | |
| 302 | }), | |
| 303 | ); | |
| 304 | return { | |
| 305 | hours, | |
| 306 | from: rows[0]?.at ?? null, | |
| 307 | to: rows.at(-1)?.at ?? null, | |
| 308 | stepSeconds: step, | |
| 309 | series, | |
| 310 | detail: `one series' points: { series: "node" or "forge", hours }, at most ${DETAIL_POINTS} (a longer window is averaged down to them)`, | |
| 311 | }; | |
| 312 | } | |
| 313 | ||
| 314 | /** One series' points for `telemetry_history { series }`: at most `DETAIL_POINTS`, and it says so. */ | |
| 315 | export function historyDetail(app: App, hours: number, target: (typeof HISTORY_SERIES)[number]) { | |
| 316 | const { step, rows } = samplesOver(app, hours); | |
| 317 | const samples = rows.filter((r) => r.target === target).length; | |
| 318 | const points = bucketed(rows, target, DETAIL_POINTS); | |
| 319 | return { | |
| 320 | hours, | |
| 321 | series: target, | |
| 322 | stepSeconds: step, | |
| 323 | samples, | |
| 324 | cap: DETAIL_POINTS, | |
| 325 | says: samples > points.length ? `${samples} samples averaged into ${points.length} points (at most ${DETAIL_POINTS}); cpuCoresMax keeps each point's busiest sample` : `all ${samples} samples`, | |
| 326 | ...columns(points), | |
| 327 | }; | |
| 236 | 328 | } |
| 237 | 329 | |
| 238 | 330 | /** One target's hourly series in `historyBrief`, rounded for reading: cores, GiB and load. */ |
src/web/studio/cards.ts +11 −17
| @@ -412,26 +412,20 @@ export function cardFor( | ||
| 412 | 412 | return { kind, title: CARD_TITLE[kind], status: `${nodes.length} repositor${nodes.length === 1 ? "y" : "ies"} · from ${text(v["root"])}`, rows, actions }; |
| 413 | 413 | } |
| 414 | 414 | if (kind === "forges") { |
| 415 | // `forges` lists `{ says, forges: [clientRows] }`; a plan, a code or a refusal has no `forges` array, so no card. | |
| 415 | // `forges` lists `{ says, columns, url, forges: ["name | state | version | billing"] }`, unopened links | |
| 416 | // already first; a plan, a code, one forge's row or a refusal has no `forges` array, so no card. | |
| 416 | 417 | const v = obj(value); |
| 417 | 418 | if (!Array.isArray(v["forges"])) return undefined; |
| 418 | const all = v["forges"].map(obj); | |
| 419 | const word = (f: Obj): string => { | |
| 420 | const stage = obj(f["stage"]); | |
| 421 | return stage["resend"] === true ? "resend" : text(stage["words"]).toLowerCase() || "being made"; | |
| 422 | }; | |
| 423 | // Unopened-for-days links first; the rest keep the server's order. | |
| 424 | const ordered = [...all.filter((f) => obj(f["stage"])["resend"] === true), ...all.filter((f) => obj(f["stage"])["resend"] !== true)]; | |
| 425 | for (const f of ordered.slice(0, SENT_ROWS)) { | |
| 426 | const owner = text(f["for"]); | |
| 427 | rows.push({ | |
| 428 | label: text(f["name"]), | |
| 429 | value: `${owner === "" ? "no one named" : `for ${owner}`} · ${word(f)}`, | |
| 430 | ...(web(text(f["url"])) ? { link: text(f["url"]) } : {}), | |
| 431 | }); | |
| 419 | const lines = v["forges"].map(text); | |
| 420 | const pattern = text(v["url"]); | |
| 421 | for (const line of lines.slice(0, SENT_ROWS)) { | |
| 422 | const [name = "", ...rest] = line.split(" | "); | |
| 423 | const own = rest.find((p) => /^https?:\/\//.test(p)); | |
| 424 | const url = own ?? pattern.split("<name>").join(name); | |
| 425 | rows.push({ label: name, value: rest.filter((p) => p !== own && p !== "-").join(" · "), ...(web(url) ? { link: url } : {}) }); | |
| 432 | 426 | } |
| 433 | if (all.length > SENT_ROWS) rows.push({ label: "More", value: `${all.length - SENT_ROWS} more not shown` }); | |
| 434 | return { kind, title: CARD_TITLE[kind], status: `${all.length} forge${all.length === 1 ? "" : "s"} sent`, rows, actions }; | |
| 427 | if (lines.length > SENT_ROWS) rows.push({ label: "More", value: `${lines.length - SENT_ROWS} more not shown` }); | |
| 428 | return { kind, title: CARD_TITLE[kind], status: `${lines.length} forge${lines.length === 1 ? "" : "s"} sent`, rows, actions }; | |
| 435 | 429 | } |
| 436 | 430 | if (tool === "asks_act") { |
| 437 | 431 | // Only a done bulk action has a card: its receipt, and the undo that takes it back. |
test/client-list.test.ts +12 −12
| @@ -67,7 +67,7 @@ describe("the client list", () => { | ||
| 67 | 67 | }, |
| 68 | 68 | body: JSON.stringify(body), |
| 69 | 69 | }); |
| 70 | const mcp = (token: string) => | |
| 70 | const mcp = (token: string, args: Record<string, unknown> = {}) => | |
| 71 | 71 | fetch(`${parentServers.url}/mcp`, { |
| 72 | 72 | method: "POST", |
| 73 | 73 | headers: { |
| @@ -79,7 +79,7 @@ describe("the client list", () => { | ||
| 79 | 79 | jsonrpc: "2.0", |
| 80 | 80 | id: 1, |
| 81 | 81 | method: "tools/call", |
| 82 | params: { name: "forges", arguments: {} }, | |
| 82 | params: { name: "forges", arguments: args }, | |
| 83 | 83 | }), |
| 84 | 84 | }); |
| 85 | 85 | |
| @@ -179,11 +179,11 @@ describe("the client list", () => { | ||
| 179 | 179 | // The parent, asking with the secret it kept, does. |
| 180 | 180 | // What it says is what a person did there (#12262): the forge's own boot and telemetry are |
| 181 | 181 | // not that. |
| 182 | let rows = (await (await mcp(adminRw)).json()) as any; | |
| 183 | expect(JSON.parse(rows.result.content[0].text).forges.find((f: any) => f.name === "maria").lastActivityAt).toBeNull(); | |
| 182 | let rows = (await (await mcp(adminRw, { name: "maria" })).json()) as any; | |
| 183 | expect(JSON.parse(rows.result.content[0].text).lastActivityAt).toBeNull(); | |
| 184 | 184 | child.db.run("INSERT INTO session (token_hash, user_id, expires_at) SELECT 'sign-in-1', id, '2099-01-01T00:00:00.000Z' FROM user WHERE kind = 'user' AND is_agent = 0 LIMIT 1"); |
| 185 | rows = (await (await mcp(adminRw)).json()) as any; | |
| 186 | const maria = JSON.parse(rows.result.content[0].text).forges.find((f: any) => f.name === "maria"); | |
| 185 | rows = (await (await mcp(adminRw, { name: "maria" })).json()) as any; | |
| 186 | const maria = JSON.parse(rows.result.content[0].text); | |
| 187 | 187 | expect(typeof maria.lastActivityAt).toBe("string"); |
| 188 | 188 | // The secret itself is never in an answer. |
| 189 | 189 | expect(rows.result.content[0].text).not.toMatch(/status|secret/i); |
| @@ -308,9 +308,9 @@ describe("the client list", () => { | ||
| 308 | 308 | } |
| 309 | 309 | expect(row).toMatch(/data-claimed="yes"/); |
| 310 | 310 | expect(row).not.toContain("claim-link"); |
| 311 | const tool = (await (await mcp(adminRw)).json()) as any; | |
| 312 | const value = JSON.parse(tool.result.content[0].text); | |
| 313 | const rows = Object.fromEntries(value.forges.map((f: any) => [f.name, f])); | |
| 311 | // The list is a line a forge; each whole row is one `name` away. | |
| 312 | const readRow = async (name: string) => JSON.parse(((await (await mcp(adminRw, { name })).json()) as any).result.content[0].text); | |
| 313 | const rows = { maria: await readRow("maria"), lou: await readRow("lou") }; | |
| 314 | 314 | expect(rows.maria.for).toBe("Maria's bakery"); |
| 315 | 315 | expect(rows.maria.apps).toEqual(["alice/bakery"]); |
| 316 | 316 | expect(rows.maria.claimed).toBe(true); |
| @@ -329,8 +329,8 @@ describe("the client list", () => { | ||
| 329 | 329 | return /not claimed yet|no everyday account yet|no tell yet|going: last tell|has not reported yet/.exec(row)?.[0]; |
| 330 | 330 | }; |
| 331 | 331 | const mariaStep = async () => { |
| 332 | const tool = (await (await mcp(adminRw)).json()) as any; | |
| 333 | return JSON.parse(tool.result.content[0].text).forges.find((f: any) => f.name === "maria").nextStep; | |
| 332 | const tool = (await (await mcp(adminRw, { name: "maria" })).json()) as any; | |
| 333 | return JSON.parse(tool.result.content[0].text).nextStep; | |
| 334 | 334 | }; |
| 335 | 335 | // The claim made the child's person an admin; nothing else yet. |
| 336 | 336 | // clientRows copies the beat's firstTellAt onto the row: none told yet reads "not yet". |
| @@ -386,7 +386,7 @@ describe("the client list", () => { | ||
| 386 | 386 | const body = (await api.json()) as { items: any[]; next_cursor: null }; |
| 387 | 387 | expect(body.next_cursor).toBeNull(); |
| 388 | 388 | const tool = (await (await mcp(adminRw)).json()) as any; |
| 389 | const forges = JSON.parse(tool.result.content[0].text).forges as any[]; | |
| 389 | const forges = (JSON.parse(tool.result.content[0].text).forges as string[]).map((line) => ({ name: line.split(" | ")[0] })); | |
| 390 | 390 | // Same rows; their order depends on each child's cached activity, which can age out between the |
| 391 | 391 | // two asks on a slow machine (maria, from an earlier test, is unreachable here), so only the |
| 392 | 392 | // set is compared. |
test/client-states.test.ts +17 −2
| @@ -14,6 +14,10 @@ import { forgeLines } from "../src/tui/screens/forges.ts"; | ||
| 14 | 14 | import { clientRows, orderRows, STAGE_WORDS, useChildFetch, STALE_WORDS, stageOf, type ClientRow } from "../src/spawn/clients.ts"; |
| 15 | 15 | import { forgeRow } from "../src/web/pages/forges.ts"; |
| 16 | 16 | import { tool } from "../src/http/mcp/tools/forges.ts"; |
| 17 | import { createToken } from "../src/core/tokens.ts"; | |
| 18 | import { createUser } from "../src/core/users.ts"; | |
| 19 | import { serve } from "../src/http/server.ts"; | |
| 20 | import { mcpTool } from "./helpers/mcp.ts"; | |
| 17 | 21 | |
| 18 | 22 | const NOW = Date.parse("2026-11-10T12:00:00Z"); |
| 19 | 23 | const DAY = 86_400_000; |
| @@ -106,8 +110,19 @@ describe("client states", () => { | ||
| 106 | 110 | ); |
| 107 | 111 | useChildFetch(app, async () => Response.json({ claimed: false, link: { state: "open", revokedAt: null, usedAt: null } })); |
| 108 | 112 | const [row] = await clientRows(app); |
| 109 | const out = (await tool.run({ app } as never, { isAdmin: true } as never, {})) as { ok: true; value: any }; | |
| 110 | const got = (out.value.forges ?? out.value.value?.forges ?? JSON.parse(JSON.stringify(out)).forges ?? [])[0]; | |
| 113 | // Over MCP as an admin: the list's line, then the whole row by name. | |
| 114 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "alice@f.dev", password: "a-good-passphrase", adminIfFirst: true }); | |
| 115 | if (!made.ok) throw new Error(made.error); | |
| 116 | const token = createToken(app.db, made.value.id, "admin", "admin").token; | |
| 117 | const servers = await serve(app); | |
| 118 | let got: any; | |
| 119 | try { | |
| 120 | const list = await mcpTool(servers.url, token, "forges"); | |
| 121 | expect(list.value.forges[0]).toStartWith(`kid | ${STALE_WORDS}`); | |
| 122 | got = (await mcpTool(servers.url, token, "forges", { name: "kid" })).value; | |
| 123 | } finally { | |
| 124 | servers.stop(); | |
| 125 | } | |
| 111 | 126 | expect(got.stage).toEqual({ ...row!.stage!, at: got.stage.at }); |
| 112 | 127 | expect(got.stage.words.startsWith(STALE_WORDS)).toBe(true); |
| 113 | 128 | expect(got.stage.href).toBe(row!.url); |
test/family-heartbeat.test.ts +2 −2
| @@ -470,9 +470,9 @@ describe("family heartbeats", () => { | ||
| 470 | 470 | accept: "application/json, text/event-stream", |
| 471 | 471 | authorization: `Bearer ${createToken(parent.db, alice.id, "mcp", "rw").token}`, |
| 472 | 472 | }, |
| 473 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "forges", arguments: {} } }), | |
| 473 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "forges", arguments: { name: "maria" } } }), | |
| 474 | 474 | }); |
| 475 | 475 | const out = JSON.parse(((await res.json()) as any).result.content[0].text); |
| 476 | expect(out.forges.find((f: any) => f.name === "maria")).toMatchObject({ spendTodayUsd: 8.5, ceilingUsd: 10 }); | |
| 476 | expect(out).toMatchObject({ spendTodayUsd: 8.5, ceilingUsd: 10 }); | |
| 477 | 477 | }); |
| 478 | 478 | }); |
test/forges-compact.test.ts added +107
| @@ -0,0 +1,107 @@ | ||
| 1 | /** | |
| 2 | * MCP `forges` lists a line a forge (#16840 follow-up): on production its two dozen whole rows | |
| 3 | * were 54 KB, more than Talk's agent reads of one answer. A hundred forges sent now answer in | |
| 4 | * about 6 KB, "name | state | version | billing" with the address once as a pattern, and `name` | |
| 5 | * reads one forge's whole row. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 8 | import { mkdirSync, writeFileSync } from "node:fs"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { forgeBilling } from "../src/spawn/client_words.ts"; | |
| 14 | import { useChildFetch } from "../src/spawn/clients.ts"; | |
| 15 | import { createToken } from "../src/core/tokens.ts"; | |
| 16 | import { createUser } from "../src/core/users.ts"; | |
| 17 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 18 | import { mcpTool } from "./helpers/mcp.ts"; | |
| 19 | import { quietLogs } from "./helpers/globals.ts"; | |
| 20 | ||
| 21 | quietLogs(); | |
| 22 | ||
| 23 | let dataDir = ""; | |
| 24 | let app: App; | |
| 25 | let servers: Servers; | |
| 26 | let token = ""; | |
| 27 | ||
| 28 | beforeAll(async () => { | |
| 29 | dataDir = await mkdtemp(join(tmpdir(), "forge-forges-compact-")); | |
| 30 | app = createApp({ dataDir, port: 0 }); | |
| 31 | mkdirSync(join(dataDir, "spawn"), { recursive: true }); | |
| 32 | const DAY = 86_400_000; | |
| 33 | for (let i = 0; i < 100; i++) { | |
| 34 | const name = `client-${String(i).padStart(3, "0")}`; | |
| 35 | writeFileSync( | |
| 36 | join(dataDir, "spawn", `${name}.json`), | |
| 37 | JSON.stringify({ | |
| 38 | name, | |
| 39 | bodyId: `cell-${name}`, | |
| 40 | done: true, | |
| 41 | placement: "hosted", | |
| 42 | size: i % 3 === 0 ? "large" : "small", | |
| 43 | apps: ["morning-paper"], | |
| 44 | forWhom: `Person ${i}`, | |
| 45 | createdAt: new Date(Date.now() - (i % 9) * DAY).toISOString(), | |
| 46 | }), | |
| 47 | ); | |
| 48 | } | |
| 49 | useChildFetch(app, async () => Response.json({ claimed: false, link: { state: "open", revokedAt: null, usedAt: null } })); | |
| 50 | servers = await serve(app); | |
| 51 | const made = await createUser(app.db, { | |
| 52 | origin: "seed", | |
| 53 | trusted: true, | |
| 54 | username: "alice", | |
| 55 | email: "[email protected]", | |
| 56 | password: "a-good-passphrase", | |
| 57 | adminIfFirst: true, | |
| 58 | }); | |
| 59 | if (!made.ok) throw new Error("user"); | |
| 60 | token = createToken(app.db, made.value.id, "admin", "admin").token; | |
| 61 | }, 60_000); | |
| 62 | ||
| 63 | afterAll(async () => { | |
| 64 | servers.stop(); | |
| 65 | app.close(); | |
| 66 | await rm(dataDir, { recursive: true, force: true }); | |
| 67 | }); | |
| 68 | ||
| 69 | test("a hundred forges answer a line each, about 6 KB, unopened links first", async () => { | |
| 70 | const said = await mcpTool(servers.url, token, "forges"); | |
| 71 | expect(said.error).toBeUndefined(); | |
| 72 | expect(Buffer.byteLength(JSON.stringify(said.value))).toBeLessThan(6_000); | |
| 73 | expect(said.value.says).toBe("100 forges sent from here."); | |
| 74 | expect(said.value.forges).toHaveLength(100); | |
| 75 | expect(said.value.url).toContain("<name>"); | |
| 76 | const resent = said.value.forges.findIndex((l: string) => l.includes("Not opened in 3 days")); | |
| 77 | const fresh = said.value.forges.findIndex((l: string) => l.includes("Link not opened")); | |
| 78 | expect(resent).toBe(0); | |
| 79 | expect(fresh).toBeGreaterThan(resent); | |
| 80 | expect(said.value.forges.find((l: string) => l.startsWith("client-003 | "))).toMatch( | |
| 81 | /^client-003 \| Not opened in 3 days, sent [A-Z][a-z]{2} \d{1,2} \| - \| -$/, | |
| 82 | ); | |
| 83 | expect(said.value.columns).toBe("name | state | version | billing"); | |
| 84 | expect(said.value.detail).toBe("name: one forge's whole row"); | |
| 85 | }); | |
| 86 | ||
| 87 | test("name reads one forge's whole row; a name never sent is not found", async () => { | |
| 88 | const one = await mcpTool(servers.url, token, "forges", { name: "client-042" }); | |
| 89 | expect(one.value).toMatchObject({ name: "client-042", for: "Person 42", size: "large", placement: "hosted" }); | |
| 90 | expect(one.value.stage.words).toBeDefined(); | |
| 91 | expect((await mcpTool(servers.url, token, "forges", { name: "nobody" })).error).toContain("No forge of that name"); | |
| 92 | }); | |
| 93 | ||
| 94 | test("billing in a few words: the month against a cap, what is lent, or a dash", () => { | |
| 95 | const base = { ceilingUsd: null, creditCapUsd: null, creditSpentUsd: null }; | |
| 96 | expect(forgeBilling({ ...base, month: null })).toBe("-"); | |
| 97 | expect(forgeBilling({ ...base, month: { ok: true, month: "2026-11", entries: 3, usd_tokens: 0.128 }, ceilingUsd: 50 })).toBe( | |
| 98 | "$0.13 this month of a $50.00 cap", | |
| 99 | ); | |
| 100 | expect(forgeBilling({ ...base, month: { ok: false, at: "x", why: "could not be read" } })).toBe( | |
| 101 | "its ledger is broken (could not be read)", | |
| 102 | ); | |
| 103 | expect(forgeBilling({ ...base, month: { ok: true, month: "2026-11", entries: 0 }, creditCapUsd: 20, creditSpentUsd: 4.5 })).toBe( | |
| 104 | "$0.00 this month; lent $4.50 of $20.00", | |
| 105 | ); | |
| 106 | expect(forgeBilling({ ...base, month: null, creditCapUsd: 20, creditSpentUsd: 0 })).toBe("lent $0.00 of $20.00"); | |
| 107 | }); |
test/forges-kept.test.ts +7 −4
| @@ -85,13 +85,16 @@ describe("on /forges and over MCP", () => { | ||
| 85 | 85 | expect(rowOf("kept").match(/data-backed-up/g)?.length).toBe(1); |
| 86 | 86 | }); |
| 87 | 87 | |
| 88 | test("the forges MCP listing carries the same words", async () => { | |
| 88 | const read = async (name: string) => { | |
| 89 | 89 | const res = await fetch(`${servers.url}/mcp`, { |
| 90 | 90 | method: "POST", |
| 91 | 91 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` }, |
| 92 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "forges", arguments: {} } }), | |
| 92 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "forges", arguments: { name } } }), | |
| 93 | 93 | }); |
| 94 | const forges = JSON.parse(((await res.json()) as any).result.content[0].text).forges as { name: string; kept?: string }[]; | |
| 95 | expect(Object.fromEntries(forges.map((f) => [f.name, f.kept]))).toEqual({ kept: "kept 5 h ago", fresh: "never kept" }); | |
| 94 | return JSON.parse(((await res.json()) as any).result.content[0].text) as { name: string; kept?: string }; | |
| 95 | }; | |
| 96 | test("the forges MCP read of a forge carries the same words", async () => { | |
| 97 | expect((await read("kept")).kept).toBe("kept 5 h ago"); | |
| 98 | expect((await read("fresh")).kept).toBe("never kept"); | |
| 96 | 99 | }); |
| 97 | 100 | }); |
test/forges-month-ledger.test.ts +4 −3
| @@ -167,15 +167,16 @@ test("the MCP forges tool carries month on each row", async () => { | ||
| 167 | 167 | servers = await serve(parent); |
| 168 | 168 | const tok = createToken(parent.db, aliceId, "rw", "rw").token; |
| 169 | 169 | try { |
| 170 | const call = async () => { | |
| 170 | const read = async (name: string) => { | |
| 171 | 171 | const res = await fetch(`${servers.url}/mcp`, { |
| 172 | 172 | method: "POST", |
| 173 | 173 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${tok}` }, |
| 174 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "forges", arguments: {} } }), | |
| 174 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "forges", arguments: { name } } }), | |
| 175 | 175 | }); |
| 176 | 176 | const j = (await res.json()) as any; |
| 177 | return Object.fromEntries(JSON.parse(String(j.result.content[0].text)).forges.map((f: any) => [f.name, f])); | |
| 177 | return JSON.parse(String(j.result.content[0].text)); | |
| 178 | 178 | }; |
| 179 | const call = async () => ({ one: await read("one"), two: await read("two") }); | |
| 179 | 180 | await call(); |
| 180 | 181 | await monthsSettled(parent); |
| 181 | 182 | const by = await call(); |
test/mcp-forges-card.test.ts +15 −17
| @@ -1,4 +1,4 @@ | ||
| 1 | /** MCP `forges` draws the `ui://forge/forges` card: a row per forge sent, resend first, text kept as plain data. */ | |
| 1 | /** MCP `forges` draws the `ui://forge/forges` card: a row per forge line, resend first, text kept as plain data. */ | |
| 2 | 2 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 3 | 3 | import { mkdirSync, writeFileSync } from "node:fs"; |
| 4 | 4 | import { mkdtemp, rm } from "node:fs/promises"; |
| @@ -14,7 +14,6 @@ import { quietLogs } from "./helpers/globals.ts"; | ||
| 14 | 14 | |
| 15 | 15 | quietLogs(); |
| 16 | 16 | |
| 17 | const row = (name: string, url: string, who: string | null, stage: { words: string; resend: boolean } | null) => ({ name, url, for: who, stage }); | |
| 18 | 17 | |
| 19 | 18 | describe("MCP forges card", () => { |
| 20 | 19 | test("forges maps to a card titled Forges you sent", () => { |
| @@ -22,26 +21,24 @@ describe("MCP forges card", () => { | ||
| 22 | 21 | expect(cardFor("forges", { forges: [] })?.title).toBe("Forges you sent"); |
| 23 | 22 | }); |
| 24 | 23 | |
| 25 | test("one row per forge, resend first, stage in words, name linked", () => { | |
| 24 | test("one row per line, in the tool's order, the address from the pattern or the line's own", () => { | |
| 26 | 25 | const card = cardFor("forges", { |
| 26 | url: "https://<name>.example", | |
| 27 | 27 | forges: [ |
| 28 | row("alpha", "https://alpha.example", "Ann", { words: "Last tell", resend: false }), | |
| 29 | row("beta", "https://beta.example", "Bob", { words: "Not opened in 3 days", resend: true }), | |
| 30 | row("gamma", "https://gamma.example", null, { words: "Signed in", resend: false }), | |
| 31 | row("delta", "https://delta.example", "Dee", null), | |
| 28 | "beta | Not opened in 3 days, sent Nov 12 | 0.7.676 | -", | |
| 29 | "alpha | Crew working | 0.7.676 | $0.13 this month", | |
| 30 | "gamma | being made | - | - | https://elsewhere.example", | |
| 32 | 31 | ], |
| 33 | 32 | })!; |
| 34 | expect(card.status).toBe("4 forges sent"); | |
| 35 | expect(card.rows.map((r) => r.label)).toEqual(["beta", "alpha", "gamma", "delta"]); | |
| 36 | expect(card.rows[0]).toEqual({ label: "beta", value: "for Bob · resend", link: "https://beta.example" }); | |
| 37 | expect(card.rows[1]!.value).toBe("for Ann · last tell"); | |
| 38 | expect(card.rows[2]!.value).toBe("no one named · signed in"); | |
| 39 | expect(card.rows[3]!.value).toBe("for Dee · being made"); | |
| 40 | expect(cardFor("forges", { forges: [row("a", "https://a.example", "x", null)] })!.status).toBe("1 forge sent"); | |
| 33 | expect(card.status).toBe("3 forges sent"); | |
| 34 | expect(card.rows.map((r) => r.label)).toEqual(["beta", "alpha", "gamma"]); | |
| 35 | expect(card.rows[0]).toEqual({ label: "beta", value: "Not opened in 3 days, sent Nov 12 · 0.7.676", link: "https://beta.example" }); | |
| 36 | expect(card.rows[2]).toEqual({ label: "gamma", value: "being made", link: "https://elsewhere.example" }); | |
| 37 | expect(cardFor("forges", { url: "https://<name>.example", forges: ["a | Signed in | 0.7.1 | -"] })!.status).toBe("1 forge sent"); | |
| 41 | 38 | }); |
| 42 | 39 | |
| 43 | 40 | test("text stays plain data and only http(s) addresses link", () => { |
| 44 | const card = cardFor("forges", { forges: [row("<img src=x onerror=1>", "javascript:alert(1)", "<b>me</b>", { words: "Sent", resend: false })] })!; | |
| 41 | const card = cardFor("forges", { url: "javascript:alert(<name>)", forges: ["<img src=x onerror=1> | Sent | 0.7.1 | <b>me</b>"] })!; | |
| 45 | 42 | expect(card.rows[0]!.label).toBe("<img src=x onerror=1>"); |
| 46 | 43 | expect(card.rows[0]!.link).toBeUndefined(); |
| 47 | 44 | expect(SHELL_JS).not.toContain("innerHTML"); |
| @@ -49,6 +46,7 @@ describe("MCP forges card", () => { | ||
| 49 | 46 | |
| 50 | 47 | test("a plan or code answer has no card", () => { |
| 51 | 48 | expect(cardFor("forges", { plan: "small" })).toBeUndefined(); |
| 49 | expect(cardFor("forges", { name: "alpha", url: "https://alpha.example" })).toBeUndefined(); | |
| 52 | 50 | }); |
| 53 | 51 | |
| 54 | 52 | describe("over MCP", () => { |
| @@ -98,8 +96,8 @@ describe("MCP forges card", () => { | ||
| 98 | 96 | expect(ok.structuredContent.card.status).toBe("2 forges sent"); |
| 99 | 97 | const rows = ok.structuredContent.card.rows; |
| 100 | 98 | expect(rows.map((r: any) => r.label)).toEqual(["beta", "alpha"]); |
| 101 | expect(rows[0].value).toBe("for Bob · resend"); | |
| 102 | expect(rows[1].value).toBe("for Ann · link not opened"); | |
| 99 | expect(rows[0].value).toStartWith("Not opened in 3 days"); | |
| 100 | expect(rows[1].value).toStartWith("Link not opened"); | |
| 103 | 101 | const no = await call(bobToken); |
| 104 | 102 | expect(no.isError).toBe(true); |
| 105 | 103 | expect(no.structuredContent?.card).toBeUndefined(); |
test/mcp-forges-usage.test.ts +6 −4
| @@ -22,11 +22,11 @@ let servers: Servers; | ||
| 22 | 22 | let token: string; |
| 23 | 23 | let rest: any; |
| 24 | 24 | |
| 25 | const forges = async (tok: string) => { | |
| 25 | const forges = async (tok: string, args: Record<string, unknown> = {}) => { | |
| 26 | 26 | const res = await fetch(`${servers.url}/mcp`, { |
| 27 | 27 | method: "POST", |
| 28 | 28 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${tok}` }, |
| 29 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "forges", arguments: {} } }), | |
| 29 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "forges", arguments: args } }), | |
| 30 | 30 | }); |
| 31 | 31 | const j = (await res.json()) as any; |
| 32 | 32 | return { error: j.result.isError === true, body: JSON.parse(String(j.result.content[0].text)) }; |
| @@ -53,10 +53,12 @@ afterAll(async () => { | ||
| 53 | 53 | await rm(dir, { recursive: true, force: true }); |
| 54 | 54 | }); |
| 55 | 55 | |
| 56 | test("each forge item carries its size and use", async () => { | |
| 56 | test("each forge's row carries its size and use, and its line its size", async () => { | |
| 57 | 57 | const { error, body } = await forges(token); |
| 58 | 58 | expect(error).toBe(false); |
| 59 | const by = Object.fromEntries(body.forges.map((f: any) => [f.name, f])); | |
| 59 | expect(body.forges.some((l: string) => l.startsWith("cell-kid | "))).toBe(true); | |
| 60 | const by: Record<string, any> = {}; | |
| 61 | for (const name of ["hosted-kid", "cell-kid"]) by[name] = (await forges(token, { name })).body; | |
| 60 | 62 | expect(by["hosted-kid"].size).toBe("small"); |
| 61 | 63 | expect(by["hosted-kid"].use).toEqual({ kind: "shared" }); |
| 62 | 64 | expect(by["cell-kid"].size).toBe("medium"); |
test/mcp-telemetry-history.test.ts +40 −20
| @@ -73,28 +73,49 @@ describe("telemetry_history over MCP", () => { | ||
| 73 | 73 | await rm(dataDir, { recursive: true, force: true }); |
| 74 | 74 | }); |
| 75 | 75 | |
| 76 | test("an admin reads the seeded samples", async () => { | |
| 76 | test("the default is a summary of each series, a few kilobytes, from the raw samples", async () => { | |
| 77 | 77 | const r = await tool(admin, { hours: 1 }); |
| 78 | expect(r.value.hours).toBe(1); | |
| 79 | expect(r.value.points.length).toBeGreaterThan(200); | |
| 80 | expect(r.value.points[0]).toMatchObject({ target: "node", cpuCores: 1.5, memoryBytes: 1000, load: 0.5 }); | |
| 81 | }); | |
| 82 | ||
| 83 | test("the default is six hours and a long window is bounded", async () => { | |
| 78 | expect(r.value).toMatchObject({ hours: 1, stepSeconds: 15 }); | |
| 79 | const node = r.value.series.node; | |
| 80 | expect(node.samples).toBeGreaterThan(200); | |
| 81 | expect(node.cpuCores).toMatchObject({ last: 1.5, min: 1.5, p95: 1.5 }); | |
| 82 | expect(node.memoryGiB.last).toBeCloseTo(1000 / 2 ** 30, 2); | |
| 83 | expect(node.load).toEqual({ last: 0.5, min: 0.5, max: 0.5, p95: 0.5 }); | |
| 84 | expect(node.points.at).toHaveLength(node.points.cpuCores.length); | |
| 85 | expect(node.points.at.length).toBeLessThanOrEqual(12); | |
| 86 | expect(r.value.series.forge).toMatchObject({ samples: 0, cpuCores: { last: null } }); | |
| 87 | expect(r.value.detail).toContain('series: "node" or "forge"'); | |
| 84 | 88 | expect((await tool(admin)).value.hours).toBe(6); |
| 85 | const day = await tool(admin, { hours: 24 }); | |
| 86 | expect(day.value.points.length).toBeLessThanOrEqual(300); | |
| 87 | const three = await tool(admin, { hours: 72 }); | |
| 88 | expect(three.value.points.length).toBeLessThanOrEqual(300); | |
| 89 | expect(three.value.points.length).toBeGreaterThan(0); | |
| 90 | expect(three.value.points[0].cpuCores).toBe(2); | |
| 91 | 89 | }); |
| 92 | 90 | |
| 93 | test("a bucket keeps its peak, so a short spike survives the mean", async () => { | |
| 94 | const day = await tool(admin, { hours: 24 }); | |
| 95 | const pts = day.value.points as { cpuCores: number; cpuCoresMax: number }[]; | |
| 96 | expect(Math.max(...pts.map((p) => p.cpuCoresMax))).toBe(9); | |
| 97 | expect(Math.max(...pts.map((p) => p.cpuCores))).toBeLessThan(9); | |
| 91 | test("a spike survives the summary in max and the peak; the p95 does not chase it", async () => { | |
| 92 | const day = (await tool(admin, { hours: 24 })).value.series.node; | |
| 93 | expect(day.cpuCores.max).toBe(9); | |
| 94 | expect(day.cpuCoresPeak).toBe(9); | |
| 95 | expect(day.cpuCores.p95).toBe(1.5); | |
| 96 | expect(Math.max(...day.points.cpuCoresMax)).toBe(9); | |
| 97 | }); | |
| 98 | ||
| 99 | test("a production-sized day of both series answers in under 6 KB; the old points ran to tens", async () => { | |
| 100 | const ins = app.db.query("INSERT INTO machine_sample (at, step, target, cpu_cores, memory_bytes, load) VALUES (?1, 15, 'forge', ?2, ?3, ?4)"); | |
| 101 | const now = Date.now(); | |
| 102 | for (let i = 0; i < 5_760; i++) ins.run(new Date(now - i * 15_000 - 7).toISOString(), 1 + (i % 7) / 3, 3e9 + i * 1e5, 0.4 + (i % 5) / 10); | |
| 103 | for (const hours of [6, 24, 72]) expect(Buffer.byteLength(JSON.stringify((await tool(admin, { hours })).value))).toBeLessThan(6_000); | |
| 104 | }); | |
| 105 | ||
| 106 | test("a named series is its points, capped, and says how", async () => { | |
| 107 | const d = (await tool(admin, { hours: 24, series: "node" })).value; | |
| 108 | expect(d).toMatchObject({ hours: 24, series: "node", cap: 150 }); | |
| 109 | expect(d.at.length).toBeLessThanOrEqual(150); | |
| 110 | expect(d.cpuCores).toHaveLength(d.at.length); | |
| 111 | expect(Math.max(...d.cpuCoresMax)).toBe(9); | |
| 112 | expect(d.says).toMatch(/^\d+ samples averaged into \d+ points \(at most 150\)/); | |
| 113 | expect(Buffer.byteLength(JSON.stringify(d))).toBeLessThan(12_000); | |
| 114 | const three = (await tool(admin, { hours: 72, series: "node" })).value; | |
| 115 | expect(three.stepSeconds).toBe(300); | |
| 116 | expect(three.cpuCores[0]).toBe(2); | |
| 117 | expect((await tool(admin, { series: "disk" })).error).toContain("series is node or forge"); | |
| 118 | expect((await tool(admin, { series: 1 })).error).toBeTruthy(); | |
| 98 | 119 | }); |
| 99 | 120 | |
| 100 | 121 | test("brief is one value an hour a target, small enough to chart", async () => { |
| @@ -105,10 +126,9 @@ describe("telemetry_history over MCP", () => { | ||
| 105 | 126 | expect(r.value.at[0]).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}$/); |
| 106 | 127 | expect(r.value.node.cpuCores).toHaveLength(r.value.at.length); |
| 107 | 128 | expect(r.value.node.memoryGiB).toHaveLength(r.value.at.length); |
| 108 | expect(r.value.forge.load.every((v: number | null) => v === null)).toBe(true); | |
| 129 | expect(r.value.forge.load).toHaveLength(r.value.at.length); | |
| 109 | 130 | // A day is about a kilobyte, where its points run to tens of kilobytes. |
| 110 | 131 | 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 | 132 | expect((await tool(admin, { hours: 1, brief: "yes" })).error).toBeTruthy(); |
| 113 | 133 | }); |
| 114 | 134 |
test/spawn-in-process-visible.test.ts +4 −3
| @@ -276,9 +276,10 @@ describe("a parent holding a forge in its own process", () => { | ||
| 276 | 276 | says: IN_PROCESS_WORDS, |
| 277 | 277 | movable: true, held: false |
| 278 | 278 | }); |
| 279 | const forges = await mcpTool(servers.url, token, "forges"); | |
| 280 | expect(forges.value.forges[0].placement).toBe("hosted"); | |
| 281 | expect(forges.value.forges[0].where.inProcess).toBe(true); | |
| 279 | // The list is a line a forge; its whole row, placement and all, is one `name` away. | |
| 280 | const forges = await mcpTool(servers.url, token, "forges", { name: row!.name }); | |
| 281 | expect(forges.value.placement).toBe("hosted"); | |
| 282 | expect(forges.value.where.inProcess).toBe(true); | |
| 282 | 283 | const api = await fetch(`${servers.url}/api/v1/forges`, { |
| 283 | 284 | headers: { authorization: `Bearer ${token}`, host: "forge.test" }, |
| 284 | 285 | }); |
test/spawn-reach-door.test.ts +3 −3
| @@ -120,10 +120,10 @@ test("/forges lists the same results, and the MCP spawn says it", async () => { | ||
| 120 | 120 | const forges = await fetch(`${servers.url}/mcp`, { |
| 121 | 121 | method: "POST", |
| 122 | 122 | headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, |
| 123 | body: JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "forges", arguments: {} } }), | |
| 123 | body: JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "forges", arguments: { name: "kid" } } }), | |
| 124 | 124 | }); |
| 125 | const body = JSON.parse(((await forges.json()) as any).result.content[0].text) as { forges: { name: string; reach: { ok: boolean } }[] }; | |
| 126 | expect(body.forges.find((f) => f.name === "kid")?.reach.ok).toBe(false); | |
| 125 | const body = JSON.parse(((await forges.json()) as any).result.content[0].text) as { name: string; reach: { ok: boolean } }; | |
| 126 | expect(body.reach.ok).toBe(false); | |
| 127 | 127 | }); |
| 128 | 128 | |
| 129 | 129 | test("/forges says Running, not reachable with each address and its result", async () => { |
test/spawn-template-record.test.ts +3 −4
| @@ -88,15 +88,14 @@ describe("a forge remembers its template", () => { | ||
| 88 | 88 | expect(madeFromOf(childDirOf(app, body.bodyId))).toEqual({ template: "alice/kit", at: sha }); |
| 89 | 89 | }, 60_000); |
| 90 | 90 | |
| 91 | test("the MCP forges read carries madeFrom on the spawned forge's row, no new tool", async () => { | |
| 91 | test("the MCP forges read of the spawned forge's row carries madeFrom, no new tool", async () => { | |
| 92 | 92 | const res = await fetch(`${base}/mcp`, { |
| 93 | 93 | method: "POST", |
| 94 | 94 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...auth }, |
| 95 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "forges", arguments: {} } }), | |
| 95 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "forges", arguments: { name: "kid" } } }), | |
| 96 | 96 | }); |
| 97 | 97 | const j = (await res.json()) as any; |
| 98 | const rows = JSON.parse(String(j.result.content[0].text)).forges as any[]; | |
| 99 | expect(rows.find((r) => r.name === "kid")?.madeFrom).toEqual({ template: "alice/kit", at: sha }); | |
| 98 | expect(JSON.parse(String(j.result.content[0].text)).madeFrom).toEqual({ template: "alice/kit", at: sha }); | |
| 100 | 99 | }, 30_000); |
| 101 | 100 | |
| 102 | 101 | const record = (template: unknown) => |
new above
offline