beatrina 0.8.6 → 0.9.43

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 (112) hide show
  1. package/NOTICES +1 -1
  2. package/README.md +6 -0
  3. package/beatrina_V0.9.43.html +1885 -0
  4. package/beatrina_V0.9.43.html.inputs.json +1 -0
  5. package/bin/beatrina.mjs +156 -26
  6. package/bin/browser.mjs +31 -0
  7. package/bin/cli.mjs +64 -5
  8. package/bin/doctor-rows.mjs +31 -0
  9. package/bin/failsafe.mjs +8 -3
  10. package/bin/finder.mjs +74 -0
  11. package/bin/lsquery.swift +55 -0
  12. package/bin/pages.mjs +81 -0
  13. package/bin/python-setup.mjs +207 -0
  14. package/bin/runtime-dirs.mjs +27 -0
  15. package/bin/sessions.mjs +30 -10
  16. package/bin/shortcut.mjs +271 -35
  17. package/bin/update-check.mjs +2 -2
  18. package/build-info.json +1 -1
  19. package/engines/js/worker.mjs +6 -3
  20. package/engines/python/adapter.py +14 -13
  21. package/engines/python/analyze.py +4 -2
  22. package/engines/python/bootstrap.py +32 -31
  23. package/engines/python/debugger.py +10 -6
  24. package/engines/python/engine.json +1 -1
  25. package/engines/python/handoff.py +4 -2
  26. package/engines/python/worker.py +39 -10
  27. package/engines/r/engine.json +1 -1
  28. package/engines/r/handoff.R +4 -3
  29. package/failsafe/ai-policy.R +16 -16
  30. package/failsafe/ai-store.R +6 -6
  31. package/failsafe/cite.R +11 -11
  32. package/failsafe/journal.R +11 -11
  33. package/failsafe/plugins.R +27 -27
  34. package/failsafe/serve.R +364 -239
  35. package/failsafe/session-documents.R +104 -0
  36. package/host/ai-authority.mjs +55 -0
  37. package/host/ai-policy.mjs +48 -26
  38. package/host/bundle.mjs +194 -0
  39. package/host/deployment.mjs +25 -18
  40. package/host/engine-js.mjs +16 -17
  41. package/host/engine-pool.mjs +56 -8
  42. package/host/engine-python.mjs +80 -31
  43. package/host/engine-r.mjs +38 -32
  44. package/host/engine-stdio.mjs +45 -12
  45. package/host/env-names.mjs +148 -0
  46. package/host/gateway-token.mjs +51 -0
  47. package/host/journal-store.mjs +10 -9
  48. package/host/main.mjs +216 -76
  49. package/host/payload.mjs +131 -0
  50. package/host/planes/README.md +1 -1
  51. package/host/planes/ai-store.mjs +6 -5
  52. package/host/planes/ai.mjs +49 -29
  53. package/host/planes/analyze.mjs +6 -5
  54. package/host/planes/bundle.mjs +344 -0
  55. package/host/planes/choose.mjs +404 -0
  56. package/host/planes/cite.mjs +18 -17
  57. package/host/planes/files.mjs +0 -0
  58. package/host/planes/jobs.mjs +43 -20
  59. package/host/planes/latex.mjs +41 -5
  60. package/host/planes/mcp.mjs +80 -91
  61. package/host/planes/pair.mjs +24 -24
  62. package/host/planes/pipe-term.mjs +2 -2
  63. package/host/planes/plugins.mjs +1 -1
  64. package/host/planes/recent-documents.mjs +170 -0
  65. package/host/planes/sessions.mjs +230 -82
  66. package/host/planes/settings.mjs +4 -4
  67. package/host/planes/terminal.mjs +13 -11
  68. package/host/planes/test-file.mjs +2 -2
  69. package/host/planes/update.mjs +6 -13
  70. package/host/plugin-store.mjs +35 -52
  71. package/host/recent-documents.mjs +124 -0
  72. package/host/runtime-dir.mjs +47 -0
  73. package/host/server.mjs +123 -21
  74. package/host/session-keep.mjs +70 -0
  75. package/host/settings.mjs +85 -37
  76. package/host/update-record.mjs +3 -2
  77. package/host/user-dirs.mjs +60 -18
  78. package/host/which.mjs +39 -0
  79. package/host/windows-runtime.mjs +6 -3
  80. package/host/worker-plane.mjs +80 -7
  81. package/host/ws.mjs +9 -2
  82. package/host/zip.mjs +237 -0
  83. package/kernel/analyze.R +1 -1
  84. package/{check → kernel/check}/acceptance.mjs +1 -1
  85. package/kernel/check/knit-file.mjs +19639 -0
  86. package/{check → kernel/check}/session.mjs +49 -8
  87. package/kernel/deployment.R +20 -20
  88. package/kernel/examples/NOTICE.md +1 -1
  89. package/kernel/fileio.R +6 -6
  90. package/kernel/index.html +2 -2
  91. package/kernel/job-run.R +83 -22
  92. package/kernel/jobs.R +28 -12
  93. package/kernel/kernel-version +1 -1
  94. package/kernel/kernel.R +24 -21
  95. package/kernel/knitr-run.R +50 -9
  96. package/kernel/latex.R +429 -30
  97. package/kernel/mcp/{carmar-mcp.mjs → beatrina-mcp.mjs} +249 -59
  98. package/kernel/notebook-page.R +7 -7
  99. package/kernel/project.R +10 -10
  100. package/kernel/settings.R +105 -56
  101. package/kernel/sniff.R +4 -4
  102. package/kernel/typst.R +121 -0
  103. package/kernel/worker.R +602 -123
  104. package/kernel/workspace-keep.R +188 -0
  105. package/lib/agent-authoring-contract.js +28 -19
  106. package/lib/cell-kinds.js +3 -3
  107. package/lib/engine-labels.js +4 -4
  108. package/menu/Beatrina Menu.app/Contents/Info.plist +14 -0
  109. package/menu/Beatrina Menu.app/Contents/MacOS/Beatrina Menu +0 -0
  110. package/menu/Beatrina Menu.app/Contents/_CodeSignature/CodeResources +115 -0
  111. package/package.json +4 -3
  112. package/carmar_V0.8.6.html +0 -1310
