rpg-engine 0.23.1 → 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 (124) hide show
  1. package/README.md +2 -2
  2. package/dist/campaign/create-campaign.d.ts +1 -1
  3. package/dist/campaign/create-campaign.js +1 -1
  4. package/dist/campaign/find-campaign.js +11 -1
  5. package/dist/campaign/host-files.d.ts +5 -6
  6. package/dist/campaign/host-files.js +100 -60
  7. package/dist/campaign/settings.d.ts +3 -3
  8. package/dist/campaign/settings.js +5 -4
  9. package/dist/cli/cli.js +11 -2
  10. package/dist/commands/config/config.js +1 -1
  11. package/dist/commands/config/dashboard.js +23 -6
  12. package/dist/commands/config/words.js +1 -0
  13. package/dist/commands/image.js +3 -3
  14. package/dist/commands/import/import.d.ts +3 -1
  15. package/dist/commands/import/import.js +13 -5
  16. package/dist/commands/instructions.js +1 -1
  17. package/dist/commands/shared/campaign/images.js +3 -2
  18. package/dist/commands/shared/campaign/mode.js +1 -1
  19. package/dist/commands/shared/characters/voices.d.ts +2 -2
  20. package/dist/commands/shared/characters/voices.js +9 -9
  21. package/dist/commands/shared/sheet/sheet.d.ts +2 -2
  22. package/dist/commands/shared/sheet/sheet.js +3 -3
  23. package/dist/core/context.d.ts +8 -2
  24. package/dist/dashboard/acts/acts.js +39 -11
  25. package/dist/dashboard/acts/head.js +7 -0
  26. package/dist/dashboard/acts/names.js +4 -2
  27. package/dist/dashboard/acts/sending.js +23 -22
  28. package/dist/dashboard/acts/sheet.js +7 -149
  29. package/dist/dashboard/acts/strip.js +10 -14
  30. package/dist/dashboard/acts/talk.js +51 -0
  31. package/dist/dashboard/acts/thing.js +169 -0
  32. package/dist/dashboard/app.js +3 -3
  33. package/dist/dashboard/guide/ar.md +13 -13
  34. package/dist/dashboard/guide/cs.md +12 -12
  35. package/dist/dashboard/guide/da.md +12 -12
  36. package/dist/dashboard/guide/de.md +11 -11
  37. package/dist/dashboard/guide/el.md +11 -11
  38. package/dist/dashboard/guide/en.md +10 -10
  39. package/dist/dashboard/guide/es.md +11 -11
  40. package/dist/dashboard/guide/fi.md +11 -11
  41. package/dist/dashboard/guide/fr.md +12 -12
  42. package/dist/dashboard/guide/he.md +11 -11
  43. package/dist/dashboard/guide/hi.md +11 -11
  44. package/dist/dashboard/guide/hu.md +11 -11
  45. package/dist/dashboard/guide/is.md +11 -11
  46. package/dist/dashboard/guide/it.md +38 -38
  47. package/dist/dashboard/guide/ja.md +11 -11
  48. package/dist/dashboard/guide/ko.md +12 -12
  49. package/dist/dashboard/guide/nb.md +11 -11
  50. package/dist/dashboard/guide/nl.md +11 -11
  51. package/dist/dashboard/guide/pl.md +11 -11
  52. package/dist/dashboard/guide/pt.md +11 -11
  53. package/dist/dashboard/guide/ro.md +12 -12
  54. package/dist/dashboard/guide/ru.md +12 -12
  55. package/dist/dashboard/guide/sv.md +12 -12
  56. package/dist/dashboard/guide/tr.md +12 -12
  57. package/dist/dashboard/guide/uk.md +11 -11
  58. package/dist/dashboard/guide/zh.md +12 -12
  59. package/dist/dashboard/i18n/ar.json +24 -10
  60. package/dist/dashboard/i18n/cs.json +24 -10
  61. package/dist/dashboard/i18n/da.json +24 -10
  62. package/dist/dashboard/i18n/de.json +24 -10
  63. package/dist/dashboard/i18n/el.json +24 -10
  64. package/dist/dashboard/i18n/es.json +24 -10
  65. package/dist/dashboard/i18n/fi.json +24 -10
  66. package/dist/dashboard/i18n/fr.json +24 -10
  67. package/dist/dashboard/i18n/he.json +24 -10
  68. package/dist/dashboard/i18n/hi.json +24 -10
  69. package/dist/dashboard/i18n/hu.json +24 -10
  70. package/dist/dashboard/i18n/is.json +24 -10
  71. package/dist/dashboard/i18n/it.json +102 -88
  72. package/dist/dashboard/i18n/ja.json +24 -10
  73. package/dist/dashboard/i18n/ko.json +24 -10
  74. package/dist/dashboard/i18n/nb.json +24 -10
  75. package/dist/dashboard/i18n/nl.json +24 -10
  76. package/dist/dashboard/i18n/pl.json +24 -10
  77. package/dist/dashboard/i18n/pt.json +24 -10
  78. package/dist/dashboard/i18n/ro.json +24 -10
  79. package/dist/dashboard/i18n/ru.json +24 -10
  80. package/dist/dashboard/i18n/sv.json +24 -10
  81. package/dist/dashboard/i18n/tr.json +24 -10
  82. package/dist/dashboard/i18n/uk.json +24 -10
  83. package/dist/dashboard/i18n/zh.json +24 -10
  84. package/dist/dashboard/packages/packages.js +1 -1
  85. package/dist/dashboard/parts/icons.js +2 -0
  86. package/dist/dashboard/parts/labels.js +1 -0
  87. package/dist/dashboard/parts/layout.js +34 -0
  88. package/dist/dashboard/parts/widgets.js +6 -2
  89. package/dist/dashboard/settings/language-choice.js +1 -1
  90. package/dist/dashboard/settings/settings.js +61 -36
  91. package/dist/dashboard/settings/tabs.js +14 -0
  92. package/dist/dashboard/sheet/sheet.js +54 -33
  93. package/dist/dashboard/shell/notices.js +2 -2
  94. package/dist/dashboard/style.css +122 -47
  95. package/dist/helpers/antigravity.d.ts +47 -0
  96. package/dist/helpers/antigravity.js +434 -0
  97. package/dist/helpers/chosen.d.ts +11 -7
  98. package/dist/helpers/chosen.js +64 -37
  99. package/dist/helpers/index.d.ts +1 -0
  100. package/dist/helpers/index.js +2 -1
  101. package/dist/helpers/opencode.js +117 -24
  102. package/dist/helpers/programs.d.ts +8 -0
  103. package/dist/helpers/programs.js +35 -2
  104. package/dist/helpers/stop.d.ts +2 -0
  105. package/dist/helpers/stop.js +20 -1
  106. package/dist/helpers/svg.d.ts +4 -1
  107. package/dist/helpers/svg.js +16 -4
  108. package/dist/instructions/index.d.ts +4 -2
  109. package/dist/instructions/index.js +6 -3
  110. package/dist/server/bell/antigravity.d.ts +7 -2
  111. package/dist/server/bell/antigravity.js +24 -6
  112. package/dist/server/bell/index.d.ts +1 -1
  113. package/dist/server/bell/index.js +1 -1
  114. package/dist/server/bell/listener.js +6 -1
  115. package/dist/server/fence.d.ts +21 -0
  116. package/dist/server/fence.js +69 -0
  117. package/dist/server/mcp.js +26 -0
  118. package/dist/server/player-acts.js +1 -1
  119. package/dist/server/subagent.d.ts +4 -0
  120. package/dist/server/subagent.js +30 -0
  121. package/instructions/voices-antigravity.md +1 -0
  122. package/instructions/voices-codex.md +1 -0
  123. package/instructions/voices-opencode.md +1 -1
  124. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
