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

The Minecraft kind's console adapter answers /forge in game in under 300 ms, in rich text, and keeps a conversation #18533

opened this

Merged 2h 51m ago, live in production

scout/forge:scout/18466-the-minecraft-kind-s-console-adapter-ans → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/18466-the-minecraft-kind-s-console-adapter-ans was merged into main as b9e784c.

Review

Sign in to review this change.
11 files changed +210 −6
docs/features/game-forge-command.md added +15
@@ -0,0 +1,15 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: Game /forge command in rich text
4 ---
5 # /forge in the game
6
7 A player on a game box's proxy types `/forge …`; the proxy plugin hands it to the box's agent with the player's name and UUID as the proxy verified them, and the agent sends it in its heartbeat (`src/games/door.ts`, `src/games/chat.ts`). The forge answers in that same response when the answer is ready (a read or a question, within 250 ms), and at a later poll when it is the crew's.
8
9 - `/forge status` and `/forge servers`: reads, as the forge account the UUID is linked to.
10 - `/forge ask <words>`: starts a new Talk conversation. `/forge reply <words>`: continues the account's latest one on that box. Other words behave as before (`/forge clear`, a question, a plan with its confirmation).
11 - Every answer carries `component`: the kind's rich reply (`src/kinds/minecraft/speak.ts`), a gold [forge] prefix, grey lines (at most 6 of 120 characters, no § codes) and a [reply] click that only puts `/forge reply ` in the chat box. Somebody's words are only ever a `text` field, never a command. `text` stays beside it for a plugin that does not read `component`; the box's agent passes both on.
12 - Who the player is is the proxy's UUID, never a typed name: a name with another player's UUID is refused and its link dropped, and a name nobody linked reads nothing. The limits are the account's (5 commands and 30 reads a minute, 12 Talk turns a minute), counted when a command is accepted.
13 - The box's token stays with the agent; the plugin gets answers only.
14
15 No terminal screen: it is a command typed in the game; `src/tui/screens/games.ts` shows the servers.
src/games/agent.sh +1 −1
@@ -1623,7 +1623,7 @@ desk_heard() {
16231623 # not written again. The container says the number of each one it wrote; one it did not write comes
16241624 # again. One over 16 KiB never goes in, so it counts as had.
16251625 desk_told() {
1626 local state wrote put='def put: {id, uuid, text, confirm} + (if (.lines | type) == "array" then {lines} else {} end) | tojson; '
1626 local state wrote put='def put: {id, uuid, text, confirm} + (if (.lines | type) == "array" then {lines} else {} end) + (if (.component | type) == "object" then {component} else {} end) | tojson; '
16271627 desk_here && jq -e '(.told // []) | length > 0' >/dev/null 2>&1 <<<"$1" || return 0
16281628 state="$(desk_state)"
16291629 # shellcheck disable=SC2016
src/games/chat.ts +10 −2
@@ -39,6 +39,7 @@ import { composeServices, readCompose, serviceEnv } from "./compose.ts";
3939 import { asksIn, keepAsk, say, takeConfirmed, type Confirmed, type Where } from "./door.ts";
4040 import { holdBuild, type Holding } from "./door_hold.ts";
4141 import { doorOf, lockDoor, windowUsed } from "./write_window.ts";
42 import { defaultKind } from "../kinds/index.ts";
4243 import { readLines, readOf } from "./forge_read.ts";
4344 import { commitServer, planServer, wishOn } from "./presets.ts";
4445 import { peopleOf } from "./people.ts";
@@ -308,7 +309,12 @@ export function gameAsk(app: App, box: GameBox, sent: unknown, compose: string |
308309 const at: Where = { service, player: ask.player, ask: ask.id };
309310 if (ask.confirms === "") {
310311 if (service === "") say(app.db, box, at, ["Join a server of this network first, then ask again."], "");
311 else one(app, box, at, ask.words, compose, origin, now, { uuid: ask.uuid, confirmed: undefined });
312 else {
313 // The kind's own words (`/forge ask`, `/forge reply`); the rest is the door's as typed.
314 const heard = defaultKind().console.forge.hear(ask.words);
315 if ("refused" in heard) say(app.db, box, at, [heard.refused], "");
316 else one(app, box, at, heard.words, compose, origin, now, { uuid: ask.uuid, confirmed: undefined, fresh: heard.fresh });
317 }
312318 continue;
313319 }
314320 const confirmed = takeConfirmed(app.db, box, ask, now);
@@ -335,7 +341,7 @@ function one(
335341 compose: string,
336342 origin: string,
337343 now: number,
338 door?: { readonly uuid: string; readonly confirmed: Confirmed | undefined },
344 door?: { readonly uuid: string; readonly confirmed: Confirmed | undefined; readonly fresh?: boolean },
339345 ): void {
340346 const db = app.db;
341347 const { service, player } = at;
@@ -536,6 +542,8 @@ function one(
536542 if (!changesNetwork(app, user, box)) return refuse(user.id, "not an operator of the box", notBox(user, box));
537543 return later("plan", words);
538544 }
545 // `/forge ask` starts a new conversation: the kept pointer goes, so Talk makes one.
546 if (door?.fresh === true) db.query("DELETE FROM game_talk WHERE box_id = ?1 AND user_id = ?2").run(box.id, user.id);
539547 later("talk", words);
540548 }
541549
src/games/door.ts +7 −1
@@ -10,6 +10,7 @@
1010 */
1111
1212 import type { Database } from "bun:sqlite";
13 import { defaultKind } from "../kinds/index.ts";
1314 import { tell, type GameBox } from "./store.ts";
1415
1516 /** Where a player typed: the server they are on, and the request when it came from the proxy. */
@@ -110,6 +111,11 @@ export interface Told {
110111 readonly uuid: string;
111112 readonly text: string;
112113 readonly confirm: boolean;
114 /**
115 * The text as the player's chat shows it (the kind's rich reply); absent on a confirm, whose code
116 * the plugin shows itself. `text` stays for a plugin that does not read this.
117 */
118 readonly component?: unknown;
113119 }
114120
115121 /** Forgets the answers the box says it has; only ones it was handed. */
@@ -144,7 +150,7 @@ export function toldTo(db: Database, box: GameBox, now = Date.now(), got?: unkno
144150 // The plugin's code would outlive what the forge still takes.
145151 confirm === 1 && told_at !== "" && now - Date.parse(told_at) > CONFIRM_MS - CODE_MS
146152 ? { n, id, uuid, text: "The forge's question reached you too late to answer: ask again.", confirm: false }
147 : { n, id, uuid, text, confirm: confirm === 1 },
153 : { n, id, uuid, text, confirm: confirm === 1, ...(confirm === 1 ? {} : { component: defaultKind().console.forge.say(text.split("\n")) }) },
148154 );
149155 })();
150156 }
src/games/forge_read.ts +1 −1
@@ -22,7 +22,7 @@ export function readOf(words: string): Read | undefined {
2222 }
2323
2424 /** One line of somebody's text: no control characters, no colour codes, cut. */
25 const line = (text: string, most = 120): string => {
25 export const line = (text: string, most = 120): string => {
2626 const flat = text.replace(/§.?/gu, "").replace(/[\p{Cc}\s]+/gu, " ").trim();
2727 return flat.length <= most ? flat : `${flat.slice(0, most - 3)}...`;
2828 };
src/kinds/kind.ts +12
@@ -60,6 +60,18 @@ export interface ConsoleAdapter {
6060 crash(lines: readonly string[]): Crash | undefined;
6161 /** Publish a crash's text where anyone with the link can read it, at the person's own click. */
6262 share(app: App, text: string): Promise<{ ok: true; id: string } | { ok: false; error: string }>;
63 /**
64 * `/forge` in the game (#18466): what a player typed, and how the forge's lines reach their chat.
65 */
66 forge: {
outdated

Nothing in production calls forge. Wire it from the games door / agent heartbeat path and retire the plain tellraw text that does the same job.

67 /**
68 * The words after `/forge`: what the door is asked, and whether `ask` starts a new
69 * conversation.
70 */
71 hear(typed: string): { readonly words: string; readonly fresh: boolean } | { readonly refused: string };
72 /** The lines as the plugin shows them to the asking player: one Adventure component. */
73 say(lines: readonly string[]): unknown;
74 };
6375 }
6476
6577 /** A part not moved yet: it names where its code still lives. */
src/kinds/minecraft/command.ts added +18
@@ -0,0 +1,18 @@
1 /**
2 * `/forge` as a player types it (#18466). Only what is Minecraft's is here: the two words that
3 * choose a conversation. Everything else the proxy sends is the door's own (`games/chat.ts`: the
4 * account behind the player's UUID, their role, the limits, the reads, Talk).
5 *
6 * /forge ask <words> starts a new Talk conversation
7 * /forge reply <words> continues the player's latest one
8 * /forge <anything else> as typed: status, servers, help, clear, or words for the crew
9 */
10
11 /** What a player typed after `/forge`, as the door is asked it. */
12 export function hear(typed: string): { readonly words: string; readonly fresh: boolean } | { readonly refused: string } {
13 const [head = "", ...rest] = typed.trim().split(/\s+/);
14 const word = head.toLowerCase();
15 if (word !== "ask" && word !== "reply") return { words: typed.trim(), fresh: false };
16 const words = rest.join(" ");
17 return words === "" ? { refused: `Say what after /forge ${word}.` } : { words, fresh: word === "ask" };
18 }
src/kinds/minecraft/index.ts +3 −1
@@ -5,12 +5,14 @@
55
66 import type { Kind } from "../kind.ts";
77 import { consoleHtml, consoleText, crashOf, shareOnMclogs } from "./console.ts";
8 import { hear } from "./command.ts";
89 import { minecraftDesign } from "./compose.ts";
10 import { say } from "./speak.ts";
911
1012 export const minecraft: Kind = {
1113 name: "minecraft",
outdated

handler(door) needs a real door. ask and reply should reach Talk, with the player's verified identity, not a typed name.

1214 compose: { design: minecraftDesign },
13 console: { html: consoleHtml, text: consoleText, crash: crashOf, share: shareOnMclogs },
15 console: { html: consoleHtml, text: consoleText, crash: crashOf, share: shareOnMclogs, forge: { hear, say } },
1416 people: { stub: true, livesIn: "src/games/people.ts" },
1517 identity: { stub: true, livesIn: "src/core/proven_identities.ts" },
1618 metrics: { stub: true, livesIn: "src/games/metrics.ts" },
src/kinds/minecraft/speak.ts added +44
@@ -0,0 +1,44 @@
1 /**
2 * What `/forge` says back in the game (#18466): Adventure components (the JSON a proxy plugin hands
3 * to `Component.json`), never a string with § codes. Pure: lines in, one component out. Every reply
4 * starts with a coloured [forge] prefix, is private (the plugin sends it to the asking player only)
5 * and short (at most `MOST_LINES` lines of 120 characters). Hover shows where it came
6 * from; click-to-suggest puts a follow-up command in the player's chat box. Somebody's text is only
7 * ever a `text` field: never a command or an event.
8 */
9
10 import { line as plain } from "../../games/forge_read.ts";
11
12 interface Component {
13 readonly text: string;
14 readonly color?: string;
15 readonly bold?: boolean;
16 readonly hoverEvent?: { readonly action: "show_text"; readonly contents: string };
17 readonly clickEvent?: { readonly action: "suggest_command"; readonly value: string };
18 readonly extra?: readonly Component[];
19 }
20
21 /**
22 * One more than the lines the door writes at most (`LINES_OUT`), so a closing link is never cut.
23 */
24 const MOST_LINES = 6;
25
26 const prefix: Component = { text: "[forge] ", color: "gold", bold: true, hoverEvent: { action: "show_text", contents: "Said by your forge" } };
27
28 /**
29 * The click that puts `/forge reply ` in the player's chat box: a fixed command, never their
30 * text's.
31 */
32 const replyClick: Component = {
33 text: " [reply]",
34 color: "aqua",
35 hoverEvent: { action: "show_text", contents: "Click to type this" },
36 clickEvent: { action: "suggest_command", value: "/forge reply " },
37 };
38
39 /** A reply: the prefix, the lines (grey, cut), then the way on. */
40 export function say(lines: readonly string[]): Component {
41 const shown = lines.map((l) => plain(l)).filter((l) => l !== "").slice(0, MOST_LINES);
42 const body: Component[] = shown.map((l, i) => ({ text: i === 0 ? l : `\n${l}`, color: "gray" }));
43 return { text: "", extra: [prefix, ...body, replyClick] };
44 }
test/game-door.test.ts +62
@@ -21,6 +21,7 @@ import { readCompose } from "../src/games/compose.ts";
2121 import { CONFIRM_MS, toldTo } from "../src/games/door.ts";
2222 import { openWindow, setWindowMinutes } from "../src/games/write_window.ts";
2323 import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts";
24 import { kindNamed } from "../src/kinds/index.ts";
2425 import { forgeHttp, serve } from "../src/http/server.ts";
2526 import { chatAged } from "./helpers/game-chat-clock.ts";
2627 import { quietLogs } from "./helpers/globals.ts";
@@ -311,6 +312,28 @@ test("plain words reach Talk at once, the next words continue that conversation,
311312 expect(kinds(8)).toContain("clear");
312313 }, 30_000);
313314
315 test("/forge ask starts a new conversation, /forge reply continues the account's latest one", async () => {
316 // Its own account: Talk's per-minute limit is the account's, and the tests above spend Ada's.
317 const made = await createUser(app.db, { username: "op", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true });
318 if (!made.ok) throw new Error(made.error);
319 const op = made.value;
320 const uuid = "00000000-0000-4000-8000-0000000000b1";
321 app.db.query("INSERT INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, 'op_mc', ?2, ?3, '')").run(box.id, op.id, uuid);
322 grant(app.db, box.id, op.id, "operator");
323 const say = async (words: string): Promise<string> => (await send([request(words, { uuid, name: "op_mc" })]))[0]!.text;
324 expect(await say("ask why is the hub slow?")).toStartWith("Asked the crew");
325 const one = conversation(op);
326 expect(one).toBeDefined();
327 anHourOn();
328 expect(await say("reply and the nether?")).toStartWith("Asked the crew");
329 expect(conversation(op)).toBe(one);
330 anHourOn();
331 expect(await say("ask something else")).toStartWith("Asked the crew");
332 expect(conversation(op)).not.toBe(one);
333 anHourOn();
334 expect(await say("ask")).toBe("Say what after /forge ask.");
335 }, 30_000);
336
314337 test("a change in any phrasing goes to Talk as words, and the door itself changes nothing: no game command is queued", async () => {
315338 for (const words of ["can you restart the hub", "I want survival wiped", "gamemode creative"]) {
316339 anHourOn();
@@ -458,6 +481,45 @@ test("a read taken in a sync is answered in the same reply, not at the next poll
458481 app.db.query("DELETE FROM game_told").run();
459482 });
460483
484 test("a read taken in a sync comes back in the same reply as the kind's rich component, and the box's token is nowhere in it", async () => {
485 app.db
486 .query("INSERT OR REPLACE INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, 'ada', ?2, ?3, ?4)")
487 .run(box.id, ada.id, ADA, new Date().toISOString());
488 anHourOn();
489 const read = request("servers");
490 const res = await forgeHttp(app).handle(
491 new Request("http://forge.test/api/v1/games/agent/sync", {
492 method: "POST",
493 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
494 body: JSON.stringify({ agent: 1, light: true, told: true, got: [], ask: [read] }),
495 }),
496 );
497 const body = await res.text();
498 expect(body).not.toContain(token);
499 const { told } = JSON.parse(body) as { told: { id: string; text: string; component: unknown }[] };
500 expect(told[0]!.id).toBe(read.id);
501 expect(told[0]!.component).toEqual(kindNamed("minecraft")!.console.forge.say(["hub: running, 1 player"]));
502 expect(JSON.stringify(told[0]!.component)).toContain("[forge] ");
503 app.db.query("DELETE FROM game_told").run();
504 });
505
506 test("a typed name is not an identity: the proxy's UUID decides whose account answers", async () => {
507 app.db
508 .query("INSERT OR REPLACE INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, 'ada', ?2, ?3, ?4)")
509 .run(box.id, ada.id, ADA, new Date().toISOString());
510 anHourOn();
511 // Ada's name with another player's UUID reads nothing of Ada's and drops the link's claim to it.
512 const [spoof] = await send([request("status", { uuid: EVE })]);
513 expect(spoof!.text).toContain("was linked as another player");
514 expect(spoof!.text).not.toContain("The forge is up");
515 app.db.query("INSERT OR REPLACE INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, 'ada', ?2, ?3, ?4)").run(box.id, ada.id, ADA, new Date().toISOString());
516 anHourOn();
517 // Another name with Ada's UUID is a name nobody linked.
518 const [other] = await send([request("ask why is it slow?", { name: "eve" })]);
519 expect(other!.text).toContain("not linked");
520 expect(conversation()).toBeUndefined();
521 });
522
461523 test("the sync hands an agent that keeps one the proxy's snapshot: each linked player's own answers, once per version", async () => {
462524 app.db
463525 .query("INSERT OR REPLACE INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, 'ada', ?2, ?3, ?4)")
test/minecraft-command.test.ts added +37
@@ -0,0 +1,37 @@
1 /** `/forge` in the game (#18466): the words that choose a conversation, and the rich reply. */
2 import { expect, test } from "bun:test";
3 import { kindNamed } from "../src/kinds/index.ts";
4
5 const forge = kindNamed("minecraft")!.console.forge;
6 const json = (c: unknown): string => JSON.stringify(c);
7
8 test("ask starts a conversation, reply continues one, anything else goes to the door as typed", () => {
9 expect(forge.hear(" ask a void world ")).toEqual({ words: "a void world", fresh: true });
10 expect(forge.hear("Reply and the nether?")).toEqual({ words: "and the nether?", fresh: false });
11 expect(forge.hear("status")).toEqual({ words: "status", fresh: false });
12 expect(forge.hear("who is on?")).toEqual({ words: "who is on?", fresh: false });
13 expect(forge.hear("asking about it")).toEqual({ words: "asking about it", fresh: false });
14 });
15
16 test("ask and reply with no words are refused kindly", () => {
17 expect(forge.hear("ask")).toEqual({ refused: "Say what after /forge ask." });
18 expect(forge.hear("reply ")).toEqual({ refused: "Say what after /forge reply." });
19 });
20
21 test("a reply is one component: prefix, grey lines, a fixed click to /forge reply", () => {
22 const c = json(forge.say(["Up.", "Two servers."]));
23 expect(c).toContain('"text":"[forge] ","color":"gold","bold":true');
24 expect(c).toContain('"text":"\\nTwo servers.","color":"gray"');
25 expect(c).toContain('"action":"suggest_command","value":"/forge reply "');
26 expect(c).not.toContain("§");
27 });
28
29 test("somebody's text is only ever a text field, stripped of codes, controls and length", () => {
30 const c = json(forge.say(["§aHi\u0007 there", "x".repeat(300), ...Array.from({ length: 20 }, (_, i) => `line ${String(i)}`)]));
31 expect(c).toContain('"text":"Hi there"');
32 expect(c).not.toContain("§");
33 expect(c).not.toContain("x".repeat(121));
34 expect(c.match(/line \d+/g)?.length).toBe(4);
35 expect(c.match(/"clickEvent"/g)?.length).toBe(1);
36 expect(json(forge.say(["/op me"]))).toContain('"text":"/op me"');
37 });

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

Keyboard shortcuts

Docs