rpg-engine 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/README.md +5 -5
  2. package/dist/campaign/create-campaign.d.ts +6 -1
  3. package/dist/campaign/create-campaign.js +41 -13
  4. package/dist/campaign/find-campaign.d.ts +5 -0
  5. package/dist/campaign/find-campaign.js +20 -5
  6. package/dist/campaign/host-files.d.ts +14 -4
  7. package/dist/campaign/host-files.js +193 -36
  8. package/dist/campaign/index.d.ts +2 -2
  9. package/dist/campaign/index.js +2 -2
  10. package/dist/campaign/settings.d.ts +3 -3
  11. package/dist/campaign/settings.js +5 -4
  12. package/dist/cli/cli.js +28 -7
  13. package/dist/commands/config/config.js +1 -1
  14. package/dist/commands/config/dashboard.js +28 -6
  15. package/dist/commands/config/words.js +2 -1
  16. package/dist/commands/image.d.ts +3 -0
  17. package/dist/commands/image.js +32 -5
  18. package/dist/commands/import/import.d.ts +3 -1
  19. package/dist/commands/import/import.js +16 -3
  20. package/dist/commands/init.d.ts +2 -0
  21. package/dist/commands/init.js +21 -3
  22. package/dist/commands/instructions.js +1 -1
  23. package/dist/commands/shared/campaign/git.js +1 -1
  24. package/dist/commands/shared/campaign/images.js +6 -3
  25. package/dist/commands/shared/campaign/mode.js +1 -1
  26. package/dist/commands/shared/characters/voices.d.ts +2 -2
  27. package/dist/commands/shared/characters/voices.js +9 -6
  28. package/dist/commands/shared/sheet/sheet.d.ts +2 -2
  29. package/dist/commands/shared/sheet/sheet.js +3 -3
  30. package/dist/core/context.d.ts +21 -6
  31. package/dist/core/context.js +2 -1
  32. package/dist/dashboard/acts/acts.js +39 -11
  33. package/dist/dashboard/acts/head.js +7 -0
  34. package/dist/dashboard/acts/names.js +4 -2
  35. package/dist/dashboard/acts/sending.js +23 -22
  36. package/dist/dashboard/acts/sheet.js +7 -149
  37. package/dist/dashboard/acts/strip.js +10 -14
  38. package/dist/dashboard/acts/talk.js +51 -0
  39. package/dist/dashboard/acts/thing.js +169 -0
  40. package/dist/dashboard/app.js +3 -3
  41. package/dist/dashboard/guide/ar.md +17 -14
  42. package/dist/dashboard/guide/cs.md +15 -12
  43. package/dist/dashboard/guide/da.md +15 -12
  44. package/dist/dashboard/guide/de.md +14 -11
  45. package/dist/dashboard/guide/el.md +14 -11
  46. package/dist/dashboard/guide/en.md +13 -10
  47. package/dist/dashboard/guide/es.md +14 -11
  48. package/dist/dashboard/guide/fi.md +14 -11
  49. package/dist/dashboard/guide/fr.md +14 -11
  50. package/dist/dashboard/guide/he.md +14 -11
  51. package/dist/dashboard/guide/hi.md +14 -11
  52. package/dist/dashboard/guide/hu.md +14 -11
  53. package/dist/dashboard/guide/is.md +14 -11
  54. package/dist/dashboard/guide/it.md +57 -54
  55. package/dist/dashboard/guide/ja.md +14 -11
  56. package/dist/dashboard/guide/ko.md +15 -12
  57. package/dist/dashboard/guide/nb.md +14 -11
  58. package/dist/dashboard/guide/nl.md +16 -13
  59. package/dist/dashboard/guide/pl.md +14 -11
  60. package/dist/dashboard/guide/pt.md +14 -11
  61. package/dist/dashboard/guide/ro.md +15 -12
  62. package/dist/dashboard/guide/ru.md +14 -11
  63. package/dist/dashboard/guide/sv.md +15 -12
  64. package/dist/dashboard/guide/tr.md +15 -12
  65. package/dist/dashboard/guide/uk.md +15 -12
  66. package/dist/dashboard/guide/zh.md +15 -12
  67. package/dist/dashboard/i18n/ar.json +28 -11
  68. package/dist/dashboard/i18n/cs.json +28 -11
  69. package/dist/dashboard/i18n/da.json +28 -11
  70. package/dist/dashboard/i18n/de.json +28 -11
  71. package/dist/dashboard/i18n/el.json +28 -11
  72. package/dist/dashboard/i18n/es.json +28 -11
  73. package/dist/dashboard/i18n/fi.json +28 -11
  74. package/dist/dashboard/i18n/fr.json +28 -11
  75. package/dist/dashboard/i18n/he.json +28 -11
  76. package/dist/dashboard/i18n/hi.json +28 -11
  77. package/dist/dashboard/i18n/hu.json +28 -11
  78. package/dist/dashboard/i18n/is.json +28 -11
  79. package/dist/dashboard/i18n/it.json +104 -87
  80. package/dist/dashboard/i18n/ja.json +28 -11
  81. package/dist/dashboard/i18n/ko.json +28 -11
  82. package/dist/dashboard/i18n/nb.json +28 -11
  83. package/dist/dashboard/i18n/nl.json +28 -11
  84. package/dist/dashboard/i18n/pl.json +28 -11
  85. package/dist/dashboard/i18n/pt.json +28 -11
  86. package/dist/dashboard/i18n/ro.json +28 -11
  87. package/dist/dashboard/i18n/ru.json +28 -11
  88. package/dist/dashboard/i18n/sv.json +28 -11
  89. package/dist/dashboard/i18n/tr.json +28 -11
  90. package/dist/dashboard/i18n/uk.json +28 -11
  91. package/dist/dashboard/i18n/zh.json +28 -11
  92. package/dist/dashboard/packages/packages.js +1 -1
  93. package/dist/dashboard/parts/icons.js +2 -0
  94. package/dist/dashboard/parts/labels.js +2 -1
  95. package/dist/dashboard/parts/layout.js +34 -0
  96. package/dist/dashboard/parts/widgets.js +6 -2
  97. package/dist/dashboard/settings/language-choice.js +1 -1
  98. package/dist/dashboard/settings/settings.js +73 -39
  99. package/dist/dashboard/settings/tabs.js +14 -0
  100. package/dist/dashboard/sheet/sheet.js +54 -33
  101. package/dist/dashboard/shell/notices.js +2 -2
  102. package/dist/dashboard/style.css +135 -52
  103. package/dist/helpers/antigravity.d.ts +47 -0
  104. package/dist/helpers/antigravity.js +434 -0
  105. package/dist/helpers/briefs.d.ts +4 -0
  106. package/dist/helpers/briefs.js +13 -0
  107. package/dist/helpers/chosen.d.ts +15 -7
  108. package/dist/helpers/chosen.js +96 -45
  109. package/dist/helpers/index.d.ts +4 -2
  110. package/dist/helpers/index.js +6 -3
  111. package/dist/helpers/opencode.d.ts +13 -0
  112. package/dist/helpers/opencode.js +295 -0
  113. package/dist/helpers/programs.d.ts +8 -0
  114. package/dist/helpers/programs.js +35 -2
  115. package/dist/helpers/stop.d.ts +2 -0
  116. package/dist/helpers/stop.js +20 -1
  117. package/dist/helpers/svg.d.ts +4 -1
  118. package/dist/helpers/svg.js +16 -4
  119. package/dist/instructions/index.d.ts +4 -2
  120. package/dist/instructions/index.js +6 -3
  121. package/dist/server/approver.d.ts +4 -2
  122. package/dist/server/approver.js +27 -7
  123. package/dist/server/bell/antigravity.d.ts +15 -0
  124. package/dist/server/bell/antigravity.js +113 -0
  125. package/dist/server/bell/index.d.ts +2 -0
  126. package/dist/server/bell/index.js +2 -0
  127. package/dist/server/bell/listener.d.ts +43 -0
  128. package/dist/server/bell/listener.js +154 -0
  129. package/dist/server/dashboard/index.d.ts +10 -1
  130. package/dist/server/dashboard/index.js +6 -1
  131. package/dist/server/dashboard/news.d.ts +3 -1
  132. package/dist/server/dashboard/news.js +64 -10
  133. package/dist/server/fence.d.ts +21 -0
  134. package/dist/server/fence.js +69 -0
  135. package/dist/server/mcp.d.ts +3 -2
  136. package/dist/server/mcp.js +37 -7
  137. package/dist/server/player-acts.d.ts +21 -1
  138. package/dist/server/player-acts.js +39 -3
  139. package/dist/server/route/front.d.ts +3 -0
  140. package/dist/server/route/front.js +97 -0
  141. package/dist/server/route/index.d.ts +3 -0
  142. package/dist/server/route/index.js +3 -0
  143. package/dist/server/route/notes.d.ts +8 -0
  144. package/dist/server/route/notes.js +50 -0
  145. package/dist/server/route/router.d.ts +31 -0
  146. package/dist/server/route/router.js +215 -0
  147. package/dist/server/subagent.d.ts +4 -0
  148. package/dist/server/subagent.js +30 -0
  149. package/instructions/start.md +1 -1
  150. package/instructions/voices-antigravity.md +1 -0
  151. package/instructions/voices-codex.md +1 -0
  152. package/instructions/voices-opencode.md +1 -0
  153. package/package.json +3 -2
  154. package/plugins/opencode.js +174 -0
  155. package/dist/server/bell-listener.d.ts +0 -10
  156. package/dist/server/bell-listener.js +0 -52