1
  // Codex and Claude Code on the player's computer, found, installed and signed in with the player's yes (D-424), and what they do for the game: pictures made
2
2
  // from words (D-308, D-390), Codex's painted else Claude's SVG, the importer's reading and the page's words; OpenCode for the last two in its own chat
3
- // (D-578 (3)); injected through Context, so that tests never spend.
3
+ // (D-578 (3)), and Antigravity's agy for the same in its own (D-579 (1)); injected through Context, so that tests never spend.
4
+ export { antigravityPainter, antigravityReader, antigravitySays, antigravityWriter, painterSettings, playerModel, readerSettings, sealedSettings } from "./antigravity.js";
4
5
  export { antigravityBrief, chatBrief, drawnBrief, paintedBrief, svgBrief } from "./briefs.js";
5
6
  export { antigravityClient, chatDrawing, codexClient, hostPictures, hostReader, hostWriter, openCodeClient } from "./chosen.js";
6
7
  export { claudeSays } from "./claude.js";
@@ -3,11 +3,12 @@
3
3
  // the player's folders, with every tool denied but what it needs; the project's own configuration is left out, and the session it made is deleted as it ends.
4
4
  import { spawn, spawnSync } from "node:child_process";
5
5
  import { randomBytes } from "node:crypto";
6
- import { mkdtempSync, readFileSync, rmSync } from "node:fs";
6
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
7
7
  import { tmpdir } from "node:os";
8
- import { delimiter, dirname, join } from "node:path";
9
- import { knownReady } from "./programs.js";
10
- import { stopProcess, stopTree } from "./stop.js";
8
+ import { basename, join } from "node:path";
9
+ import { isAlive } from "../core/process-mark.js";
10
+ import { chatEnvironment, isOwn, knownReady } from "./programs.js";
11
+ import { stopProcess, stopTree, whenEnded } from "./stop.js";
11
12
  // The same limits as Claude's: a brief in three minutes, a run of the importer in thirty.
12
13
  const longest = 3 * 60 * 1000;
13
14
  const longestReading = 30 * 60 * 1000;
