rpg-engine 0.22.0 → 0.23.1

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 (119) hide show
  1. package/README.md +5 -5
  2. package/dist/campaign/create-campaign.d.ts +5 -0
  3. package/dist/campaign/create-campaign.js +40 -12
  4. package/dist/campaign/find-campaign.d.ts +5 -0
  5. package/dist/campaign/find-campaign.js +10 -5
  6. package/dist/campaign/host-files.d.ts +15 -4
  7. package/dist/campaign/host-files.js +130 -13
  8. package/dist/campaign/index.d.ts +2 -2
  9. package/dist/campaign/index.js +2 -2
  10. package/dist/cli/cli.js +18 -6
  11. package/dist/commands/config/dashboard.js +6 -1
  12. package/dist/commands/config/words.js +1 -1
  13. package/dist/commands/image.d.ts +3 -0
  14. package/dist/commands/image.js +31 -4
  15. package/dist/commands/import/import.d.ts +1 -1
  16. package/dist/commands/import/import.js +5 -0
  17. package/dist/commands/init.d.ts +2 -0
  18. package/dist/commands/init.js +21 -3
  19. package/dist/commands/shared/campaign/git.js +1 -1
  20. package/dist/commands/shared/campaign/images.js +5 -3
  21. package/dist/commands/shared/characters/voices.d.ts +2 -2
  22. package/dist/commands/shared/characters/voices.js +8 -5
  23. package/dist/core/context.d.ts +15 -6
  24. package/dist/core/context.js +2 -1
  25. package/dist/dashboard/guide/ar.md +7 -4
  26. package/dist/dashboard/guide/cs.md +6 -3
  27. package/dist/dashboard/guide/da.md +6 -3
  28. package/dist/dashboard/guide/de.md +6 -3
  29. package/dist/dashboard/guide/el.md +6 -3
  30. package/dist/dashboard/guide/en.md +5 -2
  31. package/dist/dashboard/guide/es.md +6 -3
  32. package/dist/dashboard/guide/fi.md +6 -3
  33. package/dist/dashboard/guide/fr.md +7 -4
  34. package/dist/dashboard/guide/he.md +6 -3
  35. package/dist/dashboard/guide/hi.md +6 -3
  36. package/dist/dashboard/guide/hu.md +6 -3
  37. package/dist/dashboard/guide/is.md +6 -3
  38. package/dist/dashboard/guide/it.md +37 -34
  39. package/dist/dashboard/guide/ja.md +6 -3
  40. package/dist/dashboard/guide/ko.md +6 -3
  41. package/dist/dashboard/guide/nb.md +6 -3
  42. package/dist/dashboard/guide/nl.md +8 -5
  43. package/dist/dashboard/guide/pl.md +6 -3
  44. package/dist/dashboard/guide/pt.md +6 -3
  45. package/dist/dashboard/guide/ro.md +6 -3
  46. package/dist/dashboard/guide/ru.md +7 -4
  47. package/dist/dashboard/guide/sv.md +6 -3
  48. package/dist/dashboard/guide/tr.md +7 -4
  49. package/dist/dashboard/guide/uk.md +7 -4
  50. package/dist/dashboard/guide/zh.md +6 -3
  51. package/dist/dashboard/i18n/ar.json +5 -2
  52. package/dist/dashboard/i18n/cs.json +5 -2
  53. package/dist/dashboard/i18n/da.json +5 -2
  54. package/dist/dashboard/i18n/de.json +5 -2
  55. package/dist/dashboard/i18n/el.json +5 -2
  56. package/dist/dashboard/i18n/es.json +5 -2
  57. package/dist/dashboard/i18n/fi.json +5 -2
  58. package/dist/dashboard/i18n/fr.json +5 -2
  59. package/dist/dashboard/i18n/he.json +5 -2
  60. package/dist/dashboard/i18n/hi.json +5 -2
  61. package/dist/dashboard/i18n/hu.json +5 -2
  62. package/dist/dashboard/i18n/is.json +5 -2
  63. package/dist/dashboard/i18n/it.json +5 -2
  64. package/dist/dashboard/i18n/ja.json +5 -2
  65. package/dist/dashboard/i18n/ko.json +5 -2
  66. package/dist/dashboard/i18n/nb.json +5 -2
  67. package/dist/dashboard/i18n/nl.json +5 -2
  68. package/dist/dashboard/i18n/pl.json +5 -2
  69. package/dist/dashboard/i18n/pt.json +5 -2
  70. package/dist/dashboard/i18n/ro.json +5 -2
  71. package/dist/dashboard/i18n/ru.json +5 -2
  72. package/dist/dashboard/i18n/sv.json +5 -2
  73. package/dist/dashboard/i18n/tr.json +5 -2
  74. package/dist/dashboard/i18n/uk.json +5 -2
  75. package/dist/dashboard/i18n/zh.json +5 -2
  76. package/dist/dashboard/parts/labels.js +1 -1
  77. package/dist/dashboard/settings/settings.js +13 -4
  78. package/dist/dashboard/shell/notices.js +1 -1
  79. package/dist/dashboard/style.css +15 -7
  80. package/dist/helpers/briefs.d.ts +4 -0
  81. package/dist/helpers/briefs.js +13 -0
  82. package/dist/helpers/chosen.d.ts +8 -4
  83. package/dist/helpers/chosen.js +38 -14
  84. package/dist/helpers/index.d.ts +3 -2
  85. package/dist/helpers/index.js +5 -3
  86. package/dist/helpers/opencode.d.ts +13 -0
  87. package/dist/helpers/opencode.js +202 -0
  88. package/dist/instructions/index.d.ts +2 -2
  89. package/dist/instructions/index.js +3 -3
  90. package/dist/server/approver.d.ts +4 -2
  91. package/dist/server/approver.js +27 -7
  92. package/dist/server/bell/antigravity.d.ts +10 -0
  93. package/dist/server/bell/antigravity.js +95 -0
  94. package/dist/server/bell/index.d.ts +2 -0
  95. package/dist/server/bell/index.js +2 -0
  96. package/dist/server/bell/listener.d.ts +43 -0
  97. package/dist/server/bell/listener.js +149 -0
  98. package/dist/server/dashboard/index.d.ts +10 -1
  99. package/dist/server/dashboard/index.js +6 -1
  100. package/dist/server/dashboard/news.d.ts +3 -1
  101. package/dist/server/dashboard/news.js +64 -10
  102. package/dist/server/mcp.d.ts +3 -2
  103. package/dist/server/mcp.js +11 -7
  104. package/dist/server/player-acts.d.ts +21 -1
  105. package/dist/server/player-acts.js +38 -2
  106. package/dist/server/route/front.d.ts +3 -0
  107. package/dist/server/route/front.js +97 -0
  108. package/dist/server/route/index.d.ts +3 -0
  109. package/dist/server/route/index.js +3 -0
  110. package/dist/server/route/notes.d.ts +8 -0
  111. package/dist/server/route/notes.js +50 -0
  112. package/dist/server/route/router.d.ts +31 -0
  113. package/dist/server/route/router.js +215 -0
  114. package/instructions/start.md +1 -1
  115. package/instructions/voices-opencode.md +1 -0
  116. package/package.json +3 -2
  117. package/plugins/opencode.js +174 -0
  118. package/dist/server/bell-listener.d.ts +0 -10
  119. package/dist/server/bell-listener.js +0 -52