@@ -10,7 +10,7 @@ import { comparableText } from "../../core/text.js";
10
10
  import { codexClient } from "../../helpers/index.js";
11
11
  import { playerCharacters } from "../../pages/index.js";
12
12
  import { readNotes, removeNote, writeNote } from "../../player-notes/index.js";
13
- import { actText, giveBackAct, markHeard, markRung, takeActs, withdrawAct } from "../player-acts.js";
13
+ import { actText, giveBackAct, giveBackHeld, hearHeld, holdActs, markHeard, markRung, takeActs, takeHeld, withdrawAct } from "../player-acts.js";
14
14
  import { mostSaid, readBody, securityHeaders, sendJson } from "./files.js";
15
15
  // What the master reads after a note the player shares (D-378), tried against injection: what the player thinks, never a fact
16
16
  // nor an instruction; the world keeps what is decided.
@@ -242,15 +242,53 @@ export function deliverActs(served) {
242
242
  return;
243
243
  }
244
244
  if (served.bell !== undefined) {
245
- markRung(served.acts);
246
- served.bell.end("ring");
245
+ ringBell(served, served.bell, served.bellWords === true);
247
246
  served.bell = undefined;
248
247
  served.notify();
249
248
  }
250
249
  }
250
+ /**
251
+ * Rings for a hook: "ring" alone, the sentences marked rung for the master's next call; or, for a hook that asked for the player's words, "ring" with them on the
252
+ * next lines, with what the character knows of the thing each names (D-578): held until the hook says it took them, then heard once a call of the master
253
+ * begins; given back to those waiting when a call begins before the hook took them, as when it was killed, or none begins within `heldFor`.
254
+ */
255
+ function ringBell(served, response, words) {
256
+ // A hook gone a moment ago takes nothing: the sentences wait for the next hook, or the master's next call.
257
+ if (response.destroyed) {
258
+ return;
259
+ }
260
+ if (!words) {
261
+ markRung(served.acts);
262
+ response.end("ring");
263
+ return;
264
+ }
265
+ const taken = holdActs(served.acts);
266
+ const ids = taken.map((one) => one.id);
267
+ const texts = taken.map((one) => {
268
+ const known = one.item === undefined ? undefined : knownOfThing(served, one.item);
269
+ return known === undefined ? one.text : `${one.text}\n\n${known}`;
270
+ });
271
+ // The hook says it took them by their ids, which come on the first line.
272
+ response.end(`ring ${ids.join(",")}\n${texts.join("\n\n")}`);
273
+ setTimeout(() => {
274
+ if (giveBackHeld(served.acts, ids)) {
275
+ served.notify();
276
+ deliverActs(served);
277
+ }
278
+ }, served.heldFor).unref();
279
+ }
280
+ /** As a call of the master begins: the sentences held for it are heard, and the chat listens again, whatever its last hook did. */
281
+ export function callBegins(served) {
282
+ const changed = served.acts.held.length > 0 || served.bellGone === true;
283
+ hearHeld(served.acts);
284
+ served.bellGone = false;
285
+ if (changed) {
286
+ served.notify();
287
+ }
288
+ }
251
289
  /**
252
290
  * Claude Code's doorbell (D-495): the hook of the chat that ended its turn waits here, one at a time, and hears "ring" when the player says a sentence, or one
253
- * already waits. With probe, the chat's session and campaign, and the other chats of the campaign that wait for its page, for the hook to find its own
291
+ * already waits; with words, as OpenCode's hook asks, with the sentences themselves (D-578). With probe, the chat's session and campaign, and the other chats of the campaign that wait for its page, for the hook to find its own
254
292
  * server; with also, one of those, which says so as it asks (D-577).
255
293
  */