@@ -40,11 +41,18 @@ export function openCodeReader(program = "opencode") {
40
41
  return {
41
42
  ready: () => ready().ready,
42
43
  program: () => "OpenCode",
44
+ clean: () => void sweepRuns(program),
45
+ // The model OpenCode named when it was asked whether it is ready, for the player, as it may be paid by the call.
46
+ model: () => {
47
+ const model = ready();
48
+ return model.ready ? model.maker : undefined;
49
+ },
43
50
  read: async (folder, brief, writable, signal) => {
44
51
  const model = ready();
45
52
  if (!model.ready || model.maker === undefined) {
46
53
  return { failed: model.ready ? "OpenCode has no model" : model.why };
47
54
  }
55
+ ownRepository(folder);
48
56
  const ran = await runAgent(program, model.maker, folder, readerAgent(writable), brief, longestReading, signal);
49
57
  if (ran.code === 0 && ran.error === undefined && ran.text !== undefined) {
50
58
  return { said: ran.text };
@@ -54,6 +62,15 @@ export function openCodeReader(program = "opencode") {
54
62
  },
55
63
  };
56
64
  }
65
+ /**
66
+ * A git repository of the import's folder's own, where the campaign above it is one: OpenCode lets an agent read up to the root of the repository it runs in,
67
+ * the campaign's secrets too, and with its own the import's folder is the root. Without git on this computer nothing is done, as no campaign is a repository.
68
+ */
69
+ function ownRepository(folder) {
70
+ if (!existsSync(join(folder, ".git"))) {
71
+ spawnSync("git", ["init", "-q"], { cwd: folder, windowsHide: true, timeout: 15_000, stdio: "ignore" });
72
+ }
73
+ }
57
74
  /** The importer's fence (D-489 (1)), as Elena's probe proved it: everything denied, then reading in the folder and editing in the folders given, never outside it. */
58
75
  export function readerRules(writable) {
59
76
  return [
@@ -127,11 +144,25 @@ function runAgent(program, model, folder, agent, brief, limit, signal) {
127
144
  const config = { agents: { [agent.name]: { description: agent.system, mode: "primary", system: agent.system, permissions: agent.rules } } };
128
145
  const environment = { ...openCodeEnvironment(), OPENCODE_CONFIG_CONTENT: JSON.stringify(config), OPENCODE_DISABLE_PROJECT_CONFIG: "1" };
129
146
  const line = `${program} run --standalone --agent ${agent.name} -m "${model}" --format json --archived --session ${session}`;
147
+ void sweepRuns(program);
148
+ markRun(session, { engine: process.pid, program });
130
149
  return new Promise((done) => {
131
150
  // Off Windows it leads a group of its own: the shell alone, stopped, would leave OpenCode running with the output held open.
132
151
  const child = spawn(line, { shell: true, windowsHide: true, cwd: folder, env: environment, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32" });
152
+ let stopped = false;
153
+ if (child.pid !== undefined) {
154
+ markRun(session, { engine: process.pid, child: child.pid, program });
155
+ }
133
156
  // Dropped while it runs: OpenCode stops with its own server.
134
- const stop = () => (process.platform === "win32" || child.pid === undefined ? stopTree(child) : stopProcess(child.pid));
157
+ const stop = () => {
158
+ stopped = true;
159
+ if (process.platform === "win32" || child.pid === undefined) {
160
+ stopTree(child);
161
+ }
162
+ else {
163
+ stopProcess(child.pid);
164
+ }
165
+ };
135
166
  signal?.addEventListener("abort", stop, { once: true });
136
167
  let output = "";
137
168
  let errors = "";
@@ -142,14 +173,20 @@ function runAgent(program, model, folder, agent, brief, limit, signal) {
142
173
  child.stderr.on("data", (chunk) => (errors += chunk));
143
174
  child.stdin.on("error", () => undefined);
144
175
  child.on("error", () => undefined);
145
- child.on("close", (code) => {
176
+ whenEnded(child, (exitCode) => {
146
177
  clearTimeout(timer);
147
178
  signal?.removeEventListener("abort", stop);
148
179
  const events = eventsOf(output);
149
180
  const text = events.filter((event) => event.type === "text").map((event) => event.part?.text).filter((one) => typeof one === "string" && one.trim() !== "").at(-1);
150
181
  const failed = events.find((event) => event.type === "error");
151
182
  const error = failed === undefined ? undefined : errorText(failed);
152
- void deleteSession(program, session).then(() => done({ code, errors, ...(typeof text === "string" ? { text: text.trim() } : {}), ...(error === undefined ? {} : { error }) }));
183
+ // A run stopped after its last step finished keeps its answer.
184
+ const finished = events.some((event) => event.type === "step_finish" && event.part?.reason === "stop");
185
+ const code = stopped && finished && error === undefined ? 0 : exitCode;
186
+ void deleteSession(program, session).then(() => {
187
+ unmarkRun(session);
188
+ done({ code, errors, ...(typeof text === "string" ? { text: text.trim() } : {}), ...(error === undefined ? {} : { error }) });
189
+ });
153
190
  });
154
191
  child.stdin.end(brief);
155
192
  });
@@ -166,6 +203,75 @@ function deleteSession(program, session) {
166
203
  });
167
204
  });
168
205
  }
206
+ // The marks of the runs under way, one a session: a run stopped from outside, as by an import's cancel, leaves its own, and the next sweep deletes its session.
207
+ function runsFolder() {
208
+ return join(tmpdir(), "rpg-opencode-runs");
209
+ }
210
+ function markRun(session, mark) {
211
+ try {
212
+ mkdirSync(runsFolder(), { recursive: true });
213
+ writeFileSync(join(runsFolder(), `${session}.json`), JSON.stringify(mark));
214
+ }
215
+ catch {
216
+ // No mark: a run stopped from outside would leave its session, as before.
217
+ }
218
+ }
219
+ function unmarkRun(session) {
220
+ try {
221
+ rmSync(join(runsFolder(), `${session}.json`), { force: true });
222
+ }
223
+ catch {
224
+ // Held a moment: a sweep finds its engine alive, or takes it later.
225
+ }
226
+ }
227
+ /**
228
+ * Deletes the sessions that runs of `program` stopped from outside left: each mark whose engine process is gone, its OpenCode stopped first if it still runs.
229
+ * Only marks of the same program line, never a line read from a file alone. Never throws.
230
+ */
231
+ async function sweepRuns(program) {
232
+ try {
233
+ const marks = readdirSync(runsFolder()).filter((name) => /^ses_rpg[0-9a-f]{20}\.json$/.test(name));
234
+ for (const name of marks) {
235
+ const file = join(runsFolder(), name);
236
+ const mark = markOf(file);
237
+ if (mark === undefined || mark.program !== program || isAlive(mark.engine) || !isOwn(file)) {
238
+ continue;
239
+ }
240
+ await sweepRun(program, file, mark);
241
+ }
242
+ }
243
+ catch {
244
+ // No marks: nothing to sweep.
245
+ }
246
+ }
247
+ // One mark of a run whose engine is gone: its OpenCode stopped if it still runs, its session deleted, the mark taken away.
248
+ async function sweepRun(program, file, mark) {
249
+ const taken = `${file}.taken`;
250
+ try {
251
+ // Taken by this sweep alone: another at the same time finds it gone.
252
+ renameSync(file, taken);
253
+ }
254
+ catch {
255
+ return;
256
+ }
257
+ if (mark.child !== undefined && isAlive(mark.child)) {
258
+ stopProcess(mark.child);
259
+ }
260
+ await deleteSession(program, basename(file, ".json"));
261
+ rmSync(taken, { force: true });
262
+ }
263
+ function markOf(file) {
264
+ try {
265
+ const mark = JSON.parse(readFileSync(file, "utf8"));
266
+ const pid = (value) => (typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined);
267
+ const engine = pid(mark.engine);
268
+ const child = pid(mark.child);
269
+ return engine === undefined || typeof mark.program !== "string" ? undefined : { engine, program: mark.program, ...(child === undefined ? {} : { child }) };
270
+ }
271
+ catch {
272
+ return undefined;
273
+ }
274
+ }
169
275
  function eventsOf(output) {
170
276
  return output.split("\n").flatMap((line) => {
171
277
  try {
@@ -181,22 +287,9 @@ function errorText(event) {
181
287
  const message = event.error?.data?.message ?? event.error?.name;
182
288
  return typeof message === "string" && message !== "" ? message : "it failed";
183
289
  }
184
- /**
185
- * The environment of OpenCode's runs: the chat's own, without what names the campaign, as the chat's session and folder, nor what OpenCode would take from the
186
- * chat; the player's keys and settings stay, as their model needs them. On Windows the shell does not look for programs in the folder it starts in.
187
- */
290
+ // The chat's variables OpenCode's runs never get: the engine's, the chat's session and folder, and what OpenCode would take from the chat.
291
+ const chatVariables = /^(RPG_|OPENCODE_(SESSION_ID|CLIENT|CONFIG_CONTENT|DISABLE_PROJECT_CONFIG|SERVER_PASSWORD)$|PWD$|OLDPWD$|INIT_CWD$)/i;
292
+ /** The environment of OpenCode's runs: the chat's own, without what names the campaign; the player's keys and settings stay, as their model needs them. */
188
293
  function openCodeEnvironment() {
189
- // The folder the chat runs in, a campaign's; never a root, which every path would name.
190
- const here = dirname(process.cwd()) === process.cwd() ? "\u0000" : process.cwd().toLowerCase();
191
- const chats = /^(RPG_|OPENCODE_(SESSION_ID|CLIENT|CONFIG_CONTENT|DISABLE_PROJECT_CONFIG|SERVER_PASSWORD)$|PWD$|OLDPWD$|INIT_CWD$)/i;
192
- const kept = Object.entries(process.env).flatMap(([variable, value]) => {
193
- if (value === undefined || chats.test(variable)) {
194
- return [];
195
- }
196
- if (variable.toUpperCase() === "PATH") {
197
- return [[variable, value.split(delimiter).filter((folder) => !folder.toLowerCase().startsWith(here)).join(delimiter)]];
198
- }
199
- return value.toLowerCase().includes(here) ? [] : [[variable, value]];
200
- });
201
- return { ...Object.fromEntries(kept), NoDefaultCurrentDirectoryInExePath: "1" };
294
+ return chatEnvironment(chatVariables);
202
295
  }
@@ -22,6 +22,14 @@ export declare function knownReady(check: () => PicturesReady): (again?: boolean
22
22
  * told not to look for programs in the folder it starts in, which could be a campaign's.
23
23
  */
24
24
  export declare function helperEnvironment(name: HelperName): NodeJS.ProcessEnv;
25
+ /** Whether a file or folder of the temporary folder is this user's own, never another's left to have the engine stop or run something; always on Windows. */
26
+ export declare function isOwn(path: string): boolean;
27
+ /**
28
+ * The environment of a program of the chat in use, as OpenCode or Antigravity: the chat's own, without the variables whose names `dropped` matches nor any that
29
+ * names the `campaign`'s folder, and the PATH without its folders; the player's keys and settings stay. On Windows the shell does not look for programs in the
30
+ * folder it starts in.
31
+ */
32
+ export declare function chatEnvironment(dropped: RegExp, campaign?: string): NodeJS.ProcessEnv;
25
33
  /**
26
34
  * The player's sign-in, started once and kept alive until it ends or ten minutes pass. It answers once the program printed its link, for a browser that did
27
35
  * not open, or ended, or after a few seconds; how it ends later is told by the next call.
@@ -1,9 +1,9 @@
1
1
  // Codex and Claude Code with the player's own login (D-424, D-425): found on the PATH or in the engine's folder, installed there with npm, never globally, and
2
2
  // signed in by the player in the browser; started through the shell from a folder of no campaign, without the chat's variables or an API key.
3
3
  import { spawn, spawnSync } from "node:child_process";
4
- import { existsSync, readFileSync } from "node:fs";
4
+ import { existsSync, readFileSync, statSync } from "node:fs";
5
5
  import { homedir, tmpdir } from "node:os";
6
- import { delimiter, join } from "node:path";
6
+ import { delimiter, dirname, join } from "node:path";
7
7
  import { stopTree } from "./stop.js";
8
8
  // The npm package of each program.
9
9
  const packages = { codex: "@openai/codex", claude: "@anthropic-ai/claude-code" };
@@ -132,6 +132,39 @@ export function helperEnvironment(name) {
132
132
  const own = Object.fromEntries(Object.entries(process.env).filter(([variable]) => kept.has(variable.toUpperCase()) || !dropped.test(variable)));
133
133
  return { ...own, NoDefaultCurrentDirectoryInExePath: "1" };
134
134
  }
135
+ /** Whether a file or folder of the temporary folder is this user's own, never another's left to have the engine stop or run something; always on Windows. */
136
+ export function isOwn(path) {
137
+ try {
138
+ return process.getuid === undefined || statSync(path).uid === process.getuid();
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ }
144
+ /**
145
+ * The environment of a program of the chat in use, as OpenCode or Antigravity: the chat's own, without the variables whose names `dropped` matches nor any that
146
+ * names the `campaign`'s folder, and the PATH without its folders; the player's keys and settings stay. On Windows the shell does not look for programs in the
147
+ * folder it starts in.
148
+ */
149
+ export function chatEnvironment(dropped, campaign = process.cwd()) {
150
+ // The folder the chat runs in, a campaign's; never a root, which every path would name.
151
+ const here = dirname(campaign) === campaign ? "\u0000" : campaign.toLowerCase().replace(/[\\/]+$/, "");
152
+ // A folder of the PATH in the campaign: the campaign itself or one below it, never a sibling whose name begins the same.
153
+ const inCampaign = (folder) => {
154
+ const path = folder.toLowerCase().replace(/[\\/]+$/, "");
155
+ return path === here || path.startsWith(`${here}\\`) || path.startsWith(`${here}/`);
156
+ };
157
+ const kept = Object.entries(process.env).flatMap(([variable, value]) => {
158
+ if (value === undefined || dropped.test(variable)) {
159
+ return [];
160
+ }
161
+ if (variable.toUpperCase() === "PATH") {
162
+ return [[variable, value.split(delimiter).filter((folder) => !inCampaign(folder)).join(delimiter)]];
163
+ }
164
+ return value.toLowerCase().includes(here) ? [] : [[variable, value]];
165
+ });
166
+ return { ...Object.fromEntries(kept), NoDefaultCurrentDirectoryInExePath: "1" };
167
+ }
135
168
  /**
136
169
  * The player's sign-in, started once and kept alive until it ends or ten minutes pass. It answers once the program printed its link, for a browser that did
137
170
  * not open, or ended, or after a few seconds; how it ends later is told by the next call.
@@ -1,5 +1,7 @@
1
1
  import { type ChildProcess } from "node:child_process";
2
2
  /** Stops a process of another's, by its number, with every process it started: on Windows its tree, elsewhere its group, as a detached process leads one. */
3
3
  export declare function stopProcess(pid: number): void;
4
+ /** Calls `ended` once with a child's exit code: at its close, or two seconds after its exit where a process it started holds its output open. */
5
+ export declare function whenEnded(child: ChildProcess, ended: (code: number | null) => void): void;
4
6
  /** Stops a process and, on Windows, every process it started. */
5
7
  export declare function stopTree(child: ChildProcess): void;
@@ -1,4 +1,5 @@
1
- // A maker of pictures run through the shell, stopped whole when its time runs out: on Windows the shell's child lives on after the shell, so its tree goes.
1
+ // A maker of pictures run through the shell, stopped whole when its time runs out: on Windows the shell's child lives on after the shell, so its tree goes; and
2
+ // taken as ended once it exited, even where a process it started holds its output open.
2
3
  import { spawnSync } from "node:child_process";
3
4
  /** Stops a process of another's, by its number, with every process it started: on Windows its tree, elsewhere its group, as a detached process leads one. */
4
5
  export function stopProcess(pid) {
@@ -18,6 +19,24 @@ export function stopProcess(pid) {
18
19
  }
19
20
  }
20
21
  }
22
+ // How long a child's output may stay open after it exited, held by a process it started, before what was heard is taken as all.
23
+ const outputWait = 2000;
24
+ /** Calls `ended` once with a child's exit code: at its close, or two seconds after its exit where a process it started holds its output open. */
25
+ export function whenEnded(child, ended) {
26
+ let done = false;
27
+ const end = (code) => {
28
+ if (done) {
29
+ return;
30
+ }
31
+ done = true;
32
+ child.stdout?.destroy();
33
+ child.stderr?.destroy();
34
+ ended(code);
35
+ };
36
+ child.on("close", end);
37
+ // Unreferenced: an output held open keeps the process alive until then, and one closed needs no wait.
38
+ child.on("exit", (code) => setTimeout(() => end(code), outputWait).unref());
39
+ }
21
40
  /** Stops a process and, on Windows, every process it started. */
22
41
  export function stopTree(child) {
23
42
  if (process.platform === "win32" && child.pid !== undefined) {
@@ -1,4 +1,7 @@
1
- /** The SVG rebuilt from what is allowed, its root always in the SVG namespace; undefined when it has no single allowed root, does not close, or is too large. */
1
+ /**
2
+ * The SVG rebuilt from what is allowed, its root always in the SVG namespace; undefined when it has no single allowed root, does not close, is too large, or has
3
+ * no shape left.
4
+ */
2
5
  export declare function cleanSvg(svg: string): string | undefined;
3
6
  /** The SVG in a model's answer, from <svg to </svg>, whatever came around it; undefined when there is none. */
4
7
  export declare function svgIn(answer: string): string | undefined;
@@ -64,7 +64,12 @@ const camel = new Map(["viewBox", "preserveAspectRatio", "gradientUnits", "gradi
64
64
  const largest = 100 * 1024;
65
65
  const token = /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<![^>]*>|<\?[\s\S]*?\?>|<\/?([A-Za-z][\w:.-]*)((?:\s+[^\s=>/]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?)*)\s*(\/?)>|[^<]+|</g;
66
66
  const attribute = /([^\s=>/]+)(?:\s*=\s*("[^"]*"|'[^']*'|[^\s>]+))?/g;
67
- /** The SVG rebuilt from what is allowed, its root always in the SVG namespace; undefined when it has no single allowed root, does not close, or is too large. */
67
+ // The elements that draw something; a drawing keeps at least one.
68
+ const shapeElements = new Set(["path", "rect", "circle", "ellipse", "polygon", "polyline", "line"]);
69
+ /**
70
+ * The SVG rebuilt from what is allowed, its root always in the SVG namespace; undefined when it has no single allowed root, does not close, is too large, or has
71
+ * no shape left.
72
+ */
68
73
  export function cleanSvg(svg) {
69
74
  if (Buffer.byteLength(svg) > largest) {
70
75
  return undefined;
@@ -73,6 +78,7 @@ export function cleanSvg(svg) {
73
78
  const open = [];
74
79
  let skipping = 0;
75
80
  let roots = 0;
81
+ let shapes = 0;
76
82
  for (const [whole, rawName, rawAttributes = "", selfClosing] of svg.matchAll(token)) {
77
83
  if (rawName === undefined) {
78
84
  continue;
@@ -98,13 +104,15 @@ export function cleanSvg(svg) {
98
104
  continue;
99
105
  }
100
106
  roots += name === "svg" ? 1 : 0;
107
+ shapes += shapeElements.has(name) ? 1 : 0;
101
108
  const namespace = name === "svg" ? ' xmlns="http://www.w3.org/2000/svg"' : "";
102
109
  kept.push(`<${name}${namespace}${keptAttributes(rawAttributes)}${selfClosing === "/" ? "/" : ""}>`);
103
110
  if (selfClosing !== "/") {
104
111
  open.push({ name, skipped: false });
105
112
  }
106
113
  }
107
- return roots === 1 && open.length === 0 ? kept.join("") : undefined;
114
+ // A drawing with no shape left, as one of text alone, would hide a good picture behind an empty one.
115
+ return roots === 1 && open.length === 0 && shapes > 0 ? kept.join("") : undefined;
108
116
  }
109
117
  /** The SVG in a model's answer, from <svg to </svg>, whatever came around it; undefined when there is none. */
110
118
  export function svgIn(answer) {
@@ -112,7 +120,10 @@ export function svgIn(answer) {
112
120
  const end = answer.lastIndexOf("</svg>");
113
121
  return start < 0 || end < start ? undefined : answer.slice(start, end + "</svg>".length);
114
122
  }
115
- /** An element's allowed attributes, each once, with no outer url(), no markup in a value, and no double quote, which could close the value and open another. */
123
+ /**
124
+ * An element's allowed attributes, each once, with no outer url(), closed or not, no markup or CSS escape in a value, and no double quote, which could close the
125
+ * value and open another.
126
+ */
116
127
  function keptAttributes(rawAttributes) {
117
128
  const seen = new Set();
118
129
  return [...rawAttributes.matchAll(attribute)].flatMap(([, rawKey, rawValue = '""']) => {
@@ -120,7 +131,8 @@ function keptAttributes(rawAttributes) {
120
131
  const quoted = rawValue.length >= 2 && (rawValue[0] === '"' || rawValue[0] === "'") && rawValue.at(-1) === rawValue[0];
121
132
  const value = (quoted ? rawValue.slice(1, -1) : rawValue).replaceAll('"', "'");
122
133
  const urls = [...value.matchAll(/url\s*\(([^)]*)\)/gi)].map((found) => found[1].trim().replace(/^'|'$/g, ""));
123
- if (!attributes.has(key) || seen.has(key) || urls.some((url) => !/^#[\w-]+$/.test(url)) || /[<>&]/.test(value)) {
134
+ const outer = urls.some((url) => !/^#[\w-]+$/.test(url)) || /url\s*\(\s*["']?\s*(?![\s"'#])/i.test(value);
135
+ if (!attributes.has(key) || seen.has(key) || outer || /[<>&\\]/.test(value)) {
124
136
  return [];
125
137
  }
126
138
  seen.add(key);
@@ -10,8 +10,10 @@ export declare function hostInstructions(): {
10
10
  start: string;
11
11
  character: string;
12
12
  };
13
- /** When and how the master calls the character agent, in play, where the host has it (D-490); in OpenCode, how its subagent answers. */
14
- export declare function voicesInstructions(way: string, openCode?: boolean): string;
13
+ /** A host that has the character agent (D-490, D-580). */
14
+ export type VoicesHost = "claudeCode" | "openCode" | "codex" | "antigravity";
15
+ /** When and how the master calls the character agent, in play, where the host has it (D-490), with the host's own way of calling it (D-580). */
16
+ export declare function voicesInstructions(way: string, host: VoicesHost): string;
15
17
  /** The line that sends the master to the buttons, where the player sees them (D-148, D-279); for choices alone when the player rolls their own dice (ASK-8). */
16
18
  export declare function buttonsInstructions(physicalDice: boolean): string;
17
19
  /** The dashboard at its link, which the game is played with, and how the player uses it, for the master to offer it and help them (D-404). */
@@ -8,11 +8,14 @@ export function startInstructions() {
8
8
  export function hostInstructions() {
9
9
  return { start: startInstructions(), character: readInstructions("character.md") };
10
10
  }
11
- /** When and how the master calls the character agent, in play, where the host has it (D-490); in OpenCode, how its subagent answers. */
12
- export function voicesInstructions(way, openCode = false) {
11
+ // The host's own lines on calling the agent, after voices.md; Claude Code needs none.
12
+ const hostVoices = { openCode: "voices-opencode.md", codex: "voices-codex.md", antigravity: "voices-antigravity.md" };
13
+ /** When and how the master calls the character agent, in play, where the host has it (D-490), with the host's own way of calling it (D-580). */
14
+ export function voicesInstructions(way, host) {
15
+ const own = hostVoices[host];
13
16
  // Always for the main characters, or for everyone, as the player chose, on top of the key moments (D-490).
14
17
  const more = way === "important" || way === "always" ? `\n\n${readInstructions(`voices-${way}.md`)}` : "";
15
- return `${readInstructions("voices.md")}${openCode ? `\n\n${readInstructions("voices-opencode.md")}` : ""}${more}`;
18
+ return `${readInstructions("voices.md")}${own === undefined ? "" : `\n\n${readInstructions(own)}`}${more}`;
16
19
  }
17
20
  /** The line that sends the master to the buttons, where the player sees them (D-148, D-279); for choices alone when the player rolls their own dice (ASK-8). */
18
21
  export function buttonsInstructions(physicalDice) {
@@ -1,8 +1,13 @@
1
1
  /** Antigravity's own folder, where its command line keeps its history and its log. */
2
2
  export declare function antigravityFolder(userHome?: string): string;
3
3
  /**
4
- * Watches, from now on, whether the player starts a new turn in the conversation: writes in the chat, or stops it with Esc. `started` resolves then, never
5
- * otherwise; `stop` ends the watch.
4
+ * Whether the conversation is a subagent's, as the character agent's (D-580): Antigravity keeps a file for each subagent under its parent conversation, in
5
+ * its command line's folder or its app's. Such a conversation gets no doorbell.
6
+ */
7
+ export declare function isSubagentConversation(conversation: string, folders?: string[]): boolean;
8
+ /**
9
+ * Watches, from now on, whether the player starts a new turn in the conversation: writes in the chat, or stops it with Esc; or whether a message waits to be
10
+ * delivered to it, as the character's subagent's answer (D-580). `started` resolves then, never otherwise; `stop` ends the watch.
6
11
  */
7
12
  export declare function watchNewTurn(conversation: string, folder?: string, every?: number, appFolder?: string): {
8
13
  started: Promise<void>;
@@ -1,7 +1,7 @@
1
1
  // Antigravity's Stop hook holds the chat until it ends: a message the player writes meanwhile waits behind it, and Esc leaves it running. Antigravity's own
2
2
  // files tell either: the history of what the player typed, with the conversation it went to, and its log, which notes the conversation stopped; in its app,
3
3
  // the messages it keeps to send once the turn ends.
4
- import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
4
+ import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
5
5
  import { homedir } from "node:os";
6
6
  import { join } from "node:path";
7
7
  /** Antigravity's own folder, where its command line keeps its history and its log. */
@@ -9,8 +9,26 @@ export function antigravityFolder(userHome = homedir()) {
9
9
  return join(userHome, ".gemini", "antigravity-cli");
10
10
  }
11
11
  /**
12
- * Watches, from now on, whether the player starts a new turn in the conversation: writes in the chat, or stops it with Esc. `started` resolves then, never
13
- * otherwise; `stop` ends the watch.
12
+ * Whether the conversation is a subagent's, as the character agent's (D-580): Antigravity keeps a file for each subagent under its parent conversation, in
13
+ * its command line's folder or its app's. Such a conversation gets no doorbell.
14
+ */
15
+ export function isSubagentConversation(conversation, folders = [antigravityFolder(), join(antigravityFolder(), "..", "antigravity")]) {
16
+ if (!/^[\w-]+$/.test(conversation)) {
17
+ return false;
18
+ }
19
+ return folders.some((folder) => {
20
+ const brain = join(folder, "brain");
21
+ try {
22
+ return readdirSync(brain).some((parent) => existsSync(join(brain, parent, ".system_generated", "subagents", `${conversation}.json`)));
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ });
28
+ }
29
+ /**
30
+ * Watches, from now on, whether the player starts a new turn in the conversation: writes in the chat, or stops it with Esc; or whether a message waits to be
31
+ * delivered to it, as the character's subagent's answer (D-580). `started` resolves then, never otherwise; `stop` ends the watch.
14
32
  */
15
33
  export function watchNewTurn(conversation, folder = antigravityFolder(), every = 500, appFolder = join(folder, "..", "antigravity")) {
16
34
  const history = join(folder, "history.jsonl");
@@ -19,7 +37,7 @@ export function watchNewTurn(conversation, folder = antigravityFolder(), every =
19
37
  let timer;
20
38
  const started = new Promise((done) => {
21
39
  timer = setInterval(() => {
22
- if (wrote(newText(history, read), conversation) || stopped(newText(log, read), conversation) || queued(appFolder, conversation)) {
40
+ if (wrote(newText(history, read), conversation) || stopped(newText(log, read), conversation) || queued(appFolder, conversation) || queued(folder, conversation)) {
23
41
  clearInterval(timer);
24
42
  done();
25
43
  }
@@ -29,8 +47,8 @@ export function watchNewTurn(conversation, folder = antigravityFolder(), every =
29
47
  return { started, stop: () => clearInterval(timer) };
30
48
  }
31
49
  /**
32
- * Whether Antigravity's app holds a message the player wrote in the conversation while its turn has not ended: the app keeps one file for each in the
33
- * conversation's own folder, and sends them once the turn ends.
50
+ * Whether Antigravity holds a message for the conversation while its turn has not ended, as one the player wrote in its app or a subagent's answer: it keeps
51
+ * one file for each in the conversation's own folder, and sends them once the turn ends.
34
52
  */
35
53
  function queued(appFolder, conversation) {
36
54
  try {
@@ -1,2 +1,2 @@
1
- export { antigravityFolder, watchNewTurn } from "./antigravity.ts";
1
+ export { antigravityFolder, isSubagentConversation, watchNewTurn } from "./antigravity.ts";
2
2
  export { bellHeard, bellLine, type Heard, hookAnswer, listen, type ListeningHost, listeningHosts, waitForBell } from "./listener.ts";
@@ -1,2 +1,2 @@
1
- export { antigravityFolder, watchNewTurn } from "./antigravity.js";
1
+ export { antigravityFolder, isSubagentConversation, watchNewTurn } from "./antigravity.js";
2
2
  export { bellHeard, bellLine, hookAnswer, listen, listeningHosts, waitForBell } from "./listener.js";
@@ -4,7 +4,7 @@
4
4
  import { findCampaign } from "../../campaign/index.js";
5
5
  import { samePath } from "../../library/index.js";
6
6
  import { askDashboard, campaignPorts, dashboardAt } from "../dashboard/ports.js";
7
- import { watchNewTurn } from "./antigravity.js";
7
+ import { isSubagentConversation, watchNewTurn } from "./antigravity.js";
8
8
  /** What the chat hears from the doorbell: never the player's words, only where to read them. */
9
9
  export const bellLine = "The player acted on the dashboard: call status to read what they did.";
10
10
  /** The hosts whose hook runs `rpg --listen`, as its argument names them: Claude Code with none; OpenCode through the campaign's plugin. */
@@ -20,6 +20,11 @@ export async function listen(host = "claude") {
20
20
  input += String(chunk);
21
21
  }
22
22
  const hook = hookInput(input);
23
+ // A subagent's conversation, as the character agent's, is not the master's: its end lets it go at once (D-580).
24
+ if (host === "antigravity" && hook.session !== undefined && isSubagentConversation(hook.session)) {
25
+ process.stdout.write(`${hookAnswer(host, false)}\n`, () => process.exit(0));
26
+ return;
27
+ }
23
28
  const turn = host === "antigravity" && hook.session !== undefined ? watchNewTurn(hook.session) : undefined;
24
29
  const opener = hook.hostPid === undefined ? undefined : watchProcessEnd(hook.hostPid);
25
30
  const unheard = { rang: false };
@@ -0,0 +1,21 @@
1
+ /** The folders a run may read and write, by their full paths, those to write read too; and the tools let through as they are, as the painter's image tool. */
2
+ export interface Fence {
3
+ read: string[];
4
+ write: string[];
5
+ tools?: string[];
6
+ }
7
+ /** Antigravity's answer to a tool call: refused, with what the model can do instead, or allowed, which the settings may still refuse. */
8
+ export type FenceDecision = {
9
+ decision: "deny";
10
+ reason: string;
11
+ } | {
12
+ decision: "allow";
13
+ };
14
+ /** Reads the hook's input and answers it on its output, by the fence of `file`. */
15
+ export declare function fenceHere(file: string): Promise<void>;
16
+ /** The fence in `file`; undefined where it does not read, which lets nothing through. */
17
+ export declare function readFence(file: string): Fence | undefined;
18
+ /** The decision for a tool call, as Antigravity's hook gives it, by `fence`. */
19
+ export declare function fenceDecision(input: string, fence: Fence | undefined): FenceDecision;
20
+ /** Whether `path` is `folder` or inside it, by path segments; on Windows without regard to case. */
21
+ export declare function isInside(path: string, folder: string): boolean;
@@ -0,0 +1,69 @@
1
+ // The importer's soft fence in Antigravity (D-579 (1)): `rpg --fence <file>`, the hook the engine writes in agy's working folder, refuses a call outside the
2
+ // import's folder, so that the model hears why and goes on, where the settings would close the whole run. A file is read only in the folders to read and
3
+ // written only in those to write; the tools the fence names pass as they are; every other tool is refused, commands and the web among them. Its yes opens nothing the settings close: they stay the hard fence.
4
+ import { readFileSync } from "node:fs";
5
+ import { isAbsolute, relative, resolve, sep } from "node:path";
6
+ /** Reads the hook's input and answers it on its output, by the fence of `file`. */
7
+ export async function fenceHere(file) {
8
+ let input = "";
9
+ for await (const chunk of process.stdin) {
10
+ input += String(chunk);
11
+ }
12
+ process.stdout.write(JSON.stringify(fenceDecision(input, readFence(file))));
13
+ }
14
+ /** The fence in `file`; undefined where it does not read, which lets nothing through. */
15
+ export function readFence(file) {
16
+ try {
17
+ const fence = JSON.parse(readFileSync(file, "utf8"));
18
+ const names = (value) => (Array.isArray(value) && value.every((one) => typeof one === "string") ? value : undefined);
19
+ const read = names(fence.read);
20
+ const write = names(fence.write);
21
+ const tools = fence.tools === undefined ? [] : names(fence.tools);
22
+ return read === undefined || write === undefined || tools === undefined ? undefined : { read, write, ...(tools.length === 0 ? {} : { tools }) };
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ }
28
+ /** The decision for a tool call, as Antigravity's hook gives it, by `fence`. */
29
+ export function fenceDecision(input, fence) {
30
+ if (fence === undefined) {
31
+ return { decision: "deny", reason: "This run's fence does not read, so nothing can be done here: stop and say so." };
32
+ }
33
+ const { name, args, cwd } = hookCall(input);
34
+ if (name !== undefined && fence.tools?.includes(name) === true) {
35
+ return { decision: "allow" };
36
+ }
37
+ const refused = {
38
+ decision: "deny",
39
+ reason: `Only reading in ${fence.read[0] ?? "the import's folder"} and writing in ${fence.write.join(", ") || "no folder"} is possible here, by full paths; no command and no web: go on without this.`,
40
+ };
41
+ // The file a tool names, by the argument that holds a path, whatever the tool calls it: Path, TargetFile, DirectoryPath.
42
+ const given = Object.entries(args).find(([key, value]) => typeof value === "string" && /path|file|directory|dir/i.test(key))?.[1];
43
+ if (name === undefined || typeof given !== "string" || !(readingTools.test(name) || writingTools.test(name))) {
44
+ return refused;
45
+ }
46
+ const path = resolve(typeof cwd === "string" ? cwd : process.cwd(), given);
47
+ const allowed = readingTools.test(name) ? [...fence.read, ...fence.write] : fence.write;
48
+ return allowed.some((folder) => isInside(path, folder)) ? { decision: "allow" } : refused;
49
+ }
50
+ // Antigravity's tools that read a file or a folder, and those that write one, as the probe of 22 November met them; any other tool is refused.
51
+ const readingTools = /^(read_file|view_file|view_file_outline|list_dir|list_directory|find_by_name|grep_search|find|grep)$/;
52
+ const writingTools = /^(write_file|write_to_file|replace_file_content|multi_replace_file_content|edit_file)$/;
53
+ /** Whether `path` is `folder` or inside it, by path segments; on Windows without regard to case. */
54
+ export function isInside(path, folder) {
55
+ const fold = (one) => (process.platform === "win32" ? resolve(one).toLowerCase() : resolve(one));
56
+ const between = relative(fold(folder), fold(path));
57
+ return between === "" || (between !== ".." && !between.startsWith(`..${sep}`) && !isAbsolute(between));
58
+ }
59
+ function hookCall(input) {
60
+ try {
61
+ const parsed = JSON.parse(input);
62
+ const call = parsed?.toolCall;
63
+ const args = call?.args !== null && typeof call?.args === "object" ? call.args : {};
64
+ return { ...(typeof call?.name === "string" ? { name: call.name } : {}), args, cwd: parsed?.cwd };
65
+ }
66
+ catch {
67
+ return { args: {} };
68
+ }
69
+ }