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

Game door: choose whether a game-door crew turn gets a restricted tool set #18220

opened this in answer to

Merged 6h 39m ago, live in production

scout/forge:scout/18218-game-door-choose-whether-a-game-door-cre → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/18218-game-door-choose-whether-a-game-door-cre was merged into main as 7ff8263.

Review

Sign in to review this change.
11 files changed +196 −9
docs/features/games.md +1 −1
@@ -94,7 +94,7 @@ A linked name that holds operator on the server it types on can also say:
9494
9595 - `!forge give me a new void world with FAWE and bedwars`: planned like `create_server` (see New servers), and the plan's lines and memory math come back in chat, then "type !forge yes within 5 minutes". `!forge yes` commits that plan as the linked account, or says "The box changed since the preview; preview it again." when the repository moved; `!forge no` drops it. A plan answers only the same name on the same server. It changes the whole network, so it takes operator of the box, asked at the plan, at the yes and again right before the commit; operator of one server is refused.
9696 - `!forge help`.
97 - `!forge <anything else>`: a Talk conversation of the linked account. The crew's first answer comes back in chat (its first lines, then a link to the conversation): nothing the account could not read on the forge itself. Through the proxy's `/forge` the words go to Talk at once, with no confirmation first. The door has exactly the authority Talk has on the web, no more: a linked player is that account (the proxy checks the Minecraft account, and the link binds its UUID), and the crew's turn is the forge's own agent for that account, so the forge's one policy applies. Every `games` action but `list` (restart, start, settings, console, mods, servers), every admin-scope tool and every irreversible or outward action (release, archive, delete, secrets, tokens) is held as a confirm that nothing runs until the account says yes in Talk with its own session; the reply's last lines say "Held for your yes: <what it would do> [Answer it](<Talk link>)". The rest of what the account may do (close, assign, edit, merge) runs at once with a receipt and an Undo in Talk; the reply says "Done: <what> [Undo](<link>)". The proxy's own confirmation (the player's code) stays for what the door itself does: linking, dropping a plan, building a new server. The player's next words continue the same conversation on that box, and the answer's last line is the link ("Open in Talk"). `/forge clear` ends it: the next words start a new one. Any role on the server may clear: it removes only that account's own pointer on that box, never a conversation or another account's. If the kept conversation is gone (archived or deleted), the next words start a new one and say so.
97 - `!forge <anything else>`: a Talk conversation of the linked account. The crew's first answer comes back in chat (its first lines, then a link to the conversation): nothing the account could not read on the forge itself. Through the proxy's `/forge` the words go to Talk at once, with no confirmation first. A linked player is that account (the proxy checks the Minecraft account, and the link binds its UUID). The conversation is limited to reads and the held `games` tool (#18218): whatever the words say, the crew cannot close, assign, edit, merge, write a file or tell from it; it says what it found and the change is made on the forge's own page. The limit stays on that conversation if the person later writes in it on the web, and covers conversations the game door opened before the limit existed. The proxy's own confirmation (the player's code) stays for what the door itself does: linking, dropping a plan, building a new server. The player's next words continue the same conversation on that box, and the answer's last line is the link ("Open in Talk"). `/forge clear` ends it: the next words start a new one. Any role on the server may clear: it removes only that account's own pointer on that box, never a conversation or another account's. If the kept conversation is gone (archived or deleted), the next words start a new one and say so.
9898
9999 Through the proxy's `/forge` a linked account, with a role on the box or without, can also say `/forge status` (the version that runs and what the crew does, read as that account by the MCP tools `now` and `releases`) and `/forge servers` (the servers it has a role on: state, players, memory). They are not answered in chat yet. Tested on Paper 1.21.6 and Fabric 1.21.6, offline servers with no plugin that logs commands: a `tellraw` over RCON reached only its player, and neither stdout nor latest.log kept it. With the questions asked through `/forge`, they have their own limit: 30 a minute and 600 an hour an account, 60 a minute a box. A question asked through the proxy before the release that added `game_chat.door` stays in the 5 and 30 for its hour. A question in chat stays one of the 5 and 30. `status` and `servers` do not wait behind a plan; a question does.
100100
src/core/conversation_door.ts added +26
@@ -0,0 +1,26 @@
1 /**
2 * Which door a conversation was opened through, when that door limits what its crew turns may do
3 * (#18218). The game door types words a server can show to anyone, so its turns run with reads and
4 * the held games tool only: no reversible write (close, assign, edit, merge, tell...) is reachable
5 * from words typed in game. Plain data in, plain data out; `http/mcp/shared.ts` enforces it.
6 */
7 import type { Database } from "bun:sqlite";
8
9 /**
10 * The one writing tool a game-door turn keeps: it asks the player first for anything but a list.
11 */
12 export const GAME_DOOR_WRITES: readonly string[] = ["games"];
13
14 /** Limits a conversation to reads plus the held games tool. */
15 export function limitToGame(db: Database, conversationId: string): void {
16 db.query("INSERT OR REPLACE INTO conversation_door (conversation_id, door) VALUES (?1, 'game')").run(conversationId);
17 }
18
19 /** Is the conversation this via token speaks for limited to reads and the games tool? */
20 export function viaLimited(db: Database, via: string): boolean {
21 const id = via.startsWith("conversation:") ? via.slice("conversation:".length) : "";
22 return db.query("SELECT 1 FROM conversation_door WHERE conversation_id = ?1").get(id) !== null;
23 }
24
25 /** May a limited conversation's turn call this tool? Reads always; a write only if named above. */
26 export const limitedMay = (tool: string, writes: boolean): boolean => !writes || GAME_DOOR_WRITES.includes(tool);
src/core/migration-pins/20261204120000-conversation-door.pin added +1
@@ -0,0 +1,1 @@
1 dfd8c317f685010af741fbe05b11bec437d2286169c787dc86739b1d21409a66
src/core/migration-pins/20261204130000-conversation-door-backfill.pin added +1
@@ -0,0 +1,1 @@
1 6935c7a5901b2726b16cfaec73843c2581cdbb485d09c4f121ad01fe9f0fb806
src/core/migrations/20261204120000-conversation-door.ts added +8
@@ -0,0 +1,8 @@
1 // A conversation a door limits (#18218): the game door's crew turns run with reads and the held
2 // games tool only. One row per limited conversation; absent means no limit. Additive.
3 export default `
4 CREATE TABLE conversation_door (
5 conversation_id TEXT PRIMARY KEY REFERENCES conversation(id) ON DELETE CASCADE,
6 door TEXT NOT NULL
7 );
8 `;
src/core/migrations/20261204130000-conversation-door-backfill.ts added +9
@@ -0,0 +1,9 @@
1 // Limit the game conversations that existed before the limit (#18218): the one each player
2 // continues on a box (`game_talk`) and the one each kept job asked in (`game_chat_job`), when it
3 // still exists. Idempotent; the table itself is 20261204120000.
4 export default `
5 INSERT OR IGNORE INTO conversation_door (conversation_id, door)
6 SELECT c.id, 'game' FROM conversation c
7 WHERE c.id IN (SELECT conversation FROM game_talk)
8 OR c.id IN (SELECT conversation FROM game_chat_job WHERE conversation <> '');
9 `;
src/games/chat.ts +4
@@ -27,6 +27,7 @@
2727 import type { App } from "../app.ts";
2828 import { waitingConfirms } from "../actions/conversation_confirms.ts";
2929 import { talk } from "../actions/talk.ts";
30 import { limitToGame } from "../core/conversation_door.ts";
3031 import { createConversation, listTurns } from "../core/conversations.ts";
3132 import { readReceipt } from "../crew/receipt.ts";
3233 import { publicOrigin } from "../core/public_origin.ts";
@@ -705,6 +706,9 @@ function ask(app: App, box: GameBox, job: Job, user: User): void {
705706 if (!conversation.ok)
706707 return finish(app, box, job, "too many conversations", ["You hold the most conversations the forge keeps: archive one on /talk first."], "red");
707708 id = conversation.value.id;
709 // Words typed in game may read and ask about servers, never reach a reversible write
710 // (#18218).
711 limitToGame(db, id);
708712 sent = into(id);
709713 }
710714 if (!sent.ok) return finish(app, box, job, sent.error, [`The crew could not take it: ${sent.error}.`], "red");
src/http/mcp.ts +3 −3
@@ -50,7 +50,7 @@ import { CONTRIBUTE_TOKEN_HINT, CONTRIBUTE_TOKEN_WORDS, mintContributeToken } fr
5050 import { BODY_MAX, REQUEST_MAX, TITLE_MAX } from "../core/reports.ts";
5151 import { adminRefusal, everydayOf } from "../core/everyday.ts";
5252 import { claimDone, completeWrite, dropWrite, recordWrite } from "../core/conversation_writes.ts";
53 import { type Args, badArgument, alreadyDone, notAdminTool, listable, visible, plansOnly, str, REPO_ARG, lean, fenceAnswer, heldWrite, askedFirst, destroysTo, readThrough, type ToolShape } from "./mcp/shared.ts";
53 import { type Args, badArgument, alreadyDone, notAdminTool, listable, visible, plansOnly, str, REPO_ARG, lean, fenceAnswer, heldWrite, askedFirst, limitedOut, destroysTo, readThrough, type ToolShape } from "./mcp/shared.ts";
5454 import { CONVERSATION_BRIEF } from "../crew/conversation_brief.ts";
5555 import { readWidget as readKept, recordCard, recordWidget, shownLine } from "../core/talk_voice.ts";
5656 import { stepOf } from "../core/talk_steps.ts";
@@ -353,7 +353,7 @@ function rpcOne(
353353 hint: hintOf(tool, refused.error),
354354 });
355355 const held =
356 tool === undefined || unlisted ? undefined : (askedFirst(ctx, user, tool, args) ?? heldWrite(ctx, user, tool, args));
356 tool === undefined || unlisted ? undefined : (limitedOut(ctx, tool, args) ?? askedFirst(ctx, user, tool, args) ?? heldWrite(ctx, user, tool, args));
357357 if (held !== undefined) return reply(held);
358358 if (tool === undefined || !visible(tool, ctx, user))
359359 return refuse(-32602, noToolNamed(String(params["name"])), NO_TOOL_HINT);
@@ -612,7 +612,7 @@ type FreeAnswer = { jsonrpc: string; id: unknown; result?: { content?: { type: s
612612 */
613613 async function gatedShortcut(ctx: Ctx, user: User, id: unknown, tool: ToolShape, args: Args, handler: FreeHandler): Promise<unknown> {
614614 const reply = (result: unknown) => ({ jsonrpc: "2.0", id, result });
615 const held = askedFirst(ctx, user, tool, args) ?? heldWrite(ctx, user, tool, args);
615 const held = limitedOut(ctx, tool, args) ?? askedFirst(ctx, user, tool, args) ?? heldWrite(ctx, user, tool, args);
616616 if (held !== undefined) return reply(held);
617617 if (!mayToolWrite(ctx, tool.name))
618618 return reply({ content: [{ type: "text", text: READ_ONLY_REFUSAL }], isError: true, hint: hintForCode("forbidden") });
src/http/mcp/shared.ts +15
@@ -20,6 +20,7 @@ import { BOARD_NOT_SAVED } from "../../actions/board_words.ts";
2020 import { askedFor, fence, fenceTag, fenceUp, hold, named, readFenced, supersedeHeld } from "../../core/fence.ts";
2121 import { laneUnheld } from "../../core/talk_lane.ts";
2222 import { appendTurn, conversationOfVia, proposalBefore } from "../../core/conversations.ts";
23 import { limitedMay, viaLimited } from "../../core/conversation_door.ts";
2324 import { writesThisTurn } from "../../core/conversation_writes.ts";
2425 import { argumentsShown, asksFirst, destroysData, destroysSentence, tooBigToApprove, undoableWork } from "../../crew/conversation_confirm.ts";
2526 import { confirmSentence, SAID_MAX } from "../../crew/conversation_ask.ts";
@@ -363,6 +364,20 @@ const tooBig = (tool: string): Record<string, unknown> => ({
363364 export const ASKS_FIRST =
364365 "this action asks the person first, so nothing was done: Do it and Not now buttons are already just above the message box; say the sentence in `does` to them and point at the buttons there; their yes, within 10 minutes, does it once";
365366
367 /** What a limited conversation's turn is told when it reaches for a write it may not make. */
368 export const DOOR_LIMITED =
369 "this conversation came from the game, where the crew only reads and asks about servers: nothing was done; say what you found, and that the change is made on the forge's own page";
370
371 /**
372 * A write the forge's agent may not make in a conversation its door limits (#18218): refused at
373 * once, before anything is held or done. Undefined: go on.
374 */
375 export function limitedOut(ctx: Ctx, tool: ToolShape, args: Args): Record<string, unknown> | undefined {
376 const via = ctx.auth.through;
377 if (via === undefined || limitedMay(tool.name, tool.writes === true && !plansOnly(tool, args)) || !viaLimited(ctx.app.db, via)) return undefined;
378 return { content: [{ type: "text", text: `forbidden: ${DOOR_LIMITED}` }], isError: true };
379 }
380
366381 /**
367382 * Asked first (#7650): for the forge's own agent, a call of a tool on the
368383 * list in `crew/conversation_confirm.ts` — and any call of an admin-scope
test/conversation-door.test.ts added +119
@@ -0,0 +1,119 @@
1 /**
2 * A conversation the game door opened is limited (#18218): its crew turns read, and keep the held
3 * games tool, but never reach a reversible write; a conversation from anywhere else is unchanged.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { limitedMay, limitToGame, viaLimited } from "../src/core/conversation_door.ts";
12 import { createConversation } from "../src/core/conversations.ts";
13 import migration from "../src/core/migrations/20261204130000-conversation-door-backfill.ts";
14 import { waitingFor } from "../src/core/fence.ts";
15 import { boxNamed, createGameBox } from "../src/games/store.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { mintViaToken } from "../src/core/via_token.ts";
18 import { DOOR_LIMITED } from "../src/http/mcp/shared.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20
21 let dir = "";
22 let app: App;
23 let servers: Servers;
24 let ada: User;
25 let rpcId = 1;
26
27 const call = async (token: string, name: string, args: Record<string, unknown>) => {
28 const res = await fetch(`${servers.url}/mcp`, {
29 method: "POST",
30 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
31 body: JSON.stringify({ jsonrpc: "2.0", id: rpcId++, method: "tools/call", params: { name, arguments: { ...args } } }),
32 });
33 const body: any = await res.json();
34 return { text: String(body.result?.content?.[0]?.text ?? ""), isError: body.result?.isError === true };
35 };
36
37 const tokenFor = (conversation: string): string => {
38 const minted = mintViaToken(app.db, ada.id, `conversation:${conversation}`, "", new Date(Date.now() + 600_000).toISOString());
39 if (!minted.ok) throw new Error(minted.error);
40 return minted.value.token;
41 };
42
43 beforeAll(async () => {
44 dir = await mkdtemp(join(tmpdir(), "forge-conversation-door-"));
45 app = createApp({ dataDir: dir, port: 0 });
46 servers = await serve(app);
47 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "ada", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
48 if (!u.ok) throw new Error(u.error);
49 ada = u.value;
50 createGameBox(app.db, { name: "mc" });
51 const box = boxNamed(app.db, "mc")!;
52 app.db
53 .query("INSERT INTO game_service (box_id, name, state, health, started_at, cpu_pct, mem_mib, seen_at, asleep, online_json) VALUES (?1, 'hub', 'running', '', '', 0, 0, '', 0, '[]')")
54 .run(box.id);
55 }, 30_000);
56
57 afterAll(async () => {
58 servers.stop();
59 app.close();
60 await rm(dir, { recursive: true, force: true });
61 });
62
63 test("a limited conversation keeps reads and the games tool, nothing else that writes", () => {
64 expect(limitedMay("whoami_can", false)).toBe(true);
65 expect(limitedMay("games", true)).toBe(true);
66 for (const name of ["close", "assign", "edit", "merge", "write_file", "tell"]) expect(limitedMay(name, true), name).toBe(false);
67 });
68
69 test("only the conversation the game door limited is limited", () => {
70 const game = createConversation(app.db, ada.id).value.id;
71 const web = createConversation(app.db, ada.id).value.id;
72 limitToGame(app.db, game);
73 expect(viaLimited(app.db, `conversation:${game}`)).toBe(true);
74 expect(viaLimited(app.db, `conversation:${web}`)).toBe(false);
75 expect(viaLimited(app.db, "nothing")).toBe(false);
76 });
77
78 test("a reversible write is refused in a game conversation and goes ahead in a web one", async () => {
79 const made = await createRepo(app, ada, { name: "door", visibility: "public" });
80 if (!made.ok) throw new Error(String(made.error));
81 const game = createConversation(app.db, ada.id).value.id;
82 const web = createConversation(app.db, ada.id).value.id;
83 limitToGame(app.db, game);
84 const args = { repo: "ada/door", text: "from the game" };
85
86 const refused = await call(tokenFor(game), "tell", args);
87 expect(refused.isError).toBe(true);
88 expect(refused.text).toContain(DOOR_LIMITED);
89
90 const read = await call(tokenFor(game), "whoami_can", {});
91 expect(read.text).not.toContain(DOOR_LIMITED);
92
93 const allowed = await call(tokenFor(web), "tell", args);
outdated

This passes whenever games is not refused by the door, so it does not show the call is held. Assert needs_confirm and that the waiting count rises by one. Also assert that action: "list" is not held.

94 expect(allowed.text).not.toContain(DOOR_LIMITED);
95 });
96
97 test("a game conversation's games call is held for the player's yes; a read is not", async () => {
98 const game = createConversation(app.db, ada.id).value.id;
99 limitToGame(app.db, game);
100 const waiting = () => waitingFor(app.db, ada.id).length;
101 const before = waiting();
102 const asked = await call(tokenFor(game), "games", { action: "power", box: "mc", service: "hub", kind: "restart" });
103 expect(asked.text).not.toContain(DOOR_LIMITED);
104 expect(JSON.parse(asked.text).needs_confirm).toEqual(expect.any(String));
105 expect(waiting()).toBe(before + 1);
106 const listed = await call(tokenFor(game), "games", { action: "list" });
107 expect(listed.text).not.toContain("needs_confirm");
108 expect(waiting()).toBe(before + 1);
109 });
110
111 test("the migration limits the game conversations that already exist", () => {
112 const talk = createConversation(app.db, ada.id).value.id;
113 const web = createConversation(app.db, ada.id).value.id;
114 app.db.query("INSERT INTO game_talk (box_id, user_id, conversation, created_at) VALUES ('b1', ?1, ?2, '')").run(ada.id, talk);
115 app.db.exec("DELETE FROM conversation_door");
116 app.db.exec(migration);
117 expect(viaLimited(app.db, `conversation:${talk}`)).toBe(true);
118 expect(viaLimited(app.db, `conversation:${web}`)).toBe(false);
119 });
test/game-door.test.ts +9 −5
@@ -316,7 +316,7 @@ test("a change in any phrasing goes to Talk as words, and the door itself change
316316 }
317317 });
318318
319 test("what a crew turn does for a game player: the games tool and an admin write are held, never run (the forge's one policy, as in Talk)", async () => {
319 test("what a crew turn does for a game player: the games tool is held and any other write is refused, never run", async () => {
320320 await toldFor("restart the hub");
321321 const id = conversation()!;
322322 const via = `conversation:${id}`;
@@ -330,7 +330,8 @@ test("what a crew turn does for a game player: the games tool and an admin write
330330 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
331331 });
332332 const body = (await res.json()) as { result?: { content?: { text?: string }[]; isError?: boolean } };
333 return JSON.parse(body.result?.content?.[0]?.text ?? "{}") as Record<string, unknown>;
333 const text = body.result?.content?.[0]?.text ?? "{}";
334 return text.startsWith("{") ? (JSON.parse(text) as Record<string, unknown>) : { refused: text };
334335 };
335336 try {
336337 const waiting = () => waitingFor(app.db, ada.id).length;
@@ -346,10 +347,13 @@ test("what a crew turn does for a game player: the games tool and an admin write
346347 expect(waiting()).toBe(before + 1);
347348 }
348349 expect(commands()).toBe(0);
349 // An admin-scope write.
350 // Any other write is out of reach from words typed in game (#18218): refused, nothing held,
351 // nothing run.
350352 const before = waiting();
351 expect((await tool("release_now", {}))["needs_confirm"]).toEqual(expect.any(String));
352 expect(waiting()).toBe(before + 1);
353 const refused = await tool("release_now", {});
354 expect(refused["needs_confirm"]).toBeUndefined();
355 expect(String(refused["refused"])).toContain("forbidden");
356 expect(waiting()).toBe(before);
353357 expect(commands()).toBe(0);
354358 // A read is not held.
355359 expect((await tool("games", { action: "list" }))["needs_confirm"]).toBeUndefined();

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

Keyboard shortcuts

Docs