dialogue-namespace.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import { createEngine, type DialogueDef } from "@nengine/core";
  6. import { createEngineNamespaces, McpGateway } from "../src/index.js";
  7. const TIME_YAML = [
  8. "id: default",
  9. "dayLengthTicks: 480",
  10. "seasons:",
  11. " - { name: spring, dayCount: 28 }",
  12. "start: { day: 1, season: spring }",
  13. "",
  14. ].join("\n");
  15. const FARM_YAML = [
  16. "id: farm",
  17. "width: 2",
  18. "height: 2",
  19. 'tilesetRef: "tiles"',
  20. "spawn: { x: 0, y: 0 }",
  21. "layers:",
  22. " - name: ground",
  23. " data:",
  24. " - [a, b]",
  25. " - [b, a]",
  26. "",
  27. ].join("\n");
  28. const DIALOGUE_DEF = {
  29. id: "welcome",
  30. startNode: "hello",
  31. nodes: [
  32. {
  33. id: "hello",
  34. text: "Hello!",
  35. choices: [
  36. { text: "Give me a seed", to: "thanks", actions: [{ action: "give-item", itemId: "parsnip-seed", qty: 1 }] },
  37. { text: "No thanks", to: "bye" },
  38. ],
  39. },
  40. { id: "thanks", text: "Here you go." },
  41. { id: "bye", text: "Bye!" },
  42. ],
  43. };
  44. interface Setup {
  45. engine: ReturnType<typeof createEngine>;
  46. gateway: McpGateway;
  47. tmp: string;
  48. close: () => Promise<void>;
  49. }
  50. async function setup(): Promise<Setup> {
  51. const tmp = await mkdtemp(join(tmpdir(), "farm-dialogue-"));
  52. await mkdir(join(tmp, "maps"), { recursive: true });
  53. await writeFile(join(tmp, "time.yaml"), TIME_YAML);
  54. await writeFile(join(tmp, "maps", "farm.yaml"), FARM_YAML);
  55. const engine = createEngine({ contentDir: tmp });
  56. const gateway = new McpGateway();
  57. for (const namespace of createEngineNamespaces(engine, { gateway })) {
  58. gateway.register(namespace);
  59. }
  60. await engine.start();
  61. return {
  62. engine,
  63. gateway,
  64. tmp,
  65. close: async () => {
  66. await engine.stop();
  67. await rm(tmp, { recursive: true, force: true });
  68. },
  69. };
  70. }
  71. async function callText(gateway: McpGateway, name: string, args: Record<string, unknown> = {}): Promise<{
  72. ok: boolean;
  73. text: string;
  74. }> {
  75. const result = await gateway.callTool(name, args);
  76. return { ok: result.isError !== true, text: result.content[0]?.text ?? "" };
  77. }
  78. describe("dialogue namespace", () => {
  79. it("dialogue.create writes content/dialogues/<id>.yaml, registers live, and persists across restart", async () => {
  80. const { engine, gateway, tmp, close } = await setup();
  81. try {
  82. const created = await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF });
  83. expect(created.ok).toBe(true);
  84. expect(JSON.parse(created.text) as DialogueDef).toEqual(DIALOGUE_DEF);
  85. expect(engine.registry.get<DialogueDef>("dialogue", "welcome")).toEqual(DIALOGUE_DEF);
  86. const file = await readFile(join(tmp, "dialogues", "welcome.yaml"), "utf8");
  87. expect(file).toContain("id: welcome");
  88. expect(file).toContain("startNode: hello");
  89. expect(file).toContain("give-item");
  90. await engine.stop();
  91. const reloaded = createEngine({ contentDir: tmp });
  92. await reloaded.start();
  93. try {
  94. expect(reloaded.registry.get<DialogueDef>("dialogue", "welcome")).toEqual(DIALOGUE_DEF);
  95. } finally {
  96. await reloaded.stop();
  97. }
  98. } finally {
  99. await close();
  100. }
  101. });
  102. it("dialogue.validate accepts a valid def and rejects invalid ones", async () => {
  103. const { gateway, close } = await setup();
  104. try {
  105. const valid = await callText(gateway, "dialogue.validate", { def: DIALOGUE_DEF });
  106. expect(valid.ok).toBe(true);
  107. expect(JSON.parse(valid.text)).toEqual(DIALOGUE_DEF);
  108. const badStart = await callText(gateway, "dialogue.validate", {
  109. def: { ...DIALOGUE_DEF, startNode: "ghost" },
  110. });
  111. expect(badStart.ok).toBe(false);
  112. expect(badStart.text).toMatch(/startNode/);
  113. const mixed = await callText(gateway, "dialogue.validate", {
  114. def: {
  115. ...DIALOGUE_DEF,
  116. nodes: [{ id: "hello", text: "x", to: "bye", choices: [{ text: "Go", to: "bye" }] }],
  117. },
  118. });
  119. expect(mixed.ok).toBe(false);
  120. expect(mixed.text).toMatch(/choices and to/);
  121. const badTarget = await callText(gateway, "dialogue.validate", {
  122. def: { ...DIALOGUE_DEF, nodes: [{ id: "hello", text: "x", to: "ghost" }] },
  123. });
  124. expect(badTarget.ok).toBe(false);
  125. expect(badTarget.text).toMatch(/to must be a declared node/);
  126. } finally {
  127. await close();
  128. }
  129. });
  130. it("dialogue.create rejects an invalid def and does not write or register", async () => {
  131. const { engine, gateway, tmp, close } = await setup();
  132. try {
  133. const bad = await callText(gateway, "dialogue.create", {
  134. def: { ...DIALOGUE_DEF, startNode: "nope" },
  135. });
  136. expect(bad.ok).toBe(false);
  137. expect(engine.registry.get("dialogue", "welcome")).toBeUndefined();
  138. await expect(readFile(join(tmp, "dialogues", "welcome.yaml"))).rejects.toThrow();
  139. } finally {
  140. await close();
  141. }
  142. });
  143. it("duplicate dialogue.create overwrites the existing definition", async () => {
  144. const { engine, gateway, tmp, close } = await setup();
  145. try {
  146. await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF });
  147. const recreated = await callText(gateway, "dialogue.create", {
  148. def: { ...DIALOGUE_DEF, nodes: [...DIALOGUE_DEF.nodes, { id: "extra", text: "extra" }] },
  149. });
  150. expect(recreated.ok).toBe(true);
  151. const current = engine.registry.get<DialogueDef>("dialogue", "welcome");
  152. expect(current?.nodes).toHaveLength(4);
  153. const file = await readFile(join(tmp, "dialogues", "welcome.yaml"), "utf8");
  154. expect(file).toContain("extra");
  155. } finally {
  156. await close();
  157. }
  158. });
  159. it("dialogue.update merges a patch, validates, rewrites the file, and re-registers", async () => {
  160. const { engine, gateway, tmp, close } = await setup();
  161. try {
  162. await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF });
  163. const updated = await callText(gateway, "dialogue.update", {
  164. id: "welcome",
  165. patch: { startNode: "bye" },
  166. });
  167. expect(updated.ok).toBe(true);
  168. const def = JSON.parse(updated.text) as DialogueDef;
  169. expect(def.startNode).toBe("bye");
  170. expect(def.nodes).toHaveLength(3);
  171. const file = await readFile(join(tmp, "dialogues", "welcome.yaml"), "utf8");
  172. expect(file).toContain("startNode: bye");
  173. const missing = await callText(gateway, "dialogue.update", {
  174. id: "nope",
  175. patch: { startNode: "bye" },
  176. });
  177. expect(missing.ok).toBe(false);
  178. expect(missing.text).toMatch(/dialogue not found: nope/);
  179. const badPatch = await callText(gateway, "dialogue.update", {
  180. id: "welcome",
  181. patch: { startNode: "ghost" },
  182. });
  183. expect(badPatch.ok).toBe(false);
  184. expect(engine.registry.get<DialogueDef>("dialogue", "welcome")?.startNode).toBe("bye");
  185. } finally {
  186. await close();
  187. }
  188. });
  189. it("dialogue.list returns {dialogues:[...]} summaries", async () => {
  190. const { gateway, close } = await setup();
  191. try {
  192. await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF });
  193. await callText(gateway, "dialogue.create", {
  194. def: {
  195. id: "other",
  196. startNode: "a",
  197. nodes: [
  198. { id: "a", text: "a" },
  199. { id: "b", text: "b" },
  200. ],
  201. },
  202. });
  203. const listed = await callText(gateway, "dialogue.list");
  204. expect(listed.ok).toBe(true);
  205. expect(JSON.parse(listed.text)).toEqual({
  206. dialogues: [
  207. { id: "welcome", nodeCount: 3, startNode: "hello" },
  208. { id: "other", nodeCount: 2, startNode: "a" },
  209. ],
  210. });
  211. } finally {
  212. await close();
  213. }
  214. });
  215. it("dialogue.get returns the full def; unknown id is an error result", async () => {
  216. const { gateway, close } = await setup();
  217. try {
  218. await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF });
  219. const got = await callText(gateway, "dialogue.get", { dialogueId: "welcome" });
  220. expect(got.ok).toBe(true);
  221. expect(JSON.parse(got.text)).toEqual(DIALOGUE_DEF);
  222. const missing = await callText(gateway, "dialogue.get", { dialogueId: "nope" });
  223. expect(missing.ok).toBe(false);
  224. expect(missing.text).toMatch(/dialogue not found: nope/);
  225. const blank = await callText(gateway, "dialogue.get", { dialogueId: "" });
  226. expect(blank.ok).toBe(false);
  227. expect(blank.text).toMatch(/non-empty string/);
  228. } finally {
  229. await close();
  230. }
  231. });
  232. it("dialogue.start returns the current node; unknown dialogue is an error result", async () => {
  233. const { engine, gateway, close } = await setup();
  234. try {
  235. await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF });
  236. const started = await callText(gateway, "dialogue.start", { dialogueId: "welcome" });
  237. expect(started.ok).toBe(true);
  238. expect(JSON.parse(started.text)).toEqual({
  239. dialogueId: "welcome",
  240. nodeId: "hello",
  241. text: "Hello!",
  242. choices: [
  243. { text: "Give me a seed", to: "thanks" },
  244. { text: "No thanks", to: "bye" },
  245. ],
  246. });
  247. expect(engine.world.get("dialogue:active")?.nodeId).toBe("hello");
  248. const missing = await callText(gateway, "dialogue.start", { dialogueId: "nope" });
  249. expect(missing.ok).toBe(false);
  250. expect(missing.text).toMatch(/unknown dialogue: nope/);
  251. } finally {
  252. await close();
  253. }
  254. });
  255. it("dialogue.choose advances the dialogue and errors on bad indices / no active dialogue", async () => {
  256. const { engine, gateway, close } = await setup();
  257. try {
  258. await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF });
  259. await callText(gateway, "dialogue.start", { dialogueId: "welcome" });
  260. const chosen = await callText(gateway, "dialogue.choose", { index: 0 });
  261. expect(chosen.ok).toBe(true);
  262. expect(JSON.parse(chosen.text)).toEqual({
  263. dialogueId: "welcome",
  264. nodeId: "thanks",
  265. text: "Here you go.",
  266. choices: [],
  267. });
  268. expect(engine.world.get("dialogue:active")).toBeUndefined();
  269. const ended = await callText(gateway, "dialogue.choose", { index: 0 });
  270. expect(ended.ok).toBe(false);
  271. expect(ended.text).toMatch(/no active dialogue/);
  272. await callText(gateway, "dialogue.start", { dialogueId: "welcome" });
  273. const outOfRange = await callText(gateway, "dialogue.choose", { index: 9 });
  274. expect(outOfRange.ok).toBe(false);
  275. expect(outOfRange.text).toMatch(/choice index out of range/);
  276. const nonInt = await callText(gateway, "dialogue.choose", { index: -1 });
  277. expect(nonInt.ok).toBe(false);
  278. expect(nonInt.text).toMatch(/non-negative integer/);
  279. } finally {
  280. await close();
  281. }
  282. });
  283. it("resources dialogue://catalog and dialogue://{id}; missing id rejects", async () => {
  284. const { gateway, close } = await setup();
  285. try {
  286. await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF });
  287. const catalog = await gateway.readResource("dialogue://catalog");
  288. expect(JSON.parse(catalog.contents[0]?.text ?? "{}")).toEqual({ dialogues: [DIALOGUE_DEF] });
  289. const single = await gateway.readResource("dialogue://welcome");
  290. expect(JSON.parse(single.contents[0]?.text ?? "{}")).toEqual(DIALOGUE_DEF);
  291. await expect(gateway.readResource("dialogue://missing")).rejects.toThrow(/dialogue not found: missing/);
  292. } finally {
  293. await close();
  294. }
  295. });
  296. it("serves the dialogue.create-prompt prompt", async () => {
  297. const { gateway, close } = await setup();
  298. try {
  299. const prompt = await gateway.getPrompt("dialogue.create-prompt", {});
  300. const text = prompt.messages[0]?.content.text ?? "";
  301. expect(text).toContain("nodes");
  302. expect(text).toContain("choices");
  303. expect(text).toContain("content/dialogues/<id>.yaml");
  304. expect(text).toContain("dialogue.validate");
  305. expect(text).toContain("give-item");
  306. } finally {
  307. await close();
  308. }
  309. });
  310. });