player-namespace.test.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. import { mkdtemp, mkdir, 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 CropDef, type DialogueDef, type ItemDef, type PlantingSystem, type ShopDef } 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: 5",
  18. "height: 5",
  19. 'tilesetRef: "tiles"',
  20. "spawn: { x: 0, y: 0 }",
  21. "layers:",
  22. " - name: ground",
  23. " data:",
  24. " - [grass, grass, water, water, water]",
  25. " - [grass, grass, water, water, water]",
  26. " - [grass, grass, grass, grass, grass]",
  27. " - [grass, grass, grass, grass, grass]",
  28. " - [grass, grass, grass, grass, grass]",
  29. "",
  30. ].join("\n");
  31. const PARSNIP_SEED: ItemDef = { id: "parsnip-seed", name: "Parsnip Seed", kind: "seed", stackable: true };
  32. const PARSNIP: ItemDef = { id: "parsnip", name: "Parsnip", kind: "material", stackable: true };
  33. const PARSNIP_CROP: CropDef = {
  34. id: "parsnip",
  35. seedItem: "parsnip-seed",
  36. stages: [
  37. { name: "sprout", days: 1, waterRequired: true },
  38. { name: "mature", days: 1, waterRequired: false },
  39. ],
  40. seasons: ["spring"],
  41. drops: [{ itemId: "parsnip", qty: 1 }],
  42. };
  43. const GENERAL_STORE: ShopDef = {
  44. id: "general-store",
  45. buys: [{ itemId: "parsnip", price: 30 }],
  46. sells: [{ itemId: "parsnip-seed", price: 20, stock: 99 }],
  47. };
  48. const WELCOME: DialogueDef = {
  49. id: "welcome",
  50. startNode: "hello",
  51. nodes: [
  52. { id: "hello", text: "Welcome!", choices: [{ text: "Thanks", to: "farewell" }] },
  53. { id: "farewell", text: "See ya" },
  54. ],
  55. };
  56. interface Setup {
  57. engine: ReturnType<typeof createEngine>;
  58. gateway: McpGateway;
  59. close: () => Promise<void>;
  60. }
  61. async function setup(): Promise<Setup> {
  62. const tmp = await mkdtemp(join(tmpdir(), "farm-player-ns-"));
  63. await mkdir(join(tmp, "maps"), { recursive: true });
  64. await writeFile(join(tmp, "time.yaml"), TIME_YAML);
  65. await writeFile(join(tmp, "maps", "farm.yaml"), FARM_YAML);
  66. const engine = createEngine({ contentDir: tmp });
  67. const gateway = new McpGateway();
  68. for (const namespace of createEngineNamespaces(engine, { gateway })) {
  69. gateway.register(namespace);
  70. }
  71. await engine.start();
  72. engine.registry.register("item", PARSNIP_SEED);
  73. engine.registry.register("item", PARSNIP);
  74. engine.registry.register("crop", PARSNIP_CROP);
  75. engine.registry.register("shop", GENERAL_STORE);
  76. engine.registry.register("dialogue", WELCOME);
  77. return {
  78. engine,
  79. gateway,
  80. close: async () => {
  81. await engine.stop();
  82. await rm(tmp, { recursive: true, force: true });
  83. },
  84. };
  85. }
  86. async function callText(gateway: McpGateway, name: string, args: Record<string, unknown> = {}): Promise<{
  87. ok: boolean;
  88. text: string;
  89. }> {
  90. const result = await gateway.callTool(name, args);
  91. return { ok: result.isError !== true, text: result.content[0]?.text ?? "" };
  92. }
  93. describe("player namespace", () => {
  94. it("player.intent move relocates the player entity", async () => {
  95. const { engine, gateway, close } = await setup();
  96. try {
  97. const moved = await callText(gateway, "player.intent", { action: "move", tile: { x: 3, y: 2 } });
  98. expect(moved.ok).toBe(true);
  99. expect(JSON.parse(moved.text)).toEqual({ action: "move", tile: { x: 3, y: 2 }, ok: true, detail: "moved to (3,2)" });
  100. expect(engine.world.get("player")).toMatchObject({ x: 3, y: 2 });
  101. } finally {
  102. await close();
  103. }
  104. });
  105. it("player.intent interact follows the priority order: till → sow → water → harvest", async () => {
  106. const { engine, gateway, close } = await setup();
  107. try {
  108. const inv = engine.systems.get("inventory");
  109. const growth = engine.systems.get("growth");
  110. if (!inv || !growth) throw new Error("systems not booted");
  111. const tilled = await callText(gateway, "player.intent", { action: "interact", tile: { x: 2, y: 2 } });
  112. expect(JSON.parse(tilled.text)).toMatchObject({ ok: true, detail: "tilled plot" });
  113. inv.give("parsnip-seed", 1);
  114. const sown = await callText(gateway, "player.intent", { action: "interact", tile: { x: 2, y: 2 } });
  115. expect(JSON.parse(sown.text)).toMatchObject({ ok: true, detail: "sowed Parsnip Seed" });
  116. expect(inv.count("parsnip-seed")).toBe(0);
  117. const watered = await callText(gateway, "player.intent", { action: "interact", tile: { x: 2, y: 2 } });
  118. expect(JSON.parse(watered.text)).toMatchObject({ ok: true, detail: "watered plot" });
  119. const notReady = await callText(gateway, "player.intent", { action: "interact", tile: { x: 2, y: 2 } });
  120. expect(notReady.ok).toBe(false);
  121. expect(notReady.text).toMatch(/player\.intent: crop parsnip is not ready to harvest/);
  122. const planting = engine.systems.get<PlantingSystem>("planting");
  123. if (!planting) throw new Error("planting system not booted");
  124. growth.forceStage("plot:2:2", 1);
  125. const harvested = await callText(gateway, "player.intent", { action: "interact", tile: { x: 2, y: 2 } });
  126. expect(JSON.parse(harvested.text)).toMatchObject({ ok: true, detail: "harvested parsnip" });
  127. expect(inv.count("parsnip")).toBe(1);
  128. } finally {
  129. await close();
  130. }
  131. });
  132. it("player.intent validates action and tile arguments", async () => {
  133. const { gateway, close } = await setup();
  134. try {
  135. const badAction = await callText(gateway, "player.intent", { action: "dance", tile: { x: 1, y: 1 } });
  136. expect(badAction.ok).toBe(false);
  137. expect(badAction.text).toMatch(/action must be one of "move", "interact", "buy", "sell", "talk", "choose", "select-seed"/);
  138. const badTile = await callText(gateway, "player.intent", { action: "move", tile: { x: 1.5, y: 0 } });
  139. expect(badTile.ok).toBe(false);
  140. expect(badTile.text).toMatch(/non-negative integers/);
  141. const water = await callText(gateway, "player.intent", { action: "move", tile: { x: 2, y: 0 } });
  142. expect(water.ok).toBe(false);
  143. expect(water.text).toMatch(/player\.intent: intent\.move: tile \(2,0\) is not walkable/);
  144. } finally {
  145. await close();
  146. }
  147. });
  148. it("resource player://state reads the live player entity", async () => {
  149. const { gateway, close } = await setup();
  150. try {
  151. await callText(gateway, "player.intent", { action: "move", tile: { x: 4, y: 4 } });
  152. const state = await gateway.readResource("player://state");
  153. expect(JSON.parse(state.contents[0]?.text ?? "{}")).toMatchObject({ id: "player", type: "player", x: 4, y: 4 });
  154. } finally {
  155. await close();
  156. }
  157. });
  158. it("player.* exposes no prompts (runtime-entity namespace)", async () => {
  159. const { gateway, close } = await setup();
  160. try {
  161. const prompts = gateway.listPrompts().map((prompt) => prompt.name);
  162. expect(prompts.some((name) => name.startsWith("player."))).toBe(false);
  163. } finally {
  164. await close();
  165. }
  166. });
  167. it("player.intent buy/sell/talk/choose/select-seed drive the extended actions", async () => {
  168. const { engine, gateway, close } = await setup();
  169. try {
  170. const player = engine.world.get("player");
  171. if (!player) throw new Error("player entity not seeded");
  172. player.gold = 100;
  173. const bought = await callText(gateway, "player.intent", {
  174. action: "buy",
  175. shopId: "general-store",
  176. itemId: "parsnip-seed",
  177. qty: 2,
  178. });
  179. expect(bought.ok).toBe(true);
  180. expect(JSON.parse(bought.text)).toMatchObject({
  181. action: "buy",
  182. ok: true,
  183. detail: { shopId: "general-store", itemId: "parsnip-seed", qty: 2, total: 40, gold: 60 },
  184. });
  185. const missingItem = await callText(gateway, "player.intent", { action: "buy", shopId: "general-store" });
  186. expect(missingItem.ok).toBe(false);
  187. expect(missingItem.text).toMatch(/buy requires itemId/);
  188. engine.world.create({ id: "npc:clerk", type: "npc", x: 3, y: 3, dialogue: "welcome" });
  189. const talked = await callText(gateway, "player.intent", { action: "talk", npcId: "npc:clerk" });
  190. expect(talked.ok).toBe(true);
  191. expect(JSON.parse(talked.text)).toMatchObject({ action: "talk", ok: true, detail: { dialogueId: "welcome" } });
  192. const chosen = await callText(gateway, "player.intent", { action: "choose", index: 0 });
  193. expect(chosen.ok).toBe(true);
  194. expect(JSON.parse(chosen.text)).toMatchObject({ action: "choose", ok: true, detail: { nodeId: "farewell" } });
  195. const selected = await callText(gateway, "player.intent", { action: "select-seed", seedItemId: "parsnip-seed" });
  196. expect(selected.ok).toBe(true);
  197. expect(JSON.parse(selected.text)).toMatchObject({
  198. action: "select-seed",
  199. ok: true,
  200. detail: { selectedSeed: "parsnip-seed" },
  201. });
  202. expect(engine.world.get("player")).toMatchObject({ selectedSeed: "parsnip-seed" });
  203. const notASeed = await callText(gateway, "player.intent", { action: "select-seed", seedItemId: "hoe" });
  204. expect(notASeed.ok).toBe(false);
  205. expect(notASeed.text).toMatch(/hoe is not a seed item/);
  206. } finally {
  207. await close();
  208. }
  209. });
  210. });