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,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
+ };
@@ -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
+ }
@@ -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 the subagent tool, and its answer comes later as a message: once you started it, end your turn without a word to the player, and narrate when its lines come.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rpg-engine",
3
- "version": "0.22.0",
3
+ "version": "0.23.1",
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
- }