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
@@ -1,10 +1,13 @@
1
- import { chatBrief } from "./briefs.js";
1
+ import { antigravityBrief, chatBrief, drawnBrief } from "./briefs.js";
2
2
  import { claudePictures, claudeReader, claudeWriter } from "./claude.js";
3
3
  import { codexPictures, codexReader, codexWriter } from "./codex.js";
4
+ import { openCodeReader, openCodeWriter } from "./opencode.js";
4
5
  /** The chat whose own pictures are Codex's, as its MCP client names itself. */
5
6
  export const codexClient = "codex-mcp-client";
6
7
  /** Antigravity's chat, as its MCP client names itself: it makes its pictures itself. */
7
8
  export const antigravityClient = "antigravity-client";
9
+ /** OpenCode's chat, as its MCP client names itself: its master draws the pictures, and OpenCode does the work outside the chat there, and nowhere else (D-578 (3)). */
10
+ export const openCodeClient = "opencode";
8
11
  /**
9
12
  * The pictures of this computer, by the campaign's choice, which `choice` reads when a picture is asked: unset or chat, the chat `host` names, by its own
10
13
  * means; codex; elevenlabs, or the name of another image tool of the master's, from the brief. Codex, where it cannot or refuses, leaves the picture to the chat
@@ -13,8 +16,14 @@ export const antigravityClient = "antigravity-client";
13
16
  export function hostPictures(host, choice = () => undefined, codex = codexPictures(), claude = claudePictures()) {
14
17
  let refused;
15
18
  let lastChoice;
16
- // The chat in use, by its own means.
17
- const chat = () => (host() === codexClient ? codex : host() === antigravityClient ? antigravityPictures : claude);
19
+ // The chat in use, by its own means: Claude's drawing in Claude Code, whose clients' names start with claude, and where no chat names itself.
20
+ const chat = () => {
21
+ const name = host() ?? "";
22
+ if (name === "" || name.toLowerCase().startsWith("claude")) {
23
+ return claude;
24
+ }
25
+ return name === codexClient ? codex : name === antigravityClient ? antigravityPictures : chatDrawing(chatNames[name] ?? name);
26
+ };
18
27
  // The maker the campaign chose, and whether it is Codex apart from the chat in use, which leaves the picture to it where it cannot.
19
28
  const chosen = () => {
20
29
  const said = choice()?.trim();
@@ -39,9 +48,9 @@ export function hostPictures(host, choice = () => undefined, codex = codexPictur
39
48
  if (!other.ready().ready) {
40
49
  return { refused: instead.why };
41
50
  }
42
- // A chat that paints itself gets no picture to make after its call answered: the next ones are its own.
51
+ // A chat that paints or draws itself gets no picture to make after its call answered: the next ones are its own.
43
52
  if (other.brief !== undefined) {
44
- return { refused: `${instead.why}; the next pictures are yours to make with your own image tool` };
53
+ return { refused: `${instead.why}; the next pictures are yours to ${drawsItself(other) ? "draw as SVG code and give with image, svg" : "make with your own image tool"}` };
45
54
  }
46
55
  const made = await other.make(subject);
47
56
  return "refused" in made ? { refused: `${instead.why}; ${instead.by} made none either: ${made.refused}` } : { ...made, instead };
@@ -59,7 +68,7 @@ export function hostPictures(host, choice = () => undefined, codex = codexPictur
59
68
  }
60
69
  const said = codexReady(again);
61
70
  const instead = said.ready ? undefined : fallbackOf(said);
62
- return said.ready || instead === undefined ? said : { ready: true, maker: instead.by, instead };
71
+ return said.ready || instead === undefined ? said : { ready: true, maker: instead.by, ...(drawsItself(chat()) ? { draws: true } : {}), instead };
63
72
  },
64
73
  make: async (subject) => {
65
74
  const { maker, codexApart } = chosen();
@@ -101,12 +110,27 @@ const unnamedTool = {
101
110
  make: () => Promise.resolve({ refused: "the master makes the pictures with another tool, which the player has not named yet" }),
102
111
  brief: chatBrief,
103
112
  };
104
- // Antigravity paints in its own chat, from the brief the image command gives it: the engine starts nothing.
113
+ // Antigravity paints in its own chat, from the brief the image command gives it, or draws the SVG where its tool fails: the engine starts nothing.
105
114
  const antigravityPictures = {
106
115
  ready: () => ({ ready: true, maker: "Antigravity" }),
107
116
  make: () => Promise.resolve({ refused: "Antigravity makes its pictures in its own chat" }),
108
- brief: chatBrief,
117
+ brief: antigravityBrief,
109
118
  };
119
+ // The chats' names for the player, by the names their MCP clients give themselves; any other is shown as it comes.
120
+ const chatNames = { [openCodeClient]: "OpenCode" };
121
+ /** A chat that draws its pictures itself as SVG code (D-572), as OpenCode: from the SVG brief image gives it, handed back with image, svg; the engine starts nothing. */
122
+ export function chatDrawing(name) {
123
+ return {
124
+ ready: () => ({ ready: true, maker: name, draws: true }),
125
+ make: () => Promise.resolve({ refused: `${name} draws its pictures in its own chat` }),
126
+ brief: drawnBrief,
127
+ };
128
+ }
129
+ // Whether a maker is a chat that draws itself; one with no brief never is, and is not asked.
130
+ function drawsItself(maker) {
131
+ const said = maker.brief === undefined ? undefined : maker.ready();
132
+ return said?.ready === true && said.draws === true;
133
+ }
110
134
  // An image tool of the master's own, by its name, as ElevenLabs's: the same brief, and the engine starts nothing.
