@beatos/bridge-runner 0.8.1 → 0.9.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.
@@ -0,0 +1,236 @@
1
+ /**
2
+ * The read wall of a read-only chat session (BEA-107).
3
+ *
4
+ * Checked on Claude Code 2.1.319: in -p mode with --tools Read,Grep,Glob and
5
+ * --permission-mode dontAsk, Read, Grep and Glob work on ANY path; allow
6
+ * rules do not limit them. Only deny rules do. So a read turn gets a deny
7
+ * rule for everything outside its folder (the scanned project folder):
8
+ *
9
+ * - for each folder above the root, up to the drive root, every entry
10
+ * except the one on the path to the root: a folder as <entry>/**, a file
11
+ * as <entry> (a link gets both; a link is never listed);
12
+ * - but NO rule for a link that points at the root, into it, or at a folder
13
+ * above it (see "Links" below);
14
+ * - every other drive letter that exists, as X:/**;
15
+ * - each rule in every path form Claude Code matches (C:/..., //c/...,
16
+ * and ~/... under the home folder).
17
+ *
18
+ * A name with a character outside [A-Za-z0-9._ -] gets "?" for each such
19
+ * character; when that glob would also match the allowed name, the entry is
20
+ * skipped (and counted: never named in a log), and the caller must refuse the
21
+ * turn when anything was skipped. Never a rule over the root.
22
+ * More than WALL_MAX rules, or a folder that cannot be listed: no wall can be
23
+ * built, and the turn must not run.
24
+ *
25
+ * Work access gets no wall: it has a shell, a wall would give false comfort.
26
+ *
27
+ * Links. Claude Code follows a link in a deny rule. Found live on 2026-11-14
28
+ * (2.1.319): every Windows PC has the hidden link C:/Documents and Settings
29
+ * -> C:/Users, and the rule for it made Glob and Grep hide every file under
30
+ * C:/Users, the session's own folder too ("No files found"; Read by full
31
+ * path still worked). So a link whose real target is the root, is in the
32
+ * root, or is a folder above the root gets no rule. That opens nothing: a
33
+ * read through such a link ends at a real path, and every real neighbor has
34
+ * its own rule. Checked with the real CLI, with a control: Read, Grep and
35
+ * Glob for the folder next door, asked for through that link, are refused,
36
+ * and a search that starts above the root does not show it
37
+ * (scripts/sessions-live-check.mjs, checks 8 to 10). A link that cannot be
38
+ * resolved keeps its rules. To resolve a link is to open the place it points
39
+ * at, so only a link to a place on this computer, on the root's own drive,
40
+ * is resolved: a link to a network share or to another drive keeps its
41
+ * rules unseen (no wait for a server that is off, no login sent to it).
42
+ *
43
+ * Not in these rules: on Windows a walled folder also opens by its 8.3 short
44
+ * name (DOCUME~1), and a rule here sees only the long name. chatDenyRules in
45
+ * safety.ts closes that for every chat turn (shortNameRules: no name with
46
+ * "~" and a digit can be read). Use the wall only together with it.
47
+ */
48
+ import { existsSync, lstatSync, readdirSync, readlinkSync, realpathSync } from "node:fs";
49
+ export const WALL_MAX = 6000;
50
+ export const realWallFs = {
51
+ lstat(p) {
52
+ try {
53
+ const s = lstatSync(p);
54
+ return { isDirectory: s.isDirectory(), isSymbolicLink: s.isSymbolicLink() };
55
+ }
56
+ catch {
57
+ return null;
58
+ }
59
+ },
60
+ readdir(p) {
61
+ try {
62
+ return readdirSync(p);
63
+ }
64
+ catch {
65
+ return null;
66
+ }
67
+ },
68
+ driveExists(letter) {
69
+ try {
70
+ return existsSync(`${letter}:\\`);
71
+ }
72
+ catch {
73
+ return false;
74
+ }
75
+ },
76
+ readlink(p) {
77
+ try {
78
+ return readlinkSync(p);
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ },
84
+ realpath(p) {
85
+ try {
86
+ return realpathSync(p);
87
+ }
88
+ catch {
89
+ return null;
90
+ }
91
+ },
92
+ };
93
+ const SAFE = /^[A-Za-z0-9._ -]$/;
94
+ /** A name as a deny glob: "?" for every character outside the safe set. */
95
+ export function globName(name) {
96
+ return [...name].map((c) => (SAFE.test(c) ? c : "?")).join("");
97
+ }
98
+ /** Does a "?" glob match a name? (one "?" per character: per code point) */
99
+ function globMatches(glob, name, caseless) {
100
+ const g = [...glob];
101
+ const n = [...name];
102
+ if (g.length !== n.length)
103
+ return false;
104
+ return g.every((c, i) => c === "?" || (caseless ? c.toLowerCase() === n[i].toLowerCase() : c === n[i]));
105
+ }
106
+ function split(abs) {
107
+ const p = abs.replace(/\\/g, "/");
108
+ const d = /^([A-Za-z]):(\/.*)?$/.exec(p);
109
+ if (d)
110
+ return { drive: `${d[1].toUpperCase()}:`, parts: (d[2] ?? "").split("/").filter(Boolean) };
111
+ if (p.startsWith("/"))
112
+ return { drive: "", parts: p.split("/").filter(Boolean) };
113
+ return null;
114
+ }
115
+ /** "C:/" or "/" for a drive root (never "C:", which means the current folder on C). */
116
+ const dirPath = (drive, parts) => (parts.length ? `${drive}/${parts.join("/")}` : `${drive}/`);
117
+ const childPath = (dir, name) => (dir.endsWith("/") ? `${dir}${name}` : `${dir}/${name}`);
118
+ /** A path as the OS gives it, made comparable: forward slashes, no \\?\ prefix, no slash at the end. */
119
+ function comparable(p, caseless) {
120
+ let s = p.replace(/\\/g, "/").replace(/^\/\/\?\//, "");
121
+ if (s.length > 1)
122
+ s = s.replace(/\/+$/, "");
123
+ return caseless ? s.toLowerCase() : s;
124
+ }
125
+ /** Is `real` the root, a folder above it, or something in it? (both made comparable) */
126
+ function onRootPath(real, root) {
127
+ const a = real.endsWith("/") ? real : `${real}/`;
128
+ const b = root.endsWith("/") ? root : `${root}/`;
129
+ return a.startsWith(b) || b.startsWith(a);
130
+ }
131
+ /**
132
+ * Is the place a link names on this computer and on the root's drive? A
133
+ * network place (//server/share, \\?\UNC\...) or another drive letter is
134
+ * not: it is never resolved. A relative target is beside the link: local.
135
+ */
136
+ function localTarget(direct, drive) {
137
+ let s = direct.replace(/\\/g, "/");
138
+ if (/^\/\/\?\/UNC\//i.test(s))
139
+ return false;
140
+ s = s.replace(/^\/\/\?\//, "");
141
+ if (s.startsWith("//"))
142
+ return false;
143
+ const d = /^([A-Za-z]):/.exec(s);
144
+ if (d)
145
+ return drive !== "" && `${d[1].toUpperCase()}:` === drive;
146
+ return true;
147
+ }
148
+ /** Every form Claude Code matches: C:/x, //c/x, and ~/x under home. */
149
+ export function readForms(target, home, caseless) {
150
+ const out = [`Read(${target})`];
151
+ const d = /^([A-Za-z]):\/(.*)$/.exec(target);
152
+ if (d)
153
+ out.push(`Read(//${d[1].toLowerCase()}/${d[2]})`);
154
+ const h = home.replace(/\\/g, "/").replace(/\/+$/, "");
155
+ const t = caseless ? target.toLowerCase() : target;
156
+ const hh = caseless ? h.toLowerCase() : h;
157
+ if (h && t.startsWith(`${hh}/`))
158
+ out.push(`Read(~/${target.slice(h.length + 1)})`);
159
+ return out;
160
+ }
161
+ /** The deny rules that keep a read turn inside `root`. */
162
+ export function readWall(root, opts) {
163
+ const fs = opts.fs ?? realWallFs;
164
+ const platform = opts.platform ?? process.platform;
165
+ const caseless = platform === "win32";
166
+ const max = opts.max ?? WALL_MAX;
167
+ const s = split(root);
168
+ if (!s || s.parts.length === 0)
169
+ return { ok: false, why: "bad_root", rules: 0 };
170
+ const rules = [];
171
+ let skipped = 0;
172
+ let rootLinks = 0;
173
+ const rootPath = dirPath(s.drive, s.parts);
174
+ const rootReal = comparable(fs.realpath?.(rootPath) ?? rootPath, caseless);
175
+ const add = (target) => rules.push(...readForms(target, opts.home, caseless));
176
+ /** Does this link point at the root, into it, or at a folder above it? Only a local link is resolved. */
177
+ const onTheRootPath = (link) => {
178
+ if (!fs.realpath)
179
+ return false;
180
+ if (fs.readlink) {
181
+ const direct = fs.readlink(link);
182
+ if (direct === null || !localTarget(direct, s.drive))
183
+ return false;
184
+ }
185
+ const real = fs.realpath(link);
186
+ return real !== null && onRootPath(comparable(real, caseless), rootReal);
187
+ };
188
+ for (let i = s.parts.length - 1; i >= 0; i--) {
189
+ const allowed = s.parts[i];
190
+ // The folders above the root, as globs (a "?" there only widens the deny side).
191
+ const dir = dirPath(s.drive, s.parts.slice(0, i));
192
+ const globDir = dirPath(s.drive, s.parts.slice(0, i).map(globName));
193
+ const names = fs.readdir(dir);
194
+ if (names === null)
195
+ return { ok: false, why: "cannot_list", rules: rules.length };
196
+ for (const name of names) {
197
+ if (caseless ? name.toLowerCase() === allowed.toLowerCase() : name === allowed)
198
+ continue;
199
+ const g = globName(name);
200
+ if (g !== name && globMatches(g, allowed, caseless)) {
201
+ skipped += 1;
202
+ continue;
203
+ }
204
+ const full = childPath(dir, name);
205
+ const st = fs.lstat(full);
206
+ const target = childPath(globDir, g);
207
+ if (!st || st.isSymbolicLink) {
208
+ // A link onto the root's own path: Claude Code follows it, and a rule for it would hide the root.
209
+ if (st?.isSymbolicLink && onTheRootPath(full)) {
210
+ rootLinks += 1;
211
+ continue;
212
+ }
213
+ // Any other link, or an entry that cannot be read (locked, gone): wall it off both ways.
214
+ add(target);
215
+ add(`${target}/**`);
216
+ }
217
+ else if (st.isDirectory)
218
+ add(`${target}/**`);
219
+ else
220
+ add(target);
221
+ if (rules.length > max)
222
+ return { ok: false, why: "too_many", rules: rules.length };
223
+ }
224
+ }
225
+ if (caseless && s.drive) {
226
+ for (let c = 65; c <= 90; c++) {
227
+ const letter = String.fromCharCode(c);
228
+ if (`${letter}:` === s.drive || !fs.driveExists(letter))
229
+ continue;
230
+ rules.push(`Read(${letter}:/**)`, `Read(//${letter.toLowerCase()}/**)`);
231
+ }
232
+ }
233
+ if (rules.length > max)
234
+ return { ok: false, why: "too_many", rules: rules.length };
235
+ return { ok: true, rules, skipped, rootLinks };
236
+ }
package/dist/runner.js CHANGED
@@ -44,12 +44,13 @@ import { ApiError, } from "./api.js";
44
44
  import { answerText, parseAgentReply } from "./agent-reply.js";
45
45
  import { briefText, CONTINUE_PROMPT, REPLY_PROMPT, RETRY_PROMPT, rulesText, START_PROMPT, } from "./brief.js";
46
46
  import { classifyError, retryDelaySeconds, sessionUsage, } from "./claude.js";
47
+ import { parseSessionsConfig } from "./config.js";
47
48
  import { Outbox } from "./outbox.js";
48
49
  import { decideAction } from "./policy.js";
49
50
  import { claudeArgs, comprehensionArgs, sessionSettings, agentEnv } from "./safety.js";
50
51
  import { processVideos, realVideoFs } from "./video.js";
51
52
  import { comprehensionLanguage, comprehensionPrompt, comprehensionTaskText, TASK_TEXT_FILE, useSavedVideos, VAULT_LIMITS, } from "./video-vault.js";
52
- export const RUNNER_VERSION = "0.8.1";
53
+ export const RUNNER_VERSION = "0.9.1";
53
54
  /** A model name from Bridge goes into argv: plain names only. */
54
55
  const MODEL_RE = /^[A-Za-z0-9._-]{1,64}$/;
55
56
  const CLAIM_REFRESH_MS = 5 * 60_000;
@@ -169,6 +170,7 @@ export class Runner {
169
170
  }
170
171
  this.runnerStatus = "revoked";
171
172
  this.stopLive("revoked");
173
+ this.d.sessions?.update({ runnerId: this.state.runnerId, enabled: false });
172
174
  return false;
173
175
  }
174
176
  throw err;
@@ -181,8 +183,29 @@ export class Runner {
181
183
  await this.sendInventory();
182
184
  if (r.status !== "revoked")
183
185
  await this.folderStep(r);
186
+ this.sessionsStep(r);
184
187
  return true;
185
188
  }
189
+ /** The sessions switch and the folder scan go to the engine; a paused or revoked runner is off. */
190
+ sessionsStep(r) {
191
+ const s = this.d.sessions;
192
+ if (!s)
193
+ return;
194
+ try {
195
+ s.update({
196
+ runnerId: r.runner_id,
197
+ enabled: r.status === "active" && r.sessions?.enabled === true,
198
+ ...(r.sessions ? { pollMs: r.sessions.poll_ms } : {}),
199
+ ...(this.d.folders ? { folders: this.d.folders.shownPaths() } : {}),
200
+ });
201
+ }
202
+ catch (err) {
203
+ this.log(`sessions: update failed (${err.name})`);
204
+ }
205
+ }
206
+ sessionsAccess() {
207
+ return parseSessionsConfig(this.d.cfg.sessions).access;
208
+ }
186
209
  /**
187
210
  * Project folders (BEA-96 slice 3): take the owner's picks from the reply,
188
211
  * rescan the roots now and then, and send the list in one more heartbeat
@@ -266,6 +289,8 @@ export class Runner {
266
289
  // Usage screen (BEA-87): the cap and how runs are paid on this computer.
267
290
  max_runs_per_day: this.d.cfg.maxRunsPerDay,
268
291
  billing: this.d.cfg.billing,
292
+ // Sessions in Bridge (BEA-107): the access set in config.json; "off" when off.
293
+ sessions: { access: this.sessionsAccess(), protocol: 1 },
269
294
  },
270
295
  max_concurrent: 1,
271
296
  };
package/dist/safety.js CHANGED
@@ -296,6 +296,85 @@ export function claudeArgs(i) {
296
296
  argv.push("--", i.prompt); // --add-dir and --mcp-config take many values and would eat the prompt
297
297
  return argv;
298
298
  }
299
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
300
+ const CHAT_MODEL_RE = /^[A-Za-z0-9._-]{1,64}$/;
301
+ /** The only tools of a read-only chat session (BEA-107). */
302
+ export const READ_TOOLS = "Read,Grep,Glob";
303
+ /**
304
+ * On Windows a file or folder also opens by its 8.3 short name
305
+ * (C:/Users/me/DOCUME~1 for Documents, ENV~1 for .env). A deny rule sees the
306
+ * path as it was written, so every rule by long name could be passed that
307
+ * way. Checked on Claude Code 2.1.319 with a real read session: it read a
308
+ * walled folder by BEATOS~2/SPIKE-~3 and its own .env as ENV~1; with these
309
+ * rules both are denied. A short name always has "~" and a digit, so every
310
+ * such name is denied on the drives given (one rule set per drive letter). A
311
+ * real long name with "~1" in it is refused too: the safe side.
312
+ */
313
+ export function shortNameRules(paths) {
314
+ const rules = [];
315
+ const seen = new Set();
316
+ for (const p of paths) {
317
+ const d = /^([A-Za-z]):/.exec(p);
318
+ if (!d)
319
+ continue;
320
+ const letter = d[1].toUpperCase();
321
+ if (seen.has(letter))
322
+ continue;
323
+ seen.add(letter);
324
+ for (const glob of ["**/*~[0-9]*", "**/*~[0-9]*/**"]) {
325
+ rules.push(`Read(${letter}:/${glob})`, `Read(//${letter.toLowerCase()}/${glob})`);
326
+ }
327
+ }
328
+ return rules;
329
+ }
330
+ /**
331
+ * More deny rules for every chat turn (read and work; task runs do not
332
+ * change): key and .env files anywhere under the session's root (the cwd can
333
+ * be below it, and the root can be outside ~/projects), other sessions'
334
+ * transcripts and the live registry, and every Windows short name on the
335
+ * root's drive and the home drive (shortNameRules). Work also gets Bash
336
+ * patterns for the transcripts and the registry.
337
+ */
338
+ export function chatDenyRules(root, access, home = homedir()) {
339
+ const rules = [];
340
+ for (const f of PROJECT_SECRET_FILES)
341
+ rules.push(...pathForms("Read", root, `**/${f}`));
342
+ for (const rel of [".claude/projects/**", ".claude/sessions/**"])
343
+ rules.push(...homeForms("Read", rel, home));
344
+ rules.push(...shortNameRules([root, home]));
345
+ if (access === "work")
346
+ rules.push("Bash(*.claude/projects*)", "Bash(*.claude\\projects*)", "Bash(*.claude/sessions*)", "Bash(*.claude\\sessions*)");
347
+ return rules;
348
+ }
349
+ /**
350
+ * argv for one chat turn of a Bridge session (BEA-107). The user's text goes
351
+ * by stdin, never argv. read: Read, Grep and Glob are the only tools there
352
+ * are, anything else is denied without asking. work: the same auto mode and
353
+ * deny rules as a task run. Never --dangerously-skip-permissions.
354
+ */
355
+ export function chatArgs(i) {
356
+ if (i.access !== "read" && i.access !== "work")
357
+ throw new Error("sessions are off");
358
+ if (!CHAT_MODEL_RE.test(i.model))
359
+ throw new Error("bad model name");
360
+ if (i.resumeSessionId !== undefined && !UUID_RE.test(i.resumeSessionId))
361
+ throw new Error("bad session id");
362
+ if (i.fork && !i.resumeSessionId)
363
+ throw new Error("a copy needs the session it copies");
364
+ const argv = ["-p", "--output-format", "stream-json", "--verbose", "--model", i.model];
365
+ if (i.resumeSessionId)
366
+ argv.push("--resume", i.resumeSessionId);
367
+ if (i.fork)
368
+ argv.push("--fork-session");
369
+ if (i.access === "read")
370
+ argv.push("--tools", READ_TOOLS, "--allowedTools", READ_TOOLS, "--permission-mode", "dontAsk");
371
+ else
372
+ argv.push("--permission-mode", "auto");
373
+ if (!i.settingsFile || i.settingsFile.trim().startsWith("{"))
374
+ throw new Error("chat settings go in a file");
375
+ argv.push("--settings", i.settingsFile, "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--no-chrome", "--append-system-prompt-file", i.rulesFile);
376
+ return argv;
377
+ }
299
378
  /**
300
379
  * argv for the short "comprension" session of a processed video (BEA-96
301
380
  * slice 8): the same CLI and login as a run, but Read is the only tool there