@beatos/bridge-runner 0.1.0 → 0.2.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.
package/README.md CHANGED
@@ -20,6 +20,7 @@ computer to the internet. Nothing is merged, deployed or sent without your yes.
20
20
  - [Projects: where the agent works](#projects-where-the-agent-works)
21
21
  - [The key](#the-key)
22
22
  - [Safety model](#safety-model)
23
+ - [What is on this computer (opt-in)](#what-is-on-this-computer-opt-in)
23
24
  - [Files and logs](#files-and-logs)
24
25
  - [Update](#update)
25
26
  - [Uninstall](#uninstall)
@@ -205,8 +206,8 @@ Every field:
205
206
  | `maxRunsPerDay` | number | `8` | How many runs this computer starts per day. |
206
207
  | `billing` | `subscription` or `metered` | `subscription` | `subscription`: a Claude plan, runs report $0. `metered`: an API key, runs report the cost. |
207
208
  | `pollSeconds` | number | `30` | How often the runner checks BeatOS. |
208
- | `taskRoot` | string | `~/.beatos-runner/tasks` | Where each task's files go. |
209
- | `worktreeRoot` | string | `~/.beatos-runner/worktrees` | Where git projects get their work copies. |
209
+ | `taskRoot` | string | `~/beatos-runner-work/tasks` | Where each task's files go (`TAREA.md`, rules, your answers). Use a full path (`~` is not expanded). The agent must read and write here, so it must be outside `~/.beatos-runner` and outside `protectPaths`. |
210
+ | `worktreeRoot` | string | `~/beatos-runner-work/worktrees` | Where git projects get their work copies. Same rule as `taskRoot`. |
210
211
  | `claudePath` | string | found by itself | The Claude Code program. `BEATOS_RUNNER_CLAUDE` also sets it. |
211
212
  | `ghUser` | string | none | The GitHub CLI account the runner uses to push and open pull requests. |
212
213
  | `protectPaths` | string array | `[]` | More folders the agent may not read or change. See the next section. |
@@ -272,7 +273,7 @@ How to check it works:
272
273
  | `exclude` | Never takes tasks from this project. |
273
274
 
274
275
  A task from a project that is not listed works in a scratch folder in
275
- `~/.beatos-runner/tasks/<TASK>`.
276
+ `~/beatos-runner-work/tasks/<TASK>`.
276
277
 
277
278
  ## The key
278
279
 
@@ -302,9 +303,34 @@ These rules are in the code. No setting turns them off.
302
303
  - Text in tasks, comments, web pages and files is data for the agent, not new
303
304
  orders.
304
305
 
306
+ ## What is on this computer (opt-in)
307
+
308
+ Runner 0.2.0 and newer can show, on the runner's page in Bridge, which
309
+ assistants this computer has and what they hold. **It is off by default.**
310
+ Only the runner's owner can turn it on (Bridge, Runners, click the runner,
311
+ "What is on this computer"), and only the owner sees it.
312
+
313
+ When it is on, the runner sends a list once and then every 6 hours:
314
+
315
+ - the assistants it finds: Claude Code (`~/.claude`), PAI, LifeOS, Codex
316
+ (`~/.codex`), Gemini CLI, Hermes and Pi;
317
+ - their agents, skills, hooks and MCP tools, by name and description;
318
+ - Claude Code sessions (active now, last 24 hours, last 7 days) and tokens per
319
+ model over the last 7 days, counted from the logs in `~/.claude/projects`.
320
+
321
+ What it never sends: file contents, keys, env values, a hook's command line, an
322
+ MCP server's command or URL, or a full path. Paths go as `~/...`; a full path
323
+ inside a description becomes `~/...` or `…`.
324
+
325
+ Turn it off on the same page. BeatOS then deletes the list, and the runner
326
+ stops reading.
327
+
305
328
  ## Files and logs
306
329
 
307
- Everything is in `~/.beatos-runner` (or `BEATOS_RUNNER_HOME`):
330
+ The runner uses two folders in your home folder.
331
+
332
+ `~/.beatos-runner` (or `BEATOS_RUNNER_HOME`): the runner's own files. The
333
+ agent can never read or change this folder.
308
334
 
309
335
  | File or folder | What |
310
336
  | --- | --- |
@@ -312,9 +338,20 @@ Everything is in `~/.beatos-runner` (or `BEATOS_RUNNER_HOME`):
312
338
  | `config.json` | Your settings. |
313
339
  | `state.json` | Open runs and today's count. |
314
340
  | `outbox/` | Events saved before they are sent, so nothing is lost offline. |
341
+ | `runner.lock` | Present while the runner runs. |
342
+
343
+ `~/beatos-runner-work` (next to the runner folder): where the agent works.
344
+ Change it with `taskRoot` and `worktreeRoot`.
345
+
346
+ | Folder | What |
347
+ | --- | --- |
315
348
  | `tasks/<TASK>/` | Each task's brief (`TAREA.md`), rules and your answers. |
316
349
  | `worktrees/` | Work copies of git projects. |
317
- | `runner.lock` | Present while the runner runs. |
350
+
351
+ At start, the runner checks that the agent may read and write both work
352
+ folders. If a deny rule covers one of them (for example a `taskRoot` inside
353
+ `~/.beatos-runner` or inside a `protectPaths` entry), it does not start and
354
+ says which rule blocks it.
318
355
 
319
356
  Logs go to the terminal, with the prefix `[bridge-runner]`. To keep them in a
320
357
  file:
@@ -346,20 +383,22 @@ Your key and settings stay. Stop the runner (Ctrl+C) before you update.
346
383
 
347
384
  1. In Bridge, Runners: **Revoke key** on the computer's card, then **Remove**.
348
385
  2. Stop the runner (Ctrl+C).
349
- 3. Delete the runner folder:
386
+ 3. Delete the runner folder and the work folder:
350
387
 
351
388
  macOS and Linux:
352
389
 
353
390
  ```bash
354
- rm -rf ~/.beatos-runner
391
+ rm -rf ~/.beatos-runner ~/beatos-runner-work
355
392
  ```
356
393
 
357
394
  Windows (PowerShell):
358
395
 
359
396
  ```powershell
360
- Remove-Item -Recurse -Force $HOME\.beatos-runner
397
+ Remove-Item -Recurse -Force $HOME\.beatos-runner, $HOME\beatos-runner-work
361
398
  ```
362
399
 
400
+ If you set `taskRoot` or `worktreeRoot`, delete those folders too.
401
+
363
402
  4. Optional: clear the npx copy with `npm cache clean --force`.
364
403
 
365
404
  ## Troubleshooting
@@ -374,6 +413,8 @@ Your key and settings stay. Stop the runner (Ctrl+C) before you update.
374
413
  | "no agent key" | Pair this computer first, or set `BEATOS_RUNNER_KEY`. |
375
414
  | "no agent set" | Pair this computer first, or set `agentName` in `config.json`. |
376
415
  | "another runner is already running" | One runner per computer. Close the other terminal. If none runs, delete `~/.beatos-runner/runner.lock`. |
416
+ | A run says it cannot read `TAREA.md` (runner 0.1.0) | Update to 0.1.1 or newer (`npx @beatos/bridge-runner@latest`). In 0.1.0 the task folder was inside `~/.beatos-runner`, which the agent may not read. On 0.1.0, set full paths in `config.json`, like `"taskRoot": "/home/you/beatos-runner-work/tasks"` and `"worktreeRoot": "/home/you/beatos-runner-work/worktrees"` (Windows: `"C:/Users/you/beatos-runner-work/tasks"`). |
417
+ | "taskRoot ... is blocked for the agent by" | The task or work folder is under a denied path. Move `taskRoot` and `worktreeRoot` outside `~/.beatos-runner` and outside `protectPaths`, or remove the default lines from `config.json`. |
377
418
  | "the runner key was refused" | The key was revoked. Pair again with a new code. |
378
419
  | The card says offline | Start the runner and keep the terminal open. Check the internet connection. A sleeping computer is offline. |
379
420
  | No tasks are picked up | Check: the task is delegated to **Local AI**; the runner is not paused; the daily limit (`maxRunsPerDay`) is not reached; the task's project is not `exclude`; the task has no machine target for another computer; the task is not blocked or waiting. |
package/dist/config.js CHANGED
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import { existsSync, readdirSync, readFileSync } from "node:fs";
8
8
  import { homedir, hostname } from "node:os";
9
- import { join } from "node:path";
9
+ import { dirname, join } from "node:path";
10
10
  /**
11
11
  * The real Claude Code executable. On Windows the npm `claude.cmd` shim cannot
12
12
  * be spawned without a shell and mangles multi-line arguments, so look for
@@ -36,6 +36,15 @@ export function findClaude(env = process.env, platform = process.platform, home
36
36
  export function defaultStateDir() {
37
37
  return join(homedir(), ".beatos-runner");
38
38
  }
39
+ /**
40
+ * Where the agent works: task briefs and git work copies. It sits NEXT TO
41
+ * the state folder (~/beatos-runner-work), never inside it: the state folder
42
+ * holds the key and is denied to every agent session, so a task inside it
43
+ * could not read its own TAREA.md (0.1.0 bug).
44
+ */
45
+ export function defaultWorkDir(stateDir) {
46
+ return join(dirname(stateDir), "beatos-runner-work");
47
+ }
39
48
  export function loadConfig(env = process.env) {
40
49
  const stateDir = env.BEATOS_RUNNER_HOME || defaultStateDir();
41
50
  const file = env.BEATOS_RUNNER_CONFIG || join(stateDir, "config.json");
@@ -55,8 +64,8 @@ export function loadConfig(env = process.env) {
55
64
  billing: raw.billing === "metered" ? "metered" : "subscription",
56
65
  pollSeconds: raw.pollSeconds ?? 30,
57
66
  stateDir,
58
- taskRoot: raw.taskRoot ?? join(stateDir, "tasks"),
59
- worktreeRoot: raw.worktreeRoot ?? join(stateDir, "worktrees"),
67
+ taskRoot: raw.taskRoot ?? join(defaultWorkDir(stateDir), "tasks"),
68
+ worktreeRoot: raw.worktreeRoot ?? join(defaultWorkDir(stateDir), "worktrees"),
60
69
  claudePath: raw.claudePath ?? findClaude(env),
61
70
  ghUser: raw.ghUser,
62
71
  protectPaths: Array.isArray(raw.protectPaths) ? raw.protectPaths.filter((p) => typeof p === "string") : [],
@@ -0,0 +1,377 @@
1
+ /**
2
+ * What is on this computer (BEA-97 part B): the assistants found here, their
3
+ * agents, skills, hooks and MCP tools, and Claude Code session counts and
4
+ * tokens per model from its own logs.
5
+ *
6
+ * Off by default. The runner scans only when beatos.app says the owner turned
7
+ * it on for this runner (the heartbeat reply), then every 6 hours.
8
+ *
9
+ * Privacy rules (never change):
10
+ * - names and descriptions only: never file contents, never keys or env values;
11
+ * - a hook sends its event and script name, never its command line;
12
+ * - an MCP tool sends its name and transport, never its command, URL or env;
13
+ * - paths are sent as ~/..., and a path outside the home folder is never sent.
14
+ */
15
+ import { createReadStream, existsSync, readdirSync, readFileSync, statSync } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { basename, join, relative, sep } from "node:path";
18
+ import { createInterface } from "node:readline";
19
+ export const NAME_MAX = 120;
20
+ export const DESCRIPTION_MAX = 300;
21
+ export const ITEMS_MAX = 300;
22
+ const LOG_BYTES_MAX = 300 * 1024 * 1024;
23
+ const DAY = 24 * 3600 * 1000;
24
+ const clip = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
25
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
26
+ const POSIX_ROOTS = "home|Users|root|mnt|var|etc|opt|Volumes|private|tmp|srv|media";
27
+ /** Anything that still looks like a full path after scrubbing. */
28
+ const STILL_A_PATH = new RegExp(`[A-Za-z]:[\\\\/]|\\\\\\\\|\\w\\\\\\w|(^|[\\s("'\`])/(${POSIX_ROOTS})/`, "i");
29
+ /**
30
+ * A name or description written by a person may hold a full path. The home
31
+ * folder becomes ~ (with / or \ in it), other drive, UNC and absolute POSIX
32
+ * paths become "…". If anything path-like is still left (a path with spaces,
33
+ * for example), the text is dropped: null.
34
+ */
35
+ export function scrubPaths(text, home) {
36
+ const parts = home.split(/[\\/]+/).filter(Boolean).map(escapeRe);
37
+ const lead = /^[\\/]/.test(home) ? "[\\\\/]+" : "";
38
+ // The lookahead stops C:\Users\al from matching inside C:\Users\alex.
39
+ const homeRe = new RegExp(lead + parts.join("[\\\\/]+") + "(?![\\w.-])", "gi");
40
+ const out = text
41
+ .replace(/file:\/\/\/?/gi, "")
42
+ .replace(homeRe, "~")
43
+ .replace(/~[\\/]+/g, "~/")
44
+ .replace(/~\/[^\s"'`)]*/g, (m) => m.replace(/\\/g, "/"))
45
+ .replace(/[A-Za-z]:[\\/][^\s"'`)]*/g, "…")
46
+ .replace(/\\\\[^\s"'`)]+/g, "…")
47
+ .replace(new RegExp(`(^|[\\s("'\`])/(?:${POSIX_ROOTS})/[^\\s"'\`)]*`, "gi"), "$1…");
48
+ return STILL_A_PATH.test(out) ? null : out;
49
+ }
50
+ /** "~/.claude/skills/x" for a path under home; null for any other path. */
51
+ export function tildePath(p, home) {
52
+ const rel = relative(home, p);
53
+ if (!rel || rel.startsWith("..") || /^[a-zA-Z]:/.test(rel) || rel.startsWith(sep))
54
+ return rel ? null : "~";
55
+ return `~/${rel.split(sep).join("/")}`;
56
+ }
57
+ /** name and description from a Markdown file's front matter (--- ... ---). */
58
+ export function frontMatter(text) {
59
+ const m = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---/.exec(text);
60
+ if (!m)
61
+ return {};
62
+ const out = {};
63
+ const lines = m[1].split(/\r?\n/);
64
+ for (let i = 0; i < lines.length; i++) {
65
+ const kv = /^(name|description):\s*(.*)$/.exec(lines[i]);
66
+ if (!kv)
67
+ continue;
68
+ let value = kv[2].trim();
69
+ if (value === ">" || value === "|" || value === ">-" || value === "|-") {
70
+ const parts = [];
71
+ while (i + 1 < lines.length && /^\s+\S/.test(lines[i + 1]))
72
+ parts.push(lines[++i].trim());
73
+ value = parts.join(" ");
74
+ }
75
+ value = value.replace(/^["']|["']$/g, "").trim();
76
+ if (value)
77
+ out[kv[1]] = value;
78
+ }
79
+ return out;
80
+ }
81
+ function readText(p) {
82
+ try {
83
+ return readFileSync(p, "utf8");
84
+ }
85
+ catch {
86
+ return null;
87
+ }
88
+ }
89
+ function readJson(p) {
90
+ const t = readText(p);
91
+ if (t === null)
92
+ return null;
93
+ try {
94
+ const v = JSON.parse(t);
95
+ return v && typeof v === "object" ? v : null;
96
+ }
97
+ catch {
98
+ return null;
99
+ }
100
+ }
101
+ function dirs(p) {
102
+ try {
103
+ return readdirSync(p, { withFileTypes: true })
104
+ .filter((d) => d.isDirectory() && !d.name.startsWith("."))
105
+ .map((d) => d.name)
106
+ .sort();
107
+ }
108
+ catch {
109
+ return [];
110
+ }
111
+ }
112
+ function files(p, ext) {
113
+ try {
114
+ return readdirSync(p, { withFileTypes: true })
115
+ .filter((d) => d.isFile() && d.name.endsWith(ext))
116
+ .map((d) => d.name)
117
+ .sort();
118
+ }
119
+ catch {
120
+ return [];
121
+ }
122
+ }
123
+ function item(kind, name, home, file, description) {
124
+ const it = { kind, name: clip(scrubPaths(name, home) ?? "(name hidden)", NAME_MAX) };
125
+ const desc = description ? scrubPaths(description, home) : null;
126
+ if (desc)
127
+ it.description = clip(desc, DESCRIPTION_MAX);
128
+ const path = file ? tildePath(file, home) : null;
129
+ if (path)
130
+ it.path = path;
131
+ return it;
132
+ }
133
+ /** Each <dir>/<name>/SKILL.md, and one level deeper for skill groups. */
134
+ export function scanSkills(root, home) {
135
+ const out = [];
136
+ const visit = (dir, depth) => {
137
+ for (const d of dirs(dir)) {
138
+ const file = join(dir, d, "SKILL.md");
139
+ const text = readText(file);
140
+ if (text !== null) {
141
+ const fm = frontMatter(text);
142
+ out.push(item("skill", fm.name ?? d, home, join(dir, d), fm.description));
143
+ }
144
+ else if (depth < 1) {
145
+ visit(join(dir, d), depth + 1);
146
+ }
147
+ }
148
+ };
149
+ visit(root, 0);
150
+ return out;
151
+ }
152
+ /** Each <dir>/*.md agent file. */
153
+ export function scanAgents(root, home) {
154
+ return files(root, ".md").map((f) => {
155
+ const fm = frontMatter(readText(join(root, f)) ?? "");
156
+ return item("agent", fm.name ?? f.replace(/\.md$/, ""), home, join(root, f), fm.description);
157
+ });
158
+ }
159
+ /** The script a hook runs, by name: never the command line. */
160
+ export function hookScript(command) {
161
+ // Never env values (VAR=x), flags (--token=x), or URLs: drop those tokens.
162
+ const tokens = command
163
+ .split(/\s+/)
164
+ .map((t) => t.replace(/^["']|["']$/g, ""))
165
+ .filter((t) => t && !t.includes("=") && !t.includes("://") && !t.startsWith("-"));
166
+ const names = tokens.map((t) => basename(t.replace(/\\/g, "/")));
167
+ const script = [...names].reverse().find((n) => /^[\w.-]+\.(ts|mts|js|mjs|cjs|sh|ps1|py|cmd|bat|rb)$/i.test(n));
168
+ if (script)
169
+ return script;
170
+ const program = names[0];
171
+ return program && /^[A-Za-z][\w.-]{0,40}$/.test(program) ? program : "command";
172
+ }
173
+ /** settings.json hooks: one item per event and script. */
174
+ export function scanHooks(settings) {
175
+ const hooks = settings?.hooks;
176
+ if (!hooks || typeof hooks !== "object")
177
+ return [];
178
+ const out = [];
179
+ const seen = new Set();
180
+ for (const [event, groups] of Object.entries(hooks)) {
181
+ if (!Array.isArray(groups))
182
+ continue;
183
+ for (const g of groups) {
184
+ if (!Array.isArray(g?.hooks))
185
+ continue;
186
+ for (const h of g.hooks) {
187
+ if (typeof h?.command !== "string")
188
+ continue;
189
+ const name = `${event}: ${hookScript(h.command)}`;
190
+ const matcher = typeof g.matcher === "string" && g.matcher ? g.matcher : "";
191
+ if (seen.has(name + matcher))
192
+ continue;
193
+ seen.add(name + matcher);
194
+ const it = { kind: "hook", name: clip(name, NAME_MAX) };
195
+ if (matcher)
196
+ it.description = clip(`Runs for: ${matcher}`, DESCRIPTION_MAX);
197
+ out.push(it);
198
+ }
199
+ }
200
+ }
201
+ return out;
202
+ }
203
+ /** MCP server names and transport only. */
204
+ export function mcpTools(servers) {
205
+ if (!servers || typeof servers !== "object")
206
+ return [];
207
+ return Object.entries(servers).map(([name, s]) => {
208
+ const transport = typeof s?.type === "string" ? s.type : s?.url ? "http" : "stdio";
209
+ return { kind: "tool", name: clip(name, NAME_MAX), description: `MCP server (${transport})` };
210
+ });
211
+ }
212
+ /** [mcp_servers.<name>] tables in a Codex config.toml. */
213
+ export function codexMcpTools(toml) {
214
+ if (!toml)
215
+ return [];
216
+ const names = new Set();
217
+ // [mcp_servers.github] and its sub-tables ([mcp_servers.github.env]) are one tool.
218
+ for (const m of toml.matchAll(/^\s*\[mcp_servers\.(?:"([^"]+)"|([^.\]\s]+))/gm))
219
+ names.add(m[1] ?? m[2]);
220
+ return [...names].map((name) => ({ kind: "tool", name: clip(name, NAME_MAX), description: "MCP server" }));
221
+ }
222
+ const byName = (a, b) => a.kind.localeCompare(b.kind) || a.name.localeCompare(b.name);
223
+ /** The assistants found under the home folder, with what each has. */
224
+ export function scanAssistants(home) {
225
+ const out = [];
226
+ const add = (id, name, dir, items) => {
227
+ if (!existsSync(dir))
228
+ return;
229
+ out.push({ id, name, path: tildePath(dir, home) ?? "~", items: items().sort(byName).slice(0, ITEMS_MAX) });
230
+ };
231
+ const claude = join(home, ".claude");
232
+ add("claude-code", "Claude Code", claude, () => {
233
+ const settings = readJson(join(claude, "settings.json"));
234
+ const userConfig = readJson(join(home, ".claude.json"));
235
+ const tools = [...mcpTools(userConfig?.mcpServers), ...mcpTools(settings?.mcpServers)];
236
+ const unique = [...new Map(tools.map((t) => [t.name, t])).values()];
237
+ return [
238
+ ...scanAgents(join(claude, "agents"), home),
239
+ ...scanSkills(join(claude, "skills"), home),
240
+ ...scanHooks(settings),
241
+ ...unique,
242
+ ];
243
+ });
244
+ add("pai", "PAI", join(claude, "PAI"), () => []);
245
+ add("lifeos", "LifeOS", join(claude, "LIFEOS"), () => []);
246
+ const codex = join(home, ".codex");
247
+ add("codex", "Codex", codex, () => [
248
+ ...scanAgents(join(codex, "agents"), home),
249
+ ...scanSkills(join(codex, "skills"), home),
250
+ ...codexMcpTools(readText(join(codex, "config.toml"))),
251
+ ]);
252
+ add("gemini", "Gemini CLI", join(home, ".gemini"), () => {
253
+ const settings = readJson(join(home, ".gemini", "settings.json"));
254
+ return mcpTools(settings?.mcpServers);
255
+ });
256
+ add("hermes", "Hermes", join(home, ".hermes"), () => scanSkills(join(home, ".hermes", "skills"), home));
257
+ add("pi", "Pi", join(home, ".pi"), () => [
258
+ ...scanSkills(join(home, ".pi", "agent", "skills"), home),
259
+ ...scanAgents(join(home, ".pi", "agent", "agents"), home),
260
+ ]);
261
+ return out;
262
+ }
263
+ /**
264
+ * Claude Code sessions from ~/.claude/projects/<project>/<session>.jsonl:
265
+ * how many, and tokens per model over the last 7 days. One message is
266
+ * counted once (Claude Code writes one line per content block).
267
+ */
268
+ export async function scanClaudeSessions(home, now) {
269
+ const root = join(home, ".claude", "projects");
270
+ if (!existsSync(root))
271
+ return null;
272
+ const since = now - 7 * DAY;
273
+ // A session is projects/<p>/<id>.jsonl. Its subagents write under
274
+ // projects/<p>/<id>/**.jsonl: their tokens count for that session, but
275
+ // they are not sessions of their own.
276
+ const logs = [];
277
+ const add = (file, session) => {
278
+ try {
279
+ const st = statSync(file);
280
+ if (st.mtimeMs >= since)
281
+ logs.push({ file, session, mtime: st.mtimeMs, size: st.size });
282
+ }
283
+ catch {
284
+ // gone while scanning
285
+ }
286
+ };
287
+ const nested = (dir, session, depth) => {
288
+ for (const f of files(dir, ".jsonl"))
289
+ add(join(dir, f), session);
290
+ if (depth < 3)
291
+ for (const d of dirs(dir))
292
+ nested(join(dir, d), session, depth + 1);
293
+ };
294
+ for (const p of dirs(root)) {
295
+ for (const f of files(join(root, p), ".jsonl"))
296
+ add(join(root, p, f), join(root, p, f));
297
+ for (const d of dirs(join(root, p)))
298
+ nested(join(root, p, d), join(root, p, `${d}.jsonl`), 1);
299
+ }
300
+ logs.sort((a, b) => b.mtime - a.mtime);
301
+ const sessionLogs = logs.filter((l) => l.file === l.session);
302
+ const models = new Map();
303
+ let bytes = 0;
304
+ let partial = false;
305
+ for (const log of logs) {
306
+ if (bytes + log.size > LOG_BYTES_MAX) {
307
+ partial = true;
308
+ continue;
309
+ }
310
+ bytes += log.size;
311
+ try {
312
+ await countLog(log.file, log.session, since, models);
313
+ }
314
+ catch {
315
+ // Locked, deleted or unreadable: skip this one file.
316
+ partial = true;
317
+ }
318
+ }
319
+ return {
320
+ assistant: "claude-code",
321
+ active: sessionLogs.filter((l) => l.mtime >= now - 10 * 60 * 1000).length,
322
+ last24h: sessionLogs.filter((l) => l.mtime >= now - DAY).length,
323
+ last7d: sessionLogs.length,
324
+ models: [...models.values()]
325
+ .map(({ files: f, ...m }) => ({ ...m, sessions: f.size }))
326
+ .sort((a, b) => b.outputTokens - a.outputTokens),
327
+ partial,
328
+ };
329
+ }
330
+ /** Adds one log file's tokens per model; each message once. */
331
+ async function countLog(file, session, since, models) {
332
+ const seen = new Set();
333
+ const input = createReadStream(file, { encoding: "utf8" });
334
+ const lines = createInterface({ input, crlfDelay: Infinity });
335
+ try {
336
+ for await (const line of lines) {
337
+ if (!line.includes('"usage"'))
338
+ continue;
339
+ let row;
340
+ try {
341
+ row = JSON.parse(line);
342
+ }
343
+ catch {
344
+ continue;
345
+ }
346
+ const msg = row.message;
347
+ const model = msg?.model;
348
+ if (!model || !msg.usage || model.startsWith("<"))
349
+ continue;
350
+ if (row.timestamp && Date.parse(row.timestamp) < since)
351
+ continue;
352
+ if (msg.id) {
353
+ if (seen.has(msg.id))
354
+ continue;
355
+ seen.add(msg.id);
356
+ }
357
+ let m = models.get(model);
358
+ if (!m) {
359
+ m = { model, sessions: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, files: new Set() };
360
+ models.set(model, m);
361
+ }
362
+ m.files.add(session);
363
+ m.inputTokens += msg.usage.input_tokens ?? 0;
364
+ m.outputTokens += msg.usage.output_tokens ?? 0;
365
+ m.cacheReadTokens += msg.usage.cache_read_input_tokens ?? 0;
366
+ m.cacheWriteTokens += msg.usage.cache_creation_input_tokens ?? 0;
367
+ }
368
+ }
369
+ finally {
370
+ lines.close();
371
+ input.destroy();
372
+ }
373
+ }
374
+ /** The whole report the runner sends when beatos.app asks for it. */
375
+ export async function scanInventory(home = homedir(), now = Date.now()) {
376
+ return { version: 1, assistants: scanAssistants(home), sessions: await scanClaudeSessions(home, now) };
377
+ }
package/dist/main.js CHANGED
@@ -16,12 +16,14 @@
16
16
  * mid-session continues the same session, and every saved event is sent, on
17
17
  * the next start.
18
18
  */
19
+ import { scanInventory } from "./inventory.js";
19
20
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
20
21
  import { join } from "node:path";
21
22
  import { BeatosApi } from "./api.js";
22
23
  import { runClaude } from "./claude.js";
23
24
  import { loadConfig, loadKey } from "./config.js";
24
25
  import { pair } from "./pair.js";
26
+ import { agentPathProblems } from "./safety.js";
25
27
  import { makeClaudeExec, Runner, RUNNER_VERSION } from "./runner.js";
26
28
  import { Workspace } from "./workspace.js";
27
29
  const USAGE = `BeatOS Bridge runner ${RUNNER_VERSION}
@@ -89,6 +91,17 @@ async function main() {
89
91
  console.error("[bridge-runner] no agent set: connect this computer first with npx @beatos/bridge-runner pair <CODE> (or set agentName in ~/.beatos-runner/config.json)");
90
92
  return 2;
91
93
  }
94
+ // The agent must read and write these; a deny rule over them blocks every task.
95
+ const problems = agentPathProblems([
96
+ { label: "taskRoot", path: cfg.taskRoot },
97
+ { label: "worktreeRoot", path: cfg.worktreeRoot },
98
+ ], { protectPaths: cfg.protectPaths, stateDir: cfg.stateDir });
99
+ if (problems.length > 0) {
100
+ for (const p of problems)
101
+ console.error(`[bridge-runner] ${p.label} ${p.path} is blocked for the agent by: ${p.rule}`);
102
+ console.error("[bridge-runner] the agent could not read its own task there. Move it: set taskRoot and worktreeRoot in config.json to a folder outside ~/.beatos-runner and outside protectPaths (default: ~/beatos-runner-work).");
103
+ return 2;
104
+ }
92
105
  const lock = takeLock(cfg.stateDir);
93
106
  if (!lock) {
94
107
  console.error("[bridge-runner] another runner is already running on this computer");
@@ -100,6 +113,7 @@ async function main() {
100
113
  api,
101
114
  workspace: new Workspace(cfg),
102
115
  claude: makeClaudeExec(cfg, runClaude),
116
+ inventory: () => scanInventory(),
103
117
  });
104
118
  console.log(`[bridge-runner] ${cfg.runnerName} -> ${cfg.beatosUrl} as ${cfg.agentName}, every ${cfg.pollSeconds}s`);
105
119
  let stop = false;
package/dist/runner.js CHANGED
@@ -31,7 +31,7 @@ import { classifyError, retryDelaySeconds, sessionUsage, } from "./claude.js";
31
31
  import { Outbox } from "./outbox.js";
32
32
  import { decideAction } from "./policy.js";
33
33
  import { claudeArgs, sessionSettings, agentEnv } from "./safety.js";
34
- export const RUNNER_VERSION = "0.1.0";
34
+ export const RUNNER_VERSION = "0.2.0";
35
35
  /** A model name from Bridge goes into argv: plain names only. */
36
36
  const MODEL_RE = /^[A-Za-z0-9._-]{1,64}$/;
37
37
  const CLAIM_REFRESH_MS = 5 * 60_000;
@@ -55,6 +55,8 @@ export class Runner {
55
55
  /** Each open run's state as the server saw it this tick. */
56
56
  serverRuns = new Map();
57
57
  runnerStatus = "active";
58
+ /** No new inventory read before this time (1 h after a send, 10 min after a failure). */
59
+ inventoryRetryAt = 0;
58
60
  constructor(deps) {
59
61
  this.d = deps;
60
62
  mkdirSync(deps.cfg.stateDir, { recursive: true });
@@ -132,21 +134,7 @@ export class Runner {
132
134
  async heartbeat() {
133
135
  let r;
134
136
  try {
135
- r = await this.d.api.heartbeat({
136
- name: this.d.cfg.runnerName,
137
- kind: "pc",
138
- ...(this.d.cfg.workspaceId ? { workspace_id: this.d.cfg.workspaceId } : {}),
139
- runner_version: RUNNER_VERSION,
140
- capabilities: {
141
- connectors: ["claude"],
142
- profile: this.d.cfg.profile,
143
- browser_level: 1,
144
- // Usage screen (BEA-87): the cap and how runs are paid on this computer.
145
- max_runs_per_day: this.d.cfg.maxRunsPerDay,
146
- billing: this.d.cfg.billing,
147
- },
148
- max_concurrent: 1,
149
- });
137
+ r = await this.d.api.heartbeat(this.heartbeatBody());
150
138
  }
151
139
  catch (err) {
152
140
  if (err instanceof ApiError && err.status === 401) {
@@ -163,8 +151,49 @@ export class Runner {
163
151
  this.runnerStatus = r.status;
164
152
  if (r.status === "revoked")
165
153
  this.stopLive("revoked");
154
+ if (r.status !== "revoked" && r.inventory?.enabled && r.inventory.send)
155
+ await this.sendInventory();
166
156
  return true;
167
157
  }
158
+ /**
159
+ * The owner turned on "What is on this computer" and the server wants a
160
+ * fresh list (first time, or 6 hours old): read it and send it in one more
161
+ * heartbeat. A failure only logs; the next heartbeat asks again.
162
+ */
163
+ async sendInventory() {
164
+ if (!this.d.inventory || this.now() < this.inventoryRetryAt)
165
+ return;
166
+ try {
167
+ const inventory = await this.d.inventory();
168
+ // The status in this reply is read on the next tick.
169
+ await this.d.api.heartbeat({ ...this.heartbeatBody(), inventory });
170
+ // Even if the server keeps asking, read at most once an hour.
171
+ this.inventoryRetryAt = this.now() + 60 * 60 * 1000;
172
+ this.log("sent what is on this computer (names and descriptions only)");
173
+ }
174
+ catch (err) {
175
+ // Not on every heartbeat: wait 10 minutes before reading again.
176
+ this.inventoryRetryAt = this.now() + 10 * 60 * 1000;
177
+ this.log(`could not send what is on this computer (${err.message})`);
178
+ }
179
+ }
180
+ heartbeatBody() {
181
+ return {
182
+ name: this.d.cfg.runnerName,
183
+ kind: "pc",
184
+ ...(this.d.cfg.workspaceId ? { workspace_id: this.d.cfg.workspaceId } : {}),
185
+ runner_version: RUNNER_VERSION,
186
+ capabilities: {
187
+ connectors: ["claude"],
188
+ profile: this.d.cfg.profile,
189
+ browser_level: 1,
190
+ // Usage screen (BEA-87): the cap and how runs are paid on this computer.
191
+ max_runs_per_day: this.d.cfg.maxRunsPerDay,
192
+ billing: this.d.cfg.billing,
193
+ },
194
+ max_concurrent: 1,
195
+ };
196
+ }
168
197
  /** Kill the live Claude session, if any (pause, stop, revoke). */
169
198
  stopLive(reason, runId) {
170
199
  if (!this.live || (runId && this.live.runId !== runId))
@@ -491,7 +520,7 @@ export class Runner {
491
520
  place: rec.place,
492
521
  model: rec.model ?? this.d.cfg.model,
493
522
  rulesFile: join(rec.place.brief, "REGLAS.md"),
494
- settings: sessionSettings(rec.place, undefined, this.d.cfg.protectPaths),
523
+ settings: sessionSettings(rec.place, undefined, this.d.cfg.protectPaths, this.d.cfg.stateDir),
495
524
  prompt,
496
525
  ...(resume && rec.sessionId ? { resumeSessionId: rec.sessionId } : {}),
497
526
  });
package/dist/safety.js CHANGED
@@ -153,7 +153,7 @@ export function pathForms(tool, path) {
153
153
  rules.push(`${tool}(//${drive[1].toLowerCase()}/${drive[2]}/**)`);
154
154
  return rules;
155
155
  }
156
- export function denyRules(place, home = homedir(), protectPaths = []) {
156
+ export function denyRules(place, home = homedir(), protectPaths = [], stateDir) {
157
157
  const rules = [...ALWAYS_DENY, ...LOCAL_DENY];
158
158
  for (const rel of [...SECRET_PATHS, ...protectPaths])
159
159
  for (const tool of ["Read", "Edit", "Write"])
@@ -165,14 +165,76 @@ export function denyRules(place, home = homedir(), protectPaths = []) {
165
165
  for (const tool of ["Edit", "Write", "MultiEdit", "NotebookEdit"])
166
166
  rules.push(...pathForms(tool, place.projectPath));
167
167
  }
168
+ // The runner's own folder (key, config, outbox) also when BEATOS_RUNNER_HOME moves it.
169
+ if (stateDir)
170
+ for (const tool of ["Read", "Edit", "Write"])
171
+ rules.push(...pathForms(tool, stateDir));
168
172
  return rules;
169
173
  }
174
+ /** A home-relative deny glob as a regex over a home-relative posix path. */
175
+ function globRegex(glob, caseless) {
176
+ let re = "";
177
+ for (let i = 0; i < glob.length; i++) {
178
+ const c = glob[i];
179
+ if (c === "*" && glob[i + 1] === "*") {
180
+ i++;
181
+ if (glob[i + 1] === "/") {
182
+ i++;
183
+ re += "(?:.*/)?";
184
+ }
185
+ else
186
+ re += ".*";
187
+ }
188
+ else if (c === "*")
189
+ re += "[^/]*";
190
+ else
191
+ re += c.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
192
+ }
193
+ return new RegExp(`^${re}$`, caseless ? "i" : "");
194
+ }
195
+ const posixPath = (p) => p.replace(/\\/g, "/").replace(/\/+$/, "");
196
+ /**
197
+ * Checks the folders the agent works in (task briefs, git work copies)
198
+ * against every deny rule a session gets. A folder under a denied path
199
+ * would block every task, so the runner refuses to start instead.
200
+ */
201
+ export function agentPathProblems(folders, opts = {}) {
202
+ const caseless = (opts.platform ?? process.platform) === "win32";
203
+ const norm = (p) => (caseless ? posixPath(p).toLowerCase() : posixPath(p));
204
+ const home = norm(opts.home ?? homedir());
205
+ const homeRules = [
206
+ ...[...SECRET_PATHS, ...(opts.protectPaths ?? [])].map((g) => ({ g, rule: `~/${g} (no read, edit or write)` })),
207
+ ...CONTROL_PATHS.map((g) => ({ g, rule: `~/${g} (no edit or write)` })),
208
+ ];
209
+ const bashParts = ALWAYS_DENY.map((r) => /^Bash\(\*(.+)\*\)$/.exec(r)?.[1]).filter((x) => Boolean(x) && !x.includes("*") && !x.includes(" "));
210
+ const out = [];
211
+ for (const { label, path } of folders) {
212
+ const abs = norm(path);
213
+ const probe = `${abs}/TAREA.md`;
214
+ const add = (rule) => out.push({ label, path, rule });
215
+ if (opts.stateDir) {
216
+ const state = norm(opts.stateDir);
217
+ if (abs === state || abs.startsWith(`${state}/`))
218
+ add(`${opts.stateDir} (the runner's own folder)`);
219
+ }
220
+ if (probe.startsWith(`${home}/`)) {
221
+ const rel = probe.slice(home.length + 1);
222
+ for (const { g, rule } of homeRules)
223
+ if (globRegex(g, caseless).test(rel))
224
+ add(rule);
225
+ }
226
+ for (const part of bashParts)
227
+ if (abs.includes(caseless ? part.toLowerCase() : part))
228
+ add(`shell commands that mention ${part}`);
229
+ }
230
+ return out;
231
+ }
170
232
  /** The --settings every agent session starts with. */
171
- export function sessionSettings(place, home = homedir(), protectPaths = []) {
233
+ export function sessionSettings(place, home = homedir(), protectPaths = [], stateDir) {
172
234
  return {
173
235
  disableAllHooks: true,
174
236
  worktree: { bgIsolation: "none" },
175
- permissions: { deny: denyRules(place, home, protectPaths) },
237
+ permissions: { deny: denyRules(place, home, protectPaths, stateDir) },
176
238
  };
177
239
  }
178
240
  /** Everything but names that look like secrets (the runner's own key included). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@beatos/bridge-runner",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "description": "BeatOS Bridge runner: a small program on your own computer that takes BeatOS tasks for your agent and works them with Claude Code. It only dials out to beatos.app.",
6
6
  "license": "MIT",