111
135
  function masterTool(name) {
112
136
  return {
@@ -115,17 +139,17 @@ function masterTool(name) {
115
139
  brief: chatBrief,
116
140
  };
117
141
  }
118
- /** The writer of text of this computer for the chat `host` names (D-406), chosen as the pictures are: Codex first, then Claude. */
119
- export function hostWriter(host, codex = codexWriter(), claude = claudeWriter()) {
120
- const writers = () => (host() === codexClient ? [codex] : [codex, claude]);
142
+ /** The writer of text of this computer for the chat `host` names (D-406): Codex first, then Claude; in OpenCode, OpenCode before them. */
143
+ export function hostWriter(host, codex = codexWriter(), claude = claudeWriter(), openCode = openCodeWriter()) {
144
+ const writers = () => (host() === codexClient ? [codex] : host() === openCodeClient ? [openCode, codex, claude] : [codex, claude]);
121
145
  return {
122
146
  ready: () => writers().some((writer) => writer.ready()),
123
147
  write: (brief) => (writers().find((writer) => writer.ready()) ?? codex).write(brief),
124
148
  };
125
149
  }
126
- /** The importer of this computer for the chat `host` names (D-489 (1)): Codex in Codex, else Claude first, which Elena's probe measured, then Codex. */
127
- export function hostReader(host, codex = codexReader(), claude = claudeReader()) {
128
- const readers = () => (host() === codexClient ? [codex] : [claude, codex]);
150
+ /** The importer of this computer for the chat `host` names (D-489 (1)): Codex in Codex, else Claude first, which Elena's probe measured, then Codex; in OpenCode, OpenCode before them. */
151
+ export function hostReader(host, codex = codexReader(), claude = claudeReader(), openCode = openCodeReader()) {
152
+ const readers = () => (host() === codexClient ? [codex] : host() === openCodeClient ? [openCode, claude, codex] : [claude, codex]);
129
153
  return {
130
154
  ready: () => readers().some((reader) => reader.ready()),
131
155
  program: () => readers().find((reader) => reader.ready())?.program?.(),
@@ -1,7 +1,8 @@
1
- export { chatBrief, paintedBrief, svgBrief } from "./briefs.ts";
2
- export { antigravityClient, codexClient, hostPictures, hostReader, hostWriter } from "./chosen.ts";
1
+ export { antigravityBrief, chatBrief, drawnBrief, paintedBrief, svgBrief } from "./briefs.ts";
2
+ export { antigravityClient, chatDrawing, codexClient, hostPictures, hostReader, hostWriter, openCodeClient } from "./chosen.ts";
3
3
  export { claudeSays } from "./claude.ts";
4
4
  export { codexPictures, codexSays } from "./codex.ts";
5
+ export { openCodeReader, openCodeWriter, readerRules } from "./opencode.ts";
5
6
  export { computerHelpers, helperChanges, helperCommand, queueInCodex } from "./programs.ts";
6
7
  export { stopProcess } from "./stop.ts";
7
8
  export { cleanSvg, svgIn } from "./svg.ts";
@@ -1,9 +1,11 @@
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
- // from words (D-308, D-390), Codex's painted else Claude's SVG, the importer's reading and the page's words; injected through Context, so that tests never spend.
3
- export { chatBrief, paintedBrief, svgBrief } from "./briefs.js";
4
- export { antigravityClient, codexClient, hostPictures, hostReader, hostWriter } from "./chosen.js";
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.
4
+ export { antigravityBrief, chatBrief, drawnBrief, paintedBrief, svgBrief } from "./briefs.js";
5
+ export { antigravityClient, chatDrawing, codexClient, hostPictures, hostReader, hostWriter, openCodeClient } from "./chosen.js";
5
6
  export { claudeSays } from "./claude.js";
6
7
  export { codexPictures, codexSays } from "./codex.js";
8
+ export { openCodeReader, openCodeWriter, readerRules } from "./opencode.js";
7
9
  export { computerHelpers, helperChanges, helperCommand, queueInCodex } from "./programs.js";
8
10
  export { stopProcess } from "./stop.js";
9
11
  export { cleanSvg, svgIn } from "./svg.js";
@@ -0,0 +1,13 @@
1
+ import type { DocumentReader, TextWriter } from "../core/context.ts";
2
+ /** A permission rule of an OpenCode agent: the last that matches decides. */
3
+ export interface OpenCodeRule {
4
+ action: string;
5
+ resource: string;
6
+ effect: "allow" | "deny";
7
+ }
8
+ /** OpenCode on this computer as a writer of text (D-406): an agent that may use no tool, in an empty folder of its own. `program` is the line that starts it. */
9
+ export declare function openCodeWriter(program?: string): TextWriter;
10
+ /** OpenCode on this computer as the importer (D-489 (1)): in the import's folder, reading only there and writing only in the folders given. */
11
+ export declare function openCodeReader(program?: string): DocumentReader;
12
+ /** 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. */
13
+ export declare function readerRules(writable: string[]): OpenCodeRule[];
@@ -0,0 +1,202 @@
1
+ // OpenCode does the work outside the chat where it is the chat in use (D-578 (3)): the writer of text (D-406) and the importer (D-489 (1)), with the player's own
2
+ // model, the last one they chose in it, never one or a key the engine picks. Each run has an agent of its own, given in the environment and never as a file in
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
+ import { spawn, spawnSync } from "node:child_process";
5
+ import { randomBytes } from "node:crypto";
6
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
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";
11
+ // The same limits as Claude's: a brief in three minutes, a run of the importer in thirty.
12
+ const longest = 3 * 60 * 1000;
13
+ const longestReading = 30 * 60 * 1000;
14
+ // How long the deletion of a session may take: it took under a second.
15
+ const deleteWait = 30_000;
16
+ /** OpenCode on this computer as a writer of text (D-406): an agent that may use no tool, in an empty folder of its own. `program` is the line that starts it. */
17
+ export function openCodeWriter(program = "opencode") {
18
+ const ready = openCodeReady(program);
19
+ return {
20
+ ready: () => ready().ready,
21
+ write: async (brief) => {
22
+ const model = ready();
23
+ if (!model.ready || model.maker === undefined) {
24
+ return undefined;
25
+ }
26
+ const folder = mkdtempSync(join(tmpdir(), "rpg-writing-"));
27
+ try {
28
+ const ran = await runAgent(program, model.maker, folder, writerAgent, brief, longest);
29
+ return ran.code === 0 && ran.error === undefined ? ran.text : undefined;
30
+ }
31
+ finally {
32
+ rmSync(folder, { recursive: true, force: true });
33
+ }
34
+ },
35
+ };
36
+ }
37
+ /** OpenCode on this computer as the importer (D-489 (1)): in the import's folder, reading only there and writing only in the folders given. */
38
+ export function openCodeReader(program = "opencode") {
39
+ const ready = openCodeReady(program);
40
+ return {
41
+ ready: () => ready().ready,
42
+ program: () => "OpenCode",
43
+ read: async (folder, brief, writable, signal) => {
44
+ const model = ready();
45
+ if (!model.ready || model.maker === undefined) {
46
+ return { failed: model.ready ? "OpenCode has no model" : model.why };
47
+ }
48
+ const ran = await runAgent(program, model.maker, folder, readerAgent(writable), brief, longestReading, signal);
49
+ if (ran.code === 0 && ran.error === undefined && ran.text !== undefined) {
50
+ return { said: ran.text };
51
+ }
52
+ const said = ran.error ?? ran.errors.trim().split("\n").at(-1)?.trim() ?? "";
53
+ return { failed: said === "" ? "OpenCode stopped without an answer" : `OpenCode said: ${said}` };
54
+ },
55
+ };
56
+ }
57
+ /** 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
+ export function readerRules(writable) {
59
+ return [
60
+ { action: "*", resource: "*", effect: "deny" },
61
+ { action: "read", resource: "*", effect: "allow" },
62
+ { action: "glob", resource: "*", effect: "allow" },
63
+ { action: "grep", resource: "*", effect: "allow" },
64
+ ...writable.flatMap((name) => [{ action: "edit", resource: `${name}/*`, effect: "allow" }, { action: "edit", resource: `${name}/**`, effect: "allow" }]),
65
+ { action: "external_directory", resource: "*", effect: "deny" },
66
+ ];
67
+ }
68
+ const writerAgent = { name: "rpg-writer", system: "You write what a brief asks, and only that.", rules: [{ action: "*", resource: "*", effect: "deny" }] };
69
+ function readerAgent(writable) {
70
+ return { name: "rpg-reader", system: "You read a player's documents and write a tabletop adventure from them, as files in this folder.", rules: readerRules(writable) };
71
+ }
72
+ // Whether OpenCode is ready, by the line that starts it: asked once, as the other helpers are, and remembered.
73
+ const readies = new Map();
74
+ function openCodeReady(program) {
75
+ const known = readies.get(program) ?? knownReady(() => modelOf(program));
76
+ readies.set(program, known);
77
+ return known;
78
+ }
79
+ /**
80
+ * The player's model in OpenCode, as its maker, without starting one: OpenCode answers, the last model the player chose (`recent[0]` of model.json in its state
81
+ * folder), and that model among those OpenCode can use now. Not ready otherwise.
82
+ */
83
+ function modelOf(program) {
84
+ const paths = quietRun(`${program} debug paths`);
85
+ const state = paths === undefined ? undefined : /^state\s+(.+?)\s*$/m.exec(paths)?.[1];
86
+ if (state === undefined) {
87
+ return { ready: false, why: "OpenCode does not answer on this computer" };
88
+ }
89
+ const model = lastModel(join(state, "model.json"));
90
+ if (model === undefined) {
91
+ return { ready: false, why: "OpenCode has no model chosen yet: the player picks one in it" };
92
+ }
93
+ const models = quietRun(`${program} models --standalone`);
94
+ if (models === undefined || !models.split(/\r?\n/).some((line) => line.trim() === model.name)) {
95
+ return { ready: false, why: `OpenCode cannot use its model ${model.name} now` };
96
+ }
97
+ return { ready: true, maker: model.variant === undefined ? model.name : `${model.name}#${model.variant}` };
98
+ }
99
+ /** The last model the player chose in OpenCode, with its variant; undefined where there is none, or one whose name the shell could misread. */
100
+ function lastModel(file) {
101
+ try {
102
+ const json = JSON.parse(readFileSync(file, "utf8"));
103
+ const first = json.recent?.[0];
104
+ const name = typeof first?.providerID === "string" && typeof first.modelID === "string" ? `${first.providerID}/${first.modelID}` : undefined;
105
+ const variant = name === undefined ? undefined : json.variant?.[name];
106
+ const safe = (value) => /^[\w.:/@+-]+$/.test(value);
107
+ if (name === undefined || !safe(name)) {
108
+ return undefined;
109
+ }
110
+ return typeof variant === "string" && safe(variant) ? { name, variant } : { name };
111
+ }
112
+ catch {
113
+ return undefined;
114
+ }
115
+ }
116
+ /** What a quick command of OpenCode printed, from a folder of no campaign; undefined where it failed. */
117
+ function quietRun(line) {
118
+ const run = spawnSync(line, { shell: true, encoding: "utf8", timeout: 15_000, windowsHide: true, cwd: tmpdir(), env: openCodeEnvironment() });
119
+ return run.error === undefined && run.status === 0 ? run.stdout : undefined;
120
+ }
121
+ /**
122
+ * One run of an agent: `opencode run` with a session whose name the engine chose, deleted however the run ends; the answer is the last text part of its
123
+ * events, as a model may write two whole answers in two steps.
124
+ */
125
+ function runAgent(program, model, folder, agent, brief, limit, signal) {
126
+ const session = `ses_rpg${randomBytes(10).toString("hex")}`;
127
+ const config = { agents: { [agent.name]: { description: agent.system, mode: "primary", system: agent.system, permissions: agent.rules } } };
128
+ const environment = { ...openCodeEnvironment(), OPENCODE_CONFIG_CONTENT: JSON.stringify(config), OPENCODE_DISABLE_PROJECT_CONFIG: "1" };
129
+ const line = `${program} run --standalone --agent ${agent.name} -m "${model}" --format json --archived --session ${session}`;
130
+ return new Promise((done) => {
131
+ // Off Windows it leads a group of its own: the shell alone, stopped, would leave OpenCode running with the output held open.
132
+ const child = spawn(line, { shell: true, windowsHide: true, cwd: folder, env: environment, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32" });
133
+ // Dropped while it runs: OpenCode stops with its own server.
134
+ const stop = () => (process.platform === "win32" || child.pid === undefined ? stopTree(child) : stopProcess(child.pid));
135
+ signal?.addEventListener("abort", stop, { once: true });
136
+ let output = "";
137
+ let errors = "";
138
+ const timer = setTimeout(stop, limit);
139
+ child.stdout.setEncoding("utf8");
140
+ child.stderr.setEncoding("utf8");
141
+ child.stdout.on("data", (chunk) => (output += chunk));
142
+ child.stderr.on("data", (chunk) => (errors += chunk));
143
+ child.stdin.on("error", () => undefined);
144
+ child.on("error", () => undefined);
145
+ child.on("close", (code) => {
146
+ clearTimeout(timer);
147
+ signal?.removeEventListener("abort", stop);
148
+ const events = eventsOf(output);
149
+ const text = events.filter((event) => event.type === "text").map((event) => event.part?.text).filter((one) => typeof one === "string" && one.trim() !== "").at(-1);
150
+ const failed = events.find((event) => event.type === "error");
151
+ 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 }) }));
153
+ });
154
+ child.stdin.end(brief);
155
+ });
156
+ }
157
+ /** Deletes a session of the engine's from the player's OpenCode, whether the run made it or not. */
158
+ function deleteSession(program, session) {
159
+ return new Promise((done) => {
160
+ const child = spawn(`${program} session delete ${session} --standalone`, { shell: true, windowsHide: true, cwd: tmpdir(), env: openCodeEnvironment(), stdio: "ignore" });
161
+ const timer = setTimeout(() => stopTree(child), deleteWait);
162
+ child.on("error", () => undefined);
163
+ child.on("close", () => {
164
+ clearTimeout(timer);
165
+ done();
166
+ });
167
+ });
168
+ }
169
+ function eventsOf(output) {
170
+ return output.split("\n").flatMap((line) => {
171
+ try {
172
+ const event = JSON.parse(line);
173
+ return typeof event === "object" && event !== null ? [event] : [];
174
+ }
175
+ catch {
176
+ return [];
177
+ }
178
+ });
179
+ }
180
+ function errorText(event) {
181
+ const message = event.error?.data?.message ?? event.error?.name;
182
+ return typeof message === "string" && message !== "" ? message : "it failed";
183
+ }
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
+ */
188
+ 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" };
202
+ }
@@ -10,8 +10,8 @@ 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
+ /** 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;
15
15
  /** 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
16
  export declare function buttonsInstructions(physicalDice: boolean): string;
17
17
  /** 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,11 @@ 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
+ /** 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) {
13
13
  // Always for the main characters, or for everyone, as the player chose, on top of the key moments (D-490).
14
14
  const more = way === "important" || way === "always" ? `\n\n${readInstructions(`voices-${way}.md`)}` : "";
15
- return `${readInstructions("voices.md")}${more}`;
15
+ return `${readInstructions("voices.md")}${openCode ? `\n\n${readInstructions("voices-opencode.md")}` : ""}${more}`;
16
16
  }
17
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). */
18
18
  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,10 @@
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
+ * 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.
6
+ */
7
+ export declare function watchNewTurn(conversation: string, folder?: string, every?: number, appFolder?: string): {
8
+ started: Promise<void>;
9
+ stop: () => void;
10
+ };
@@ -0,0 +1,95 @@
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, 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
+ * 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.
14
+ */
15
+ export function watchNewTurn(conversation, folder = antigravityFolder(), every = 500, appFolder = join(folder, "..", "antigravity")) {
16
+ const history = join(folder, "history.jsonl");
17
+ const log = join(folder, "cli.log");
18
+ const read = { [history]: placeOf(history), [log]: placeOf(log) };
19
+ let timer;
20
+ const started = new Promise((done) => {
21
+ timer = setInterval(() => {
22
+ if (wrote(newText(history, read), conversation) || stopped(newText(log, read), conversation) || queued(appFolder, conversation)) {
23
+ clearInterval(timer);
24
+ done();
25
+ }
26
+ }, every);
27
+ timer.unref();
28
+ });
29
+ return { started, stop: () => clearInterval(timer) };
30
+ }
31
+ /**
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.
34
+ */
35
+ function queued(appFolder, conversation) {
36
+ try {
37
+ return readdirSync(join(appFolder, "brain", conversation, ".system_generated", "messages", "undelivered")).length > 0;
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ }
43
+ /** Whether these lines of Antigravity's history hold something the player typed in the conversation: a message, or a command such as /clear. */
44
+ function wrote(lines, conversation) {
45
+ return lines.split("\n").some((line) => {
46
+ try {
47
+ return JSON.parse(line).conversationId === conversation;
48
+ }
49
+ catch {
50
+ return false;
51
+ }
52
+ });
53
+ }
54
+ /** Whether these lines of Antigravity's log say the conversation was stopped, as Esc does. */
55
+ function stopped(lines, conversation) {
56
+ return lines.includes(`Cancelling conversation ${conversation}`);
57
+ }
58
+ /**
59
+ * 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
60
+ * in two parts. A file that shrank, or was written anew in its place, is read from its start.
61
+ */
62
+ function newText(file, read) {
63
+ const now = placeOf(file);
64
+ const before = read[file];
65
+ const from = before === undefined || now.offset < before.offset || now.identity !== before.identity ? 0 : before.offset;
66
+ if (now.offset <= from) {
67
+ read[file] = { offset: now.offset, identity: now.identity };
68
+ return "";
69
+ }
70
+ try {
71
+ const descriptor = openSync(file, "r");
72
+ try {
73
+ const buffer = Buffer.alloc(now.offset - from);
74
+ const length = readSync(descriptor, buffer, 0, buffer.length, from);
75
+ const whole = buffer.subarray(0, buffer.subarray(0, length).lastIndexOf(10) + 1);
76
+ read[file] = { offset: from + whole.length, identity: now.identity };
77
+ return whole.toString("utf8");
78
+ }
79
+ finally {
80
+ closeSync(descriptor);
81
+ }
82
+ }
83
+ catch {
84
+ return "";
85
+ }
86
+ }
87
+ function placeOf(file) {
88
+ try {
89
+ const stats = statSync(file);
90
+ return { offset: stats.size, identity: stats.ino };
91
+ }
92
+ catch {
93
+ return { offset: 0, identity: 0 };
94
+ }
95
+ }
@@ -0,0 +1,2 @@
1
+ export { antigravityFolder, 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, 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>;