256
294
  export function listenForBell(request, response, served, asked) {
@@ -271,21 +309,33 @@ export function listenForBell(request, response, served, asked) {
271
309
  return;
272
310
  }
273
311
  response.writeHead(200, { ...securityHeaders, "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" });
274
- if (served.belled !== true) {
312
+ // A hook that was given the player's words says it took them, before it speaks them.
313
+ const took = asked.get("took");
314
+ if (took !== null) {
315
+ takeHeld(served.acts, took.split(",").slice(0, 100));
316
+ response.end("ok");
317
+ return;
318
+ }
319
+ if (served.belled !== true || served.bellGone === true) {
275
320
  served.belled = true;
321
+ served.bellGone = false;
276
322
  served.notify();
277
323
  }
324
+ const words = asked.has("words");
278
325
  if (served.acts.pending.length > 0 && (served.context.chat?.calls ?? 0) === 0) {
279
- markRung(served.acts);
280
- response.end("ring");
326
+ ringBell(served, response, words);
281
327
  served.notify();
282
328
  return;
283
329
  }
284
330
  served.bell?.end("dismissed");
285
331
  served.bell = response;
332
+ served.bellWords = words;
333
+ // A hook that goes away without a ring, as when the chat was stopped, leaves nobody to call the master: the page offers to copy the sentence instead.
286
334
  request.on("close", () => {
287
335
  if (served.bell === response) {
288
336
  served.bell = undefined;
337
+ served.bellGone = true;
338
+ served.notify();
289
339
  }
290
340
  });
291
341
  }
@@ -348,12 +398,16 @@ Narrate as found only what this does not say.`;
348
398
  return undefined;
349
399
  }
350
400
  }
401
+ // The sentences held for the master show as those the doorbell rang for: no longer taken back.
351
402
  function actsShown(served) {
352
- return { pending: served.acts.pending, heard: served.acts.heard, bell: hasBell(served) };
403
+ return { pending: [...served.acts.held, ...served.acts.pending], heard: served.acts.heard, bell: hasBell(served) };
353
404
  }
354
- /** Whether a sentence said on the page reaches the master at once (D-495): Claude Code's doorbell came in this chat, or Codex named its thread. */
405
+ /**
406
+ * Whether a sentence said on the page reaches the master at once (D-495): Claude Code's doorbell came in this chat, and its last hook did not go away without
407
+ * a ring; or Codex named its thread.
408
+ */
355
409
  function hasBell(served) {
356
- return served.belled === true || (inCodex(served) && served.context.chat?.thread !== undefined && served.queueBroken !== true && served.queue.ready());
410
+ return (served.belled === true && served.bellGone !== true) || (inCodex(served) && served.context.chat?.thread !== undefined && served.queueBroken !== true && served.queue.ready());
357
411
  }
358
412
  function inCodex(served) {
359
413
  return served.context.host?.() === codexClient;
@@ -0,0 +1,21 @@
1
+ /** The folders a run may read and write, by their full paths, those to write read too; and the tools let through as they are, as the painter's image tool. */
2
+ export interface Fence {
3
+ read: string[];
4
+ write: string[];
5
+ tools?: string[];
6
+ }
7
+ /** Antigravity's answer to a tool call: refused, with what the model can do instead, or allowed, which the settings may still refuse. */
8
+ export type FenceDecision = {
9
+ decision: "deny";
10
+ reason: string;
11
+ } | {
12
+ decision: "allow";
13
+ };
14
+ /** Reads the hook's input and answers it on its output, by the fence of `file`. */
15
+ export declare function fenceHere(file: string): Promise<void>;
16
+ /** The fence in `file`; undefined where it does not read, which lets nothing through. */
17
+ export declare function readFence(file: string): Fence | undefined;
18
+ /** The decision for a tool call, as Antigravity's hook gives it, by `fence`. */
19
+ export declare function fenceDecision(input: string, fence: Fence | undefined): FenceDecision;
20
+ /** Whether `path` is `folder` or inside it, by path segments; on Windows without regard to case. */
21
+ export declare function isInside(path: string, folder: string): boolean;
@@ -0,0 +1,69 @@
1
+ // The importer's soft fence in Antigravity (D-579 (1)): `rpg --fence <file>`, the hook the engine writes in agy's working folder, refuses a call outside the
2
+ // import's folder, so that the model hears why and goes on, where the settings would close the whole run. A file is read only in the folders to read and
3
+ // written only in those to write; the tools the fence names pass as they are; every other tool is refused, commands and the web among them. Its yes opens nothing the settings close: they stay the hard fence.
4
+ import { readFileSync } from "node:fs";
5
+ import { isAbsolute, relative, resolve, sep } from "node:path";
6
+ /** Reads the hook's input and answers it on its output, by the fence of `file`. */
7
+ export async function fenceHere(file) {
8
+ let input = "";
9
+ for await (const chunk of process.stdin) {
10
+ input += String(chunk);
11
+ }
12
+ process.stdout.write(JSON.stringify(fenceDecision(input, readFence(file))));
13
+ }
14
+ /** The fence in `file`; undefined where it does not read, which lets nothing through. */
15
+ export function readFence(file) {
16
+ try {
17
+ const fence = JSON.parse(readFileSync(file, "utf8"));
18
+ const names = (value) => (Array.isArray(value) && value.every((one) => typeof one === "string") ? value : undefined);
19
+ const read = names(fence.read);
20
+ const write = names(fence.write);
21
+ const tools = fence.tools === undefined ? [] : names(fence.tools);
22
+ return read === undefined || write === undefined || tools === undefined ? undefined : { read, write, ...(tools.length === 0 ? {} : { tools }) };
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ }
28
+ /** The decision for a tool call, as Antigravity's hook gives it, by `fence`. */
29
+ export function fenceDecision(input, fence) {
30
+ if (fence === undefined) {
31
+ return { decision: "deny", reason: "This run's fence does not read, so nothing can be done here: stop and say so." };
32
+ }
33
+ const { name, args, cwd } = hookCall(input);
34
+ if (name !== undefined && fence.tools?.includes(name) === true) {
35
+ return { decision: "allow" };
36
+ }
37
+ const refused = {
38
+ decision: "deny",
39
+ reason: `Only reading in ${fence.read[0] ?? "the import's folder"} and writing in ${fence.write.join(", ") || "no folder"} is possible here, by full paths; no command and no web: go on without this.`,
40
+ };
41
+ // The file a tool names, by the argument that holds a path, whatever the tool calls it: Path, TargetFile, DirectoryPath.
42
+ const given = Object.entries(args).find(([key, value]) => typeof value === "string" && /path|file|directory|dir/i.test(key))?.[1];
43
+ if (name === undefined || typeof given !== "string" || !(readingTools.test(name) || writingTools.test(name))) {
44
+ return refused;
45
+ }
46
+ const path = resolve(typeof cwd === "string" ? cwd : process.cwd(), given);
47
+ const allowed = readingTools.test(name) ? [...fence.read, ...fence.write] : fence.write;
48
+ return allowed.some((folder) => isInside(path, folder)) ? { decision: "allow" } : refused;
49
+ }
50
+ // Antigravity's tools that read a file or a folder, and those that write one, as the probe of 22 November met them; any other tool is refused.
51
+ const readingTools = /^(read_file|view_file|view_file_outline|list_dir|list_directory|find_by_name|grep_search|find|grep)$/;
52
+ const writingTools = /^(write_file|write_to_file|replace_file_content|multi_replace_file_content|edit_file)$/;
53
+ /** Whether `path` is `folder` or inside it, by path segments; on Windows without regard to case. */
54
+ export function isInside(path, folder) {
55
+ const fold = (one) => (process.platform === "win32" ? resolve(one).toLowerCase() : resolve(one));
56
+ const between = relative(fold(folder), fold(path));
57
+ return between === "" || (between !== ".." && !between.startsWith(`..${sep}`) && !isAbsolute(between));
58
+ }
59
+ function hookCall(input) {
60
+ try {
61
+ const parsed = JSON.parse(input);
62
+ const call = parsed?.toolCall;
63
+ const args = call?.args !== null && typeof call?.args === "object" ? call.args : {};
64
+ return { ...(typeof call?.name === "string" ? { name: call.name } : {}), args, cwd: parsed?.cwd };
65
+ }
66
+ catch {
67
+ return { args: {} };
68
+ }
69
+ }
@@ -1,4 +1,5 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { Readable } from "node:stream";
2
3
  import { type Context } from "../core/context.ts";
3
4
  import { SessionStore } from "../core/session-store.ts";
4
5
  /** The line that closes every answer of a tool, a phrase of the page's, so that its languages have it. */
@@ -11,9 +12,9 @@ export declare const masterScreenLine = "The text above lies behind the master's
11
12
  export declare function createMcpServer(context?: Context, environment?: Record<string, string | undefined>, beforeCall?: () => Promise<void>): McpServer;
12
13
  /**
13
14
  * Serves the tools over standard input and output, as AI hosts expect, with the files kept for the whole session (D-137, D-193). It ends when the host
14
- * goes and its input closes: its watchers, or a player's form still waiting, never keep it alive.
15
+ * goes and its input closes: its watchers, or a player's form still waiting, never keep it alive. `input` is the process's own, or what the router passes on.
15
16
  */
16
- export declare function startMcpServer(): Promise<void>;
17
+ export declare function startMcpServer(input?: Readable): Promise<void>;
17
18
  /**
18
19
  * Opens the player's dashboard as the chat starts and before the first call that finds a campaign in the server's folder, as after init, and lets that call
19
20
  * wait for it, so that its status gives the link (D-270, D-277, D-577); never in a folder without a campaign. Where another chat of the campaign serves its
@@ -4,7 +4,7 @@ import { spawn } from "node:child_process";
4
4
  import { homedir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { z } from "zod";
7
- import { chosenPictureMaker, findCampaign, hasCharacterAgent, readTextSetting, refreshHostFiles } from "../campaign/index.js";
7
+ import { chosenPictureMaker, findCampaign, hasCharacterAgent, readTextSetting, refreshHostFiles, refreshUserHostFiles } from "../campaign/index.js";
8
8
  import { chatFolders } from "../chats/index.js";
9
9
  import { commands } from "../commands/index.js";
10
10
  import { installCampaignSystem } from "../commands/package/install.js";
@@ -30,6 +30,7 @@ import { npmEngine, npmPackages } from "../packages/index.js";
30
30
  import { loadSystemCode } from "../systems/index.js";
31
31
  import { chatKeeper } from "./chats.js";
32
32
  import { answers, campaignPageElsewhere, campaignPorts, dashboardAt, isCampaignPage, startDashboard } from "./dashboard/index.js";
33
+ import { fromSubagent, subagentRefusal } from "./subagent.js";
33
34
  // While the player decides, the call reports progress this often, so that a host does not take it for a call that hangs.
34
35
  const progressEvery = 20 * 1000;
35
36
  // A form closed faster than anyone could read it was never shown: the host declares forms it does not show (ASK-6).
@@ -122,12 +123,12 @@ export function createMcpServer(context = defaultContext(), environment = proces
122
123
  }
123
124
  /**
124
125
  * Serves the tools over standard input and output, as AI hosts expect, with the files kept for the whole session (D-137, D-193). It ends when the host
125
- * goes and its input closes: its watchers, or a player's form still waiting, never keep it alive.
126
+ * goes and its input closes: its watchers, or a player's form still waiting, never keep it alive. `input` is the process's own, or what the router passes on.
126
127
  */
127
- export async function startMcpServer() {
128
+ export async function startMcpServer(input = process.stdin) {
128
129
  const leave = () => process.exit(0);
129
- process.stdin.on("end", leave);
130
- process.stdin.on("close", leave);
130
+ input.on("end", leave);
131
+ input.on("close", leave);
131
132
  // The pictures, by the campaign's choice, else by the chat in use, which names itself as the session starts (D-308, D-572).
132
133
  let server;
133
134
  const host = () => server?.server.getClientVersion()?.name;
@@ -157,7 +158,7 @@ export async function startMcpServer() {
157
158
  server = createMcpServer(served, process.env, dashboardOpener(served, session).open);
158
159
  // The extensions' tools are there in the first list the host asks for.
159
160
  await firstExtensions.get(server);
160
- await server.connect(new StdioServerTransport());
161
+ await server.connect(new StdioServerTransport(input));
161
162
  }
162
163
  /**
163
164
  * Opens the player's dashboard as the chat starts and before the first call that finds a campaign in the server's folder, as after init, and lets that call
@@ -233,8 +234,11 @@ async function preload(context, session) {
233
234
  if (root !== undefined) {
234
235
  session.track(root);
235
236
  // An agent written now reaches only the chats after this one (D-490).
236
- context.characterAgent = hasCharacterAgent(root);
237
+ context.characterAgents = hasCharacterAgent(root);
237
238
  refreshHostFiles(root, hostInstructions(), context.platform);
239
+ if (context.userHome !== undefined) {
240
+ refreshUserHostFiles(context.userHome, context.platform);
241
+ }
238
242
  campaignWorld(root, context);
239
243
  // What the last session left, committed as this one starts, where the campaign keeps itself in git (D-576).
240
244
  void commitSessionStart(root, context);
@@ -360,6 +364,13 @@ function inputIssue(tool, issue, given) {
360
364
  return path === "" ? `${issue.message}.` : `${path}: ${issue.message}.`;
361
365
  }
362
366
  async function runTool(command, input, context, extra, prepare, installer, outside, examples) {
367
+ // A character's subagent only looks, and takes none of the master's lines (D-580).
368
+ if (fromSubagent(extra._meta)) {
369
+ // Only view, and only as a character: without `as` it would be the player's own view, which is not theirs.
370
+ const as = input?.as;
371
+ const looks = command.name === "view" && typeof as === "string" && as.trim() !== "";
372
+ return looks ? subagentView(command, input, context, extra, prepare, examples) : { content: [{ type: "text", text: subagentRefusal }], isError: true };
373
+ }
363
374
  const keepAlive = command.needsPlayer || command.waitsForPlayer
364
375
  ? reportProgress(extra, () => (context.page?.asking?.() === true ? "waiting for the player's click on the dashboard" : "waiting for the player"))
365
376
  : command.slow === true
@@ -382,6 +393,7 @@ async function runTool(command, input, context, extra, prepare, installer, outsi
382
393
  if (chat !== undefined) {
383
394
  chat.calls++;
384
395
  chat.thread = typeof thread === "string" && thread !== "" ? thread : chat.thread;
396
+ chat.beforeCall?.();
385
397
  }
386
398
  try {
387
399
  // In a session, the files that changed since the last call are read again; instructions starts a chat, or follows a summary: everything is checked (D-193).
@@ -439,6 +451,24 @@ async function runTool(command, input, context, extra, prepare, installer, outsi
439
451
  }
440
452
  }
441
453
  }
454
+ /**
455
+ * A view of a character's subagent (D-580): it runs as any call, but takes none of the lines meant for the master, as what the player changed or what changed
456
+ * outside the chat, counts in none of the chat's calls, and tells the master's chat nothing.
457
+ */
458
+ async function subagentView(command, input, context, extra, prepare, examples) {
459
+ try {
460
+ if (context.files instanceof SessionStore) {
461
+ await context.files.ready(false);
462
+ }
463
+ await prepare();
464
+ const checked = checkedInput(command, input, examples.shown);
465
+ const text = command.format(await command.run(checked, { ...context, told: new Set(context.told), signal: extra.signal }));
466
+ return { content: [{ type: "text", text }, masterOnly(context)] };
467
+ }
468
+ catch (error) {
469
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }, masterOnly(context)], isError: true };
470
+ }
471
+ }
442
472
  /**
443
473
  * The campaign's game system installed by itself when it is one of ours not on this computer (SYS-10, D-514 (3)): tried once for each system a campaign of
444
474
  * the server's folder names, before a call; its line, that it was installed or why not, for the call that answers.
@@ -5,10 +5,16 @@ export interface Act {
5
5
  /** The thing of the sheet it starts from, by its page, whose known text the master hears with it (T-218). */
6
6
  item?: string;
7
7
  rung?: boolean;
8
+ /** Held for a hook that speaks it as the player: whether the hook said it took it (D-578). */
9
+ taken?: boolean;
8
10
  }
9
- /** The sentences said and not yet heard, in order, and the ids of those heard lately, for the page to tell. */
11
+ /**
12
+ * The sentences said and not yet heard, in order; those given to a hook that speaks them as the player, held until the master's next call begins (D-578);
13
+ * and the ids of those heard lately, for the page to tell.
14
+ */
10
15
  export interface Acts {
11
16
  pending: Act[];
17
+ held: Act[];
12
18
  heard: string[];
13
19
  }
14
20
  export declare function newActs(): Acts;
@@ -20,6 +26,20 @@ export declare function withdrawAct(acts: Acts, id: string): "withdrawn" | "hear
20
26
  export declare function markRung(acts: Acts): void;
21
27
  /** Marks sentences heard, as a call or Codex's queue took them. */
22
28
  export declare function markHeard(acts: Acts, ids: string[]): void;
29
+ /** Holds the sentences waiting, as given to a hook that speaks them as the player, until it says it took them, then until the master's next call begins. */
30
+ export declare function holdActs(acts: Acts): Act[];
31
+ /** Marks held sentences as taken by the hook they were given to: they are on their way to the chat. */
32
+ export declare function takeHeld(acts: Acts, ids: string[]): void;
33
+ /**
34
+ * As a call of the master begins: the held sentences their hook took are heard; those it never took, as from a hook killed meanwhile, go back to the head of
35
+ * those waiting, for this call to take.
36
+ */
37
+ export declare function hearHeld(acts: Acts): void;
38
+ /**
39
+ * Gives the held sentences among `ids` that the hook never took back to the head of those waiting, as the master never began a call after them; whether any
40
+ * came back. One the hook took is in the chat already, however long the master takes to call: given back, it would be said twice.
41
+ */
42
+ export declare function giveBackHeld(acts: Acts, ids: string[]): boolean;
23
43
  /** Gives a sentence back to the head of those waiting, as one Codex never took. */
24
44
  export declare function giveBackAct(acts: Acts, act: Act): void;
25
45
  /**
@@ -5,7 +5,7 @@ const heardKept = 20;
5
5
  // What does not show, or breaks a line in the player's words, from a single sentence: control characters, which no process could take either.
6
6
  const unseen = /[\u0000-\u001f\u007f]+/g;
7
7
  export function newActs() {
8
- return { pending: [], heard: [] };
8
+ return { pending: [], held: [], heard: [] };
9
9
  }
10
10
  /** The player's words as one sentence: what does not show taken away, every break a space; empty when nothing is left. */
11
11
  export function actText(text) {
@@ -15,7 +15,7 @@ export function actText(text) {
15
15
  export function withdrawAct(acts, id) {
16
16
  const index = acts.pending.findIndex((act) => act.id === id);
17
17
  if (index === -1) {
18
- return acts.heard.includes(id) ? "heard" : "unknown";
18
+ return acts.heard.includes(id) || acts.held.some((act) => act.id === id) ? "heard" : "unknown";
19
19
  }
20
20
  // The doorbell rang for it: the master is called, and would find nothing.
21
21
  if (acts.pending[index].rung === true) {
@@ -33,6 +33,42 @@ export function markHeard(acts, ids) {
33
33
  acts.pending = acts.pending.filter((act) => !ids.includes(act.id));
34
34
  acts.heard = [...acts.heard.filter((id) => !ids.includes(id)), ...ids].slice(-heardKept);
35
35
  }
36
+ /** Holds the sentences waiting, as given to a hook that speaks them as the player, until it says it took them, then until the master's next call begins. */
37
+ export function holdActs(acts) {
38
+ const taken = acts.pending;
39
+ acts.pending = [];
40
+ acts.held = [...acts.held, ...taken.map((act) => ({ ...act, rung: true, taken: false }))];
41
+ return taken;
42
+ }
43
+ /** Marks held sentences as taken by the hook they were given to: they are on their way to the chat. */
44
+ export function takeHeld(acts, ids) {
45
+ acts.held = acts.held.map((act) => (ids.includes(act.id) ? { ...act, taken: true } : act));
46
+ }
47
+ /**
48
+ * As a call of the master begins: the held sentences their hook took are heard; those it never took, as from a hook killed meanwhile, go back to the head of
49
+ * those waiting, for this call to take.
50
+ */
51
+ export function hearHeld(acts) {
52
+ const held = acts.held;
53
+ acts.held = [];
54
+ markHeard(acts, held.filter((act) => act.taken === true).map((act) => act.id));
55
+ acts.pending = [...held.filter((act) => act.taken !== true).map(waiting), ...acts.pending];
56
+ }
57
+ /**
58
+ * Gives the held sentences among `ids` that the hook never took back to the head of those waiting, as the master never began a call after them; whether any
59
+ * came back. One the hook took is in the chat already, however long the master takes to call: given back, it would be said twice.
60
+ */
61
+ export function giveBackHeld(acts, ids) {
62
+ const back = acts.held.filter((act) => ids.includes(act.id) && act.taken !== true);
63
+ acts.held = acts.held.filter((act) => !back.includes(act));
64
+ acts.pending = [...back.map(waiting), ...acts.pending];
65
+ return back.length > 0;
66
+ }
67
+ /** A held sentence as one waiting again, neither rung for nor taken. */
68
+ function waiting(act) {
69
+ const { rung: _, taken: __, ...rest } = act;
70
+ return rest;
71
+ }
36
72
  /** Gives a sentence back to the head of those waiting, as one Codex never took. */
37
73
  export function giveBackAct(acts, act) {
38
74
  acts.pending.unshift(act);
@@ -59,5 +95,5 @@ ${already}`;
59
95
  }
