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
@@ -0,0 +1,215 @@
1
+ // The router of `rpg mcp` started outside a campaign, as Antigravity's app starts it (D-578): one server for all its folders, which names in each call only the
2
+ // conversation. It keeps one child `rpg mcp` for each campaign a call plays, started the first time it is needed with the client's handshake, and one in its own
3
+ // folder for everything else: each call goes to the child of its conversation's noted campaign, the others to its own folder's, never to another campaign's.
4
+ import { isAbsolute } from "node:path";
5
+ import { samePath } from "../../library/index.js";
6
+ /** The client's meta key that names Antigravity's conversation in every call. */
7
+ export const conversationKey = "antigravity.google/conversation_id";
8
+ /** 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. */
9
+ export function mcpRouter(options) {
10
+ const looks = options.noteLooks ?? { every: 200, times: 10 };
11
+ const log = options.log ?? (() => undefined);
12
+ const children = [];
13
+ let handshake = {};
14
+ // The child that answered the client's last tools/list, and the one its last request went to.
15
+ let listedBy;
16
+ let current;
17
+ // The children's own requests to the client, by the id the router gave them.
18
+ const asked = new Map();
19
+ let askedCount = 0;
20
+ // The conversations whose note was looked for with patience already: later calls look once.
21
+ const waited = new Set();
22
+ let queue = Promise.resolve();
23
+ const childIn = (folder) => {
24
+ const found = children.find((child) => samePath(child.folder, folder));
25
+ return found ?? startChild(folder);
26
+ };
27
+ const startChild = (folder) => {
28
+ const child = { folder, pending: new Map(), server: options.start(folder) };
29
+ children.push(child);
30
+ child.server.onLine((line) => fromChild(child, line));
31
+ child.server.onEnd((reason) => ended(child, reason));
32
+ // A child started after the handshake gets it again; its answer to initialize is its own, the client had one.
33
+ if (handshake.initialize !== undefined) {
34
+ child.replayed = parsed(handshake.initialize)?.id;
35
+ child.server.write(handshake.initialize);
36
+ }
37
+ if (handshake.initialized !== undefined) {
38
+ child.server.write(handshake.initialized);
39
+ }
40
+ return child;
41
+ };
42
+ const fromChild = (child, line) => {
43
+ const message = parsed(line);
44
+ if (message === undefined || !children.includes(child)) {
45
+ return;
46
+ }
47
+ if (message.method === undefined && message.id !== undefined) {
48
+ if (child.replayed !== undefined && message.id === child.replayed) {
49
+ child.replayed = undefined;
50
+ return;
51
+ }
52
+ const request = child.pending.get(message.id);
53
+ child.pending.delete(message.id);
54
+ if (request?.method === "tools/list") {
55
+ listedBy = child;
56
+ }
57
+ options.toClient(request?.advice === undefined ? line : JSON.stringify(withAdvice(message, request.advice)));
58
+ return;
59
+ }
60
+ // A request of the child's own to the client, as a form: an id no other child's can take.
61
+ if (message.method !== undefined && message.id !== undefined) {
62
+ askedCount++;
63
+ const id = `rpg-route-${askedCount}`;
64
+ asked.set(id, { child, id: message.id });
65
+ options.toClient(JSON.stringify({ ...message, id }));
66
+ return;
67
+ }
68
+ // The child takes back a request of its own: the client knows it by the id the router gave it.
69
+ if (message.method === "notifications/cancelled") {
70
+ const requestId = message.params?.requestId;
71
+ const given = [...asked].find(([, request]) => request.child === child && request.id === requestId)?.[0];
72
+ if (given !== undefined) {
73
+ options.toClient(JSON.stringify({ ...message, params: { ...message.params, requestId: given } }));
74
+ return;
75
+ }
76
+ }
77
+ options.toClient(line);
78
+ };
79
+ // A child that ends is forgotten, and the client's requests it held are answered: the next call for its folder starts another.
80
+ const ended = (child, reason) => {
81
+ const index = children.indexOf(child);
82
+ if (index === -1) {
83
+ return;
84
+ }
85
+ children.splice(index, 1);
86
+ listedBy = listedBy === child ? undefined : listedBy;
87
+ current = current === child ? undefined : current;
88
+ log(`rpg mcp router: the server in ${child.folder} ended (${reason})`);
89
+ for (const [id] of child.pending) {
90
+ options.toClient(JSON.stringify({ jsonrpc: "2.0", id, error: { code: -32603, message: `The rpg server in ${child.folder} stopped (${reason}): call again.` } }));
91
+ }
92
+ for (const [id, request] of asked) {
93
+ if (request.child === child) {
94
+ asked.delete(id);
95
+ }
96
+ }
97
+ };
98
+ const route = async (line) => {
99
+ const message = parsed(line);
100
+ if (message === undefined) {
101
+ return;
102
+ }
103
+ // An answer of the client's to a child's request goes back to that child, with the id it gave.
104
+ if (message.method === undefined) {
105
+ const request = typeof message.id === "string" ? asked.get(message.id) : undefined;
106
+ if (request !== undefined) {
107
+ asked.delete(message.id);
108
+ request.child.server.write(JSON.stringify({ ...message, id: request.id }));
109
+ }
110
+ return;
111
+ }
112
+ if (message.method === "initialize") {
113
+ handshake = { initialize: line };
114
+ }
115
+ else if (message.method === "notifications/initialized") {
116
+ handshake.initialized = line;
117
+ }
118
+ if (message.id === undefined) {
119
+ notify(message, line);
120
+ return;
121
+ }
122
+ const request = { method: String(message.method) };
123
+ const child = message.method === "tools/call" ? await callChild(message, request) : (current ?? childIn(options.folder));
124
+ if (child === undefined) {
125
+ return;
126
+ }
127
+ child.pending.set(message.id, request);
128
+ child.server.write(line);
129
+ };
130
+ // A notification of the client's: one that cancels a request goes to the child that has it; the handshake's to the children there are; any other to all.
131
+ const notify = (message, line) => {
132
+ const cancelled = message.params?.requestId;
133
+ const holder = cancelled === undefined ? undefined : children.find((child) => child.pending.has(cancelled));
134
+ const targets = holder !== undefined ? [holder] : children.length > 0 ? children : [childIn(options.folder)];
135
+ targets.forEach((child) => child.server.write(line));
136
+ };
137
+ // The child a call goes to: its conversation's campaign as noted, else the router's own folder; a call there of a conversation the hooks never noted gets
138
+ // the advice it needs, or is answered at once when it would make a campaign in the app's own folder.
139
+ const callChild = async (message, request) => {
140
+ const conversation = conversationOf(message);
141
+ const root = conversation === undefined ? undefined : await noted(conversation);
142
+ const child = childIn(root ?? options.folder);
143
+ if (conversation !== undefined && root === undefined) {
144
+ const call = message.params;
145
+ const folder = call?.arguments?.folder;
146
+ if (call?.name === "init" && (typeof folder !== "string" || !isAbsolute(folder))) {
147
+ log(`rpg mcp router: call ${String(message.id)} of conversation ${conversation} asks init with no full path: answered without a server`);
148
+ options.toClient(JSON.stringify({ jsonrpc: "2.0", id: message.id, result: { content: [{ type: "text", text: initWhere }], isError: true } }));
149
+ return undefined;
150
+ }
151
+ request.advice = call?.name === "init" ? openThere(folder) : openThere();
152
+ }
153
+ log(`rpg mcp router: call ${String(message.id)}${conversation === undefined ? "" : ` of conversation ${conversation}`} goes to the server in ${child.folder}${root === undefined && conversation !== undefined ? " (no campaign noted for it)" : ""}`);
154
+ // The client lists its tools from one child: one whose tools it did not list may have others, as another campaign's packages give.
155
+ if (listedBy !== undefined && listedBy !== child) {
156
+ options.toClient(JSON.stringify({ jsonrpc: "2.0", method: "notifications/tools/list_changed" }));
157
+ listedBy = undefined;
158
+ }
159
+ current = child;
160
+ return child;
161
+ };
162
+ const noted = async (conversation) => {
163
+ let root = options.campaignOf(conversation);
164
+ for (let look = 1; root === undefined && !waited.has(conversation) && look <= looks.times; look++) {
165
+ await new Promise((done) => setTimeout(done, looks.every));
166
+ root = options.campaignOf(conversation);
167
+ }
168
+ waited.add(conversation);
169
+ return root;
170
+ };
171
+ // The child in the router's own folder serves from the start, as the server alone would.
172
+ childIn(options.folder);
173
+ return {
174
+ // One line at a time, in order: a call that waits for its note holds those after it.
175
+ fromClient: (line) => {
176
+ queue = queue.then(() => route(line)).catch(() => undefined);
177
+ return queue;
178
+ },
179
+ stop: () => {
180
+ for (const child of children.splice(0)) {
181
+ child.server.stop();
182
+ }
183
+ },
184
+ };
185
+ }
186
+ // What init answers, called from the app's own folder with no full path: it would make a campaign among the app's files.
187
+ const initWhere = "This chat runs in no campaign's folder, so init needs where to make the campaign: ask the player which folder, and pass its full path as folder.";
188
+ /** What the master is told after a call from the app's own folder: the chat must start in the campaign's folder, where its hooks load. */
189
+ function openThere(folder) {
190
+ const where = folder === undefined ? "the campaign's folder" : folder;
191
+ return `Tell the player: open ${where} in Antigravity and start a new chat there. This chat runs outside the campaign, and the game's hooks load only when a chat starts in its folder.`;
192
+ }
193
+ /** An answer of a call with a line added after its content; an error answer keeps its error and gets the line as its message's end. */
194
+ function withAdvice(message, advice) {
195
+ const result = message.result;
196
+ if (result !== undefined && Array.isArray(result.content)) {
197
+ return { ...message, result: { ...result, content: [...result.content, { type: "text", text: advice }] } };
198
+ }
199
+ const error = message.error;
200
+ return error === undefined ? message : { ...message, error: { ...error, message: `${String(error.message ?? "")} ${advice}`.trim() } };
201
+ }
202
+ function parsed(line) {
203
+ try {
204
+ const message = JSON.parse(line);
205
+ return message !== null && typeof message === "object" && !Array.isArray(message) ? message : undefined;
206
+ }
207
+ catch {
208
+ return undefined;
209
+ }
210
+ }
211
+ function conversationOf(message) {
212
+ const meta = message.params?._meta;
213
+ const conversation = meta?.[conversationKey];
214
+ return typeof conversation === "string" && conversation !== "" ? conversation : undefined;
215
+ }
@@ -0,0 +1,4 @@
1
+ /** The answer to a subagent's call of any tool but view. */
2
+ export declare const subagentRefusal = "You voice one character here: only view is yours, with as and your character's name. Answer with what you know.";
3
+ /** Whether a tool call comes from a subagent, by its metadata: Codex's turn with thread_source subagent, as an object or as JSON, or Antigravity's parent conversation. */
4
+ export declare function fromSubagent(meta: unknown): boolean;
@@ -0,0 +1,30 @@
1
+ // The calls of the character agent where the host starts it as a subagent that has every rpg tool, as Codex and Antigravity do (D-580): it may only look.
2
+ /** The answer to a subagent's call of any tool but view. */
3
+ export const subagentRefusal = "You voice one character here: only view is yours, with as and your character's name. Answer with what you know.";
4
+ // The keys of the call's metadata by which Codex and Antigravity say who calls.
5
+ const codexTurnKey = "x-codex-turn-metadata";
6
+ const antigravityParentKey = "antigravity.google/parent_conversation_id";
7
+ /** Whether a tool call comes from a subagent, by its metadata: Codex's turn with thread_source subagent, as an object or as JSON, or Antigravity's parent conversation. */
8
+ export function fromSubagent(meta) {
9
+ if (!isObject(meta)) {
10
+ return false;
11
+ }
12
+ const parent = meta[antigravityParentKey];
13
+ return (typeof parent === "string" && parent !== "") || codexTurn(meta[codexTurnKey])?.thread_source === "subagent";
14
+ }
15
+ // Codex's turn metadata, which comes as an object or as a JSON string; undefined when it is neither.
16
+ function codexTurn(value) {
17
+ if (typeof value !== "string") {
18
+ return isObject(value) ? value : undefined;
19
+ }
20
+ try {
21
+ const parsed = JSON.parse(value);
22
+ return isObject(parsed) ? parsed : undefined;
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ }
28
+ function isObject(value) {
29
+ return typeof value === "object" && value !== null && !Array.isArray(value);
30
+ }
@@ -1 +1 @@
1
- This folder is a tabletop role-playing campaign and you are its game master: you invent, play and rule; the `rpg` tools remember, roll and keep the accounts. Before your first reply in every chat, and again whenever the conversation has been summarized, call `instructions` (how to be its game master), then `status` (where the game stands). Follow them. Never mention tools, files or the engine to the player. Never read your app's past chats or their logs: the game remembers only through `status`.
1
+ This folder is a tabletop role-playing campaign and you are its game master: you invent, play and rule; the `rpg` server's tools remember, roll and keep the accounts. Before your first reply in every chat, and again whenever the conversation has been summarized, call `instructions` (how to be its game master), then `status` (where the game stands). Follow them. Never mention tools, files or the engine to the player. Never read your app's past chats or their logs: the game remembers only through `status`. Without `rpg` tools, do not play: tell the player to run `rpg init` in this folder and open a new chat.
@@ -0,0 +1 @@
1
+ Here the agent is the subagent rpg-character, started with invoke_subagent (TypeName rpg-character, Role the character's name, Prompt your words to them). Its answer is not yours to write: it comes by itself, later, as a message from the subagent. Once you started it, end your turn with one short line of the story and nothing else: what the player's character sees of them in the instant before they answer, a pause or a look, never their answer, and never a word about waiting, messages or agents. Narrate their answer only when that message has come.
@@ -0,0 +1 @@
1
+ Here the agent is the agent type rpg-character: start it with spawn_agent, with agent_type rpg-character, fork_turns none and your words to the character as the message, then call wait_agent until its answer comes, and narrate in the same turn, with not a word to the player in between.
@@ -0,0 +1 @@
1
+ Here the agent is the subagent rpg-character, started with the subagent tool (agent rpg-character, prompt your words to them). Its answer is not yours to write: it comes by itself, later, as a <subagent> message. Once you started it, end your turn with one short line of the story and nothing else: what the player's character sees of them in the instant before they answer, a pause or a look, never their answer, and never a word about waiting, messages or agents. Narrate their answer only when that message has come.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rpg-engine",
3
- "version": "0.22.0",
3
+ "version": "0.24.0",
4
4
  "description": "Play a tabletop role-playing game with an AI as your game master: the AI tells the story; RPG Engine remembers the world, rolls the dice and keeps the accounts.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -29,7 +29,8 @@
29
29
  "files": [
30
30
  "dist",
31
31
  "systems",
32
- "instructions"
32
+ "instructions",
33
+ "plugins"
33
34
  ],
34
35
  "scripts": {
35
36
  "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc && tsc -p src/dashboard && node -e \"require('node:fs').cpSync('src/dashboard', 'dist/dashboard', { recursive: true, filter: (path) => !/[.](tsx?|py)$|tsconfig[.]json$|[^a-z-]style$/.test(path) })\" && node src/dashboard/style/join.mjs dist/dashboard/style.css",
@@ -0,0 +1,174 @@
1
+ // RPG Engine's plugin for OpenCode (D-578), which rpg writes as .opencode/plugins/rpg.js in a campaign. OpenCode runs no hooks, so this runs the doorbell
2
+ // on its events: a turn that ends waits for the player on the dashboard (`rpg --listen opencode`), whose line comes to the chat as a message; a turn that
3
+ // starts meanwhile, or the player's message, lets that wait go. Nothing here ever stops OpenCode: what fails is left alone.
4
+ import { spawn } from "node:child_process";
5
+ import { resolve } from "node:path";
6
+
7
+ export default {
8
+ id: "rpg",
9
+ /** Follows OpenCode's events until it lets the plugin go. `run` starts a program as Node's spawn does: the tests give their own. */
10
+ async setup(context, run)
11
+ {
12
+ const chats = campaignChats(context, typeof run === "function" ? run : spawn);
13
+ const controller = new AbortController();
14
+
15
+ void (async () => {
16
+ try {
17
+ for await (const event of context.event.subscribe({ signal: controller.signal })) {
18
+ try {
19
+ chats.heard(event);
20
+ } catch {
21
+ // An event of a shape this plugin does not know: the next one is heard all the same.
22
+ }
23
+ }
24
+ } catch {
25
+ // OpenCode stopped telling its events: the doorbell waits no more, and the game goes on in the chat.
26
+ }
27
+ })();
28
+
29
+ return () => {
30
+ controller.abort();
31
+ chats.stop();
32
+ };
33
+ },
34
+ };
35
+
36
+ /** What the plugin does with OpenCode's events in the campaign's folder: its chats, and the doorbell of each. */
37
+ function campaignChats(context, run)
38
+ {
39
+ const folder = context?.location?.directory ?? process.cwd();
40
+ const ours = new Set();
41
+ const agents = new Set();
42
+ const listeners = new Map();
43
+
44
+ // A chat's doorbell, which the player's sentence on the dashboard rings: its words are sent to the chat, which starts a turn. Words the chat could not
45
+ // take come back to the page, which rings again: a doorbell waits for them.
46
+ const listen = (session) => {
47
+ letGo(session);
48
+ const waiting = hook({ cwd: folder, session_id: session, hook_event_name: "Stop", host_pid: process.pid }, (code, output) => {
49
+ if (listeners.get(session) !== waiting) {
50
+ return;
51
+ }
52
+
53
+ listeners.delete(session);
54
+
55
+ if (code === 0) {
56
+ say(session, output);
57
+ }
58
+ });
59
+
60
+ if (waiting !== undefined) {
61
+ listeners.set(session, waiting);
62
+ }
63
+ };
64
+
65
+ const say = (session, output) => {
66
+ const line = output.trim();
67
+
68
+ if (line !== "") {
69
+ Promise.resolve().then(() => context.session.prompt({ sessionID: session, text: line })).catch(() => listen(session));
70
+ }
71
+ };
72
+
73
+ // `rpg --listen opencode` in the folder, with its input on stdin, as a host runs a hook: `ended` hears its exit code and what it wrote; `said` what it
74
+ // wrote so far.
75
+ const hook = (input, ended) => {
76
+ try {
77
+ const child = run("rpg --listen opencode", { cwd: folder, shell: true, windowsHide: true, stdio: ["pipe", "pipe", "ignore"], detached: process.platform !== "win32" });
78
+ let output = "";
79
+ child.stdout?.on("data", (chunk) => {
80
+ output += String(chunk);
81
+ });
82
+ child.stdin?.on("error", () => undefined);
83
+ child.on("error", () => undefined);
84
+ child.on("close", (code) => ended(code, output));
85
+ child.stdin?.end(JSON.stringify(input));
86
+ return { child, said: () => output };
87
+ } catch {
88
+ return undefined;
89
+ }
90
+ };
91
+
92
+ // The doorbell of a chat whose turn starts: ended, with what it started; the dashboard sees it gone. Words it already had still go to the chat, after
93
+ // the player's message: the page counts them as the master's.
94
+ const letGo = (session) => {
95
+ const waiting = listeners.get(session);
96
+
97
+ if (waiting !== undefined) {
98
+ listeners.delete(session);
99
+ end(waiting.child, run);
100
+ say(session, waiting.said());
101
+ }
102
+ };
103
+
104
+ return {
105
+ heard: (event) => {
106
+ const session = event?.data?.sessionID;
107
+
108
+ if (typeof session !== "string") {
109
+ return;
110
+ }
111
+
112
+ // OpenCode's background service runs this plugin for every folder and tells it the events of all: only the chats of this folder are its own.
113
+ // The turn's start and end say no folder: the session's earlier events, its creation or its messages, have said it.
114
+ const place = event.location?.directory ?? event.data.location?.directory;
115
+
116
+ if (typeof place === "string" && sameFolder(place, folder)) {
117
+ ours.add(session);
118
+ }
119
+
120
+ if (!ours.has(session)) {
121
+ return;
122
+ }
123
+
124
+ // A subagent's session is born with its parent's: it is no chat, and nobody waits for the player after its turns.
125
+ if (event.type === "session.created" && typeof event.data.parentID === "string") {
126
+ agents.add(session);
127
+ }
128
+
129
+ if (agents.has(session)) {
130
+ return;
131
+ }
132
+
133
+ // A message of the player's, or the doorbell's own, which comes once its wait has ended, lets the wait go; a turn's end waits again, a failed one too.
134
+ if ((event.type === "session.inbox.enqueued" && event.data.item?.type === "user") || event.type === "session.execution.started") {
135
+ letGo(session);
136
+ } else if (event.type === "session.execution.succeeded" || event.type === "session.execution.failed") {
137
+ listen(session);
138
+ }
139
+ },
140
+ stop: () => {
141
+ for (const session of [...listeners.keys()]) {
142
+ letGo(session);
143
+ }
144
+ },
145
+ };
146
+ }
147
+
148
+ /** Ends a hook with what its shell started: on Windows its whole tree, else its process group; the process alone when neither can be. */
149
+ function end(child, run)
150
+ {
151
+ try {
152
+ if (child.pid === undefined) {
153
+ child.kill();
154
+ } else if (process.platform === "win32") {
155
+ run("taskkill", ["/T", "/F", "/PID", String(child.pid)], { windowsHide: true, stdio: "ignore" }).on("error", () => child.kill());
156
+ } else {
157
+ process.kill(-child.pid, "SIGTERM");
158
+ }
159
+ } catch {
160
+ try {
161
+ child.kill();
162
+ } catch {
163
+ // Gone already.
164
+ }
165
+ }
166
+ }
167
+
168
+ /** Whether OpenCode's folder of a session is this one, as the system compares paths: on Windows and macOS without the case. */
169
+ function sameFolder(place, folder)
170
+ {
171
+ const caseless = process.platform === "win32" || process.platform === "darwin";
172
+ const plain = (path) => (caseless ? resolve(path).toLowerCase() : resolve(path));
173
+ return plain(place) === plain(folder);
174
+ }
@@ -1,10 +0,0 @@
1
- /** What the chat hears from the doorbell: never the player's words, only where to read them. */
2
- export declare const bellLine = "The player acted on the dashboard: call status to read what they did.";
3
- /** Reads the hook's input, waits for the doorbell, and ends the process as Claude Code's asyncRewake reads it: 2 with the line to wake the chat, else 0. */
4
- export declare function listenHere(): Promise<void>;
5
- /**
6
- * 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
7
- * server is the one with its session; after /clear, which gives the hook a new one, the only server of its campaign, while no other chat waits there for the
8
- * page (D-577): better no ring than one in a chat that cannot read the page.
9
- */
10
- export declare function waitForBell(input: string, ports?: number[]): Promise<boolean>;
@@ -1,52 +0,0 @@
1
- // Claude Code's doorbell for the player's sentences on the dashboard (D-495): `rpg --listen`, the Stop hook init writes, waits at the dashboard of its own
2
- // chat and, when the player says a sentence, tells the chat to call status. It never carries the sentence, which reaches the master in that call.
3
- import { findCampaign } from "../campaign/index.js";
4
- import { samePath } from "../library/index.js";
5
- import { askDashboard, campaignPorts, dashboardAt } from "./dashboard/ports.js";
6
- /** What the chat hears from the doorbell: never the player's words, only where to read them. */
7
- export const bellLine = "The player acted on the dashboard: call status to read what they did.";
8
- /** Reads the hook's input, waits for the doorbell, and ends the process as Claude Code's asyncRewake reads it: 2 with the line to wake the chat, else 0. */
9
- export async function listenHere() {
10
- let input = "";
11
- for await (const chunk of process.stdin) {
12
- input += String(chunk);
13
- }
14
- // It ends as soon as it knows, whatever else the process holds: the chat hears the hook only once it ends.
15
- if (await waitForBell(input)) {
16
- process.stderr.write(`${bellLine}\n`, () => process.exit(2));
17
- }
18
- else {
19
- process.exit(0);
20
- }
21
- }
22
- /**
23
- * 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
24
- * server is the one with its session; after /clear, which gives the hook a new one, the only server of its campaign, while no other chat waits there for the
25
- * page (D-577): better no ring than one in a chat that cannot read the page.
26
- */
27
- export async function waitForBell(input, ports) {
28
- const hook = hookInput(input);
29
- const root = findCampaign(hook.cwd ?? process.cwd());
30
- if (root === undefined) {
31
- return false;
32
- }
33
- const probes = await Promise.all((ports ?? campaignPorts(root)).filter((port) => port !== 0).map(async (port) => ({ port, said: await dashboardAt(port) })));
34
- const ours = probes.flatMap((one) => (one.said !== undefined && one.said.root !== null && samePath(one.said.root, root) ? [{ port: one.port, said: one.said }] : []));
35
- // 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
36
- // engine's page does not say who waits, so it is never taken as this chat's.
37
- const only = ours.length === 1 && ours[0].said.others?.length === 0 ? ours[0] : undefined;
38
- const port = (ours.find((one) => hook.session !== undefined && one.said.session === hook.session) ?? only)?.port;
39
- return port === undefined ? false : (await askDashboard(port, "/api/bell")) === "ring";
40
- }
41
- function hookInput(input) {
42
- try {
43
- const parsed = JSON.parse(input);
44
- return {
45
- ...(typeof parsed.session_id === "string" ? { session: parsed.session_id } : {}),
46
- ...(typeof parsed.cwd === "string" ? { cwd: parsed.cwd } : {}),
47
- };
48
- }
49
- catch {
50
- return {};
51
- }
52
- }