@@ -0,0 +1,149 @@
1
+ // The doorbell for the player's sentences on the dashboard (D-495, D-578): `rpg --listen`, the Stop hook init writes for Claude Code and Antigravity, which
2
+ // OpenCode's plugin runs too, waits at the dashboard of its own chat and, when the player says a sentence, tells the chat to call status, the sentence
3
+ // reaching the master in that call; in OpenCode, whose plugin speaks as the player, it brings the sentence itself, as Codex's queue does.
4
+ import { findCampaign } from "../../campaign/index.js";
5
+ import { samePath } from "../../library/index.js";
6
+ import { askDashboard, campaignPorts, dashboardAt } from "../dashboard/ports.js";
7
+ import { watchNewTurn } from "./antigravity.js";
8
+ /** What the chat hears from the doorbell: never the player's words, only where to read them. */
9
+ export const bellLine = "The player acted on the dashboard: call status to read what they did.";
10
+ /** The hosts whose hook runs `rpg --listen`, as its argument names them: Claude Code with none; OpenCode through the campaign's plugin. */
11
+ export const listeningHosts = ["claude", "codex", "antigravity", "opencode"];
12
+ /**
13
+ * Reads the hook's input, waits for the doorbell, and ends the process as the host reads it: for Claude Code's asyncRewake, 2 with the line on stderr; for
14
+ * Codex's and Antigravity's Stop hooks, 0 with their answer on stdout; for OpenCode's plugin, 0 with the player's words, or the line, on stdout, which it sends to the chat. Else 0.
15
+ * Antigravity's hook holds the chat: it lets it go, without the bell, as soon as the player writes in the chat or stops it; OpenCode's, once OpenCode is gone.
16
+ */
17
+ export async function listen(host = "claude") {
18
+ let input = "";
19
+ for await (const chunk of process.stdin) {
20
+ input += String(chunk);
21
+ }
22
+ const hook = hookInput(input);
23
+ const turn = host === "antigravity" && hook.session !== undefined ? watchNewTurn(hook.session) : undefined;
24
+ const opener = hook.hostPid === undefined ? undefined : watchProcessEnd(hook.hostPid);
25
+ const unheard = { rang: false };
26
+ const heard = await Promise.race([
27
+ bellHeard(input, { words: host === "opencode" }).catch(() => unheard),
28
+ ...(turn === undefined ? [] : [turn.started.then(() => unheard)]),
29
+ ...(opener === undefined ? [] : [opener.ended.then(() => unheard)]),
30
+ ]);
31
+ turn?.stop();
32
+ opener?.stop();
33
+ const answer = hookAnswer(host, heard.rang, heard.words);
34
+ // It ends as soon as it knows, whatever else the process holds: the chat hears the hook only once it ends, and the dashboard sees its wait gone.
35
+ if (answer === undefined) {
36
+ process.exit(0);
37
+ }
38
+ else if (host === "claude") {
39
+ process.stderr.write(`${answer}\n`, () => process.exit(2));
40
+ }
41
+ else {
42
+ process.stdout.write(`${answer}\n`, () => process.exit(0));
43
+ }
44
+ }
45
+ /**
46
+ * What the hook says as it ends, by its host: the doorbell's line, or the answer that carries it, when it rang, and for OpenCode the player's `words` when the
47
+ * page gave them; else nothing, but Antigravity's empty answer.
48
+ */
49
+ export function hookAnswer(host, rang, words) {
50
+ if (host === "antigravity") {
51
+ return rang ? JSON.stringify({ decision: "continue", reason: bellLine }) : "{}";
52
+ }
53
+ if (!rang) {
54
+ return undefined;
55
+ }
56
+ if (host === "opencode") {
57
+ return words ?? bellLine;
58
+ }
59
+ return host === "codex" ? JSON.stringify({ decision: "block", reason: bellLine }) : bellLine;
60
+ }
61
+ /**
62
+ * Waits at the dashboard of the hook's chat until the player says a sentence: true then; false when there is none to wait at, or it goes away. The chat's own
63
+ * server is the one with its session; after /clear, which gives the hook a new one, and in hosts whose server does not know its session, the only server of
64
+ * its campaign, while no other chat waits there for the page (D-577): better no ring than one in a chat that cannot read the page. The hook may come before its
65
+ * chat's page answers, as in Antigravity: while the campaign has none, it looks again `looks.times` times, every `looks.every` ms.
66
+ */
67
+ export async function waitForBell(input, ports, looks = { every: 500, times: 10 }) {
68
+ return (await bellHeard(input, { ports, looks })).rang;
69
+ }
70
+ /**
71
+ * Waits as waitForBell does, at `ports` or the campaign's, looking again as `looks` says, and says what it heard; with `words`, it asks the page for the
72
+ * player's sentences themselves, which the page holds for the master's next call (D-578).
73
+ */
74
+ export async function bellHeard(input, options = {}) {
75
+ const { ports, looks = { every: 500, times: 10 }, words = false } = options;
76
+ const hook = hookInput(input);
77
+ // Antigravity runs its hooks in .agents: the campaign is found upwards.
78
+ const root = findCampaign(hook.cwd ?? process.cwd());
79
+ if (root === undefined) {
80
+ return { rang: false };
81
+ }
82
+ let ours = await campaignPages(root, ports ?? campaignPorts(root));
83
+ for (let look = 1; ours.length === 0 && look <= looks.times; look++) {
84
+ await new Promise((done) => setTimeout(done, looks.every));
85
+ ours = await campaignPages(root, ports ?? campaignPorts(root));
86
+ }
87
+ // The only page of the campaign, once nobody else waits for it: a chat that does could be this one, and a wrong chat cannot read the page. An older
88
+ // engine's page does not say who waits, so it is never taken as this chat's.
89
+ const only = ours.length === 1 && ours[0].said.others?.length === 0 ? ours[0] : undefined;
90
+ const port = (ours.find((one) => hook.session !== undefined && one.said.session === hook.session) ?? only)?.port;
91
+ const said = port === undefined ? undefined : await askDashboard(port, words ? "/api/bell?words" : "/api/bell");
92
+ // An older engine's page, or one with no words to give, rings alone.
93
+ if (said === "ring") {
94
+ return { rang: true };
95
+ }
96
+ // The words, after a first line with their ids: the page hears they were taken before the chat is given them.
97
+ const head = said?.match(/^ring(?: ([\w,-]*))?\n/);
98
+ if (said === undefined || head === null || head === undefined) {
99
+ return { rang: false };
100
+ }
101
+ if (port !== undefined && head[1] !== undefined && head[1] !== "") {
102
+ await askDashboard(port, `/api/bell?took=${encodeURIComponent(head[1])}`, 2000);
103
+ }
104
+ const text = said.slice(head[0].length).trim();
105
+ return { rang: true, ...(text === "" ? {} : { words: text }) };
106
+ }
107
+ /** The campaign's dashboards that answer at these ports, with what each says of itself. */
108
+ async function campaignPages(root, ports) {
109
+ const probes = await Promise.all(ports.filter((port) => port !== 0).map(async (port) => ({ port, said: await dashboardAt(port) })));
110
+ return probes.flatMap((one) => (one.said !== undefined && one.said.root !== null && samePath(one.said.root, root) ? [{ port: one.port, said: one.said }] : []));
111
+ }
112
+ /** What the hook reads of its host's input: the chat's session, Antigravity's conversation; its folder; the process of OpenCode, which its plugin names. */
113
+ function hookInput(input) {
114
+ try {
115
+ const parsed = JSON.parse(input);
116
+ const session = typeof parsed.session_id === "string" ? parsed.session_id : parsed.conversationId;
117
+ return {
118
+ ...(typeof session === "string" ? { session } : {}),
119
+ ...(typeof parsed.cwd === "string" ? { cwd: parsed.cwd } : {}),
120
+ ...(Number.isInteger(parsed.host_pid) && parsed.host_pid > 0 ? { hostPid: parsed.host_pid } : {}),
121
+ };
122
+ }
123
+ catch {
124
+ return {};
125
+ }
126
+ }
127
+ /** Looks every `every` ms whether the process `pid` still runs: `ended` once it does not. On macOS and Linux a closed terminal does not end the hook. */
128
+ function watchProcessEnd(pid, every = 2000) {
129
+ let timer;
130
+ const ended = new Promise((done) => {
131
+ timer = setInterval(() => {
132
+ if (!processRuns(pid)) {
133
+ done();
134
+ }
135
+ }, every);
136
+ timer.unref();
137
+ });
138
+ return { ended, stop: () => clearInterval(timer) };
139
+ }
140
+ // A process another user runs answers EPERM: it runs.
141
+ function processRuns(pid) {
142
+ try {
143
+ process.kill(pid, 0);
144
+ return true;
145
+ }
146
+ catch (error) {
147
+ return error.code === "EPERM";
148
+ }
149
+ }
@@ -37,6 +37,8 @@ export interface DashboardOptions {
37
37
  pageHidden?: number;
38
38
  /** Codex's queue for the player's sentences (D-495): Codex's own command, else a fake in the tests. */
39
39
  queue?: CodexQueue;
40
+ /** How long sentences given to a hook that speaks them wait for the master's next call before they are given back, in ms (D-578). */
41
+ heldFor?: number;
40
42
  }