60
96
  /** What the master hears of a sentence: the player's words quoted, as their move in the story, which the master rules as any other (D-493 (1)). */
61
97
  function actNews(text, quoted) {
62
- return `The player acts on the dashboard, in their own words, as if said in chat:\n${quoted(text)}\nRule it as the player's move, and answer as to their words in chat.`;
98
+ return `The player acts on the dashboard, in their own words, as if said in chat:\n${quoted(text)}\nRule it as the player's move, and answer as to their words in chat. If you need what they left unsaid to rule it, ask them with buttons.`;
63
99
  }
@@ -0,0 +1,3 @@
1
+ import type { Readable } from "node:stream";
2
+ /** The input the MCP server reads; undefined when the router took it, and serves until the client goes. */
3
+ export declare function serverInput(folder?: string, environment?: NodeJS.ProcessEnv): Readable | undefined;
@@ -0,0 +1,97 @@
1
+ // Where `rpg mcp` reads its client (D-578): in a campaign, straight from its input, as always; started outside one, as Antigravity's app does, which
2
+ // starts one server for all its folders, it becomes the router, with a child `rpg mcp` for each campaign a call plays and one in its own folder.
3
+ import { spawn, spawnSync } from "node:child_process";
4
+ import { createInterface } from "node:readline";
5
+ import { findCampaign } from "../../campaign/index.js";
6
+ import { userDataFolder } from "../../core/context.js";
7
+ import { notedCampaign, notesFolder, pruneNotes } from "./notes.js";
8
+ import { mcpRouter } from "./router.js";
9
+ // Set for the router's children, which serve as any server does and never route.
10
+ const routedMark = "RPG_ROUTED";
11
+ /** The input the MCP server reads; undefined when the router took it, and serves until the client goes. */
12
+ export function serverInput(folder = process.cwd(), environment = process.env) {
13
+ if (environment[routedMark] === "1" || findCampaign(folder) !== undefined) {
14
+ return process.stdin;
15
+ }
16
+ // Outside a campaign every client gets the router, which passes the lines through to its own folder's child until a call names a conversation: Antigravity's
17
+ // app speaks before its initialize, so its name comes too late to choose by.
18
+ route(process.stdin, folder);
19
+ return undefined;
20
+ }
21
+ /** The router at work on the process's input and output, its children `rpg mcp` started as this one was; what it does goes to stderr. */
22
+ function route(input, folder) {
23
+ const log = (line) => process.stderr.write(`${line}\n`);
24
+ const home = userDataFolder();
25
+ pruneNotes(home, new Date());
26
+ const router = mcpRouter({
27
+ folder,
28
+ start: startChild,
29
+ campaignOf: (conversation) => notedCampaign(home, conversation),
30
+ toClient: (line) => process.stdout.write(`${line}\n`),
31
+ log,
32
+ });
33
+ log(`rpg mcp router: serving from ${folder}, outside any campaign; the campaigns of the app's conversations are noted in ${notesFolder(home)}`);
34
+ const lines = createInterface({ input, crlfDelay: Infinity });
35
+ lines.on("line", (line) => void router.fromClient(line));
36
+ // The client is gone: every child ends with it.
37
+ lines.on("close", () => {
38
+ router.stop();
39
+ process.exit(0);
40
+ });
41
+ }
42
+ /** A child `rpg mcp` in a folder, as this process was started; its end, as when its folder is gone, is told to the router. */
43
+ function startChild(folder) {
44
+ const child = spawn(process.execPath, [...process.execArgv, process.argv[1] ?? "", "mcp"], {
45
+ cwd: folder,
46
+ env: { ...process.env, [routedMark]: "1" },
47
+ stdio: ["pipe", "pipe", "inherit"],
48
+ windowsHide: true,
49
+ detached: process.platform !== "win32",
50
+ });
51
+ let endListener = () => undefined;
52
+ let stopping = false;
53
+ const end = (reason) => {
54
+ if (!stopping) {
55
+ stopping = true;
56
+ endListener(reason);
57
+ }
58
+ };
59
+ child.stdin.on("error", () => undefined);
60
+ child.on("error", (error) => end(error.message));
61
+ child.on("exit", (code, signal) => end(signal ?? `exit code ${String(code)}`));
62
+ return {
63
+ write: (line) => {
64
+ if (child.stdin.writable) {
65
+ child.stdin.write(`${line}\n`);
66
+ }
67
+ },
68
+ onLine: (listener) => void createInterface({ input: child.stdout, crlfDelay: Infinity }).on("line", listener),
69
+ onEnd: (listener) => (endListener = listener),
70
+ stop: () => {
71
+ stopping = true;
72
+ endTree(child.pid, () => child.kill());
73
+ },
74
+ };
75
+ }
76
+ /** Ends a process with what it started: on Windows its whole tree, else its process group; the process alone when neither can be. */
77
+ function endTree(pid, alone) {
78
+ try {
79
+ if (pid === undefined) {
80
+ alone();
81
+ }
82
+ else if (process.platform === "win32") {
83
+ spawnSync("taskkill", ["/T", "/F", "/PID", String(pid)], { windowsHide: true, stdio: "ignore" });
84
+ }
85
+ else {
86
+ process.kill(-pid, "SIGTERM");
87
+ }
88
+ }
89
+ catch {
90
+ try {
91
+ alone();
92
+ }
93
+ catch {
94
+ // Gone already.
95
+ }
96
+ }
97
+ }
@@ -0,0 +1,3 @@
1
+ export { serverInput } from "./front.ts";
2
+ export { noteConversation, notedCampaign, notesFolder, pruneNotes } from "./notes.ts";
3
+ export { type ChildServer, conversationKey, mcpRouter, type RouterOptions } from "./router.ts";
@@ -0,0 +1,3 @@
1
+ export { serverInput } from "./front.js";
2
+ export { noteConversation, notedCampaign, notesFolder, pruneNotes } from "./notes.js";
3
+ export { conversationKey, mcpRouter } from "./router.js";
@@ -0,0 +1,8 @@
1
+ /** Notes that the conversation plays the campaign at `root`; a note that cannot be written leaves the conversation to the server's own folder. */
2
+ export declare function noteConversation(home: string, conversation: string, root: string): void;
3
+ /** The campaign a conversation plays, as its note says; undefined without one, or once the folder is no campaign. */
4
+ export declare function notedCampaign(home: string, conversation: string): string | undefined;
5
+ /** Takes away the notes not written for a month, as of `now`. */
6
+ export declare function pruneNotes(home: string, now: Date): void;
7
+ /** The folder of the notes, in the engine's data folder. */
8
+ export declare function notesFolder(home: string): string;
@@ -0,0 +1,50 @@
1
+ // Which campaign each conversation of Antigravity's app plays: its hook, run in the campaign's folder, notes it as it approves an rpg tool, and the router
2
+ // reads it, since the app starts one rpg server for all its folders and names only the conversation (D-578). A small file per conversation, in the engine's
3
+ // data folder on this computer, never in a campaign; those not written for a month go as the router starts.
4
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { campaignFileName } from "../../campaign/index.js";
7
+ // How long a note is kept after it was last written: each call of an rpg tool writes it again.
8
+ const keptFor = 30 * 24 * 60 * 60 * 1000;
9
+ /** Notes that the conversation plays the campaign at `root`; a note that cannot be written leaves the conversation to the server's own folder. */
10
+ export function noteConversation(home, conversation, root) {
11
+ try {
12
+ mkdirSync(notesFolder(home), { recursive: true });
13
+ writeFileSync(notePath(home, conversation), `${root}\n`);
14
+ }
15
+ catch {
16
+ // The game goes on where the server runs.
17
+ }
18
+ }
19
+ /** The campaign a conversation plays, as its note says; undefined without one, or once the folder is no campaign. */
20
+ export function notedCampaign(home, conversation) {
21
+ try {
22
+ const root = readFileSync(notePath(home, conversation), "utf8").trim();
23
+ return root !== "" && existsSync(join(root, campaignFileName)) ? root : undefined;
24
+ }
25
+ catch {
26
+ return undefined;
27
+ }
28
+ }
29
+ /** Takes away the notes not written for a month, as of `now`. */
30
+ export function pruneNotes(home, now) {
31
+ try {
32
+ for (const name of readdirSync(notesFolder(home))) {
33
+ const path = join(notesFolder(home), name);
34
+ if (now.getTime() - statSync(path).mtimeMs > keptFor) {
35
+ rmSync(path, { force: true });
36
+ }
37
+ }
38
+ }
39
+ catch {
40
+ // No notes yet, or none that can go: they stay.
41
+ }
42
+ }
43
+ /** The folder of the notes, in the engine's data folder. */
44
+ export function notesFolder(home) {
45
+ return join(home, "antigravity-conversations");
46
+ }
47
+ // A conversation's id as a file name: only letters, digits, dashes and underscores.
48
+ function notePath(home, conversation) {
49
+ return join(notesFolder(home), `${conversation.replace(/[^\w-]/g, "_").slice(0, 120)}.txt`);
50
+ }
@@ -0,0 +1,31 @@
1
+ /** A child `rpg mcp` as the router drives it: the lines it is given, the lines it writes, its end, as when it exits or its folder is gone, and stopping it. */
2
+ export interface ChildServer {
3
+ write(line: string): void;
4
+ onLine(listener: (line: string) => void): void;
5
+ onEnd(listener: (reason: string) => void): void;
6
+ stop(): void;
7
+ }
8
+ export interface RouterOptions {
9
+ /** The folder the server was started in, where the child for every call without a noted campaign runs. */
10
+ folder: string;
11
+ /** Starts a child `rpg mcp` in a folder. */
12
+ start: (folder: string) => ChildServer;
13
+ /** The campaign a conversation plays, as noted; undefined until noted. */
14
+ campaignOf: (conversation: string) => string | undefined;
15
+ /** Writes a line to the client. */
16
+ toClient: (line: string) => void;
17
+ /** How long a conversation's first call waits for its note, which may come a moment after it: so many looks, so many ms apart. */
18
+ noteLooks?: {
19
+ every: number;
20
+ times: number;
21
+ };
22
+ /** A line about what the router does, for the player who looks at its stderr. */
23
+ log?: (line: string) => void;
24
+ }
25
+ /** The client's meta key that names Antigravity's conversation in every call. */
26
+ export declare const conversationKey = "antigravity.google/conversation_id";
27
+ /** A router between the client and its children: give it each line the client writes, in order; `stop` ends every child, as the client goes. */
28
+ export declare function mcpRouter(options: RouterOptions): {
29
+ fromClient(line: string): Promise<void>;
30
+ stop(): void;
31
+ };