Public: anyone can read this; the crew can change it.
Games: plain sentences carried out by the games tool and the New server box #18056
Green, waits for a review (pushed since the last review), 2h 2m
sold/games-wish → main 15 commits
8 files
changed +983
−18
docs/features/game-wish.md added +21
| @@ -0,0 +1,21 @@ | ||
| 1 | --- | |
| 2 | topic: Hosting forges for others, and getting paid | |
| 3 | row: Game servers in plain words | |
| 4 | --- | |
| 5 | # Game servers in plain words | |
| 6 | ||
| 7 | The **New server** box on `/games/<box>`, the terminal's `n` on the Games screen and the games tool's `wish` action all take the same sentence and do the same thing. It takes any change to a box's servers, not only a new one. | |
| 8 | ||
| 9 | ## What it reads | |
| 10 | ||
| 11 | - A new server: "a flat world called build", "a void world with FAWE and bedwars". | |
| 12 | - A setting: "set difficulty to hard on survival", "view distance 12 on arena", "turn pvp off on hub". | |
| 13 | - A plugin or mod: "add worldedit to hub", "remove luckperms from arena", "update all on survival". A name that is not a slug is searched on Modrinth. | |
| 14 | - A plugin's config: "config luckperms server-name = lobby on arena". | |
| 15 | - Several in a row, split by `;` or "then": "new server called pvp; set difficulty to hard on pvp". | |
| 16 | ||
| 17 | It is read by rules, not by a model, so the same words always give the same result. Nothing is guessed: when the words leave a choice open (which server, which setting, which of two plugins) the answer is a question, and your pick goes back into the sentence. Words it cannot read come back with what to say instead. "When nobody is on" is not offered for plugins yet and is refused as such. | |
| 18 | ||
| 19 | ## Doing it | |
| 20 | ||
| 21 | The preview shows what each step would change, in order, and changes nothing. **Do it** (or `y` in the terminal, or `dryRun: false` in the tool) does the steps in order, each on what the one before saved. It stops at the first step that fails, says what you asked in it and why it did not go, and says whether what came before it is saved. Each step needs the role its own action needs: a new server, an operator of the box; any other, an operator of that server. |
src/games/wish.ts added +228
| @@ -0,0 +1,228 @@ | ||
| 1 | /** | |
| 2 | * Game servers in plain words, with no model (#18042): a sentence compiles, by rules alone and in | |
| 3 | * well under a millisecond, to intents the forge's existing plans carry out (`planServer`, | |
| 4 | * `previewSettings`, `planInstall`, `planRemove`, `planUpdate`, `planConfig`). Every intent is still | |
| 5 | * previewed and committed as on the page. When the words leave a choice open (which server, which | |
| 6 | * setting, which of two plugins), the answer is a question with fixed options, never a guess; the | |
| 7 | * person's pick goes back into the sentence and it compiles again. After platOS's sentence-to-spec | |
| 8 | * kernel: each step carries the rule that made it. | |
| 9 | */ | |
| 10 | ||
| 11 | import { ALIASES, parseWish, type Wish } from "./presets.ts"; | |
| 12 | import { SETTINGS, type Setting } from "./settings.ts"; | |
| 13 | ||
| 14 | export type Intent = | |
| 15 | | { readonly kind: "server"; readonly wish: Wish } | |
| 16 | | { readonly kind: "set"; readonly service: string; readonly key: string; readonly value: string } | |
| 17 | | { readonly kind: "install" | "remove" | "update"; readonly service: string; readonly ref: string } | |
| 18 | | { readonly kind: "config"; readonly service: string; readonly file: string; readonly path: string; readonly value: string }; | |
| 19 | ||
| 20 | /** A choice the words left open: the sentence again with one option put in answers it. */ | |
| 21 | export interface Question { | |
| 22 | readonly prompt: string; | |
| 23 | readonly options: readonly { readonly label: string; readonly describe: string; readonly sentence: string }[]; | |
| 24 | } | |
| 25 | ||
| 26 | export interface Compiled { | |
| 27 | readonly steps: readonly Intent[]; | |
| 28 | readonly questions: readonly Question[]; | |
| 29 | /** What could not be read, in words, with what to say instead. */ | |
| 30 | readonly refused: readonly string[]; | |
| 31 | /** Each rule that fired, in order. */ | |
| 32 | readonly rationale: readonly string[]; | |
| 33 | } | |
| 34 | ||
| 35 | /** Words for a setting that its key does not say. */ | |
| 36 | const PHRASES: Readonly<Record<string, string>> = { | |
| 37 | "game mode": "gamemode", | |
| 38 | mode: "gamemode", | |
| 39 | whitelist: "white-list", | |
| 40 | seed: "level-seed", | |
| 41 | "message of the day": "motd", | |
| 42 | "max player": "max-players", | |
| 43 | players: "max-players", | |
| 44 | flying: "allow-flight", | |
| 45 | flight: "allow-flight", | |
| 46 | nether: "allow-nether", | |
| 47 | monsters: "spawn-monsters", | |
| 48 | mobs: "spawn-monsters", | |
| 49 | structures: "generate-structures", | |
| 50 | }; | |
| 51 | const ON = /^(?:on|true|yes|enabled?|allow(?:ed)?)$/; | |
| 52 | const OFF = /^(?:off|false|no|disabled?|none)$/; | |
| 53 | ||
| 54 | const words = (s: string): string => s.toLowerCase().replace(/[^a-z0-9.\- ]/g, " ").replace(/\s+/g, " ").trim(); | |
| 55 | ||
| 56 | /** The settings a phrase can mean: an exact phrase first, else each key whose words all appear in it. */ | |
| 57 | export function settingsFor(phrase: string, table: readonly Setting[] = SETTINGS): Setting[] { | |
| 58 | const p = ` ${words(phrase)} `; | |
| 59 | for (const [said, key] of Object.entries(PHRASES)) if (p.includes(` ${said} `)) return table.filter((s) => s.key === key); | |
| 60 | const exact = table.filter((s) => s.file === "server.properties" && p.includes(` ${s.key.replace(/-/g, " ")} `)); | |
| 61 | if (exact.length > 0) return exact; | |
| 62 | // One word of a key ("distance"): every server.properties key holding it, so two make a question. | |
| 63 | const one = p.trim().split(" ").filter((w) => w.length >= 4); | |
| 64 | return table.filter((s) => s.file === "server.properties" && one.some((w) => s.key.split("-").includes(w))); | |
| 65 | } | |
| 66 | ||
| 67 | /** A value as the setting's kind takes it, or why not. */ | |
| 68 | export function valueFor(s: Setting, said: string): { ok: true; value: string } | { ok: false; error: string } { | |
| 69 | const v = words(said); | |
| 70 | const t = s.type; | |
| 71 | if (t.kind === "bool") return ON.test(v) ? { ok: true, value: "true" } : OFF.test(v) ? { ok: true, value: "false" } : { ok: false, error: `${s.key} is on or off.` }; | |
| 72 | if (t.kind === "int" || t.kind === "float") { | |
| 73 | const n = Number(v); | |
| 74 | if (!Number.isFinite(n) || (t.kind === "int" && !Number.isInteger(n))) return { ok: false, error: `${s.key} is a number.` }; | |
| 75 | if (n < t.min || n > t.max) return { ok: false, error: `${s.key} is from ${String(t.min)} to ${String(t.max)}.` }; | |
| 76 | return { ok: true, value: String(n) }; | |
| 77 | } | |
| 78 | if (t.kind === "enum") { | |
| 79 | const hit = t.values.find((x) => x === v); | |
| 80 | return hit === undefined ? { ok: false, error: `${s.key} is one of ${t.values.join(", ")}.` } : { ok: true, value: hit }; | |
| 81 | } | |
| 82 | return said.length <= t.max ? { ok: true, value: said.trim() } : { ok: false, error: `${s.key} is at most ${String(t.max)} characters.` }; | |
| 83 | } | |
| 84 | ||
| 85 | /** Clauses: split where a sentence starts another order ("; ", " then ", " and set"). */ | |
| 86 | const clauses = (sentence: string): string[] => | |
| 87 | sentence | |
| 88 | .split(/;|\bthen\b|\band (?=(?:set|make|add|install|remove|update|config|new)\b)/i) | |
| 89 | .map((c) => c.trim()) | |
| 90 | .filter((c) => c !== ""); | |
| 91 | ||
| 92 | /** The server a clause names ("on survival", "to arena", "from hub"), or a question when it names none and there are several. */ | |
| 93 | function serverOf(clause: string, services: readonly string[]): { service: string } | { ask: Question } | { none: true } { | |
| 94 | const named = /\b(?:on|to|from|in)\s+([a-z0-9][a-z0-9-]*)\s*$/i.exec(clause.trim())?.[1]?.toLowerCase(); | |
| 95 | if (named !== undefined && services.includes(named)) return { service: named }; | |
| 96 | if (services.length === 1) return { service: services[0]! }; | |
| 97 | if (services.length === 0) return { none: true }; | |
| 98 | return { | |
| 99 | ask: { | |
| 100 | prompt: "Which server?", | |
| 101 | options: services.map((s) => ({ label: s, describe: `Do it on ${s}`, sentence: `${withoutServer(clause, services)} on ${s}` })), | |
| 102 | }, | |
| 103 | }; | |
| 104 | } | |
| 105 | const withoutServer = (clause: string, services: readonly string[]): string => { | |
| 106 | const m = /\s+(?:on|to|from|in)\s+([a-z0-9][a-z0-9-]*)\s*$/i.exec(clause); | |
| 107 | return m !== null && services.includes(m[1]!.toLowerCase()) ? clause.slice(0, m.index) : clause; | |
| 108 | }; | |
| 109 | ||
| 110 | /** | |
| 111 | * Compile a sentence on a box whose servers are `services` (the game servers, not the proxy). | |
| 112 | * `existing` are names already taken, for a new server's free name. | |
| 113 | */ | |
| 114 | export function compile(sentence: string, services: readonly string[], existing: readonly string[] = services): Compiled { | |
| 115 | const steps: Intent[] = []; | |
| 116 | const questions: Question[] = []; | |
| 117 | const refused: string[] = []; | |
| 118 | const rationale: string[] = []; | |
| 119 | const taken = [...existing]; | |
| 120 | const games = [...services]; | |
| 121 | for (const raw of clauses(sentence)) { | |
| 122 | const c = raw.replace(/^(?:please\s+)?(?:can you\s+)?/i, "").trim(); | |
| 123 | const lower = c.toLowerCase(); | |
| 124 | // A new server: the words the New server box already reads, with themes. | |
| 125 | if (/^(?:a |an |new |give me |make |build |create )?(?:a |an |new )*(?:\w+\s+){0,6}(?:world|server)\b/i.test(lower) && !/^(?:set|add|install|remove|update|config)\b/i.test(lower)) { | |
| 126 | const wish = parseWish(c, taken); | |
| 127 | steps.push({ kind: "server", wish }); | |
| 128 | taken.push(wish.name); | |
| 129 | games.push(wish.name); | |
| 130 | rationale.push(`"${c}": a new server, ${wish.name} (${wish.level}${wish.plugins.length > 0 ? `, ${wish.plugins.join(", ")}` : ""}${(wish.themes ?? []).length > 0 ? `; searched: ${wish.themes!.join(", ")}` : ""})`); | |
| 131 | continue; | |
| 132 | } | |
| 133 | // config <plugin> <path> = <value> [on S] | |
| 134 | const conf = /^config\s+(\S+)\s+([A-Za-z0-9_.-]+)\s*=\s*(.+)$/i.exec(withoutServer(c, games)); | |
| 135 | if (conf !== null) { | |
| 136 | const where = serverOf(c, games); | |
| 137 | if ("ask" in where) questions.push(where.ask); | |
| 138 | else if ("service" in where) { | |
| 139 | steps.push({ kind: "config", service: where.service, file: `plugins/${conf[1]!}/config.yml`, path: conf[2]!, value: conf[3]!.trim() }); | |
| 140 | rationale.push(`"${c}": ${conf[1]}'s config.yml, ${conf[2]} = ${conf[3]!.trim()}, on ${where.service}`); | |
| 141 | } else refused.push(`"${c}": there is no server to change yet.`); | |
| 142 | continue; | |
| 143 | } | |
| 144 | // add | install | remove | update <thing> [to|from|on S] | |
| 145 | const mod = /^(add|install|remove|uninstall|delete|update|upgrade)\s+(.+)$/i.exec(c); | |
| 146 | if (mod !== null) { | |
| 147 | // Waiting for a quiet box is not built for mods: saying so is refused, not read as a plugin's name. | |
| 148 | if (/\bwhen (?:nobody|no one|noone) is on\s*$/i.test(mod[2]!)) { | |
| 149 | refused.push(`"${c}": waiting until nobody is on is not offered for this yet. Say it without "when nobody is on".`); | |
| 150 | continue; | |
| 151 | } | |
| 152 | const rest = mod[2]!; | |
| 153 | const where = serverOf(rest, games); | |
| 154 | const thing = words(withoutServer(rest, games)); | |
| 155 | const verb = mod[1]!.toLowerCase(); | |
| 156 | const kind = /^(?:add|install)$/.test(verb) ? "install" : /^(?:update|upgrade)$/.test(verb) ? "update" : "remove"; | |
| 157 | if ("ask" in where) { | |
| 158 | questions.push(where.ask); | |
| 159 | continue; | |
| 160 | } | |
| 161 | if (!("service" in where)) { | |
| 162 | refused.push(`"${c}": there is no server to change yet.`); | |
| 163 | continue; | |
| 164 | } | |
| 165 | const ref = kind === "update" && /^(?:all|everything|every mod|mods|plugins)$/.test(thing) ? "all" : (ALIASES[thing.replace(/\s+/g, "")] ?? ALIASES[thing] ?? thing); | |
| 166 | steps.push({ kind, service: where.service, ref }); | |
| 167 | rationale.push(`"${c}": ${kind} ${ref} on ${where.service}${ref === thing && !(thing in ALIASES) ? " (a name Modrinth is asked for)" : ""}`); | |
| 168 | continue; | |
| 169 | } | |
| 170 | // set <setting> to <value> [on S] | make <setting> <value> [on S] | <setting> <value> [on S] | |
| 171 | const body = withoutServer(c, games).replace(/^(?:set|make|change|turn)\s+/i, ""); | |
| 172 | const sv = /^(.+?)\s+(?:to|=|is)\s+(.+)$/i.exec(body) ?? /^(.+?)\s+(\S+)$/.exec(body); | |
| 173 | if (sv !== null) { | |
| 174 | const found = settingsFor(sv[1]!); | |
| 175 | const meant = /^(?:set|make|change|turn)\s/i.test(c) || /\s(?:to|=|is)\s/i.test(c); | |
| 176 | if (found.length === 0 && !meant) { | |
| 177 | refused.push(`"${c}": not read. Say what to do first: "new …", "set … to …", "add …", "remove …", "update …" or "config …".`); | |
| 178 | continue; | |
| 179 | } | |
| 180 | if (found.length === 0) { | |
| 181 | refused.push(`"${c}": no setting is called "${sv[1]}". Say a setting by its name, as "view distance" or "difficulty".`); | |
| 182 | continue; | |
| 183 | } | |
| 184 | if (found.length > 1) { | |
| 185 | questions.push({ prompt: `Which setting is "${sv[1]}"?`, options: found.map((s) => ({ label: s.key, describe: s.about, sentence: c.replace(sv[1]!, s.key.replace(/-/g, " ")) })) }); | |
| 186 | continue; | |
| 187 | } | |
| 188 | const where = serverOf(c, games); | |
| 189 | if ("ask" in where) { | |
| 190 | questions.push(where.ask); | |
| 191 | continue; | |
| 192 | } | |
| 193 | if (!("service" in where)) { | |
| 194 | refused.push(`"${c}": there is no server to change yet.`); | |
| 195 | continue; | |
| 196 | } | |
| 197 | const value = valueFor(found[0]!, sv[2]!); | |
| 198 | if (!value.ok) { | |
| 199 | refused.push(`"${c}": ${value.error}`); | |
| 200 | continue; | |
| 201 | } | |
| 202 | steps.push({ kind: "set", service: where.service, key: found[0]!.key, value: value.value }); | |
| 203 | rationale.push(`"${c}": ${found[0]!.key} = ${value.value} on ${where.service}`); | |
| 204 | continue; | |
| 205 | } | |
| 206 | refused.push(`"${c}": not read. Say what to do first: "new …", "set … to …", "add …", "remove …", "update …" or "config …".`); | |
| 207 | } | |
| 208 | return { steps, questions, refused, rationale }; | |
| 209 | } | |
| 210 | ||
| 211 | /** Modrinth hits for a name: the one to install, or a question when two are close. */ | |
| 212 | export function pickHit( | |
| 213 | hits: readonly { slug: string; title: string; description: string; downloads: number; fits: boolean }[], | |
| 214 | sentence: string, | |
| 215 | said: string, | |
| 216 | ): { slug: string } | { ask: Question } | { none: true } { | |
| 217 | const fit = hits.filter((h) => h.fits && h.downloads >= 1_000); | |
| 218 | if (fit.length === 0) return { none: true }; | |
| 219 | const [a, b] = fit; | |
| 220 | if (b !== undefined && b.downloads >= a!.downloads * 0.9) | |
| 221 | return { | |
| 222 | ask: { | |
| 223 | prompt: `Which one is "${said}"?`, | |
| 224 | options: fit.slice(0, 3).map((h) => ({ label: h.title, describe: `${h.description} (${h.downloads.toLocaleString("en-US")} downloads)`, sentence: sentence.replace(said, h.slug) })), | |
| 225 | }, | |
| 226 | }; | |
| 227 | return { slug: a!.slug }; | |
| 228 | } |
src/games/wish_run.ts added +178
| @@ -0,0 +1,178 @@ | ||
| 1 | /** | |
| 2 | * A sentence carried out on a box (#18042): compiled by `wish.ts`, each step planned with the | |
| 3 | * plan the page and the tools already use, and, only when asked, committed in order. Questions and | |
| 4 | * refusals come back as they are; nothing is guessed. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import type { User } from "../core/users.ts"; | |
| 9 | import { composeServices, readCompose } from "./compose.ts"; | |
| 10 | import { commitPlan, modsOf, planInstall, planRemove, planUpdate, type Plan } from "./mods.ts"; | |
| 11 | import { search, type Result } from "./modrinth.ts"; | |
| 12 | import { commitConfig, configMounts, planConfig } from "./plugin_config.ts"; | |
| 13 | import { commitServer, planServer } from "./presets.ts"; | |
| 14 | import { commitSettings, previewSettings } from "./settings.ts"; | |
| 15 | import { isGameServer } from "./sleep.ts"; | |
| 16 | import { mayDo, roleOn, servicesOf, type GameBox } from "./store.ts"; | |
| 17 | import { compile, pickHit, type Intent, type Question } from "./wish.ts"; | |
| 18 | ||
| 19 | export type WishRun = | |
| 20 | | { readonly kind: "ask"; readonly questions: readonly Question[]; readonly refused: readonly string[] } | |
| 21 | | { readonly kind: "refused"; readonly refused: readonly string[] } | |
| 22 | | { | |
| 23 | readonly kind: "plan"; | |
| 24 | readonly understood: readonly string[]; | |
| 25 | /** What each step would change (or did), in words. */ | |
| 26 | readonly changes: readonly { readonly says: string; readonly lines: readonly string[] }[]; | |
| 27 | /** Set when a step stopped the run: what was asked in it, and why not. What came before it is saved when `committed`. */ | |
| 28 | readonly failed?: { readonly asked: string; readonly error: string }; | |
| 29 | readonly committed: boolean; | |
| 30 | }; | |
| 31 | ||
| 32 | /** Why a run stopped, said as a person would: what was asked, why not, and what that leaves. */ | |
| 33 | export const failedWords = (run: Extract<WishRun, { kind: "plan" }>): string => | |
| 34 | run.failed === undefined ? "" : `Could not do "${run.failed.asked}": ${run.failed.error}${run.committed ? " What came before it is saved." : " Nothing was changed."}`; | |
| 35 | ||
| 36 | /** A plan in plain lines, in order, for a screen: each step's own lines, or its one sentence. */ | |
| 37 | export const planLines = (run: Extract<WishRun, { kind: "plan" }>): string[] => run.changes.flatMap((st) => (st.lines.length === 0 ? [st.says] : st.lines)); | |
| 38 | ||
| 39 | /** The box's game servers, never its proxy or waker. */ | |
| 40 | export async function gameServersOf(app: App, box: GameBox): Promise<string[]> { | |
| 41 | const compose = await readCompose(app, box); | |
| 42 | const names = new Set([...servicesOf(app.db, box.id).map((s) => s.name), ...(compose === undefined ? [] : composeServices(compose.text))]); | |
| 43 | return compose === undefined ? [...names].sort() : [...names].filter((n) => isGameServer(compose.text, n)).sort(); | |
| 44 | } | |
| 45 | ||
| 46 | /** A plain `key: value` line at a dotted path ("a.b.c") of a YAML text, replaced in place so comments and order stay. */ | |
| 47 | export function setYamlKey(text: string, path: string, value: string): Result<string> { | |
| 48 | const lines = text.split("\n"); | |
| 49 | const keys = path.split("."); | |
| 50 | let from = 0; | |
| 51 | let indent = -1; | |
| 52 | for (const [depth, key] of keys.entries()) { | |
| 53 | let at = -1; | |
| 54 | let level = -1; | |
| 55 | for (let i = from; i < lines.length; i++) { | |
| 56 | const l = lines[i]!; | |
| 57 | if (l.trim() === "" || l.trimStart().startsWith("#")) continue; | |
| 58 | const lead = l.length - l.trimStart().length; | |
| 59 | if (lead <= indent) break; | |
| 60 | if (level < 0) level = lead; | |
| 61 | if (lead === level && l.trimStart().startsWith(`${key}:`)) { | |
| 62 | at = i; | |
| 63 | break; | |
| 64 | } | |
| 65 | } | |
| 66 | if (at < 0) return { ok: false, error: `No key ${path} in the file; say the key in full as it is written there.` }; | |
| 67 | if (depth === keys.length - 1) { | |
| 68 | const l = lines[at]!; | |
| 69 | const lead = l.slice(0, l.length - l.trimStart().length); | |
| 70 | const old = l.trimStart().slice(key.length + 1).trim(); | |
| 71 | if (old === "" || old === "|" || old === ">") return { ok: false, error: `${path} holds more than one value; change the file with plugin_config_set.` }; | |
| 72 | const comment = /\s+#.*$/.exec(old)?.[0] ?? ""; | |
| 73 | lines[at] = `${lead}${key}: ${/^(?:true|false|-?\d+(?:\.\d+)?)$/.test(value) ? value : JSON.stringify(value)}${comment}`; | |
| 74 | return { ok: true, value: lines.join("\n") }; | |
| 75 | } | |
| 76 | indent = lines[at]!.length - lines[at]!.trimStart().length; | |
| 77 | from = at + 1; | |
| 78 | } | |
| 79 | return { ok: false, error: `No key ${path} in the file.` }; | |
| 80 | } | |
| 81 | ||
| 82 | /** Plan one intent on the box as it is now; `commit` commits it, and returns what was said. */ | |
| 83 | async function carry( | |
| 84 | app: App, | |
| 85 | user: User, | |
| 86 | box: GameBox, | |
| 87 | intent: Intent, | |
| 88 | sentence: string, | |
| 89 | commit: boolean, | |
| 90 | ): Promise<{ ok: true; says: string; lines: readonly string[]; ask?: Question } | { ok: false; error: string }> { | |
| 91 | const fail = (error: string) => ({ ok: false, error }) as const; | |
| 92 | const sha = (s: string): string => s.slice(0, 10); | |
| 93 | if (intent.kind === "server") { | |
| 94 | const p = await planServer(app, box, intent.wish); | |
| 95 | if (!p.ok) return fail(p.error); | |
| 96 | if (!commit) return { ok: true, says: p.value.done, lines: p.value.lines }; | |
| 97 | const done = await commitServer(app, user, box, p.value, p.value.sha); | |
| 98 | return done.ok ? { ok: true, says: `${p.value.done} (${sha(done.sha)})`, lines: p.value.lines } : fail(done.error); | |
| 99 | } | |
| 100 | if (intent.kind === "set") { | |
| 101 | const p = await previewSettings(app, box, intent.service, { [intent.key]: intent.value }); | |
| 102 | if (!p.ok) return fail(p.error); | |
| 103 | if (!commit) return { ok: true, says: `Set ${intent.key} to ${intent.value} on ${intent.service}`, lines: p.value.lines }; | |
| 104 | const done = await commitSettings(app, user, box, intent.service, p.value); | |
| 105 | return done.ok ? { ok: true, says: `Set ${intent.key} to ${intent.value} on ${intent.service} (${sha(done.value)})`, lines: p.value.lines } : fail(done.error); | |
| 106 | } | |
| 107 | if (intent.kind === "config") { | |
| 108 | const compose = await readCompose(app, box); | |
| 109 | const before = compose === undefined ? undefined : configMounts(compose.text, intent.service).find((m) => m.file === intent.file)?.content; | |
| 110 | if (before === undefined) return fail(`${intent.file} is not kept in the repository yet; put it there first (plugin_config_set), then its keys can be set in words.`); | |
| 111 | const edited = setYamlKey(before, intent.path, intent.value); | |
| 112 | if (!edited.ok) return fail(edited.error); | |
| 113 | const p = await planConfig(app, box, intent.service, intent.file, edited.value); | |
| 114 | if (!p.ok) return fail(p.error); | |
| 115 | if (!commit) return { ok: true, says: p.value.done, lines: p.value.lines }; | |
| 116 | const done = await commitConfig(app, user, box, intent.service, p.value); | |
| 117 | return done.ok ? { ok: true, says: `${p.value.done} (${sha(done.value)})`, lines: p.value.lines } : fail(done.error); | |
| 118 | } | |
| 119 | const mods = await modsOf(app, box, intent.service); | |
| 120 | if (!mods.ok) return fail(mods.error); | |
| 121 | const m = mods.value; | |
| 122 | let ref = intent.ref; | |
| 123 | let plan: Result<Plan>; | |
| 124 | if (intent.kind === "remove") plan = await planRemove(m, intent.service, ref); | |
| 125 | else if (intent.kind === "update") plan = await planUpdate(app, m, intent.service, ref); | |
| 126 | else { | |
| 127 | // A name that is not a slug is searched for, and the clear winner installed; two close ones are a question. | |
| 128 | if (/\s/.test(ref)) { | |
| 129 | const hits = await search(app, m.target, ref); | |
| 130 | if (!hits.ok) return fail(hits.error); | |
| 131 | const pick = pickHit(hits.value, sentence, ref); | |
| 132 | if ("ask" in pick) return { ok: true, says: pick.ask.prompt, lines: [], ask: pick.ask }; | |
| 133 | if ("none" in pick) return fail(`Nothing on Modrinth called "${ref}" runs on ${intent.service}.`); | |
| 134 | ref = pick.slug; | |
| 135 | } | |
| 136 | plan = await planInstall(app, m, intent.service, ref); | |
| 137 | } | |
| 138 | if (!plan.ok) return fail(plan.error); | |
| 139 | if (!commit) return { ok: true, says: plan.value.done, lines: plan.value.lines }; | |
| 140 | const done = await commitPlan(app, user, box, intent.service, m, plan.value); | |
| 141 | return done.ok ? { ok: true, says: `${plan.value.done} (${sha(done.value)})`, lines: plan.value.lines } : fail(done.error); | |
| 142 | } | |
| 143 | ||
| 144 | /** | |
| 145 | * Carry out `sentence` on `box`. With `commit` false every step is planned on the box as it is; a | |
| 146 | * step on a server this sentence adds waits for it ("planned once it exists"). With `commit` | |
| 147 | * true each step is planned on what the one before committed, in order, stopping at the first | |
| 148 | * that fails. | |
| 149 | */ | |
| 150 | export async function runWish(app: App, user: User, box: GameBox, sentence: string, commit: boolean): Promise<WishRun> { | |
| 151 | // Each step needs what its own action needs: a new server, the box's operator; any other, the service's. | |
| 152 | const mayStep = (i: Intent): boolean => mayDo(roleOn(app.db, user, box.id, i.kind === "server" ? "" : i.service), "operator"); | |
| 153 | const services = (await gameServersOf(app, box)).filter((n) => mayDo(roleOn(app.db, user, box.id, n), "viewer")); | |
| 154 | const compiled = compile(sentence, services); | |
| 155 | if (compiled.questions.length > 0) return { kind: "ask", questions: compiled.questions, refused: compiled.refused }; | |
| 156 | if (compiled.refused.length > 0 || compiled.steps.length === 0) | |
| 157 | return { kind: "refused", refused: compiled.refused.length > 0 ? compiled.refused : ['Say what to do: "new …", "set … to …", "add …", "remove …", "update …" or "config …".'] }; | |
| 158 | const denied = compiled.steps.findIndex((i) => !mayStep(i)); | |
| 159 | if (denied >= 0) { | |
| 160 | const i = compiled.steps[denied]!; | |
| 161 | return { kind: "refused", refused: [`Step ${String(denied + 1)}: you are not an operator of ${i.kind === "server" ? box.name : i.service}; nothing was changed.`] }; | |
| 162 | } | |
| 163 | const changes: { says: string; lines: readonly string[] }[] = []; | |
| 164 | const added = new Set<string>(); | |
| 165 | for (const [i, intent] of compiled.steps.entries()) { | |
| 166 | if (intent.kind === "server") added.add(intent.wish.name); | |
| 167 | if (!commit && intent.kind !== "server" && added.has(intent.service)) { | |
| 168 | // Said as a sentence: what it will do, once the server it names is there. | |
| 169 | changes.push({ says: `Then, once ${intent.service} is in the network: ${compiled.rationale[i]!.replace(/^"[^"]*":\s*/, "")}`, lines: [] }); | |
| 170 | continue; | |
| 171 | } | |
| 172 | const got = await carry(app, user, box, intent, sentence, commit); | |
| 173 | if (!got.ok) return { kind: "plan", understood: compiled.rationale, changes, failed: { asked: /^"([^"]*)"/.exec(compiled.rationale[i] ?? "")?.[1] ?? "that", error: got.error }, committed: commit && i > 0 }; | |
| 174 | if (got.ask !== undefined) return { kind: "ask", questions: [got.ask], refused: [] }; | |
| 175 | changes.push({ says: got.says, lines: got.lines }); | |
| 176 | } | |
| 177 | return { kind: "plan", understood: compiled.rationale, changes, committed: commit }; | |
| 178 | } |
src/http/mcp/tools/games.ts +19 −3
| @@ -23,6 +23,7 @@ import { linkShown } from "../../../games/snapshots.ts"; | ||
| 23 | 23 | import { takeBack } from "../../../games/take_back.ts"; |
| 24 | 24 | import { newestProof, proofWords } from "../../../games/lent_proof.ts"; |
| 25 | 25 | import { queueWorld } from "../../../games/worlds.ts"; |
| 26 | import { failedWords, runWish } from "../../../games/wish_run.ts"; | |
| 26 | 27 | |
| 27 | 28 | export const tool: Tool = { |
| 28 | 29 | name: "games", |
| @@ -32,14 +33,14 @@ export const tool: Tool = { | ||
| 32 | 33 | inputSchema: { |
| 33 | 34 | type: "object", |
| 34 | 35 | properties: { |
| 35 | action: { type: "string", enum: ["list", "metrics", "console", "take_back", "power", "env", "mods", "mods_search", "mods_pack_search", "mods_install", "mods_update", "mods_remove", "mods_pack", "pack", "pack_link", "pack_end", "people", "config", "config_set", "plugin_config", "plugin_config_set", "plugin_config_revert", "sleep", "create_server", "remove_server", "world"] }, | |
| 36 | action: { type: "string", enum: ["list", "metrics", "console", "take_back", "power", "env", "mods", "mods_search", "mods_pack_search", "mods_install", "mods_update", "mods_remove", "mods_pack", "pack", "pack_link", "pack_end", "people", "config", "config_set", "plugin_config", "plugin_config_set", "plugin_config_revert", "sleep", "create_server", "remove_server", "wish", "world"] }, | |
| 36 | 37 | op: { type: "string", enum: ["list", ...PEOPLE_OPS, "import", "restore", "snapshot"] }, |
| 37 | 38 | player: { type: "string", maxLength: 17 }, |
| 38 | 39 | to: { type: "string", maxLength: 64 }, |
| 39 | 40 | window: { type: "string", enum: Object.keys(WINDOWS) }, |
| 40 | 41 | url: { type: "string", maxLength: 3800 }, |
| 41 | 42 | snapshot: { type: "string", maxLength: 120 }, |
| 42 | words: { type: "string", maxLength: 300 }, | |
| 43 | words: { type: "string", maxLength: 300, description: "wish: plain sentences; create_server: a kind" }, | |
| 43 | 44 | name: { type: "string", maxLength: 31 }, |
| 44 | 45 | level: { type: "string", enum: [...LEVELS] }, |
| 45 | 46 | plugins: { type: "array", items: { type: "string", maxLength: 100 }, maxItems: 10 }, |
| @@ -63,7 +64,7 @@ export const tool: Tool = { | ||
| 63 | 64 | heldNotWhen: (args) => |
| 64 | 65 | ["list", "metrics", "mods", "mods_search", "mods_pack_search", "pack", "config", "plugin_config"].includes(String(args["action"])) || |
| 65 | 66 | (args["action"] === "people" && args["op"] === "list") || |
| 66 | ((String(args["action"]).startsWith("mods_") || ["config_set", "plugin_config_set", "plugin_config_revert", "create_server", "remove_server"].includes(String(args["action"]))) && args["dryRun"] !== false), | |
| 67 | ((String(args["action"]).startsWith("mods_") || ["config_set", "plugin_config_set", "plugin_config_revert", "create_server", "remove_server", "wish"].includes(String(args["action"]))) && args["dryRun"] !== false), | |
| 67 | 68 | async run(ctx, user, args) { |
| 68 | 69 | const action = str(args["action"]); |
| 69 | 70 | const db = ctx.app.db; |
| @@ -127,6 +128,21 @@ export const tool: Tool = { | ||
| 127 | 128 | const done = await commitServer(ctx.app, user, box, planned.value, str(args["sha"])); |
| 128 | 129 | return done.ok ? good({ says: `${planned.value.done} (${done.sha.slice(0, 10)}); the box brings it up on its next check-in.`, sha: done.sha, lines: planned.value.lines }) : bad("refused", done.error); |
| 129 | 130 | } |
| 131 | if (action === "wish") { | |
| 132 | if (box === undefined || !seesBox(db, user, box.id)) return bad("not_found", "no such box here"); | |
| 133 | if (!mayDo(roleOn(db, user, box.id), "operator")) return bad("forbidden", `you are not an operator of ${box.name}`); | |
| 134 | const words = str(args["words"]).trim(); | |
| 135 | if (words === "") return bad("invalid", "say what you want as `words`, in plain sentences: 'set difficulty to hard on survival; add worldedit; new void world called pvp'. A choice left open comes back as questions, unread words as refused; dryRun: false commits the steps in order and stops at the first that fails; 'when nobody is on' installs are held, not built yet."); | |
| 136 | const run = await runWish(ctx.app, user, box, words, args["dryRun"] === false); | |
| 137 | if (run.kind === "ask") return good({ says: "The words leave a choice open; send the sentence of the option you mean.", questions: run.questions, ...(run.refused.length > 0 ? { refused: run.refused } : {}) }); | |
| 138 | if (run.kind === "refused") return bad("refused", run.refused.join(" ")); | |
| 139 | if (run.failed !== undefined) return bad("refused", failedWords(run)); | |
| 140 | return good({ | |
| 141 | ...(args["dryRun"] === false ? { says: run.committed ? "Done; each change comes to the box on its next check-in." : "Nothing to commit: every step is held." } : { planned: true, says: "These are the plans; nothing changed. Send the same words with dryRun: false to commit them in order." }), | |
| 142 | understood: run.understood, | |
| 143 | changes: run.changes, | |
| 144 | }); | |
| 145 | } | |
| 130 | 146 | // Who may is the command's own: a shell one has no service. |
| 131 | 147 | if (action === "take_back") { |
| 132 | 148 | if (box === undefined || !seesBox(db, user, box.id)) return bad("not_found", "no such box here"); |
src/tui/screens/games.ts +50 −3
| @@ -67,7 +67,8 @@ import { truncate, wrap } from "../term/width.ts"; | ||
| 67 | 67 | import type { Session } from "../session.ts"; |
| 68 | 68 | import { fill, len, split } from "../ui/layout.ts"; |
| 69 | 69 | import { ListState, confirmScreen, drawList, promptScreen, type ListRow } from "./common.ts"; |
| 70 | import { commitServer, planRemoveServer, planServer, wishOn, type ServerPlan } from "../../games/presets.ts"; | |
| 70 | import { commitServer, planRemoveServer, type ServerPlan } from "../../games/presets.ts"; | |
| 71 | import { failedWords, planLines, runWish } from "../../games/wish_run.ts"; | |
| 71 | 72 | import { CODE_MS, linksOf, newLinkCode, NO_LINK_HERE } from "../../games/chat.ts"; |
| 72 | 73 | import type { PaletteEntry } from "./entries.ts"; |
| 73 | 74 | import { gameMapScreen } from "./game_map.ts"; |
| @@ -141,6 +142,52 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 141 | 142 | else note = planned.error; |
| 142 | 143 | ctx.invalidate(); |
| 143 | 144 | }; |
| 145 | /** | |
| 146 | * Words carried out on a box: a choice left open is asked first (one pick, its sentence said | |
| 147 | * again), then the plan in plain lines, then a yes that does every step in order. | |
| 148 | */ | |
| 149 | const wish = async (box: GameBox, words: string): Promise<void> => { | |
| 150 | const run = await runWish(f.app, f.user!, box, words, false); | |
| 151 | if (run.kind === "refused") note = run.refused.join(" "); | |
| 152 | else if (run.kind === "ask") { | |
| 153 | const q = run.questions[0]!; | |
| 154 | ctx.push( | |
| 155 | confirmScreen(ctx, screen, { | |
| 156 | title: q.prompt, | |
| 157 | body: q.options.map((o) => `${o.label}: ${o.describe}`), | |
| 158 | actions: [...q.options.map((o) => ({ label: o.label })), { label: "Not now" }], | |
| 159 | onChoose: (i) => { | |
| 160 | const picked = q.options[i]; | |
| 161 | if (picked !== undefined) void ctx.track(wish(box, picked.sentence)); | |
| 162 | }, | |
| 163 | }), | |
| 164 | ); | |
| 165 | } else if (run.failed !== undefined) note = failedWords(run); | |
| 166 | else | |
| 167 | ctx.push( | |
| 168 | confirmScreen(ctx, screen, { | |
| 169 | title: `On ${box.name}`, | |
| 170 | body: planLines(run), | |
| 171 | actions: [{ label: "Do it" }, { label: "Not now" }], | |
| 172 | yesNo: true, | |
| 173 | onChoose: (i) => { | |
| 174 | if (i !== 0) return; | |
| 175 | void ctx.track( | |
| 176 | runWish(f.app, f.user!, box, words, true).then((done) => { | |
| 177 | note = | |
| 178 | done.kind !== "plan" | |
| 179 | ? "The words need another look: preview them again." | |
| 180 | : done.failed !== undefined | |
| 181 | ? failedWords(done) | |
| 182 | : `${done.changes.map((st) => st.says).join("; ")}.`; | |
| 183 | ctx.invalidate(); | |
| 184 | }), | |
| 185 | ); | |
| 186 | }, | |
| 187 | }), | |
| 188 | ); | |
| 189 | ctx.invalidate(); | |
| 190 | }; | |
| 144 | 191 | const screen: Screen = { |
| 145 | 192 | title: "Games", |
| 146 | 193 | keys: [ |
| @@ -245,9 +292,9 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 245 | 292 | ctx.push( |
| 246 | 293 | promptScreen(ctx, screen, { |
| 247 | 294 | title: `New server on ${box.name}`, |
| 248 | label: `What kind (a void world with FAWE and bedwars). ${PREVIEW_WORDS}`, | |
| 295 | label: `What to do (set difficulty to hard on survival; a void world with FAWE and bedwars). ${PREVIEW_WORDS}`, | |
| 249 | 296 | onSubmit: async (words) => { |
| 250 | showPlan(box, `New server on ${box.name}`, "Create it", await planServer(f.app, box, await wishOn(f.app, box, words))); | |
| 297 | await wish(box, words); | |
| 251 | 298 | }, |
| 252 | 299 | }), |
| 253 | 300 | ); |
src/web/pages/games.ts +50 −12
| @@ -18,7 +18,7 @@ import { packCheckLines } from "../../games/pack_check.ts"; | ||
| 18 | 18 | import { playersBlock } from "./games_players.ts"; |
| 19 | 19 | import { queueShell } from "../../games/shell.ts"; |
| 20 | 20 | import { takeBack } from "../../games/take_back.ts"; |
| 21 | import { getUserById, getUserByName } from "../../core/users.ts"; | |
| 21 | import { getUserById, getUserByName, type User } from "../../core/users.ts"; | |
| 22 | 22 | import { blockChanges, serviceBlocks, shellBlocks, shellSays } from "../../terminal/blocks.ts"; |
| 23 | 23 | import { blockEvent, blockHtml, blocksForm, terminalBlocksJs } from "../terminal_blocks.ts"; |
| 24 | 24 | import { statusRow } from "./security.ts"; |
| @@ -77,6 +77,8 @@ import { avatar, badge, btn, disclosure, field as input, row, rowList, time } fr | ||
| 77 | 77 | import { watchBox } from "../../games/notify.ts"; |
| 78 | 78 | import { accountLinks, chatLog, newLinkCode, NO_LINK_HERE, playersOn, typedAs, unlink } from "../../games/chat.ts"; |
| 79 | 79 | import { commitServer, planRemoveServer, planServer, wishOn } from "../../games/presets.ts"; |
| 80 | import { compile } from "../../games/wish.ts"; | |
| 81 | import { failedWords, gameServersOf, planLines, runWish, type WishRun } from "../../games/wish_run.ts"; | |
| 80 | 82 | import { commitJar, heldWords, leftWords, ONLY_PINNED, pinOf, PINS, planJar } from "../../games/proxy_jars.ts"; |
| 81 | 83 | import { canSleep, commitPolicy, EMPTY_SECONDS, isGameServer, policyOf, proxyOf, proxyPort, STILL_BILLED } from "../../games/sleep.ts"; |
| 82 | 84 | import { CLOUD_EVENT, cloudFacts, GAME_CLOUD_EVENT, pinnedOfBox } from "../../actions/cloud_says.ts"; |
| @@ -110,22 +112,51 @@ const dollars = (cents: number): string => `$${(cents / 100).toFixed(2)}`; | ||
| 110 | 112 | const mib = (n: number | undefined): string => |
| 111 | 113 | n === undefined || n === 0 ? "?" : n >= 1024 ? `${(n / 1024).toFixed(1)} GiB` : `${Math.round(n)} MiB`; |
| 112 | 114 | |
| 115 | /** What the New server box was asked: one new server (planned as it always was, its sha the yes), or any other sentence. */ | |
| 116 | type Asked = { readonly one: Awaited<ReturnType<typeof planServer>> } | { readonly run: WishRun }; | |
| 117 | ||
| 118 | async function askedOf(app: Ctx["app"], user: User, box: GameBox, words: string): Promise<Asked> { | |
| 119 | const compiled = compile(words, await gameServersOf(app, box)); | |
| 120 | const only = compiled.steps.length === 1 && compiled.questions.length === 0 && compiled.refused.length === 0 ? compiled.steps[0] : undefined; | |
| 121 | if (only?.kind === "server") return { one: await planServer(app, box, await wishOn(app, box, words)) }; | |
| 122 | return { run: await runWish(app, user, box, words, false) }; | |
| 123 | } | |
| 124 | ||
| 113 | 125 | /** |
| 114 | * New server: words in ("a void world with FAWE and bedwars"), the plan out (the service, its | |
| 115 | * plugins pinned, the memory math, where players join), then one button that commits it. | |
| 126 | * New server: words in ("a void world with FAWE and bedwars", or "set difficulty to hard on | |
| 127 | * survival"), the plan out (the service, its plugins pinned, the memory math, where players join), | |
| 128 | * then one button that commits it. A choice the words leave open is buttons, one sentence each. | |
| 116 | 129 | */ |
| 117 | function newServerBlock(box: GameBox, words: string, preview: Awaited<ReturnType<typeof planServer>> | undefined): Html { | |
| 130 | function newServerBlock(box: GameBox, words: string, asked: Asked | undefined): Html { | |
| 131 | const back = `/games/${box.name}`; | |
| 132 | const body = (): Html => { | |
| 133 | if (asked === undefined) return html`<p class="muted small">Say any change to this box's servers: a new server, a setting, a plugin to add, remove or update, or a plugin's config. ${PREVIEW_WORDS}</p>`; | |
| 134 | if ("one" in asked) return asked.one.ok ? previewBlock(asked.one.value, `${back}/servers`, { op: "create", words }, "Create it", back) : html`<p role="alert">${asked.one.error}</p>`; | |
| 135 | const run = asked.run; | |
| 136 | if (run.kind === "refused") return html`<p role="alert">${run.refused.join(" ")}</p>`; | |
| 137 | if (run.kind === "ask") | |
| 138 | return html`${run.questions.map( | |
| 139 | (q) => html`<h3>${q.prompt}</h3> | |
| 140 | <form method="get" action="${back}" class="row-fields"> | |
| 141 | ${q.options.map((o) => btn(o.label, { variant: "secondary", name: "words", value: o.sentence }))} | |
| 142 | </form>`, | |
| 143 | )}`; | |
| 144 | if (run.failed !== undefined) return html`<p role="alert">${failedWords(run)}</p>`; | |
| 145 | return html`<h3>This is what will change</h3> | |
| 146 | ${rowList(planLines(run).map((l) => row({ title: l })))} | |
| 147 | <form method="post" action="${back}/servers" class="row-fields"> | |
| 148 | <input type="hidden" name="op" value="wish" /> | |
| 149 | <input type="hidden" name="words" value="${words}" /> | |
| 150 | ${btn("Do it", { variant: "primary" })} ${btn("Cancel", { variant: "ghost", href: back })} | |
| 151 | </form>`; | |
| 152 | }; | |
| 118 | 153 | return html`<section class="settings-block" data-new-server> |
| 119 | 154 | <h2>New server</h2> |
| 120 | <form method="get" action="/games/${box.name}" class="row-fields"> | |
| 121 | ${input({ name: "words", label: "What kind", placeholder: "a void world with FAWE and bedwars", required: true, value: words })} | |
| 155 | <form method="get" action="${back}" class="row-fields"> | |
| 156 | ${input({ name: "words", label: "What to do", placeholder: "set difficulty to hard on survival", required: true, value: words })} | |
| 122 | 157 | ${btn("Preview it", { variant: "secondary" })} |
| 123 | 158 | </form> |
| 124 | ${preview === undefined | |
| 125 | ? html`<p class="muted small">${PREVIEW_WORDS} Void, flat or normal; FAWE, BedWars or LuckPerms by name; it sleeps when empty, so its memory counts free.</p>` | |
| 126 | : preview.ok | |
| 127 | ? previewBlock(preview.value, `/games/${box.name}/servers`, { op: "create", words }, "Create it", `/games/${box.name}`) | |
| 128 | : html`<p role="alert">${preview.error}</p>`} | |
| 159 | ${body()} | |
| 129 | 160 | </section>`; |
| 130 | 161 | } |
| 131 | 162 | |
| @@ -148,6 +179,13 @@ export async function gameServersSubmit(ctx: Ctx): Promise<Response> { | ||
| 148 | 179 | if (got instanceof Response) return got; |
| 149 | 180 | const form = await readForm(ctx, "rw"); |
| 150 | 181 | if (form instanceof Response) return form; |
| 182 | if (field(form, "op") === "wish") { | |
| 183 | const run = await runWish(ctx.app, ctx.auth.user!, got.box, field(form, "words").slice(0, 300), true); | |
| 184 | const where = `/games/${got.box.name}`; | |
| 185 | if (run.kind !== "plan") return flashTo(ctx, where, { tone: "danger", message: run.kind === "refused" ? run.refused.join(" ") : "The words leave a choice open; preview them again." }); | |
| 186 | if (run.failed !== undefined) return flashTo(ctx, where, { tone: "danger", message: failedWords(run) }); | |
| 187 | return flashTo(ctx, where, { message: `${run.changes.map((st) => st.says).join("; ")}; the box brings each change on its next check-in.` }); | |
| 188 | } | |
| 151 | 189 | const planned = |
| 152 | 190 | field(form, "op") === "remove" |
| 153 | 191 | ? await planRemoveServer(ctx.app, got.box, field(form, "service")) |
| @@ -306,7 +344,7 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 306 | 344 | // A new server asked for in words (?words=…): planned for the preview before anything is written. |
| 307 | 345 | const operator = mayDo(role, "operator"); |
| 308 | 346 | const words = (ctx.url.searchParams.get("words") ?? "").slice(0, 300); |
| 309 | const preview = operator && words.trim() !== "" ? await planServer(ctx.app, box, await wishOn(ctx.app, box, words)) : undefined; | |
| 347 | const preview = operator && words.trim() !== "" ? await askedOf(ctx.app, ctx.auth.user!, box, words) : undefined; | |
| 310 | 348 | // A server asked to be taken out (?remove=…): its plan, the same way. |
| 311 | 349 | const leaving = operator ? (ctx.url.searchParams.get("remove") ?? "").slice(0, 64) : ""; |
| 312 | 350 | const removal = leaving === "" ? undefined : await planRemoveServer(ctx.app, box, leaving); |
test/game-wish-run.test.ts added +364
| @@ -0,0 +1,364 @@ | ||
| 1 | /** | |
| 2 | * Plain words carried out on a box (#18042): the games tool's `wish` action plans every step of a | |
| 3 | * sentence with the plans the page uses, returns questions and refusals as they are, commits in | |
| 4 | * order only on `dryRun: false`, and stops at the first step that fails. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtempSync } from "node:fs"; | |
| 8 | import { rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 13 | import { createSession } from "../src/core/sessions.ts"; | |
| 14 | import { createToken } from "../src/core/tokens.ts"; | |
| 15 | import { createUser, type User } from "../src/core/users.ts"; | |
| 16 | import { readCompose } from "../src/games/compose.ts"; | |
| 17 | import { setYamlKey } from "../src/games/wish_run.ts"; | |
| 18 | import { boxNamed, createGameBox, grant } from "../src/games/store.ts"; | |
| 19 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 20 | import { quietLogs } from "./helpers/globals.ts"; | |
| 21 | ||
| 22 | quietLogs(); | |
| 23 | ||
| 24 | // The shape of mc-network: an anchor, the proxy's toml inline with its servers and forced hosts. | |
| 25 | const COMPOSE = `name: game | |
| 26 | ||
| 27 | x-paper: &paper | |
| 28 | image: itzg/minecraft-server:latest | |
| 29 | restart: unless-stopped | |
| 30 | networks: [mc] | |
| 31 | ||
| 32 | configs: | |
| 33 | velocity_toml: | |
| 34 | content: | | |
| 35 | bind = "0.0.0.0:25565" | |
| 36 | [servers] | |
| 37 | hub = "hub:25565" | |
| 38 | survival = "survival:25565" | |
| 39 | try = ["hub"] | |
| 40 | ||
| 41 | [forced-hosts] | |
| 42 | "mc.trevato.dev" = ["hub"] | |
| 43 | "survival.mc.trevato.dev" = ["survival"] | |
| 44 | ||
| 45 | [advanced] | |
| 46 | read-timeout = 30000 | |
| 47 | paper_global: | |
| 48 | content: | | |
| 49 | _version: 31 | |
| 50 | ||
| 51 | networks: | |
| 52 | mc: | |
| 53 | driver: bridge | |
| 54 | ||
| 55 | volumes: | |
| 56 | velocity: {} | |
| 57 | hub: {} | |
| 58 | ||
| 59 | services: | |
| 60 | velocity: | |
| 61 | image: itzg/mc-proxy:latest | |
| 62 | container_name: velocity | |
| 63 | networks: [mc] | |
| 64 | environment: | |
| 65 | TYPE: VELOCITY | |
| 66 | MEMORY: 768M | |
| 67 | configs: | |
| 68 | - source: velocity_toml | |
| 69 | target: /config/velocity.toml | |
| 70 | ||
| 71 | hub: | |
| 72 | <<: *paper | |
| 73 | container_name: hub | |
| 74 | environment: | |
| 75 | TYPE: PAPER | |
| 76 | VERSION: "1.21.6" | |
| 77 | MEMORY: 1G | |
| 78 | ||
| 79 | survival: | |
| 80 | <<: *paper | |
| 81 | container_name: survival | |
| 82 | environment: | |
| 83 | TYPE: PAPER | |
| 84 | VERSION: "1.21.6" | |
| 85 | MEMORY: 3G | |
| 86 | `; | |
| 87 | ||
| 88 | // A Modrinth with FAWE and Screaming BedWars for Paper 1.21.6, and one plugin that is not. | |
| 89 | const PROJECTS = [ | |
| 90 | { id: "FAid0001", slug: "fastasyncworldedit", title: "FastAsyncWorldEdit", games: ["1.21.6"] }, | |
| 91 | { id: "SBid0001", slug: "screamingbedwars", title: "Screaming BedWars", games: ["1.21.6"] }, | |
| 92 | { id: "OLid0001", slug: "oldthing", title: "Old Thing", games: ["1.20.1"] }, | |
| 93 | { id: "GNid0001", slug: "gunplay", title: "Gun Play", games: ["1.21.6"] }, | |
| 94 | ]; | |
| 95 | const wire = (p: (typeof PROJECTS)[number]) => ({ | |
| 96 | id: `${p.id.slice(0, 2)}v00001`, | |
| 97 | project_id: p.id, | |
| 98 | version_number: "1.0.0", | |
| 99 | version_type: "release", | |
| 100 | date_published: "2026-11-01T00:00:00Z", | |
| 101 | game_versions: p.games, | |
| 102 | loaders: ["paper", "spigot"], | |
| 103 | files: [ | |
| 104 | { | |
| 105 | url: `https://cdn.modrinth.com/data/${p.id}/versions/x/${p.slug}.jar`, | |
| 106 | filename: `${p.slug}.jar`, | |
| 107 | primary: true, | |
| 108 | hashes: { sha512: "a".repeat(128), sha1: "x" }, | |
| 109 | }, | |
| 110 | ], | |
| 111 | dependencies: [], | |
| 112 | }); | |
| 113 | async function modrinth(url: string): Promise<Response> { | |
| 114 | const u = new URL(url); | |
| 115 | const p = u.pathname; | |
| 116 | const proj = /^\/v2\/project\/([^/]+)$/.exec(p); | |
| 117 | if (proj) { | |
| 118 | const x = PROJECTS.find((y) => y.id === proj[1] || y.slug === proj[1]); | |
| 119 | return x === undefined ? new Response("{}", { status: 404 }) : Response.json({ id: x.id, slug: x.slug, title: x.title }); | |
| 120 | } | |
| 121 | const list = /^\/v2\/project\/([^/]+)\/version$/.exec(p); | |
| 122 | if (list) { | |
| 123 | const games = JSON.parse(u.searchParams.get("game_versions") ?? "null") as string[] | null; | |
| 124 | return Response.json( | |
| 125 | PROJECTS.filter((x) => (x.id === list[1] || x.slug === list[1]) && (games === null || x.games.some((g) => games.includes(g)))).map( | |
| 126 | wire, | |
| 127 | ), | |
| 128 | ); | |
| 129 | } | |
| 130 | // Search: "guns" finds Gun Play (well used) and a fresh one nobody uses; anything else finds nothing. | |
| 131 | if (p === "/v2/search") { | |
| 132 | const q = u.searchParams.get("query") ?? ""; | |
| 133 | const hit = (slug: string, id: string, downloads: number) => ({ project_id: id, slug, title: slug === "gunplay" ? "Gun Play" : slug, author: "a", description: "", downloads, versions: ["1.21.6"], categories: ["paper"], server_side: "required" }); | |
| 134 | return Response.json({ hits: /guns/.test(q) ? [hit("brandnew", "BNid0001", 3), hit("gunplay", "GNid0001", 52_000)] : [] }); | |
| 135 | } | |
| 136 | const one = /^\/v2\/version\/([^/]+)$/.exec(p); | |
| 137 | if (one) { | |
| 138 | const x = PROJECTS.find((y) => wire(y).id === one[1]); | |
| 139 | return x === undefined ? new Response("{}", { status: 404 }) : Response.json(wire(x)); | |
| 140 | } | |
| 141 | return new Response("{}", { status: 404 }); | |
| 142 | } | |
| 143 | ||
| 144 | test("a yaml key is replaced in place at its dotted path, comments kept; what is not a plain value is refused", () => { | |
| 145 | const text = "# top\nserver-name: a # why\nrules:\n pvp: true\n deep:\n n: 1\nother:\n pvp: false\nblock: |\n x\n"; | |
| 146 | expect(setYamlKey(text, "rules.pvp", "false")).toEqual({ ok: true, value: text.replace(" pvp: true", " pvp: false") }); | |
| 147 | expect(setYamlKey(text, "server-name", "lobby")).toEqual({ ok: true, value: text.replace("a # why", '"lobby" # why') }); | |
| 148 | expect(setYamlKey(text, "other.pvp", "true")).toEqual({ ok: true, value: text.replace(" pvp: false", " pvp: true") }); | |
| 149 | expect(setYamlKey(text, "rules.nope", "1").ok).toBe(false); | |
| 150 | expect(setYamlKey(text, "block", "1").ok).toBe(false); | |
| 151 | }); | |
| 152 | ||
| 153 | describe("on a forge", () => { | |
| 154 | let dataDir = ""; | |
| 155 | let app: App; | |
| 156 | let http: ForgeHttp; | |
| 157 | let ada: User; | |
| 158 | let bob: User; | |
| 159 | let bobToken = ""; | |
| 160 | beforeAll(async () => { | |
| 161 | dataDir = mkdtempSync(join(tmpdir(), "forge-game-wish-")); | |
| 162 | app = createApp({ dataDir, port: 0, modrinthFetch: modrinth as unknown as typeof fetch }); | |
| 163 | http = forgeHttp(app); | |
| 164 | const u = await createUser(app.db, { username: "ada", email: "[email protected]", password: "a-good-passphrase", origin: "seed", isAdmin: true, trusted: true }); | |
| 165 | if (!u.ok) throw new Error(u.error); | |
| 166 | ada = u.value; | |
| 167 | const repo = await createRepo(app, ada, { name: "mc-network", visibility: "private" }); | |
| 168 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 169 | const seeded = await commitToBranch(app, ada, repo.value, { message: "seed", files: [{ path: "docker-compose.yml", content: COMPOSE }] }); | |
| 170 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 171 | const { token } = createGameBox(app.db, { name: "mc", repo: "ada/mc-network" }); | |
| 172 | const b = await createUser(app.db, { username: "bob", email: "[email protected]", password: "a-good-passphrase", origin: "seed", isAdmin: false, trusted: true }); | |
| 173 | if (!b.ok) throw new Error(b.error); | |
| 174 | bob = b.value; | |
| 175 | grant(app.db, boxNamed(app.db, "mc")!.id, bob.id, "viewer"); | |
| 176 | bobToken = createToken(app.db, bob.id, "g", "admin").token; | |
| 177 | await http.handle( | |
| 178 | new Request("http://forge.test/api/v1/games/agent/sync", { | |
| 179 | method: "POST", | |
| 180 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 181 | body: JSON.stringify({ agent: 1, host: { memMiB: 7_900 } }), | |
| 182 | }), | |
| 183 | ); | |
| 184 | }, 30_000); | |
| 185 | afterAll(async () => { | |
| 186 | app.close(); | |
| 187 | await rm(dataDir, { recursive: true, force: true }); | |
| 188 | }); | |
| 189 | ||
| 190 | /** The games tool as `token` calls it (ada's by default; "" is no one signed in). */ | |
| 191 | const call = async (args: Record<string, unknown>, token: string | undefined = undefined) => { | |
| 192 | const bearer = token ?? createToken(app.db, ada.id, "g", "admin").token; | |
| 193 | const res = await http.handle( | |
| 194 | new Request("http://forge.test/mcp", { | |
| 195 | method: "POST", | |
| 196 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...(bearer === "" ? {} : { authorization: `Bearer ${bearer}` }) }, | |
| 197 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "games", arguments: { box: "mc", ...args } } }), | |
| 198 | }), | |
| 199 | ); | |
| 200 | const raw = await res.text(); | |
| 201 | let body: { result?: { content?: { text: string }[] } } = {}; | |
| 202 | try { | |
| 203 | body = JSON.parse(raw) as typeof body; | |
| 204 | } catch { | |
| 205 | return { refused: `${String(res.status)} ${raw}` } as Record<string, any>; | |
| 206 | } | |
| 207 | const said = body.result?.content?.[0]?.text ?? raw; | |
| 208 | return (said.startsWith("{") ? JSON.parse(said) : { refused: said }) as Record<string, any>; | |
| 209 | }; | |
| 210 | const text = async () => (await readCompose(app, boxNamed(app.db, "mc")!))!.text; | |
| 211 | ||
| 212 | test("the action explains itself when asked with no words", async () => { | |
| 213 | expect((await call({ action: "wish" }))["refused"]).toContain("in plain sentences"); | |
| 214 | }); | |
| 215 | ||
| 216 | test("a choice left open is a question, never a guess, and the proxy is not offered as a server", async () => { | |
| 217 | const got = await call({ action: "wish", words: "set difficulty to hard" }); | |
| 218 | expect(got["planned"]).toBeUndefined(); | |
| 219 | expect(got["questions"][0].options.map((o: { label: string }) => o.label)).toEqual(["hub", "survival"]); | |
| 220 | expect(got["questions"][0].options[1].sentence).toBe("set difficulty to hard on survival"); | |
| 221 | expect((await call({ action: "wish", words: "dance a little" }))["refused"]).toContain("not read"); | |
| 222 | }); | |
| 223 | ||
| 224 | test("a dry run plans every step and changes nothing; dryRun false commits them in order", async () => { | |
| 225 | const before = await text(); | |
| 226 | const words = "set difficulty to hard on survival; add custom guns to survival; new flat world called build"; | |
| 227 | const plan = await call({ action: "wish", words }); | |
| 228 | expect(plan["planned"]).toBe(true); | |
| 229 | expect(plan["changes"]).toHaveLength(3); | |
| 230 | expect(plan["changes"][0].says).toContain("difficulty"); | |
| 231 | expect(plan["changes"][1].lines.join(" ")).toContain("Gun Play"); | |
| 232 | expect(await text()).toBe(before); | |
| 233 | const done = await call({ action: "wish", words, dryRun: false }); | |
| 234 | expect(done["says"]).toContain("Done"); | |
| 235 | const now = yamlOf(await text()); | |
| 236 | expect(now.services.survival.environment.DIFFICULTY).toBe("hard"); | |
| 237 | expect(now.services.build).toBeDefined(); | |
| 238 | }); | |
| 239 | ||
| 240 | test("a step that fails stops the run and says what was asked in it and what is saved", async () => { | |
| 241 | const dry = await call({ action: "wish", words: "remove nothing-here from hub" }); | |
| 242 | expect(dry["refused"]).toContain('Could not do "remove nothing-here from hub"'); | |
| 243 | expect(dry["refused"]).toContain("Nothing was changed."); | |
| 244 | const got = await call({ action: "wish", words: "set difficulty to peaceful on hub; remove nothing-here from hub; set pvp to off on hub", dryRun: false }); | |
| 245 | expect(got["refused"]).toContain('Could not do "remove nothing-here from hub"'); | |
| 246 | expect(got["refused"]).toContain("What came before it is saved."); | |
| 247 | const now = yamlOf(await text()); | |
| 248 | expect(now.services.hub.environment.DIFFICULTY).toBe("peaceful"); | |
| 249 | expect(now.services.hub.environment.PVP).toBeUndefined(); | |
| 250 | }); | |
| 251 | ||
| 252 | test("waiting for a quiet box is refused, not read as a plugin's name; nothing is planned", async () => { | |
| 253 | const before = await text(); | |
| 254 | const got = await call({ action: "wish", words: "add custom guns to hub when nobody is on", dryRun: false }); | |
| 255 | expect(got["refused"]).toContain('without "when nobody is on"'); | |
| 256 | expect(await text()).toBe(before); | |
| 257 | }); | |
| 258 | ||
| 259 | test("two kinds in one sentence: a dry run says what follows the new server as a sentence; the run does both in order", async () => { | |
| 260 | const words = "new flat world called build2; set difficulty to hard on build2"; | |
| 261 | const before = await text(); | |
| 262 | const plan = await call({ action: "wish", words }); | |
| 263 | expect(plan["planned"]).toBe(true); | |
| 264 | expect(plan["changes"]).toHaveLength(2); | |
| 265 | expect(plan["changes"][1].says).toBe("Then, once build2 is in the network: difficulty = hard on build2"); | |
| 266 | expect(await text()).toBe(before); | |
| 267 | const done = await call({ action: "wish", words, dryRun: false }); | |
| 268 | expect(done["says"]).toContain("Done"); | |
| 269 | expect(yamlOf(await text()).services.build2.environment.DIFFICULTY).toBe("hard"); | |
| 270 | }); | |
| 271 | ||
| 272 | test("a person who only views the box, and one who is not signed in, are refused, and nothing is planned", async () => { | |
| 273 | const viewer = await call({ action: "wish", words: "set pvp to off on hub" }, bobToken); | |
| 274 | expect(viewer["changes"]).toBeUndefined(); | |
| 275 | expect(viewer["refused"] ?? viewer["error"] ?? JSON.stringify(viewer)).not.toContain("difficulty"); | |
| 276 | const guest = await call({ action: "wish", words: "set pvp to off on hub" }, ""); | |
| 277 | expect(guest["changes"]).toBeUndefined(); | |
| 278 | expect(guest["planned"]).toBeUndefined(); | |
| 279 | const before = await text(); | |
| 280 | await call({ action: "wish", words: "set pvp to off on hub", dryRun: false }, bobToken); | |
| 281 | expect(await text()).toBe(before); | |
| 282 | }); | |
| 283 | ||
| 284 | test("the New server box previews the same sentences: questions as buttons, one sentence each, then one button that does it", async () => { | |
| 285 | const cookie = `forge_session=${createSession(app.db, ada.id).token}`; | |
| 286 | const read = async (words: string) => (await http.handle(new Request(`http://forge.test/games/mc?words=${encodeURIComponent(words)}`, { headers: { cookie } }))).text(); | |
| 287 | const asking = await read("set pvp to off"); | |
| 288 | expect(asking).toContain("Which server?"); | |
| 289 | expect(asking).toContain('value="set pvp to off on survival"'); | |
| 290 | expect(asking).not.toContain("velocity</button>"); | |
| 291 | const plan = await read("set pvp to off on survival"); | |
| 292 | expect(plan).toContain("This is what will change"); | |
| 293 | expect(plan).toContain('name="op" value="wish"'); | |
| 294 | expect(plan).toMatch(/>\s*Do it\s*</); | |
| 295 | expect(await read("dance a little")).toContain("not read"); | |
| 296 | const before = await text(); | |
| 297 | const done = await http.handle( | |
| 298 | new Request("http://forge.test/games/mc/servers", { | |
| 299 | method: "POST", | |
| 300 | headers: { cookie, "content-type": "application/x-www-form-urlencoded", origin: "http://forge.test" }, | |
| 301 | body: new URLSearchParams({ op: "wish", words: "set pvp to off on survival" }), | |
| 302 | }), | |
| 303 | ); | |
| 304 | expect(done.status).toBeLessThan(400); | |
| 305 | expect(yamlOf(await text()).services.survival.environment.PVP).toBe("false"); | |
| 306 | expect(await text()).not.toBe(before); | |
| 307 | }); | |
| 308 | ||
| 309 | const send = (u: User, body: Record<string, string>) => | |
| 310 | http.handle(new Request("http://forge.test/games/mc/servers", { method: "POST", headers: { cookie: `forge_session=${createSession(app.db, u.id).token}`, origin: "http://forge.test" }, body: new URLSearchParams(body) })); | |
| 311 | /** What the page said back, as the flash it set. */ | |
| 312 | const flash = (res: Response): { tone?: string; message: string } => { | |
| 313 | const raw = /forge_flash=([^;]+)/.exec(res.headers.get("set-cookie") ?? "")?.[1]; | |
| 314 | return raw === undefined ? { message: "" } : (JSON.parse(decodeURIComponent(raw)) as { tone?: string; message: string }); | |
| 315 | }; | |
| 316 | ||
| 317 | test("the page: words that leave a choice open change nothing and say so; a step that fails says which and what was kept", async () => { | |
| 318 | const before = await text(); | |
| 319 | const open = flash(await send(ada, { op: "wish", words: "set pvp to off" })); | |
| 320 | expect(open.tone).toBe("danger"); | |
| 321 | expect(open.message).toContain("leave a choice open"); | |
| 322 | expect(await text()).toBe(before); | |
| 323 | const mid = flash(await send(ada, { op: "wish", words: "set difficulty to easy on survival; remove nothing-here from survival" })); | |
| 324 | expect(mid.tone).toBe("danger"); | |
| 325 | expect(mid.message).toContain('Could not do "remove nothing-here from survival"'); | |
| 326 | expect(mid.message).toContain("What came before it is saved."); | |
| 327 | expect(yamlOf(await text()).services.survival.environment.DIFFICULTY).toBe("easy"); | |
| 328 | }); | |
| 329 | ||
| 330 | test("a person who only views the box is shown no way to change it and cannot post one", async () => { | |
| 331 | const cookie = `forge_session=${createSession(app.db, bob.id).token}`; | |
| 332 | const page = await (await http.handle(new Request(`http://forge.test/games/mc?words=${encodeURIComponent("set pvp to off on hub")}`, { headers: { cookie } }))).text(); | |
| 333 | expect(page).not.toContain("data-new-server"); | |
| 334 | expect(page).not.toContain("This is what will change"); | |
| 335 | const before = await text(); | |
| 336 | expect((await send(bob, { op: "wish", words: "set pvp to off on hub" })).status).toBe(404); | |
| 337 | expect(await text()).toBe(before); | |
| 338 | }); | |
| 339 | ||
| 340 | test("the terminal: a choice left open is asked, the plan is shown in plain lines, and yes does it", async () => { | |
| 341 | const { createForgeApp } = await import("../src/tui/forge.ts"); | |
| 342 | const { gamesScreen } = await import("../src/tui/screens/games.ts"); | |
| 343 | const { headlessTerminal } = await import("../src/tui/term/terminal.ts"); | |
| 344 | const { settleApp, settleUntil } = await import("./helpers/tui.ts"); | |
| 345 | const { app: tui, session } = createForgeApp(app, { sshUsername: "ada", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: ada }, { terminal: headlessTerminal(140, 30), exitHooks: false }); | |
| 346 | tui.start(); | |
| 347 | tui.ctx.push(gamesScreen(session, tui.ctx)); | |
| 348 | await settleApp(tui); | |
| 349 | const key = (k: string) => tui.dispatch({ type: "key", key: k, ctrl: false, alt: false, shift: false }); | |
| 350 | key("n"); | |
| 351 | for (const c of "set pvp to off") key(c); | |
| 352 | key("enter"); | |
| 353 | await settleUntil(tui, "Which server?"); | |
| 354 | // The first of the choices, in the box's order: the servers the earlier tests added come before hub. | |
| 355 | key("enter"); | |
| 356 | await settleUntil(tui, "PVP true → false"); | |
| 357 | key("y"); | |
| 358 | await settleUntil(tui, "Set pvp to false on build"); | |
| 359 | expect(yamlOf(await text()).services.build.environment.PVP).toBe("false"); | |
| 360 | tui.stop?.(); | |
| 361 | }, 20_000); | |
| 362 | }); | |
| 363 | ||
| 364 | const yamlOf = (t: string): any => Bun.YAML.parse(t); |
test/game-wish.test.ts added +73
| @@ -0,0 +1,73 @@ | ||
| 1 | /** | |
| 2 | * Plain words to game-server intents, by rules alone (src/games/wish.ts, #18042): each sentence | |
| 3 | * compiles to the exact intents below, or to a question, or to a refusal that says what to say. | |
| 4 | * No network and no model. | |
| 5 | */ | |
| 6 | import { expect, test } from "bun:test"; | |
| 7 | import { compile, pickHit } from "../src/games/wish.ts"; | |
| 8 | ||
| 9 | const BOX = ["survival", "arena"]; | |
| 10 | const steps = (s: string, services: readonly string[] = BOX) => compile(s, services).steps; | |
| 11 | ||
| 12 | test("new servers: the words the New server box reads, with themes", () => { | |
| 13 | expect(steps("a void world called arena2 with FAWE")).toEqual([{ kind: "server", wish: expect.objectContaining({ name: "arena2", level: "void", plugins: ["fastasyncworldedit"] }) }]); | |
| 14 | expect(steps("flat creative server")).toEqual([{ kind: "server", wish: expect.objectContaining({ name: "creative", level: "flat" }) }]); | |
| 15 | expect(steps("new server with bedwars")).toEqual([{ kind: "server", wish: expect.objectContaining({ name: "bedwars", plugins: ["screamingbedwars"] }) }]); | |
| 16 | expect(steps("a world with zombie survival and custom guns")).toEqual([{ kind: "server", wish: expect.objectContaining({ themes: ["zombie survival", "custom guns"] }) }]); | |
| 17 | }); | |
| 18 | ||
| 19 | test("settings: by their names and plain phrases, each value as its kind takes it", () => { | |
| 20 | expect(steps("set difficulty to hard on survival")).toEqual([{ kind: "set", service: "survival", key: "difficulty", value: "hard" }]); | |
| 21 | expect(steps("make pvp off on arena")).toEqual([{ kind: "set", service: "arena", key: "pvp", value: "false" }]); | |
| 22 | expect(steps("view distance 12 on survival")).toEqual([{ kind: "set", service: "survival", key: "view-distance", value: "12" }]); | |
| 23 | expect(steps("set max players to 20 on arena")).toEqual([{ kind: "set", service: "arena", key: "max-players", value: "20" }]); | |
| 24 | expect(steps("set whitelist to on on survival")).toEqual([{ kind: "set", service: "survival", key: "white-list", value: "true" }]); | |
| 25 | const out = compile("set view distance to 99 on survival", BOX); | |
| 26 | expect(out.steps).toEqual([]); | |
| 27 | expect(out.refused[0]).toContain("view-distance is from"); | |
| 28 | }); | |
| 29 | ||
| 30 | test("mods and plugins: aliases, names for Modrinth, update all, and held until nobody is on", () => { | |
| 31 | expect(steps("add Distant Horizons to survival")).toEqual([{ kind: "install", service: "survival", ref: "distant horizons" }]); | |
| 32 | expect(steps("add worldedit to arena")).toEqual([{ kind: "install", service: "arena", ref: "fastasyncworldedit" }]); | |
| 33 | expect(steps("remove luckperms from arena")).toEqual([{ kind: "remove", service: "arena", ref: "luckperms" }]); | |
| 34 | expect(steps("update all on survival")).toEqual([{ kind: "update", service: "survival", ref: "all" }]); | |
| 35 | // Waiting for a quiet box is not offered for mods: refused in words, never read as a plugin's name. | |
| 36 | const waits = compile("add Distant Horizons to survival when nobody is on", BOX); | |
| 37 | expect(waits.steps).toEqual([]); | |
| 38 | expect(waits.refused[0]).toContain('without "when nobody is on"'); | |
| 39 | expect(steps("config luckperms server-name = lobby on arena")).toEqual([{ kind: "config", service: "arena", file: "plugins/luckperms/config.yml", path: "server-name", value: "lobby" }]); | |
| 40 | }); | |
| 41 | ||
| 42 | test("an open choice is a question whose options are sentences that compile; nothing unclear is guessed", () => { | |
| 43 | const which = compile("set difficulty to hard", BOX); | |
| 44 | expect(which.steps).toEqual([]); | |
| 45 | expect(which.questions[0]!.options.map((o) => o.label)).toEqual(["survival", "arena"]); | |
| 46 | expect(steps(which.questions[0]!.options[1]!.sentence)).toEqual([{ kind: "set", service: "arena", key: "difficulty", value: "hard" }]); | |
| 47 | const setting = compile("set distance to 10 on survival", BOX); | |
| 48 | expect(setting.questions[0]!.options.map((o) => o.label)).toEqual(expect.arrayContaining(["view-distance", "simulation-distance"])); | |
| 49 | expect(compile("set colour to blue on survival", BOX).refused[0]).toContain('no setting is called "colour"'); | |
| 50 | expect(compile("dance a little", BOX).refused[0]).toContain("not read"); | |
| 51 | // One server: no question. | |
| 52 | expect(steps("set difficulty to hard", ["survival"])).toEqual([{ kind: "set", service: "survival", key: "difficulty", value: "hard" }]); | |
| 53 | }); | |
| 54 | ||
| 55 | test("two orders in one sentence run in order; the new server can be named by the next", () => { | |
| 56 | expect(steps("new server called pvp; set difficulty to hard on pvp")).toEqual([ | |
| 57 | { kind: "server", wish: expect.objectContaining({ name: "pvp" }) }, | |
| 58 | { kind: "set", service: "pvp", key: "difficulty", value: "hard" }, | |
| 59 | ]); | |
| 60 | }); | |
| 61 | ||
| 62 | test("Modrinth's hits: a clear winner is picked, two close ones are a question, none used is nothing", () => { | |
| 63 | const hit = (slug: string, downloads: number, fits = true) => ({ slug, title: slug, description: "", downloads, fits }); | |
| 64 | expect(pickHit([hit("gunplay", 52_000), hit("guns-lite", 9_000)], "add custom guns to survival", "custom guns")).toEqual({ slug: "gunplay" }); | |
| 65 | const close = pickHit([hit("weapons-a", 40_000), hit("weapons-b", 38_000)], "add custom guns to survival", "custom guns"); | |
| 66 | expect("ask" in close && close.ask.options.map((o) => o.sentence)).toEqual(["add weapons-a to survival", "add weapons-b to survival"]); | |
| 67 | expect(pickHit([hit("new", 3), hit("old", 90_000, false)], "add x to survival", "x")).toEqual({ none: true }); | |
| 68 | }); | |
| 69 | ||
| 70 | test("the same sentence compiles the same way every time", () => { | |
| 71 | const s = "new server called pvp; set difficulty to hard on pvp; add worldedit to pvp"; | |
| 72 | expect(compile(s, BOX)).toEqual(compile(s, BOX)); | |
| 73 | }); |
new above
offline