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
@@ -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). */
14
- export declare function voicesInstructions(way: string): 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). */
12
- export function voicesInstructions(way) {
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")}${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,6 +1,8 @@
1
- /** Reads the hook's input and answers it on its output. */
2
- export declare function approveHere(): Promise<void>;
1
+ /** Reads the hook's input and answers it on its output, then notes the conversation's campaign. */
2
+ export declare function approveHere(home?: string): Promise<void>;
3
3
  /** Antigravity's decision for a tool call, as its hook gives it: auto_approve for the rpg server's tools and their descriptions, else ask. */
4
4
  export declare function approval(input: string): {
5
5
  decision: "auto_approve" | "ask";
6
6
  };
7
+ /** For a call of an rpg tool, notes in `home` the campaign of the hook's folder as the one its conversation plays; nothing outside a campaign. */
8
+ export declare function noteCampaign(input: string, home: string): void;
@@ -1,26 +1,46 @@
1
1
  // Antigravity's approval of the rpg tools: `rpg --approve`, the hook init writes before each tool, lets the rpg server's tools run without asking, and the
2
- // reading of their descriptions, which Antigravity keeps in its own folder; every other tool asks the player, as the app would.
3
- /** Reads the hook's input and answers it on its output. */
4
- export async function approveHere() {
2
+ // reading of their descriptions, which Antigravity keeps in its own folder; every other tool asks the player, as the app would. As it approves an rpg tool,
3
+ // it notes which campaign the conversation plays, for the router of Antigravity's app (D-578).
4
+ import { findCampaign } from "../campaign/index.js";
5
+ import { userDataFolder } from "../core/context.js";
6
+ import { noteConversation } from "./route/index.js";
7
+ /** Reads the hook's input and answers it on its output, then notes the conversation's campaign. */
8
+ export async function approveHere(home = userDataFolder()) {
5
9
  let input = "";
6
10
  for await (const chunk of process.stdin) {
7
11
  input += String(chunk);
8
12
  }
9
13
  process.stdout.write(JSON.stringify(approval(input)));
14
+ noteCampaign(input, home);
10
15
  }
11
16
  /** Antigravity's decision for a tool call, as its hook gives it: auto_approve for the rpg server's tools and their descriptions, else ask. */
12
17
  export function approval(input) {
13
18
  const call = toolCall(input);
14
19
  const args = call.args ?? {};
15
- const rpgTool = call.name === "call_mcp_tool" && args.ServerName === "rpg";
16
20
  // The description of an rpg tool, which Antigravity reads before it calls one.
17
21
  const rpgDescription = call.name === "read_file" && typeof args.Path === "string" && /[\\/]antigravity-cli[\\/]mcp[\\/]rpg[\\/][\w-]+\.(?:json|md)$/i.test(args.Path);
18
- return { decision: rpgTool || rpgDescription ? "auto_approve" : "ask" };
22
+ return { decision: isRpgTool(input) || rpgDescription ? "auto_approve" : "ask" };
23
+ }
24
+ /** For a call of an rpg tool, notes in `home` the campaign of the hook's folder as the one its conversation plays; nothing outside a campaign. */
25
+ export function noteCampaign(input, home) {
26
+ const { conversationId, cwd } = hookFields(input);
27
+ const root = isRpgTool(input) && typeof conversationId === "string" ? findCampaign(typeof cwd === "string" ? cwd : process.cwd()) : undefined;
28
+ if (root !== undefined && typeof conversationId === "string") {
29
+ noteConversation(home, conversationId, root);
30
+ }
31
+ }
32
+ function isRpgTool(input) {
33
+ const call = toolCall(input);
34
+ return call.name === "call_mcp_tool" && call.args?.ServerName === "rpg";
19
35
  }
20
36
  function toolCall(input) {
37
+ const call = hookFields(input).toolCall;
38
+ return call !== null && typeof call === "object" ? call : {};
39
+ }
40
+ function hookFields(input) {
21
41
  try {
22
- const call = JSON.parse(input).toolCall;
23
- return call !== null && typeof call === "object" ? call : {};
42
+ const parsed = JSON.parse(input);
43
+ return parsed !== null && typeof parsed === "object" ? parsed : {};
24
44
  }
25
45
  catch {
26
46
  return {};
@@ -0,0 +1,15 @@
1
+ /** Antigravity's own folder, where its command line keeps its history and its log. */
2
+ export declare function antigravityFolder(userHome?: string): string;
3
+ /**
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.
11
+ */
12
+ export declare function watchNewTurn(conversation: string, folder?: string, every?: number, appFolder?: string): {
13
+ started: Promise<void>;
14
+ stop: () => void;
15
+ };
@@ -0,0 +1,113 @@
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
+ // 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
+ // the messages it keeps to send once the turn ends.
4
+ import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { join } from "node:path";
7
+ /** Antigravity's own folder, where its command line keeps its history and its log. */
8
+ export function antigravityFolder(userHome = homedir()) {
9
+ return join(userHome, ".gemini", "antigravity-cli");
10
+ }
11
+ /**
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.
32
+ */
33
+ export function watchNewTurn(conversation, folder = antigravityFolder(), every = 500, appFolder = join(folder, "..", "antigravity")) {
34
+ const history = join(folder, "history.jsonl");
35
+ const log = join(folder, "cli.log");
36
+ const read = { [history]: placeOf(history), [log]: placeOf(log) };
37
+ let timer;
38
+ const started = new Promise((done) => {
39
+ timer = setInterval(() => {
40
+ if (wrote(newText(history, read), conversation) || stopped(newText(log, read), conversation) || queued(appFolder, conversation) || queued(folder, conversation)) {
41
+ clearInterval(timer);
42
+ done();
43
+ }
44
+ }, every);
45
+ timer.unref();
46
+ });
47
+ return { started, stop: () => clearInterval(timer) };
48
+ }
49
+ /**
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.
52
+ */
53
+ function queued(appFolder, conversation) {
54
+ try {
55
+ return readdirSync(join(appFolder, "brain", conversation, ".system_generated", "messages", "undelivered")).length > 0;
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ }
61
+ /** Whether these lines of Antigravity's history hold something the player typed in the conversation: a message, or a command such as /clear. */
62
+ function wrote(lines, conversation) {
63
+ return lines.split("\n").some((line) => {
64
+ try {
65
+ return JSON.parse(line).conversationId === conversation;
66
+ }
67
+ catch {
68
+ return false;
69
+ }
70
+ });
71
+ }
72
+ /** Whether these lines of Antigravity's log say the conversation was stopped, as Esc does. */
73
+ function stopped(lines, conversation) {
74
+ return lines.includes(`Cancelling conversation ${conversation}`);
75
+ }
76
+ /**
77
+ * The whole lines a file gained since it was last read, as `read` keeps its place: what follows its last line's end waits for the next read, as a line written
78
+ * in two parts. A file that shrank, or was written anew in its place, is read from its start.
79
+ */
80
+ function newText(file, read) {
81
+ const now = placeOf(file);
82
+ const before = read[file];
83
+ const from = before === undefined || now.offset < before.offset || now.identity !== before.identity ? 0 : before.offset;
84
+ if (now.offset <= from) {
85
+ read[file] = { offset: now.offset, identity: now.identity };
86
+ return "";
87
+ }
88
+ try {
89
+ const descriptor = openSync(file, "r");
90
+ try {
91
+ const buffer = Buffer.alloc(now.offset - from);
92
+ const length = readSync(descriptor, buffer, 0, buffer.length, from);
93
+ const whole = buffer.subarray(0, buffer.subarray(0, length).lastIndexOf(10) + 1);
94
+ read[file] = { offset: from + whole.length, identity: now.identity };
95
+ return whole.toString("utf8");
96
+ }
97
+ finally {
98
+ closeSync(descriptor);
99
+ }
100
+ }
101
+ catch {
102
+ return "";
103
+ }
104
+ }
105
+ function placeOf(file) {
106
+ try {
107
+ const stats = statSync(file);
108
+ return { offset: stats.size, identity: stats.ino };
109
+ }
110
+ catch {
111
+ return { offset: 0, identity: 0 };
112
+ }
113
+ }
@@ -0,0 +1,2 @@
1
+ export { antigravityFolder, isSubagentConversation, watchNewTurn } from "./antigravity.ts";
2
+ export { bellHeard, bellLine, type Heard, hookAnswer, listen, type ListeningHost, listeningHosts, waitForBell } from "./listener.ts";
@@ -0,0 +1,2 @@
1
+ export { antigravityFolder, isSubagentConversation, watchNewTurn } from "./antigravity.js";
2
+ export { bellHeard, bellLine, hookAnswer, listen, listeningHosts, waitForBell } from "./listener.js";
@@ -0,0 +1,43 @@
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
+ /** The hosts whose hook runs `rpg --listen`, as its argument names them: Claude Code with none; OpenCode through the campaign's plugin. */
4
+ export declare const listeningHosts: readonly ["claude", "codex", "antigravity", "opencode"];
5
+ export type ListeningHost = (typeof listeningHosts)[number];
6
+ /**
7
+ * Reads the hook's input, waits for the doorbell, and ends the process as the host reads it: for Claude Code's asyncRewake, 2 with the line on stderr; for
8
+ * Codex's and Antigravity's Stop hooks, 0 with their answer on stdout; for OpenCode's plugin, 0 with the player's words, or the line, on stdout, which it sends to the chat. Else 0.
9
+ * Antigravity's hook holds the chat: it lets it go, without the bell, as soon as the player writes in the chat or stops it; OpenCode's, once OpenCode is gone.
10
+ */
11
+ export declare function listen(host?: ListeningHost): Promise<void>;
12
+ /**
13
+ * What the hook says as it ends, by its host: the doorbell's line, or the answer that carries it, when it rang, and for OpenCode the player's `words` when the
14
+ * page gave them; else nothing, but Antigravity's empty answer.
15
+ */
16
+ export declare function hookAnswer(host: ListeningHost, rang: boolean, words?: string): string | undefined;
17
+ /** What the hook heard at its chat's dashboard: whether it rang, and the player's words when it asked for them and the page gave some. */
18
+ export interface Heard {
19
+ rang: boolean;
20
+ words?: string;
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, and in hosts whose server does not know its session, the only server of
25
+ * its campaign, while no other chat waits there for the page (D-577): better no ring than one in a chat that cannot read the page. The hook may come before its
26
+ * chat's page answers, as in Antigravity: while the campaign has none, it looks again `looks.times` times, every `looks.every` ms.
27
+ */
28
+ export declare function waitForBell(input: string, ports?: number[], looks?: {
29
+ every: number;
30
+ times: number;
31
+ }): Promise<boolean>;
32
+ /**
33
+ * Waits as waitForBell does, at `ports` or the campaign's, looking again as `looks` says, and says what it heard; with `words`, it asks the page for the
34
+ * player's sentences themselves, which the page holds for the master's next call (D-578).
35
+ */
36
+ export declare function bellHeard(input: string, options?: {
37
+ ports?: number[];
38
+ looks?: {
39
+ every: number;
40
+ times: number;
41
+ };
42
+ words?: boolean;
43
+ }): Promise<Heard>;
@@ -0,0 +1,154 @@
1
+ // The doorbell for the player's sentences on the dashboard (D-495, D-578): `rpg --listen`, the Stop hook init writes for Claude Code and Antigravity, which
2
+ // OpenCode's plugin runs too, waits at the dashboard of its own chat and, when the player says a sentence, tells the chat to call status, the sentence
3
+ // reaching the master in that call; in OpenCode, whose plugin speaks as the player, it brings the sentence itself, as Codex's queue does.
4
+ import { findCampaign } from "../../campaign/index.js";
5
+ import { samePath } from "../../library/index.js";
6
+ import { askDashboard, campaignPorts, dashboardAt } from "../dashboard/ports.js";
7
+ import { isSubagentConversation, watchNewTurn } from "./antigravity.js";
8
+ /** What the chat hears from the doorbell: never the player's words, only where to read them. */
9
+ export const bellLine = "The player acted on the dashboard: call status to read what they did.";
10
+ /** The hosts whose hook runs `rpg --listen`, as its argument names them: Claude Code with none; OpenCode through the campaign's plugin. */
11
+ export const listeningHosts = ["claude", "codex", "antigravity", "opencode"];
12
+ /**
13
+ * Reads the hook's input, waits for the doorbell, and ends the process as the host reads it: for Claude Code's asyncRewake, 2 with the line on stderr; for
14
+ * Codex's and Antigravity's Stop hooks, 0 with their answer on stdout; for OpenCode's plugin, 0 with the player's words, or the line, on stdout, which it sends to the chat. Else 0.
15
+ * Antigravity's hook holds the chat: it lets it go, without the bell, as soon as the player writes in the chat or stops it; OpenCode's, once OpenCode is gone.
16
+ */
17
+ export async function listen(host = "claude") {
18
+ let input = "";
19
+ for await (const chunk of process.stdin) {
20
+ input += String(chunk);
21
+ }
22
+ const hook = hookInput(input);
23
+ // 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
+ }
28
+ const turn = host === "antigravity" && hook.session !== undefined ? watchNewTurn(hook.session) : undefined;
29
+ const opener = hook.hostPid === undefined ? undefined : watchProcessEnd(hook.hostPid);
30
+ const unheard = { rang: false };
31
+ const heard = await Promise.race([
32
+ bellHeard(input, { words: host === "opencode" }).catch(() => unheard),
33
+ ...(turn === undefined ? [] : [turn.started.then(() => unheard)]),
34
+ ...(opener === undefined ? [] : [opener.ended.then(() => unheard)]),
35
+ ]);
36
+ turn?.stop();
37
+ opener?.stop();
38
+ const answer = hookAnswer(host, heard.rang, heard.words);
39
+ // It ends as soon as it knows, whatever else the process holds: the chat hears the hook only once it ends, and the dashboard sees its wait gone.
40
+ if (answer === undefined) {
41
+ process.exit(0);
42
+ }
43
+ else if (host === "claude") {
44
+ process.stderr.write(`${answer}\n`, () => process.exit(2));
45
+ }
46
+ else {
47
+ process.stdout.write(`${answer}\n`, () => process.exit(0));
48
+ }
49
+ }
50
+ /**
51
+ * What the hook says as it ends, by its host: the doorbell's line, or the answer that carries it, when it rang, and for OpenCode the player's `words` when the
52
+ * page gave them; else nothing, but Antigravity's empty answer.
53
+ */
54
+ export function hookAnswer(host, rang, words) {
55
+ if (host === "antigravity") {
56
+ return rang ? JSON.stringify({ decision: "continue", reason: bellLine }) : "{}";
57
+ }
58
+ if (!rang) {
59
+ return undefined;
60
+ }
61
+ if (host === "opencode") {
62
+ return words ?? bellLine;
63
+ }
64
+ return host === "codex" ? JSON.stringify({ decision: "block", reason: bellLine }) : bellLine;
65
+ }
66
+ /**
67
+ * 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
68
+ * server is the one with its session; after /clear, which gives the hook a new one, and in hosts whose server does not know its session, the only server of
69
+ * its campaign, while no other chat waits there for the page (D-577): better no ring than one in a chat that cannot read the page. The hook may come before its
70
+ * chat's page answers, as in Antigravity: while the campaign has none, it looks again `looks.times` times, every `looks.every` ms.
71
+ */
72
+ export async function waitForBell(input, ports, looks = { every: 500, times: 10 }) {
73
+ return (await bellHeard(input, { ports, looks })).rang;
74
+ }
75
+ /**
76
+ * Waits as waitForBell does, at `ports` or the campaign's, looking again as `looks` says, and says what it heard; with `words`, it asks the page for the
77
+ * player's sentences themselves, which the page holds for the master's next call (D-578).
78
+ */
79
+ export async function bellHeard(input, options = {}) {
80
+ const { ports, looks = { every: 500, times: 10 }, words = false } = options;
81
+ const hook = hookInput(input);
82
+ // Antigravity runs its hooks in .agents: the campaign is found upwards.
83
+ const root = findCampaign(hook.cwd ?? process.cwd());
84
+ if (root === undefined) {
85
+ return { rang: false };
86
+ }
87
+ let ours = await campaignPages(root, ports ?? campaignPorts(root));
88
+ for (let look = 1; ours.length === 0 && look <= looks.times; look++) {
89
+ await new Promise((done) => setTimeout(done, looks.every));
90
+ ours = await campaignPages(root, ports ?? campaignPorts(root));
91
+ }
92
+ // 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
93
+ // engine's page does not say who waits, so it is never taken as this chat's.
94
+ const only = ours.length === 1 && ours[0].said.others?.length === 0 ? ours[0] : undefined;
95
+ const port = (ours.find((one) => hook.session !== undefined && one.said.session === hook.session) ?? only)?.port;
96
+ const said = port === undefined ? undefined : await askDashboard(port, words ? "/api/bell?words" : "/api/bell");
97
+ // An older engine's page, or one with no words to give, rings alone.
98
+ if (said === "ring") {
99
+ return { rang: true };
100
+ }
101
+ // The words, after a first line with their ids: the page hears they were taken before the chat is given them.
102
+ const head = said?.match(/^ring(?: ([\w,-]*))?\n/);
103
+ if (said === undefined || head === null || head === undefined) {
104
+ return { rang: false };
105
+ }
106
+ if (port !== undefined && head[1] !== undefined && head[1] !== "") {
107
+ await askDashboard(port, `/api/bell?took=${encodeURIComponent(head[1])}`, 2000);
108
+ }
109
+ const text = said.slice(head[0].length).trim();
110
+ return { rang: true, ...(text === "" ? {} : { words: text }) };
111
+ }
112
+ /** The campaign's dashboards that answer at these ports, with what each says of itself. */
113
+ async function campaignPages(root, ports) {
114
+ const probes = await Promise.all(ports.filter((port) => port !== 0).map(async (port) => ({ port, said: await dashboardAt(port) })));
115
+ return probes.flatMap((one) => (one.said !== undefined && one.said.root !== null && samePath(one.said.root, root) ? [{ port: one.port, said: one.said }] : []));
116
+ }
117
+ /** What the hook reads of its host's input: the chat's session, Antigravity's conversation; its folder; the process of OpenCode, which its plugin names. */
118
+ function hookInput(input) {
119
+ try {
120
+ const parsed = JSON.parse(input);
121
+ const session = typeof parsed.session_id === "string" ? parsed.session_id : parsed.conversationId;
122
+ return {
123
+ ...(typeof session === "string" ? { session } : {}),
124
+ ...(typeof parsed.cwd === "string" ? { cwd: parsed.cwd } : {}),
125
+ ...(Number.isInteger(parsed.host_pid) && parsed.host_pid > 0 ? { hostPid: parsed.host_pid } : {}),
126
+ };
127
+ }
128
+ catch {
129
+ return {};
130
+ }
131
+ }
132
+ /** Looks every `every` ms whether the process `pid` still runs: `ended` once it does not. On macOS and Linux a closed terminal does not end the hook. */
133
+ function watchProcessEnd(pid, every = 2000) {
134
+ let timer;
135
+ const ended = new Promise((done) => {
136
+ timer = setInterval(() => {
137
+ if (!processRuns(pid)) {
138
+ done();
139
+ }
140
+ }, every);
141
+ timer.unref();
142
+ });
143
+ return { ended, stop: () => clearInterval(timer) };
144
+ }
145
+ // A process another user runs answers EPERM: it runs.
146
+ function processRuns(pid) {
147
+ try {
148
+ process.kill(pid, 0);
149
+ return true;
150
+ }
151
+ catch (error) {
152
+ return error.code === "EPERM";
153
+ }
154
+ }
@@ -37,6 +37,8 @@ export interface DashboardOptions {
37
37
  pageHidden?: number;
38
38
  /** Codex's queue for the player's sentences (D-495): Codex's own command, else a fake in the tests. */
39
39
  queue?: CodexQueue;
40
+ /** How long sentences given to a hook that speaks them wait for the master's next call before they are given back, in ms (D-578). */
41
+ heldFor?: number;
40
42
  }
41
43
  /** Codex's queue: whether this computer has the command, and a message queued in a thread, as the player's own (D-495). */
42
44
  export interface CodexQueue {
@@ -118,9 +120,16 @@ export interface Served {
118
120
  acts: Acts;
119
121
  /** The other chats of the campaign that wait for its page, by session, with when each last asked (D-577). */
120
122
  others: Map<string, number>;
121
- /** The doorbell of Claude Code's hook, waiting for a sentence; and whether one ever came, so that this chat has one (D-495). */
123
+ /**
124
+ * The doorbell's hook, waiting for a sentence; whether it asked for the player's words, as OpenCode's does (D-578); whether one ever came, so that this chat
125
+ * has one (D-495); and whether the last went away without a ring, as when the chat was stopped, until a hook or a call of the master comes again.
126
+ */
122
127
  bell?: ServerResponse;
128
+ bellWords?: boolean;
123
129
  belled?: boolean;
130
+ bellGone?: boolean;
131
+ /** How long sentences given to a hook wait for the master's next call, in ms (D-578). */
132
+ heldFor: number;
124
133
  /** Codex's queue, and the sentences being put in it now (D-495). */
125
134
  queue: CodexQueue;
126
135
  queueing?: Promise<void>;
@@ -18,7 +18,7 @@ import { loadSystemCode } from "../../systems/index.js";
18
18
  import { newActs } from "../player-acts.js";
19
19
  import { choicesNews, choicesRequest } from "./choices.js";
20
20
  import { builtPage, packagePageFile, pageFile, pageHtml, pageModulesOf, pagePolicy, pageWords, securityHeaders, send, sendFile, sendImage, sendInstalledThemeFile, sendJson, sendPacked, sendThemeFile, themeAddress, themeNow, themesAddress, vendorModule, } from "./files.js";
21
- import { act, deliverActs, keepProblems, listenForBell, notes, pageNews, setupWord, story } from "./news.js";
21
+ import { act, callBegins, deliverActs, keepProblems, listenForBell, notes, pageNews, setupWord, story } from "./news.js";
22
22
  import { givePicture } from "./pictures.js";
23
23
  import { answerAsked, closeCard, listenForChanges, pagePlayer, pageSeen, rollNamesOf, spendShown } from "./player.js";
24
24
  import { answers, campaignPorts, dashboardAt } from "./ports.js";
@@ -34,6 +34,8 @@ const noticeDelay = 100;
34
34
  const pageReturn = 5000;
35
35
  // How long a question waits on pages that are open but that no one sees, as one in a tab behind, before it goes to the form or to words (D-455).
36
36
  const pageHidden = 5000;
37
+ // How long the sentences given to OpenCode's hook wait for a call of the master before they are given back (D-578).
38
+ const heldFor = 60_000;
37
39
  // How often the server looks at an import under way, for the pages to tell how far it is (D-491 (11)).
38
40
  const importLookEvery = 2000;
39
41
  /**
@@ -90,6 +92,7 @@ export async function startDashboard(context, session, options = {}) {
90
92
  acts: newActs(),
91
93
  others: new Map(),
92
94
  queue: options.queue ?? codexQueue(),
95
+ heldFor: options.heldFor ?? heldFor,
93
96
  };
94
97
  return serve(server, served);
95
98
  }
@@ -149,6 +152,7 @@ function serve(server, served) {
149
152
  // A call of the master that ends leaves the player's sentences said meanwhile for the doorbell, or for Codex's queue (D-495).
150
153
  const chat = served.context.chat;
151
154
  if (chat !== undefined) {
155
+ chat.beforeCall = () => callBegins(served);
152
156
  chat.afterCall = () => deliverActs(served);
153
157
  }
154
158
  // An import works in another process, or in the call the master waits on, writing where the session does not watch: its state is looked at now and then,
@@ -192,6 +196,7 @@ function serve(server, served) {
192
196
  served.asked?.settle("absent");
193
197
  served.bell?.end("gone");
194
198
  if (chat !== undefined) {
199
+ chat.beforeCall = undefined;
195
200
  chat.afterCall = undefined;
196
201
  }
197
202
  served.pages.forEach((page) => page.end());
@@ -30,9 +30,11 @@ export declare function act(request: IncomingMessage, response: ServerResponse,
30
30
  * messages, else by Claude Code's doorbell. Every ring comes from a sentence the player said, never from time.
31
31
  */
32
32
  export declare function deliverActs(served: Served): void;
33
+ /** As a call of the master begins: the sentences held for it are heard, and the chat listens again, whatever its last hook did. */
34
+ export declare function callBegins(served: Served): void;
33
35
  /**
34
36
  * Claude Code's doorbell (D-495): the hook of the chat that ended its turn waits here, one at a time, and hears "ring" when the player says a sentence, or one
35
- * already waits. With probe, the chat's session and campaign, and the other chats of the campaign that wait for its page, for the hook to find its own
37
+ * already waits; with words, as OpenCode's hook asks, with the sentences themselves (D-578). With probe, the chat's session and campaign, and the other chats of the campaign that wait for its page, for the hook to find its own
36
38
  * server; with also, one of those, which says so as it asks (D-577).
37
39
  */
38
40
  export declare function listenForBell(request: IncomingMessage, response: ServerResponse, served: Served, asked: URLSearchParams): void;