@@ -40,6 +40,7 @@ import fs from "node:fs";
40
40
  import os from "node:os";
41
41
  import path from "node:path";
42
42
  import { NO_INTERRUPT_TOOL, windowsInterruptPlan, windowsKillPlan } from "./windows-runtime.mjs";
43
+ import { mirrorEnv } from "./env-names.mjs";
43
44
 
44
45
  export const MAX_CONSOLE_LINE = 32000;
45
46
  /** The gap between the group SIGINT and the pid SIGINT: the measured lifetime of the spawned
@@ -58,6 +59,11 @@ export const token = () => {
58
59
  * The child's environment: a UTF-8 LC_CTYPE guaranteed, a dumb terminal, and
59
60
  * the worker's two tokens. `strip` removes variables a user's shell may carry
60
61
  * that would aim the child at a different install of its own runtime.
62
+ *
63
+ * Every `BEATRINA_*` variable goes out under its `CARMAR_*` spelling as well
64
+ * (host/env-names.mjs mirrorEnv): spike/worker.R, job-run.R and analyze.R are
65
+ * upstream code that reads the old names, and a user's own Python or Node may
66
+ * be older than this host.
61
67
  */
62
68
  export function engineEnvironment({ sentinel, cmdtag, workerDir, extra = {}, base = process.env, strip = null }) {
63
69
  const env = {};
@@ -75,10 +81,10 @@ export function engineEnvironment({ sentinel, cmdtag, workerDir, extra = {}, bas
75
81
  // TERM=dumb: readline's terminal probe writes an escape sequence to stdout
76
82
  // before anything else, and a dumb terminal keeps it out of the stream.
77
83
  env.TERM = "dumb";
78
- env.CARMAR_SENTINEL = sentinel;
79
- env.CARMAR_CMD_TAG = cmdtag;
80
- env.CARMAR_WORKER_DIR = workerDir;
81
- return env;
84
+ env.BEATRINA_SENTINEL = sentinel;
85
+ env.BEATRINA_CMD_TAG = cmdtag;
86
+ env.BEATRINA_WORKER_DIR = workerDir;
87
+ return mirrorEnv(env);
82
88
  }
83
89
 
84
90
  /**
@@ -91,8 +97,10 @@ export function engineEnvironment({ sentinel, cmdtag, workerDir, extra = {}, bas
91
97
  * is our own command echoed back (kept only for the text before the tag).
92
98
  */
93
99
  export class LineFramer {
94
- constructor({ sentinel, cmdtag, channel }) {
100
+ constructor({ sentinel, cmdtag, channel, isEcho = null }) {
95
101
  this.sentinel = sentinel;
102
+ // A raw console line the host itself wrote, echoed back whole by R's readline (Linux): not output.
103
+ this.isEcho = typeof isEcho === "function" ? isEcho : null;
96
104
  this.tag = cmdtag ? `#${cmdtag}` : null;
97
105
  this.channel = channel; // "stdout" | "stderr"
98
106
  this.tail = "";
@@ -121,6 +129,7 @@ export class LineFramer {
121
129
  const at = line.indexOf(this.tag);
122
130
  if (at >= 0) { line = line.slice(0, at); if (!line) continue; }
123
131
  }
132
+ if (this.isEcho && this.isEcho(line)) continue;
124
133
  const at = line.indexOf(this.sentinel);
125
134
  if (at < 0) { plain.push(line); continue; }
126
135
  const prefix = line.slice(0, at);
@@ -178,8 +187,8 @@ export class StdioEngine extends EventEmitter {
178
187
  }
179
188
 
180
189
  /**
181
- * Does the worker read a stop flag between top-level expressions (CARMAR_STOP_DIR)? R's does
182
- * (spike/worker.R `carmar_stop_requested`), because a signal cannot always reach R: libc's
190
+ * Does the worker read a stop flag between top-level expressions (BEATRINA_STOP_DIR)? R's does
191
+ * (spike/worker.R `beatrina_stop_requested`), because a signal cannot always reach R: libc's
183
192
  * system() ignores SIGINT in R while its child runs, and whether the signal the host sends after
184
193
  * the child dies lands before or after R walks on to the next line is a race — on Linux it lost
185
194
  * every time (`beatrina check` on .39, 2026-09-16: 0/3 Stops of system("sleep 60")). The flag is
@@ -226,7 +235,7 @@ export class StdioEngine extends EventEmitter {
226
235
  }
227
236
  const env = engineEnvironment({
228
237
  sentinel: this.sentinel, cmdtag: this.cmdtag, workerDir,
229
- extra: { ...this.extraEnv, ...(plan.env || {}), ...(this.stopDir ? { CARMAR_STOP_DIR: this.stopDir } : {}) }, strip: this.stripEnv,
238
+ extra: { ...this.extraEnv, ...(plan.env || {}), ...(this.stopDir ? { BEATRINA_STOP_DIR: this.stopDir } : {}) }, strip: this.stripEnv,
230
239
  });
231
240
  // `detached`: the worker leads its OWN process group, so an interrupt can
232
241
  // be sent to the group and reach a child under system() too — a terminal's
@@ -241,15 +250,23 @@ export class StdioEngine extends EventEmitter {
241
250
  });
242
251
  this.alive = true;
243
252
  this.pid = this.proc.pid;
244
- const out = new LineFramer({ sentinel: this.sentinel, cmdtag: this.cmdtag, channel: "stdout" });
253
+ // The boot line (and any raw console line) carries no command tag; readline echoes it whole.
254
+ this.recentRaw = [];
255
+ const out = new LineFramer({ sentinel: this.sentinel, cmdtag: this.cmdtag, channel: "stdout", isEcho: (l) => l.length > 40 && this.recentRaw.includes(l) });
245
256
  const err = new LineFramer({ sentinel: this.sentinel, cmdtag: null, channel: "stderr" });
246
257
  this.proc.stdout.setEncoding("utf8");
247
258
  this.proc.stderr.setEncoding("utf8");
248
259
  this.proc.stdout.on("data", (d) => out.feed(d).forEach((e) => this.emit("event", e)));
249
260
  this.proc.stderr.on("data", (d) => err.feed(d).forEach((e) => this.emit("event", e)));
250
261
  this.proc.stdin.on("error", () => { /* a dead worker's pipe: the exit event reports it */ });
251
- this.proc.on("error", (e) => { this.alive = false; this.emit("spawn-error", e); });
252
- this.proc.on("exit", (code, signal) => {
262
+ // A failed spawn emits `error` and `close`, but no `exit`. Give the plane
263
+ // the same terminal event and cleanup in either case, exactly once.
264
+ let finished = false;
265
+ let spawned = false;
266
+ this.proc.once("spawn", () => { spawned = true; });
267
+ const finish = (code, signal) => {
268
+ if (finished) return;
269
+ finished = true;
253
270
  this.alive = false;
254
271
  out.feed("", { flush: true }).forEach((e) => this.emit("event", e));
255
272
  err.feed("", { flush: true }).forEach((e) => this.emit("event", e));
@@ -257,7 +274,20 @@ export class StdioEngine extends EventEmitter {
257
274
  this.spilled.clear();
258
275
  if (this.stopDir) { try { fs.rmSync(this.stopDir, { recursive: true, force: true }); } catch { /* gone */ } this.stopDir = null; }
259
276
  this.emit("exit", { code, signal });
277
+ };
278
+ this.proc.on("error", (e) => {
279
+ if (finished) return;
280
+ // ChildProcess also emits error when kill/send fails after a successful
281
+ // spawn. That says nothing about whether the worker has exited.
282
+ if (spawned) {
283
+ this.emit("event", { type: "stderr", text: `${this.label} process control failed: ${e.message}` });
284
+ return;
285
+ }
286
+ this.alive = false;
287
+ this.emit("spawn-error", e);
288
+ finish(null, null);
260
289
  });
290
+ this.proc.on("exit", finish);
261
291
  this.afterSpawn();
262
292
  return Promise.resolve(this);
263
293
  }
@@ -265,6 +295,9 @@ export class StdioEngine extends EventEmitter {
265
295
  /** One RAW line on stdin, with no command framing. */
266
296
  rawLine(line) {
267
297
  if (/\n/.test(line)) throw new Error("StdioEngine.rawLine: one line, no newline");
298
+ // Remembered so an exact echo of it is not shown as output (LineFramer isEcho). Only lines long
299
+ // enough to be ours are matched: a short readline answer echoed as "Q? yes" is the user's own text.
300
+ this.recentRaw = [...(this.recentRaw || []), line].slice(-8);
268
301
  return this.write(`${line}\n`);
269
302
  }
270
303
 
@@ -280,7 +313,7 @@ export class StdioEngine extends EventEmitter {
280
313
  if (cmd.type === "exec") this.interruptRefusalSaid = false;
281
314
  let json = JSON.stringify(cmd);
282
315
  if (Buffer.byteLength(json) > MAX_CONSOLE_LINE) {
283
- const spill = path.join(os.tmpdir(), `carmar-cmd-${crypto.randomBytes(8).toString("hex")}.json`);
316
+ const spill = path.join(os.tmpdir(), `beatrina-cmd-${crypto.randomBytes(8).toString("hex")}.json`);
284
317
  fs.writeFileSync(spill, json, { mode: 0o600 });
285
318
  this.spilled.add(spill);
286
319
  json = JSON.stringify({ type: "cmdfile", path: spill });
@@ -0,0 +1,148 @@
1
+ // env-names.mjs — one place that knows the product's environment-variable names.
2
+ // beatrina-names: keep-file — this module IS the reader of the older spelling.
3
+ //
4
+ // The product is Beatrina. Its environment variables are `BEATRINA_<NAME>`.
5
+ // Every one of them was `CARMAR_<NAME>` until 2026-09-16, and that spelling is
6
+ // still ACCEPTED — launchers, CI, the R package and users' shells set it — so
7
+ // reading a variable means asking for both, new name first. Nothing in the
8
+ // host reads `process.env.CARMAR_…` or `process.env.BEATRINA_…` directly;
9
+ // it calls `readEnv(process.env, "PORT")` and gets whichever is set.
10
+ //
11
+ // Children (engines, jobs, the terminal, a spawned kernel under test) may be
12
+ // older code that knows only the old name, so an environment handed to a child
13
+ // is passed through `mirrorEnv()`, which sets each name under both prefixes.
14
+ // When the last reader of `CARMAR_` is gone, `LEGACY_PREFIX` goes with it and
15
+ // `mirrorEnv` becomes the identity.
16
+
17
+ export const PREFIX = "BEATRINA_";
18
+ export const LEGACY_PREFIX = "CARMAR_";
19
+
20
+ /** The canonical variable name for a suffix: envName("PORT") → "BEATRINA_PORT". */
21
+ export function envName(suffix) {
22
+ return PREFIX + suffix;
23
+ }
24
+
25
+ /** The names a reader accepts for a suffix, canonical first. */
26
+ export function envNames(suffix) {
27
+ return [PREFIX + suffix, LEGACY_PREFIX + suffix];
28
+ }
29
+
30
+ /**
31
+ * Read a variable under either prefix, canonical first.
32
+ * @param {Record<string, string|undefined>} source usually process.env
33
+ * @param {string} suffix the name without its prefix, e.g. "RUNTIME_DIR"
34
+ * @param {string} unset what an absent variable reads as
35
+ * @returns {string}
36
+ */
37
+ export function readEnv(source, suffix, unset = "") {
38
+ for (const name of envNames(suffix)) {
39
+ const v = valueOf(source, name);
40
+ if (v != null) return String(v);
41
+ }
42
+ return unset;
43
+ }
44
+
45
+ /** True when the variable is set under either prefix (even to ""). */
46
+ export function hasEnv(source, suffix) {
47
+ return envNames(suffix).some((name) => valueOf(source, name) != null);
48
+ }
49
+
50
+ /**
51
+ * The spelling that is actually set, for a message that names a switch:
52
+ * `envSetName(env, "NO_TERMINAL")` is "CARMAR_NO_TERMINAL" on a launcher that
53
+ * still sets the old name and "BEATRINA_NO_TERMINAL" otherwise (also when
54
+ * neither is set — the canonical name is the one to document).
55
+ */
56
+ export function envSetName(source, suffix) {
57
+ return envNames(suffix).find((name) => valueOf(source, name) != null) || envName(suffix);
58
+ }
59
+
60
+ /**
61
+ * Read a FULL variable name the way the host's `Sys.getenv`-style getters do:
62
+ * a name under either prefix is read under both (canonical first); any other
63
+ * name (`PATH`, `BEATRIX_APP_ID`, `ProgramData`) is read as it is. This is
64
+ * what lets every `env("CARMAR_PORT")` call site keep its spelling while a
65
+ * launcher that sets `BEATRINA_PORT` is honoured.
66
+ */
67
+ export function readEnvName(source, name, unset = "") {
68
+ const suffix = suffixOf(name);
69
+ if (suffix != null) return readEnv(source, suffix, unset);
70
+ const v = valueOf(source, name);
71
+ return v == null ? unset : String(v);
72
+ }
73
+
74
+ /**
75
+ * A `(name, unset = "") => string` getter over `source`, dual-read (readEnvName).
76
+ * It carries `source` so that a helper handed the GETTER (the planes get one)
77
+ * can still see which spelling is really set: asked for `BEATRINA_X`, the
78
+ * getter answers from `CARMAR_X` too, which is right for a read and wrong for
79
+ * `envSetName`.
80
+ */
81
+ export function envReader(source = process.env) {
82
+ const reader = (name, unset = "") => readEnvName(source, name, unset);
83
+ reader.source = source;
84
+ return reader;
85
+ }
86
+
87
+ /** Set a variable under BOTH prefixes on `target` (an environment object). */
88
+ export function setEnv(target, suffix, value) {
89
+ for (const name of envNames(suffix)) target[name] = String(value);
90
+ return target;
91
+ }
92
+
93
+ /** Set a FULL name on `target`; a prefixed name is set under both prefixes. */
94
+ export function setEnvName(target, name, value) {
95
+ const suffix = suffixOf(name);
96
+ if (suffix != null) return setEnv(target, suffix, value);
97
+ target[name] = String(value);
98
+ return target;
99
+ }
100
+
101
+ /** Remove a variable under BOTH prefixes from `target`. */
102
+ export function unsetEnv(target, suffix) {
103
+ for (const name of envNames(suffix)) delete target[name];
104
+ return target;
105
+ }
106
+
107
+ /** The suffix of a name under either prefix, or null for any other name. */
108
+ export function suffixOf(name) {
109
+ const n = String(name);
110
+ if (n.startsWith(PREFIX)) return n.slice(PREFIX.length);
111
+ if (n.startsWith(LEGACY_PREFIX)) return n.slice(LEGACY_PREFIX.length);
112
+ return null;
113
+ }
114
+
115
+ // A source is an environment OBJECT (process.env, a child's env) or a
116
+ // `Sys.getenv`-style GETTER (what the planes are handed); a getter answers ""
117
+ // for an unset name, so "" from a getter is read as unset.
118
+ function valueOf(source, name) {
119
+ if (!source) return undefined;
120
+ if (typeof source === "function" && source.source) return valueOf(source.source, name);
121
+ if (typeof source === "function") {
122
+ const v = source(name, undefined);
123
+ return v == null || v === "" ? undefined : v;
124
+ }
125
+ return source[name];
126
+ }
127
+
128
+ /**
129
+ * A copy of `source` in which every `BEATRINA_X` is also present as `CARMAR_X`
130
+ * and vice versa, the canonical spelling winning when both are set and differ.
131
+ * For environments handed to child processes.
132
+ * @param {Record<string, string|undefined>} source
133
+ * @returns {Record<string, string>}
134
+ */
135
+ export function mirrorEnv(source) {
136
+ const out = {};
137
+ for (const [k, v] of Object.entries(source || {})) if (v != null) out[k] = String(v);
138
+ for (const [k, v] of Object.entries(source || {})) {
139
+ if (v == null) continue;
140
+ if (k.startsWith(PREFIX)) out[LEGACY_PREFIX + k.slice(PREFIX.length)] = String(v);
141
+ }
142
+ for (const [k, v] of Object.entries(source || {})) {
143
+ if (v == null || !k.startsWith(LEGACY_PREFIX)) continue;
144
+ const canonical = PREFIX + k.slice(LEGACY_PREFIX.length);
145
+ if (out[canonical] == null) out[canonical] = String(v);
146
+ }
147
+ return out;
148
+ }
@@ -0,0 +1,51 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+
4
+ export const GATEWAY_TOKEN_HEADER = "x-beatrina-gateway-token";
5
+ export const GATEWAY_MANAGED_COMMANDS = Object.freeze(["session-new", "session_upgrade", "session_restart", "update_action"]);
6
+ export const GATEWAY_MANAGED_PATHS = Object.freeze(["/session/upgrade", "/session/restart", "/shutdown", "/pair", "/pair/approve", "/published/authorize"]);
7
+ export const GATEWAY_HIDDEN_CAPABILITIES = Object.freeze(["session-restart-v1", "published-direct-v1", "published-pairing-v3", "signed-updates-v1"]);
8
+
9
+ /** Gateway sessions are launched and upgraded exclusively by their broker. */
10
+ export function gatewayCommands(commands, enabled) {
11
+ return enabled ? commands.filter((command) => !GATEWAY_MANAGED_COMMANDS.includes(command)) : commands;
12
+ }
13
+
14
+ /** Validate a gateway credential without ever including its value in errors. */
15
+ export function validateGatewayToken(token) {
16
+ if (typeof token !== "string" || !/^(?:[a-fA-F0-9]{2}){32,256}$/.test(token)) {
17
+ throw new Error("Gateway token must contain 32–256 bytes encoded as hexadecimal.");
18
+ }
19
+ return token;
20
+ }
21
+
22
+ /** Read the gateway-only credential from a private regular file at startup. */
23
+ export function loadGatewayToken(file) {
24
+ if (file === undefined || file === null) return undefined;
25
+ if (typeof file !== "string" || !file.trim()) throw new Error("Gateway token file path is empty.");
26
+ let fd;
27
+ try {
28
+ fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | fs.constants.O_NONBLOCK);
29
+ const stat = fs.fstatSync(fd);
30
+ if (!stat.isFile() || stat.size > 1024 || (process.platform !== "win32" && (stat.mode & 0o077))) {
31
+ throw new Error("unsafe gateway token file");
32
+ }
33
+ return validateGatewayToken(fs.readFileSync(fd, "utf8").trim());
34
+ } catch {
35
+ throw new Error("Cannot load gateway token: use a private regular file containing 32–256 bytes encoded as hexadecimal.");
36
+ } finally {
37
+ if (fd !== undefined) fs.closeSync(fd);
38
+ }
39
+ }
40
+
41
+ /** Build a constant-time credential check; only absent configuration disables it. */
42
+ export function gatewayTokenGate(token) {
43
+ if (token === undefined) return () => true;
44
+ const expected = crypto.createHash("sha256").update(validateGatewayToken(token)).digest();
45
+ return (req) => {
46
+ const supplied = req.headers[GATEWAY_TOKEN_HEADER];
47
+ if (typeof supplied !== "string" || supplied.length > 512) return false;
48
+ const actual = crypto.createHash("sha256").update(supplied).digest();
49
+ return crypto.timingSafeEqual(expected, actual);
50
+ };
51
+ }
@@ -52,12 +52,13 @@ import crypto from "node:crypto";
52
52
  import fs from "node:fs";
53
53
  import path from "node:path";
54
54
  import { privateModeHeld, stateDir } from "./user-dirs.mjs";
55
+ import { envReader } from "./env-names.mjs";
55
56
 
56
57
  const TAB = 0x09;
57
58
  const NL = 0x0a;
58
59
  export const JOURNAL_KEY_RE = /^[a-z]+:[A-Za-z0-9._~-]{1,200}$/;
59
60
  export const JOURNAL_MAX_REPLY_BYTES = 6e6; // under the 8 MB frame cap, with room
60
- const envOf = (name, unset = "") => (process.env[name] == null ? unset : String(process.env[name]));
61
+ const envOf = envReader(process.env); // dual-read (host/env-names.mjs)
61
62
 
62
63
  /** A UTC stamp in the journal's evidence-filename shape: %Y%m%d-%H%M%S. */
63
64
  const stamp = () => {
@@ -73,11 +74,11 @@ const bytesOf = (text) => Buffer.byteLength(text, "utf8");
73
74
  * first's idea of where a tail is.
74
75
  */
75
76
  export function createJournalStore() {
76
- const enabled = envOf("CARMAR_NO_JOURNAL") !== "1";
77
+ const enabled = envOf("BEATRINA_NO_JOURNAL") !== "1";
77
78
  const cache = new Map();
78
79
 
79
80
  const root = () => {
80
- const explicit = envOf("CARMAR_HISTORY_DIR");
81
+ const explicit = envOf("BEATRINA_HISTORY_DIR");
81
82
  if (explicit) return explicit;
82
83
  return path.join(stateDir(), "history");
83
84
  };
@@ -87,7 +88,7 @@ export function createJournalStore() {
87
88
  * stacks; pins hold their own content), never the tail.
88
89
  */
89
90
  const budget = () => {
90
- const v = Number(envOf("CARMAR_HISTORY_BUDGET"));
91
+ const v = Number(envOf("BEATRINA_HISTORY_BUDGET"));
91
92
  return !Number.isFinite(v) || v < 65536 ? 64 * 1024 * 1024 : v;
92
93
  };
93
94
  const validKey = (key) => typeof key === "string" && JOURNAL_KEY_RE.test(key);
@@ -174,7 +175,7 @@ export function createJournalStore() {
174
175
 
175
176
  /** Atomic replace within the same directory: write a sibling, rename over. */
176
177
  const replace = (file, text) => {
177
- const temp = path.join(path.dirname(file), `.carmar-journal-${crypto.randomBytes(8).toString("hex")}`);
178
+ const temp = path.join(path.dirname(file), `.beatrina-journal-${crypto.randomBytes(8).toString("hex")}`);
178
179
  writePrivate(temp, text);
179
180
  try { fs.renameSync(temp, file); } catch (e) {
180
181
  try { fs.unlinkSync(temp); } catch { /* gone */ }
@@ -263,7 +264,7 @@ export function createJournalStore() {
263
264
  return { held: { pid: Math.trunc(prior.pid), port: prior.port, epoch: prior.epoch }, epoch: null };
264
265
  }
265
266
  const epoch = prior && typeof prior.epoch === "number" ? Math.trunc(prior.epoch) + 1 : 1;
266
- const me = { pid: mePid, port: Number.parseInt(envOf("CARMAR_PORT", "0"), 10) || 0, epoch, at: Date.now() };
267
+ const me = { pid: mePid, port: Number.parseInt(envOf("BEATRINA_PORT", "0"), 10) || 0, epoch, at: Date.now() };
267
268
  try { replace(file, JSON.stringify(me)); } catch {
268
269
  return { held: null, epoch: null, error: "The writer lease could not be written." };
269
270
  }
@@ -295,7 +296,7 @@ export function createJournalStore() {
295
296
  // ── the ops ───────────────────────────────────────────────────────────────
296
297
 
297
298
  const open = (id, key, meta, takeover) => {
298
- if (!enabled) return err("journal_open", id, "unavailable", "The document journal is disabled (CARMAR_NO_JOURNAL=1).");
299
+ if (!enabled) return err("journal_open", id, "unavailable", "The document journal is disabled (BEATRINA_NO_JOURNAL=1).");
299
300
  if (!validKey(key)) return err("journal_open", id, "invalid_key", "A journal needs a durable document key.");
300
301
  let st;
301
302
  try { st = stateOf(key); } catch (e) { return err("journal_open", id, "io", e.message); }
@@ -323,7 +324,7 @@ export function createJournalStore() {
323
324
  * directory behind, so it never calls stateOf().
324
325
  */
325
326
  const probe = (id, key) => {
326
- if (!enabled) return err("journal_probe", id, "unavailable", "The document journal is disabled (CARMAR_NO_JOURNAL=1).");
327
+ if (!enabled) return err("journal_probe", id, "unavailable", "The document journal is disabled (BEATRINA_NO_JOURNAL=1).");
327
328
  if (!validKey(key)) return err("journal_probe", id, "invalid_key", "A journal needs a durable document key.");
328
329
  const dir = dirOf(key);
329
330
  if (!fs.existsSync(dir)) return { type: "journal_probe", id, key, exists: false, path: null, pathExists: false };
@@ -674,7 +675,7 @@ export function createJournalStore() {
674
675
  try { st = stateOf(key); } catch (e) { return err("journal_export", id, "io", e.message); }
675
676
  const s = scan(st.path);
676
677
  const envelope = readEnvelope(st.dir);
677
- const head = JSON.stringify({ format: "carmar-history-export", schema: 1, key,
678
+ const head = JSON.stringify({ format: "beatrina-history-export", schema: 1, key,
678
679
  exported: Date.now(), checkpointRevision: st.checkpoint, meta: readMeta(st.dir) });
679
680
  const text = `${head.slice(0, head.length - 1)},"checkpoint":${envelope == null ? "null" : JSON.stringify(envelope)},"records":[${s.records.join(",")}]}`;
680
681
  if (bytesOf(text) > JOURNAL_MAX_REPLY_BYTES) {