41
43
  /** Codex's queue: whether this computer has the command, and a message queued in a thread, as the player's own (D-495). */
42
44
  export interface CodexQueue {
@@ -118,9 +120,16 @@ export interface Served {
118
120
  acts: Acts;
119
121
  /** The other chats of the campaign that wait for its page, by session, with when each last asked (D-577). */
120
122
  others: Map<string, number>;
121
- /** The doorbell of Claude Code's hook, waiting for a sentence; and whether one ever came, so that this chat has one (D-495). */
123
+ /**
124
+ * The doorbell's hook, waiting for a sentence; whether it asked for the player's words, as OpenCode's does (D-578); whether one ever came, so that this chat
125
+ * has one (D-495); and whether the last went away without a ring, as when the chat was stopped, until a hook or a call of the master comes again.
126
+ */
122
127
  bell?: ServerResponse;
128
+ bellWords?: boolean;
123
129
  belled?: boolean;
130
+ bellGone?: boolean;
131
+ /** How long sentences given to a hook wait for the master's next call, in ms (D-578). */
132
+ heldFor: number;
124
133
  /** Codex's queue, and the sentences being put in it now (D-495). */
125
134
  queue: CodexQueue;
126
135
  queueing?: Promise<void>;
@@ -18,7 +18,7 @@ import { loadSystemCode } from "../../systems/index.js";
18
18
  import { newActs } from "../player-acts.js";
19
19
  import { choicesNews, choicesRequest } from "./choices.js";
20
20
  import { builtPage, packagePageFile, pageFile, pageHtml, pageModulesOf, pagePolicy, pageWords, securityHeaders, send, sendFile, sendImage, sendInstalledThemeFile, sendJson, sendPacked, sendThemeFile, themeAddress, themeNow, themesAddress, vendorModule, } from "./files.js";
21
- import { act, deliverActs, keepProblems, listenForBell, notes, pageNews, setupWord, story } from "./news.js";
21
+ import { act, callBegins, deliverActs, keepProblems, listenForBell, notes, pageNews, setupWord, story } from "./news.js";
22
22
  import { givePicture } from "./pictures.js";
23
23
  import { answerAsked, closeCard, listenForChanges, pagePlayer, pageSeen, rollNamesOf, spendShown } from "./player.js";
24
24
  import { answers, campaignPorts, dashboardAt } from "./ports.js";
@@ -34,6 +34,8 @@ const noticeDelay = 100;
34
34
  const pageReturn = 5000;
35
35
  // How long a question waits on pages that are open but that no one sees, as one in a tab behind, before it goes to the form or to words (D-455).
36
36
  const pageHidden = 5000;
37
+ // How long the sentences given to OpenCode's hook wait for a call of the master before they are given back (D-578).
38
+ const heldFor = 60_000;
37
39
  // How often the server looks at an import under way, for the pages to tell how far it is (D-491 (11)).
38
40
  const importLookEvery = 2000;
39
41
  /**
@@ -90,6 +92,7 @@ export async function startDashboard(context, session, options = {}) {
90
92
  acts: newActs(),
91
93
  others: new Map(),
92
94
  queue: options.queue ?? codexQueue(),
95
+ heldFor: options.heldFor ?? heldFor,
93
96
  };
94
97
  return serve(server, served);
95
98
  }
@@ -149,6 +152,7 @@ function serve(server, served) {
149
152
  // A call of the master that ends leaves the player's sentences said meanwhile for the doorbell, or for Codex's queue (D-495).
150
153
  const chat = served.context.chat;
151
154
  if (chat !== undefined) {
155
+ chat.beforeCall = () => callBegins(served);
152
156
  chat.afterCall = () => deliverActs(served);
153
157
  }
154
158
  // An import works in another process, or in the call the master waits on, writing where the session does not watch: its state is looked at now and then,
@@ -192,6 +196,7 @@ function serve(server, served) {
192
196
  served.asked?.settle("absent");
193
197
  served.bell?.end("gone");
194
198
  if (chat !== undefined) {
199
+ chat.beforeCall = undefined;
195
200
  chat.afterCall = undefined;
196
201
  }
197
202
  served.pages.forEach((page) => page.end());
@@ -30,9 +30,11 @@ export declare function act(request: IncomingMessage, response: ServerResponse,
30
30
  * messages, else by Claude Code's doorbell. Every ring comes from a sentence the player said, never from time.
31
31
  */
32
32
  export declare function deliverActs(served: Served): void;
33
+ /** As a call of the master begins: the sentences held for it are heard, and the chat listens again, whatever its last hook did. */
34
+ export declare function callBegins(served: Served): void;
33
35
  /**
34
36
  * 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
35
- * 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
37
+ * 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
36
38
  * server; with also, one of those, which says so as it asks (D-577).
37
39
  */
38
40
  export declare function listenForBell(request: IncomingMessage, response: ServerResponse, served: Served, asked: URLSearchParams): void;
@@ -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;
@@ -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";
@@ -122,12 +122,12 @@ export function createMcpServer(context = defaultContext(), environment = proces
122
122
  }
123
123
  /**
124
124
  * 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.
125
+ * 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
126
  */
127
- export async function startMcpServer() {
127
+ export async function startMcpServer(input = process.stdin) {
128
128
  const leave = () => process.exit(0);
129
- process.stdin.on("end", leave);
130
- process.stdin.on("close", leave);
129
+ input.on("end", leave);
130
+ input.on("close", leave);
131
131
  // 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
132
  let server;
133
133
  const host = () => server?.server.getClientVersion()?.name;
@@ -157,7 +157,7 @@ export async function startMcpServer() {
157
157
  server = createMcpServer(served, process.env, dashboardOpener(served, session).open);
158
158
  // The extensions' tools are there in the first list the host asks for.
159
159
  await firstExtensions.get(server);
160
- await server.connect(new StdioServerTransport());
160
+ await server.connect(new StdioServerTransport(input));
161
161
  }
162
162
  /**
163
163
  * 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 +233,11 @@ async function preload(context, session) {
233
233
  if (root !== undefined) {
234
234
  session.track(root);
235
235
  // An agent written now reaches only the chats after this one (D-490).
236
- context.characterAgent = hasCharacterAgent(root);
236
+ context.characterAgents = hasCharacterAgent(root);
237
237
  refreshHostFiles(root, hostInstructions(), context.platform);
238
+ if (context.userHome !== undefined) {
239
+ refreshUserHostFiles(context.userHome, context.platform);
240
+ }
238
241
  campaignWorld(root, context);
239
242
  // What the last session left, committed as this one starts, where the campaign keeps itself in git (D-576).
240
243
  void commitSessionStart(root, context);
@@ -382,6 +385,7 @@ async function runTool(command, input, context, extra, prepare, installer, outsi
382
385
  if (chat !== undefined) {
383
386
  chat.calls++;
384
387
  chat.thread = typeof thread === "string" && thread !== "" ? thread : chat.thread;
388
+ chat.beforeCall?.();
385
389
  }
386
390
  try {
387
391
  // 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).
@@ -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);
@@ -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;