@beatos/bridge-runner 0.9.0 → 0.10.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.
@@ -26,7 +26,8 @@
26
26
  * Pure functions with an injected file system, home, clock and pid check, so
27
27
  * tests never read a real transcript.
28
28
  */
29
- import { closeSync, lstatSync, openSync, readdirSync, readFileSync, readSync } from "node:fs";
29
+ import { closeSync, lstatSync, openSync, readdirSync, readFileSync, readlinkSync, readSync } from "node:fs";
30
+ import { hostname } from "node:os";
30
31
  import { join } from "node:path";
31
32
  import { deniedFolder, displayPath, within } from "./folders.js";
32
33
  import { scrubPaths } from "./inventory.js";
@@ -158,6 +159,14 @@ export const realScanFs = {
158
159
  return null;
159
160
  }
160
161
  },
162
+ list(p) {
163
+ return readdirSync(p, { withFileTypes: true }).map((d) => ({
164
+ name: d.name,
165
+ isFile: d.isFile(),
166
+ isDirectory: d.isDirectory(),
167
+ isSymbolicLink: d.isSymbolicLink(),
168
+ }));
169
+ },
161
170
  readdir(p) {
162
171
  try {
163
172
  return readdirSync(p, { withFileTypes: true }).map((d) => ({
@@ -230,6 +239,32 @@ export function chunkLines(buf, fromStart, toEnd) {
230
239
  return out;
231
240
  }
232
241
  const META_PREFIX = /^\s*<(command-|local-command-|system-reminder|task-notification|bash-|user-memory-input)/;
242
+ /**
243
+ * The turns a person started: typed at the computer ("human") or sent
244
+ * through the runner ("sdk"). An allow list, as Claude Code's own test: it
245
+ * also writes "task_notification", "peer", "auto_continuation",
246
+ * "host_synthetic", "system" and "unknown", and may add more.
247
+ */
248
+ const BY_A_PERSON = new Set(["human", "sdk"]);
249
+ /** The whole text of the line Claude Code writes when a turn is interrupted. */
250
+ const INTERRUPTED = /^\[Request interrupted by user(?: for tool use)?\]$/;
251
+ /**
252
+ * A context block the app puts BEFORE the typed text. Only the names the app
253
+ * is known to write (artifact-view-context seen in real transcripts; the two
254
+ * IDE ones): any other tag a person typed first stays.
255
+ */
256
+ const LEAD_BLOCK = /^\s*<(artifact-view-context|ide_opened_file|ide_selection)\b[^>]*>[\s\S]*?<\/\1>\s*/;
257
+ /** Did a person (or the runner, for them) start this line? Lines from before these fields: yes. */
258
+ function byAPerson(l) {
259
+ if (l.turnOrigin !== undefined && l.turnOrigin !== null && !(typeof l.turnOrigin === "string" && BY_A_PERSON.has(l.turnOrigin)))
260
+ return false;
261
+ if (l.origin !== undefined && l.origin !== null) {
262
+ const kind = l.origin.kind;
263
+ if (kind !== undefined && kind !== "human")
264
+ return false;
265
+ }
266
+ return true;
267
+ }
233
268
  /** The assistant text of a line (text blocks only), or null. */
234
269
  export function assistantText(l) {
235
270
  if (l.type !== "assistant" || l.isSidechain === true)
@@ -245,10 +280,22 @@ export function assistantText(l) {
245
280
  .filter((t) => t.trim());
246
281
  return parts.length ? parts.join("\n") : null;
247
282
  }
248
- /** The plain text a person typed (a string, or text blocks only), or null for tool results and meta lines. */
283
+ /**
284
+ * The plain text a person typed (a string, or text blocks only), or null for
285
+ * tool results, meta lines and the user lines Claude Code writes itself: a
286
+ * compaction summary, a line only the transcript shows, a turn that no
287
+ * person started (a task notice, another session, a continuation), the mark
288
+ * of an interrupted turn. Found live on 2026-11-14: a session's "last
289
+ * message" in Bridge was the start of a compaction summary. A context block
290
+ * the app put before the typed text is cut off, the typed text stays.
291
+ */
249
292
  export function userText(l) {
250
293
  if (l.type !== "user" || l.isSidechain === true || l.isMeta === true)
251
294
  return null;
295
+ if (l.isCompactSummary === true || l.isVisibleInTranscriptOnly === true)
296
+ return null;
297
+ if (!byAPerson(l))
298
+ return null;
252
299
  const c = l.message?.content;
253
300
  let text;
254
301
  if (typeof c === "string")
@@ -262,6 +309,12 @@ export function userText(l) {
262
309
  return null;
263
310
  if (!text.trim() || META_PREFIX.test(text))
264
311
  return null;
312
+ // Each leading context block whole, or not at all (one that never closes stays: nothing typed is lost).
313
+ for (let m = LEAD_BLOCK.exec(text); m !== null; m = LEAD_BLOCK.exec(text))
314
+ text = text.slice(m[0].length);
315
+ // What is behind the blocks can still be a command or a system line.
316
+ if (!text.trim() || META_PREFIX.test(text) || INTERRUPTED.test(text.trim()))
317
+ return null;
265
318
  return text;
266
319
  }
267
320
  const isoOf = (v) => {
@@ -362,34 +415,103 @@ export function readHistory(fs, file, home) {
362
415
  const lines = readTail(fs, file, st.size, (ls) => historyFrom(ls, home).length >= HISTORY_MAX);
363
416
  return historyFrom(lines, home);
364
417
  }
365
- /** null: no registry on this computer (or not readable): the 10 minute fallback applies. */
366
- function readRegistry(fs, home) {
418
+ const realPidDomainReaders = {
419
+ hostname: () => hostname(),
420
+ machineId: () => readFileSync("/etc/machine-id", "utf8"),
421
+ pidNs: () => readlinkSync("/proc/self/ns/pid"),
422
+ };
423
+ /**
424
+ * This runner's own pid space, as Claude Code writes it in pidDomain (read
425
+ * from Claude Code's own code):
426
+ * - win32: "win32:" + the host name in lower case;
427
+ * - linux (also WSL): "linux:" + /etc/machine-id (trimmed) + ":" + the link
428
+ * text of /proc/self/ns/pid; a part that cannot be read is empty, and the
429
+ * name is still built (Claude Code does the same, so the two still match);
430
+ * - any other system (macOS): the platform name alone.
431
+ * null (unknown) only when the host name cannot be read. An unknown own
432
+ * domain is doubt: every entry that names a pid space then counts as foreign
433
+ * (foreignEntry), and the runner does not continue sessions in place.
434
+ *
435
+ * Where these forms come from: the Windows form was read from the Windows
436
+ * build of Claude Code 2.1.319 and is proven by the live check. The Linux and
437
+ * other forms are inferred from the same code (that build folds
438
+ * process.platform), not read from a Linux or a macOS build. They are not
439
+ * used to continue a session in place (Windows only for now), and must be
440
+ * read from a Linux and a macOS build before resume_local goes on there.
441
+ */
442
+ export function ownPidDomain(platform = process.platform, read = realPidDomainReaders) {
443
+ try {
444
+ if (platform === "win32")
445
+ return `win32:${read.hostname().toLowerCase()}`;
446
+ if (platform === "linux") {
447
+ const part = (get) => {
448
+ try {
449
+ return get();
450
+ }
451
+ catch {
452
+ return "";
453
+ }
454
+ };
455
+ return `linux:${part(read.machineId).trim()}:${part(read.pidNs)}`;
456
+ }
457
+ return platform;
458
+ }
459
+ catch {
460
+ return null;
461
+ }
462
+ }
463
+ /**
464
+ * An entry written in another pid space (WSL, a container, a shared home):
465
+ * its pid means nothing here. An entry with no pidDomain is never foreign.
466
+ * When this runner's own domain is unknown (null), every entry that names a
467
+ * pid space counts as foreign: doubt means open.
468
+ */
469
+ const foreignEntry = (e, domain) => e.pidDomain !== null && (domain === null || e.pidDomain !== domain);
470
+ /**
471
+ * The one per-session rule: this entry holds its session now. It comes
472
+ * from another pid space, has no usable pid, or its pid runs here. Used by
473
+ * sessionOpen, by openedByOther and by the cards (live), so the page and the
474
+ * check agree.
475
+ */
476
+ export function holds(e, domain, pidAlive) {
477
+ return foreignEntry(e, domain) || e.pid === null || pidAlive(e.pid);
478
+ }
479
+ /**
480
+ * A starting program may be half way through writing its registry file in
481
+ * this window. An unparsed file older than this is a leftover of a program
482
+ * that died: its pid number may already belong to another program (Windows
483
+ * reuses pids fast), so it never counts.
484
+ */
485
+ export const REGISTRY_FRESH_MS = 120_000;
486
+ /** null: no registry on this computer, or it cannot be read or LISTED (never taken as empty). */
487
+ function readLiveRegistry(fs, home) {
367
488
  const dir = join(home, ".claude", "sessions");
368
489
  const st = fs.lstat(dir);
369
490
  if (!st || !st.isDirectory || st.isSymbolicLink)
370
491
  return null;
371
- const out = new Map();
372
- for (const e of fs.readdir(dir)) {
492
+ let names;
493
+ try {
494
+ names = fs.list(dir);
495
+ }
496
+ catch {
497
+ return null;
498
+ }
499
+ const out = { entries: new Map(), list: [], files: 0, unparsed: [] };
500
+ for (const e of names) {
373
501
  if (!e.isFile || e.isSymbolicLink || !/^\d{1,10}\.json$/.test(e.name))
374
502
  continue;
503
+ out.files += 1;
504
+ const filePid = Number(e.name.slice(0, -".json".length));
375
505
  const file = join(dir, e.name);
376
- const fst = fs.lstat(file);
377
- if (!fst || !fst.isFile || fst.isSymbolicLink || fst.size > REGISTRY_FILE_MAX)
506
+ const v = readEntry(fs, file);
507
+ if (!v || typeof v.sessionId !== "string" || !UUID_RE.test(v.sessionId)) {
508
+ const fst = fs.lstat(file);
509
+ if (filePid > 0 && fst)
510
+ out.unparsed.push({ pid: filePid, mtimeMs: fst.mtimeMs, size: fst.size });
378
511
  continue;
379
- let v;
380
- try {
381
- const parsed = JSON.parse(fs.readText(file) ?? "");
382
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
383
- continue;
384
- v = parsed;
385
512
  }
386
- catch {
387
- continue;
388
- }
389
- if (typeof v.sessionId !== "string" || !UUID_RE.test(v.sessionId))
390
- continue;
391
513
  const pid = typeof v.pid === "number" && Number.isInteger(v.pid) && v.pid > 0 ? v.pid : null;
392
- out.set(v.sessionId, {
514
+ const entry = {
393
515
  pid,
394
516
  sessionId: v.sessionId,
395
517
  cwd: typeof v.cwd === "string" && v.cwd ? v.cwd : null,
@@ -397,10 +519,99 @@ function readRegistry(fs, home) {
397
519
  status: typeof v.status === "string" ? v.status : null,
398
520
  updatedAt: typeof v.updatedAt === "number" && Number.isFinite(v.updatedAt) ? v.updatedAt : null,
399
521
  entrypoint: typeof v.entrypoint === "string" ? v.entrypoint : null,
400
- });
522
+ pidDomain: typeof v.pidDomain === "string" && v.pidDomain.trim() ? v.pidDomain.trim() : null,
523
+ };
524
+ out.entries.set(v.sessionId, entry);
525
+ out.list.push(entry);
401
526
  }
402
527
  return out;
403
528
  }
529
+ /** One registry file as an object, or null (missing, a link, too big, not JSON, not an object). */
530
+ function readEntry(fs, file) {
531
+ const fst = fs.lstat(file);
532
+ if (!fst || !fst.isFile || fst.isSymbolicLink || fst.size > REGISTRY_FILE_MAX)
533
+ return null;
534
+ try {
535
+ const parsed = JSON.parse(fs.readText(file) ?? "");
536
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
537
+ return null;
538
+ return parsed;
539
+ }
540
+ catch {
541
+ return null;
542
+ }
543
+ }
544
+ /**
545
+ * True when the session is open on this computer now: a program holds it.
546
+ * Read fresh, every time. Doubt means open:
547
+ * - the registry folder cannot be read (missing, a link, a file);
548
+ * - no entry parses and at least one entry file is not empty (for example
549
+ * a new entry shape after a Claude Code update);
550
+ * - an entry for this session has no usable pid, or comes from another pid
551
+ * space (its pidDomain is not this runner's: WSL, a container, a shared
552
+ * home), whatever its pid;
553
+ * - a file that does not parse belongs to a pid that still runs, and it is
554
+ * not empty (at any age) or it is empty but fresh (120 s: a starting
555
+ * program may be half way through writing it).
556
+ * An entry whose pid is gone (stale) does not count. A file that does not
557
+ * parse is ignored when its pid is dead, or when it is empty and old (a
558
+ * leftover of a program that died; its pid number may be reused). Only
559
+ * <pid>.json files are entries; other files in the folder are ignored.
560
+ */
561
+ export function sessionOpen(fs, home, claudeSessionId, pidAlive, now = Date.now(), domain = ownPidDomain()) {
562
+ const reg = readLiveRegistry(fs, home);
563
+ if (!reg)
564
+ return true;
565
+ if (reg.list.length === 0 && reg.unparsed.some((u) => u.size > 0))
566
+ return true;
567
+ for (const e of reg.list)
568
+ if (e.sessionId === claudeSessionId && holds(e, domain, pidAlive))
569
+ return true;
570
+ return reg.unparsed.some((u) => pidAlive(u.pid) && (u.size > 0 || now - u.mtimeMs <= REGISTRY_FRESH_MS));
571
+ }
572
+ /**
573
+ * During the runner's own turn on a session from the computer: true when
574
+ * someone else opened it too. The runner's own claude -p shows as one live
575
+ * entry with entrypoint sdk-cli; anything more is someone else: two or more
576
+ * live entries for the id, a live entry with another known entrypoint (for
577
+ * example cli), or an entry from another pid space. An entry with no
578
+ * entrypoint is unknown: one alone stops nothing. Live: its pid runs, it has
579
+ * no pid, or it is foreign.
580
+ * Only parsed entries count here (a half written file may be the runner's
581
+ * own claude starting); a folder that cannot be read stops nothing.
582
+ */
583
+ export function openedByOther(fs, home, claudeSessionId, pidAlive, domain = ownPidDomain(),
584
+ /** The pid of the runner's own claude for this turn, when known (runClaude's onSpawn). */
585
+ ownPid) {
586
+ const reg = readLiveRegistry(fs, home);
587
+ if (!reg)
588
+ return false;
589
+ const live = reg.list.filter((e) => e.sessionId === claudeSessionId && holds(e, domain, pidAlive));
590
+ // The runner's own claude, by its pid AND in this pid space, is in the
591
+ // registry: that entry never counts, whatever its entrypoint, and any other
592
+ // live entry is someone else (also one with entrypoint sdk-cli). An entry
593
+ // with that pid from another pid space is not the runner's own.
594
+ const own = (e) => ownPid !== undefined && e.pid === ownPid && !foreignEntry(e, domain);
595
+ if (reg.list.some((e) => e.sessionId === claudeSessionId && own(e)))
596
+ return live.some((e) => !own(e));
597
+ // No entrypoint (null or empty) is unknown: one such entry alone is taken as the runner's own claude.
598
+ const known = (e) => typeof e.entrypoint === "string" && e.entrypoint !== "" && e.entrypoint !== "sdk-cli";
599
+ return live.length > 1 || live.some((e) => foreignEntry(e, domain) || known(e));
600
+ }
601
+ /** True when Claude Code's live registry folder can be read here: a real folder (not a link) that lists (on the given fs). */
602
+ export function registryReadable(fs, home) {
603
+ const dir = join(home, ".claude", "sessions");
604
+ try {
605
+ const st = fs.lstat(dir);
606
+ if (!st || !st.isDirectory || st.isSymbolicLink)
607
+ return false;
608
+ fs.list(dir);
609
+ return true;
610
+ }
611
+ catch {
612
+ return false;
613
+ }
614
+ }
404
615
  /** Real pid check: signal 0 asks the system whether the process exists. */
405
616
  export function pidAlive(pid) {
406
617
  try {
@@ -432,7 +643,13 @@ export class SessionScanner {
432
643
  const caseless = platform === "win32";
433
644
  const norm = (s) => (caseless ? s.toLowerCase() : s);
434
645
  const projectsRoot = join(home, ".claude", "projects");
435
- const registry = readRegistry(fs, home);
646
+ const reg = readLiveRegistry(fs, home);
647
+ const registry = reg?.entries ?? null;
648
+ const domain = input.domain === undefined ? ownPidDomain(platform) : input.domain;
649
+ const foreignAware = input.foreignAware ?? platform === "win32";
650
+ // The pid space an entry is judged against: this runner's own, or, where
651
+ // pid spaces are not told apart, the entry's own (so it is never foreign).
652
+ const against = (e) => (foreignAware ? domain : e.pidDomain);
436
653
  const since = now - input.sessions.recentDays * 24 * 3600_000;
437
654
  // 1. Candidate project folders: the encoded prefix of each allowed folder.
438
655
  const prefixes = [...input.folders.values()].map((abs) => norm(encodeCwd(abs)));
@@ -460,10 +677,24 @@ export class SessionScanner {
460
677
  }
461
678
  }
462
679
  }
463
- // 2. Every live registry entry (its process still runs), wherever its transcript is.
680
+ // 2. From ALL parsed registry entries (also two for one session):
681
+ // - held: every session with an entry that holds it (holds(), the same
682
+ // rule as sessionOpen), so the card's live flag and the check agree;
683
+ // - alive: an entry of this pid space whose pid runs here. It stays the
684
+ // only source of cwd, name, status and entrypoint, and it adds its
685
+ // session as a candidate wherever its transcript is.
686
+ // The two doubt rules of sessionOpen that hold EVERY session (no entry
687
+ // parses; an unparsed file of a live pid) do not go on the cards, by design:
688
+ // they say "cannot tell", not "this session is open".
689
+ // Another pid space counts only where foreignAware is on (Windows by
690
+ // default, the one system that continues a session in place): there the
691
+ // card and the check agree for each session.
692
+ const held = new Set();
464
693
  const alive = new Map();
465
- for (const e of registry?.values() ?? []) {
466
- if (e.pid === null || !input.pidAlive(e.pid))
694
+ for (const e of reg?.list ?? []) {
695
+ if (holds(e, against(e), input.pidAlive))
696
+ held.add(e.sessionId);
697
+ if (foreignEntry(e, against(e)) || e.pid === null || !input.pidAlive(e.pid))
467
698
  continue;
468
699
  alive.set(e.sessionId, e);
469
700
  if (!e.cwd)
@@ -482,7 +713,7 @@ export class SessionScanner {
482
713
  const known = new Map();
483
714
  const seenFiles = new Set();
484
715
  for (const c of candidates.values()) {
485
- const built = this.card(c, input, fs, platform, registry, alive, seenFiles);
716
+ const built = this.card(c, input, fs, platform, registry, alive, held, seenFiles);
486
717
  if (!built)
487
718
  continue;
488
719
  cards.push(built.card);
@@ -503,7 +734,7 @@ export class SessionScanner {
503
734
  known.delete(id);
504
735
  return { cards: out, known };
505
736
  }
506
- card(c, input, fs, platform, registry, alive, seenFiles) {
737
+ card(c, input, fs, platform, registry, alive, held, seenFiles) {
507
738
  const { home, now } = input;
508
739
  const st = fs.lstat(c.file);
509
740
  if (!st || !st.isFile || st.isSymbolicLink || st.size === 0)
@@ -539,7 +770,10 @@ export class SessionScanner {
539
770
  return null;
540
771
  // `claude -p` sessions only when this runner started them.
541
772
  const entrypoint = live?.entrypoint ?? head().entrypoint ?? item.tail.entrypoint;
542
- if (!input.started.has(c.id) && (entrypoint === null || entrypoint === "sdk-cli"))
773
+ // A session from the computer that this runner continues in place is still one from the computer
774
+ // (not started here), but while its turn runs the registry names the claude -p process.
775
+ const own = input.started.has(c.id) || Boolean(input.resumed?.has(c.id));
776
+ if (!own && (entrypoint === null || entrypoint === "sdk-cli"))
543
777
  return null;
544
778
  const tail = item.tail;
545
779
  // Title: the registry name, else the last custom title, else the first user text (80), else "Session".
@@ -561,17 +795,20 @@ export class SessionScanner {
561
795
  isLive = true;
562
796
  state = live.status === "busy" ? "working" : "idle";
563
797
  }
564
- else if (registry && !registry.has(c.id)) {
565
- isLive = false;
566
- state = "closed";
798
+ else if (held.has(c.id)) {
799
+ // Held, but by no entry of this pid space whose pid runs here (another
800
+ // pid space, or no usable pid): open, idle; cwd, name and entrypoint came
801
+ // from the transcript, as for a closed one.
802
+ isLive = true;
803
+ state = "idle";
567
804
  }
568
- else if (registry && registry.get(c.id).pid !== null) {
569
- // In the registry with a pid that is gone.
805
+ else if (registry) {
806
+ // Not in the registry, or in it with a pid that is gone.
570
807
  isLive = false;
571
808
  state = "closed";
572
809
  }
573
810
  else {
574
- // No registry, or an entry without a pid: written in the last 10 minutes = live and idle.
811
+ // No registry: written in the last 10 minutes = live and idle.
575
812
  isLive = now - st.mtimeMs <= LIVE_FALLBACK_MS;
576
813
  state = isLive ? "idle" : "closed";
577
814
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@beatos/bridge-runner",
3
- "version": "0.9.0",
3
+ "version": "0.10.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",