@vibelord/lanes 1.6.1 → 1.7.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.
- package/package.json +1 -1
- package/payload/lanes/VERSION +1 -1
- package/payload/lanes/bin/lanes +602 -4
- package/payload/lanes/container/lane +185 -5
- package/payload/lanes/container/lane-mcp +319 -55
- package/payload/lanes/container/lane-peerd +704 -0
- package/payload/lanes/container/lane_core.py +2091 -12
- package/payload/lanes/docs/AGENTS-lanes.md +50 -0
- package/payload/lanes/docs/ARCHITECTURE.md +274 -33
- package/payload/lanes/docs/DESIGN.md +7 -3
- package/payload/lanes/docs/RUNBOOK.md +295 -13
- package/payload/lanes/docs/USERGUIDE.md +218 -29
- package/payload/lanes/libexec/agent_state.py +338 -15
- package/payload/lanes/libexec/attach.py +154 -14
- package/payload/lanes/libexec/lanes_lib.py +429 -8
- package/payload/lanes/libexec/sidebar.py +464 -43
- package/payload/lanes/libexec/statusd.py +764 -34
- package/payload/lanes/libexec/tokens.py +14 -0
- package/payload/lanes/systemd/lanes-statusd.service +1 -1
- package/payload/manifest.json +4 -3
|
@@ -811,6 +811,33 @@ def repo_roots(cwd, root):
|
|
|
811
811
|
here = posixpath.dirname(here)
|
|
812
812
|
|
|
813
813
|
|
|
814
|
+
# The one `list-panes -a -F PANE_FORMAT` row of Lanes: statusd's probe (`statusd.FIELDS` is this list) and the pane
|
|
815
|
+
# binding of `rename_claude` read the same columns.
|
|
816
|
+
PANE_FIELDS = ['session_name', 'pane_pid', 'pane_dead', 'window_activity', 'pane_current_command',
|
|
817
|
+
'pane_current_path', 'window_width', 'window_height', 'session_attached', 'pane_tty',
|
|
818
|
+
'session_id', 'session_created',
|
|
819
|
+
# Alignment contract A4a: the group a session is attached onto (a Throttle Studio browser view is a
|
|
820
|
+
# grouped session), and which pane of which window represents the session's state.
|
|
821
|
+
'session_group', 'pane_active', 'window_active',
|
|
822
|
+
# Task 5 (`agent{}`): the window bell, the ids a Claude session file names its pane by
|
|
823
|
+
# (`<session>:@<win>.%<pane>`), and the pane title Codex writes its status into. APPENDED, so every
|
|
824
|
+
# column above keeps its index; the title is the one free-text column and comes LAST, so a tab inside it
|
|
825
|
+
# stays in the title (the row is split at most len(PANE_FIELDS) - 1 times) instead of shifting the ids.
|
|
826
|
+
'window_bell_flag', 'window_id', 'pane_id', 'pane_title']
|
|
827
|
+
PANE_FORMAT = '\t'.join('#{' + f + '}' for f in PANE_FIELDS)
|
|
828
|
+
|
|
829
|
+
|
|
830
|
+
def pane_rows(text):
|
|
831
|
+
"""The rows of a `list-panes -F PANE_FORMAT` answer as dicts (a tab inside the title stays in the title); a line
|
|
832
|
+
with fewer columns than PANE_FIELDS is not one of ours and is skipped."""
|
|
833
|
+
rows = []
|
|
834
|
+
for line in (text or '').splitlines():
|
|
835
|
+
values = line.split('\t', len(PANE_FIELDS) - 1)
|
|
836
|
+
if len(values) == len(PANE_FIELDS):
|
|
837
|
+
rows.append(dict(zip(PANE_FIELDS, values)))
|
|
838
|
+
return rows
|
|
839
|
+
|
|
840
|
+
|
|
814
841
|
def tmux_socket(info, socket_name):
|
|
815
842
|
return f"/proc/{info['pid']}/root/tmp/tmux-{CONTAINER_UID}/{socket_name}"
|
|
816
843
|
|
|
@@ -1368,6 +1395,367 @@ def lane_id_for(workspace_id, lane):
|
|
|
1368
1395
|
return f"{workspace_id}--{slug(lane.get('registry_name') or lane['name'])}"
|
|
1369
1396
|
|
|
1370
1397
|
|
|
1398
|
+
# ------------------------------------------------------------------ addresses (W15 L2, L2b, L2c, L2d)
|
|
1399
|
+
# A lane's registered messaging address (DM-LANES-ADDRESS-SETTINGS) is `<board>.<slug>`: its id `<board>--<slug>` with
|
|
1400
|
+
# the board separator turned into a dot. That is the form Claude Code 2.1.310 keeps as a session name (MEASURED
|
|
1401
|
+
# 2026-10-25: `/rename worlds.worlds-packages` was kept, `/rename worlds--worlds-packages` was refused and an
|
|
1402
|
+
# auto-generated name used instead; `-n/--name` takes the same names at launch). An adopted session's
|
|
1403
|
+
# `<board>--x-<slug>-<digest>` id gives `<board>.x-<slug>-<digest>` the same way, a zmx lane's `<board>--z-<name>` gives
|
|
1404
|
+
# `<board>.z-<name>`. The id itself never changes. A board manifest (`workspaces.<board>.json`, DM-LANES-CATALOG) may
|
|
1405
|
+
# give a declared terminal another address (`addresses: {<terminal name>: "<board>.<alias>"}`) and name the board's
|
|
1406
|
+
# coordinator (`coordinator: <terminal name>`); site.conf names the fleet admin by address
|
|
1407
|
+
# (LANES_FLEET_ADMIN=@<address>) and whether statusd keeps the Claude lanes' session names equal to their addresses
|
|
1408
|
+
# (LANES_NAMES_AUTO, default on). `lanes address`, `lanes names sync` and `lanes migrate addresses` (bin/lanes) are the
|
|
1409
|
+
# writers; `build_registry` the reader.
|
|
1410
|
+
ADDRESS_ALIAS = re.compile(r'[a-z0-9][a-z0-9._-]*\Z')
|
|
1411
|
+
ADDRESS_MAX = 128 # characters of a whole address, the board id included
|
|
1412
|
+
ROLES = ('coordinator', 'fleet-admin')
|
|
1413
|
+
FLEET_ADMIN_KEY, NAMES_AUTO_KEY = 'LANES_FLEET_ADMIN', 'LANES_NAMES_AUTO'
|
|
1414
|
+
DEFAULT_FLEET_ADMIN = 'fleet-management.fleet-management' # the operator's designation, 2026-10-25
|
|
1415
|
+
|
|
1416
|
+
|
|
1417
|
+
def address_of(lane_id, manifest_overrides=None, board=None):
|
|
1418
|
+
"""The registered address of `lane_id`: `manifest_overrides[lane_id]` when its board's manifest gives it one (the
|
|
1419
|
+
overrides resolved to lane ids), else derived — the id with its board separator `--` turned into `.`. `board`, when
|
|
1420
|
+
given and the id starts with `<board>--`, says where the board id ends; else the first `--` is the separator. An
|
|
1421
|
+
id without `--` is its own address. Pure."""
|
|
1422
|
+
explicit = (manifest_overrides or {}).get(lane_id)
|
|
1423
|
+
if isinstance(explicit, str) and explicit:
|
|
1424
|
+
return explicit
|
|
1425
|
+
if board and lane_id.startswith(board + '--'):
|
|
1426
|
+
return f'{board}.{lane_id[len(board) + 2:]}'
|
|
1427
|
+
head, separator, tail = lane_id.partition('--')
|
|
1428
|
+
return f'{head}.{tail}' if separator else lane_id
|
|
1429
|
+
|
|
1430
|
+
|
|
1431
|
+
def parse_address(text):
|
|
1432
|
+
"""An address as a person types it: one leading `@` dropped (`@sakio.coordinator`); '' for no text."""
|
|
1433
|
+
text = text if isinstance(text, str) else ''
|
|
1434
|
+
return text[1:] if text.startswith('@') else text
|
|
1435
|
+
|
|
1436
|
+
|
|
1437
|
+
def check_address(board, value):
|
|
1438
|
+
"""`value` as an explicit address of a lane of `board` -> `value`. LanesError unless it is `<board>.<alias>` with
|
|
1439
|
+
the alias in ADDRESS_ALIAS (lower-case letters, digits, `.`, `_`, `-`, starting with a letter or digit), at most
|
|
1440
|
+
ADDRESS_MAX characters, and without `--` — Claude refuses a session name holding `--`, so such an address could
|
|
1441
|
+
never be the lane's messaging name."""
|
|
1442
|
+
if (not isinstance(value, str) or not value.startswith(f'{board}.') or len(value) > ADDRESS_MAX
|
|
1443
|
+
or not ADDRESS_ALIAS.match(value[len(board) + 1:]) or '--' in value):
|
|
1444
|
+
raise LanesError(f'{board}: invalid address {value!r} — an address is {board}.<alias> (a-z 0-9 . _ -, starting '
|
|
1445
|
+
f'with a letter or digit, no "--", at most {ADDRESS_MAX} characters)')
|
|
1446
|
+
return value
|
|
1447
|
+
|
|
1448
|
+
|
|
1449
|
+
def board_settings(manifest, board, lanes):
|
|
1450
|
+
"""The address settings of one board manifest, checked against the board's declared `lanes` (`_workspace_lanes`'s,
|
|
1451
|
+
keyed by `registry_name`: the declared terminal name with its repository prefix) -> (overrides {terminal name:
|
|
1452
|
+
address}, coordinator terminal name or None). LanesError — a board error: `build_registry` keeps that board's
|
|
1453
|
+
previous lanes, the other boards are not touched — for an `addresses` that is no object, an address
|
|
1454
|
+
`check_address` refuses, one address given to two terminals, or a `coordinator` that is no terminal name of this
|
|
1455
|
+
board. An `addresses` key that names no terminal is kept but addresses nothing (a terminal removed since; `lanes
|
|
1456
|
+
doctor` lists it), and every other manifest key is left alone (SITE_SCHEMA is unchanged)."""
|
|
1457
|
+
raw = manifest.get('addresses')
|
|
1458
|
+
if raw is None:
|
|
1459
|
+
raw = {}
|
|
1460
|
+
if not isinstance(raw, dict):
|
|
1461
|
+
raise LanesError(f'{board}: "addresses" must be an object of terminal name -> address')
|
|
1462
|
+
overrides, owners = {}, {}
|
|
1463
|
+
for name, value in raw.items():
|
|
1464
|
+
overrides[name] = check_address(board, value)
|
|
1465
|
+
if owners.setdefault(value, name) != name:
|
|
1466
|
+
raise LanesError(f'{board}: address {value!r} is given to two terminals: {owners[value]!r} and {name!r}')
|
|
1467
|
+
coordinator = manifest.get('coordinator')
|
|
1468
|
+
names = {lane.get('registry_name') for lane in lanes if lane.get('registry_name')}
|
|
1469
|
+
if coordinator is not None and (not isinstance(coordinator, str) or coordinator not in names):
|
|
1470
|
+
raise LanesError(f'{board}: coordinator {coordinator!r} names no terminal of this board '
|
|
1471
|
+
f'(lanes address set-coordinator {board} <lane-id>)')
|
|
1472
|
+
return overrides, coordinator
|
|
1473
|
+
|
|
1474
|
+
|
|
1475
|
+
def address_site(home=None):
|
|
1476
|
+
"""(fleet admin address or None, names_auto) from site.conf (`site_conf`): LANES_FLEET_ADMIN=@<address> — the `@`
|
|
1477
|
+
optional; a value outside the lane id grammar or holding `--` is no address (None) — and LANES_NAMES_AUTO, on
|
|
1478
|
+
unless it is `0`."""
|
|
1479
|
+
site = site_conf(home)
|
|
1480
|
+
fleet = parse_address(site.get(FLEET_ADMIN_KEY))
|
|
1481
|
+
usable = bool(fleet) and bool(IDENT.match(fleet)) and '--' not in fleet and len(fleet) <= ADDRESS_MAX
|
|
1482
|
+
return (fleet if usable else None), site.get(NAMES_AUTO_KEY, '1') != '0'
|
|
1483
|
+
|
|
1484
|
+
|
|
1485
|
+
def apply_addresses(registry, strict=True):
|
|
1486
|
+
"""Give every lane of `registry` its `address` and `role` (None, 'coordinator' or 'fleet-admin' — a coordinator
|
|
1487
|
+
that is also the fleet admin is published 'fleet-admin'), from the facts `build_registry` stores: each board's
|
|
1488
|
+
`address_overrides` ({terminal name: address}) and `coordinator` (a lane id), and the site's `fleet_admin`. A
|
|
1489
|
+
registry that an action republishes (registrations: an adopted lane is rebuilt from its record, with neither key)
|
|
1490
|
+
is addressed exactly as the sync addressed it. In place. -> [(address, first lane id, second lane id)] for every
|
|
1491
|
+
address two lanes claim; `strict` (a sync) raises LanesError naming both lanes of the first instead."""
|
|
1492
|
+
fleet = registry.get('fleet_admin')
|
|
1493
|
+
owners, clashes = {}, []
|
|
1494
|
+
for workspace in registry.get('workspaces') or []:
|
|
1495
|
+
overrides = workspace.get('address_overrides') or {}
|
|
1496
|
+
coordinator = workspace.get('coordinator')
|
|
1497
|
+
for lane in workspace.get('lanes') or []:
|
|
1498
|
+
name = None if lane.get('registered_session') else lane.get('registry_name')
|
|
1499
|
+
explicit = overrides.get(name) if name else None
|
|
1500
|
+
lane['address'] = explicit if isinstance(explicit, str) and explicit else \
|
|
1501
|
+
address_of(lane['id'], board=workspace.get('id'))
|
|
1502
|
+
lane['role'] = ('fleet-admin' if fleet and lane['address'] == fleet else
|
|
1503
|
+
'coordinator' if coordinator and lane['id'] == coordinator else None)
|
|
1504
|
+
first = owners.setdefault(lane['address'], lane['id'])
|
|
1505
|
+
if first != lane['id']:
|
|
1506
|
+
clashes.append((lane['address'], first, lane['id']))
|
|
1507
|
+
if clashes and strict:
|
|
1508
|
+
address, first, second = clashes[0]
|
|
1509
|
+
raise LanesError(f'Address {address} is claimed by two lanes: {first} and {second} — give one of them another '
|
|
1510
|
+
'address (lanes address set <lane-id> <board>.<alias>)')
|
|
1511
|
+
return clashes
|
|
1512
|
+
|
|
1513
|
+
|
|
1514
|
+
def lane_addresses(registry):
|
|
1515
|
+
"""{lane id: (address, role)} of every lane `registry` lists, as published: the lane's own `address`/`role`, else
|
|
1516
|
+
(a registry.json written before addresses existed) the derived address and no role. statusd's per-lane rows read
|
|
1517
|
+
it once per registry load."""
|
|
1518
|
+
out = {}
|
|
1519
|
+
for workspace in (registry or {}).get('workspaces') or []:
|
|
1520
|
+
for lane in workspace.get('lanes') or []:
|
|
1521
|
+
address = lane.get('address')
|
|
1522
|
+
if not (isinstance(address, str) and address):
|
|
1523
|
+
address = address_of(lane['id'], board=workspace.get('id'))
|
|
1524
|
+
out.setdefault(lane['id'], (address, lane.get('role') if lane.get('role') in ROLES else None))
|
|
1525
|
+
return out
|
|
1526
|
+
|
|
1527
|
+
|
|
1528
|
+
def boards_document(registry):
|
|
1529
|
+
"""The export's `boards`: {board: {coordinator: lane id or None, address: board}} — `@<board>` reaches the board's
|
|
1530
|
+
coordinator."""
|
|
1531
|
+
return {workspace['id']: {'coordinator': workspace.get('coordinator'), 'address': workspace['id']}
|
|
1532
|
+
for workspace in registry.get('workspaces') or []}
|
|
1533
|
+
|
|
1534
|
+
|
|
1535
|
+
# Name parity (W15 L2c): a Claude lane's session name — what `ListAgents`/`SendMessage` show — is its address. `lanes
|
|
1536
|
+
# names sync` and statusd's retry type `/rename <address>` + Enter into a Claude lane at its prompt, never into one that
|
|
1537
|
+
# works, waits on a dialog or delegates.
|
|
1538
|
+
NAMES_IDLE = ('needs_input', 'idle', 'done') # agent_state.DELEGATING_FROM: the words of a Claude whose turn is over
|
|
1539
|
+
NAMES_RETRY_S = 120 # statusd retries one lane at most this often
|
|
1540
|
+
NAMES_ACTIVE_S = 20 # statusd.ACTIVE_WINDOW: output this recent = a person may be typing
|
|
1541
|
+
CLAUDE_SESSIONS = ('.claude', 'sessions') # under the container home
|
|
1542
|
+
PANE_ID = re.compile(r'%[0-9]+\Z')
|
|
1543
|
+
# The recipient-scoped dispatch lock (BEY-6838): every process that types into a lane's agent — `rename_claude` here,
|
|
1544
|
+
# and W15 part 2's `lane_core.message`, lane-peerd and statusd's inbox drain — holds an exclusive flock(2) on the
|
|
1545
|
+
# container file ~/.lz/state/dispatch/<lane id>.lock (directory 0700, file 0600, created if absent; from the host
|
|
1546
|
+
# /proc/<init pid>/root/home/coder/.lz/state/dispatch/<lane id>.lock) across its last check of the recipient, the text
|
|
1547
|
+
# and the Enter, waiting at most DISPATCH_WAIT_S for it; not taken in time, nothing is typed (`deferred`).
|
|
1548
|
+
DISPATCH_DIR = ('.lz', 'state', 'dispatch') # under the container home
|
|
1549
|
+
DISPATCH_WAIT_S = 5.0
|
|
1550
|
+
DISPATCH_POLL_S = 0.05
|
|
1551
|
+
|
|
1552
|
+
|
|
1553
|
+
def names_plan(registry, status, board=None, unattached=False):
|
|
1554
|
+
"""Which Claude lanes' session names differ from their addresses, and which of them may be renamed now -> (todo,
|
|
1555
|
+
deferred, matched): todo [(board id, lane, status row)], deferred [(board id, lane, why)], matched = how many
|
|
1556
|
+
Claude lanes' names already are their addresses. Only registry tmux lanes (declared and adopted) of `board` (all
|
|
1557
|
+
when None) whose published agent{} is Claude's with `name_match` False or None are considered: todo when the row
|
|
1558
|
+
was observed this cycle (not stale), its status is one of NAMES_IDLE, it is not delegating and its state is not
|
|
1559
|
+
`active` (output within NAMES_ACTIVE_S: a person may be typing); `unattached` (statusd's retry, which no person
|
|
1560
|
+
asked for) also defers a lane a terminal is attached to. Pure."""
|
|
1561
|
+
rows = (status or {}).get('lanes') or {}
|
|
1562
|
+
todo, deferred, matched = [], [], 0
|
|
1563
|
+
for workspace in (registry or {}).get('workspaces') or []:
|
|
1564
|
+
if board and workspace['id'] != board:
|
|
1565
|
+
continue
|
|
1566
|
+
for lane in workspace.get('lanes') or []:
|
|
1567
|
+
if lane.get('holder') != 'tmux' or not lane.get('container') or not lane.get('tmux'):
|
|
1568
|
+
continue
|
|
1569
|
+
row = rows.get(lane['id'])
|
|
1570
|
+
agent = row.get('agent') if isinstance(row, dict) else None
|
|
1571
|
+
if not isinstance(agent, dict) or agent.get('harness') != 'claude':
|
|
1572
|
+
continue
|
|
1573
|
+
if agent.get('name_match') is True:
|
|
1574
|
+
matched += 1
|
|
1575
|
+
continue
|
|
1576
|
+
why = None
|
|
1577
|
+
if row.get('stale') or row.get('state') in (None, 'unknown', 'absent', 'missing', 'dead'):
|
|
1578
|
+
why = 'not observed this cycle'
|
|
1579
|
+
elif agent.get('activity') == 'delegating':
|
|
1580
|
+
why = 'delegating to background work'
|
|
1581
|
+
elif agent.get('status') not in NAMES_IDLE:
|
|
1582
|
+
why = {'working': 'working', 'needs_approval': 'waiting for an approval',
|
|
1583
|
+
'errored': 'errored'}.get(agent.get('status'), f"agent {agent.get('status')}")
|
|
1584
|
+
elif agent.get('name_match') is None:
|
|
1585
|
+
why = 'no Claude session name observed (no session file names its pane)'
|
|
1586
|
+
elif row.get('state') == 'active':
|
|
1587
|
+
why = f'output in the last {NAMES_ACTIVE_S} s (a person may be typing)'
|
|
1588
|
+
elif unattached and (row.get('attached') or 0) > 0:
|
|
1589
|
+
why = 'a terminal is attached (a person may be typing)'
|
|
1590
|
+
if why:
|
|
1591
|
+
deferred.append((workspace['id'], lane, why))
|
|
1592
|
+
else:
|
|
1593
|
+
todo.append((workspace['id'], lane, row))
|
|
1594
|
+
return todo, deferred, matched
|
|
1595
|
+
|
|
1596
|
+
|
|
1597
|
+
def names_pause(seconds):
|
|
1598
|
+
"""time.sleep between a typed `/rename` and its Enter, named so a test records it instead of waiting."""
|
|
1599
|
+
time.sleep(seconds)
|
|
1600
|
+
|
|
1601
|
+
|
|
1602
|
+
def _open_dispatch_lock(info, lane_id):
|
|
1603
|
+
"""(fd, None) of the container's ~/.lz/state/dispatch/<lane id>.lock opened read-write (created 0600 in a 0700
|
|
1604
|
+
directory when absent, every directory created when absent), or (None, why). Reached through /proc/<init
|
|
1605
|
+
pid>/root, every component walked without following a link and the file opened O_NOFOLLOW (through the magic root
|
|
1606
|
+
an absolute link would resolve on the HOST, DEF-1796); anything but a regular file there is refused."""
|
|
1607
|
+
if not IDENT.match(str(lane_id or '')):
|
|
1608
|
+
return None, f'the lane id {lane_id!r} cannot name a dispatch lock'
|
|
1609
|
+
name = f'{lane_id}.lock'
|
|
1610
|
+
flags = os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | getattr(os, 'O_CLOEXEC', 0)
|
|
1611
|
+
fd = lock = None
|
|
1612
|
+
try:
|
|
1613
|
+
fd = open_real_dir(Path(proc_root()) / str(info['pid']) / 'root', CONTAINER_HOME.strip('/').split('/'))
|
|
1614
|
+
for part in DISPATCH_DIR:
|
|
1615
|
+
try:
|
|
1616
|
+
child = os.open(part, _DIR_FLAGS | os.O_NOFOLLOW, dir_fd=fd)
|
|
1617
|
+
except FileNotFoundError:
|
|
1618
|
+
try:
|
|
1619
|
+
os.mkdir(part, 0o700, dir_fd=fd)
|
|
1620
|
+
except FileExistsError:
|
|
1621
|
+
pass
|
|
1622
|
+
child = os.open(part, _DIR_FLAGS | os.O_NOFOLLOW, dir_fd=fd)
|
|
1623
|
+
os.fchmod(child, 0o700)
|
|
1624
|
+
os.close(fd)
|
|
1625
|
+
fd = child
|
|
1626
|
+
try:
|
|
1627
|
+
lock = os.open(name, flags | os.O_CREAT | os.O_EXCL, 0o600, dir_fd=fd)
|
|
1628
|
+
os.fchmod(lock, 0o600)
|
|
1629
|
+
except FileExistsError:
|
|
1630
|
+
lock = os.open(name, flags, dir_fd=fd)
|
|
1631
|
+
if not stat.S_ISREG(os.fstat(lock).st_mode):
|
|
1632
|
+
os.close(lock)
|
|
1633
|
+
return None, f'~/.lz/state/dispatch/{name} is not a regular file'
|
|
1634
|
+
return lock, None
|
|
1635
|
+
except OSError as error:
|
|
1636
|
+
if lock is not None:
|
|
1637
|
+
os.close(lock)
|
|
1638
|
+
return None, f'~/.lz/state/dispatch/{name} cannot be opened ({error.strerror or error})'
|
|
1639
|
+
finally:
|
|
1640
|
+
if fd is not None:
|
|
1641
|
+
os.close(fd)
|
|
1642
|
+
|
|
1643
|
+
|
|
1644
|
+
@contextlib.contextmanager
|
|
1645
|
+
def dispatch_lock(info, lane_id, timeout=None):
|
|
1646
|
+
"""Hold the lane's dispatch lock (DISPATCH_DIR, BEY-6838) for the block: an exclusive flock(2), tried every
|
|
1647
|
+
DISPATCH_POLL_S s for at most `timeout` (DISPATCH_WAIT_S, read at the call) seconds. Yields None while it is held,
|
|
1648
|
+
else why it is not (another sender holds it, or the file cannot be opened) — the caller then types nothing. The lock
|
|
1649
|
+
belongs to the open file: a holder that dies releases it, and no child inherits it (O_CLOEXEC)."""
|
|
1650
|
+
timeout = DISPATCH_WAIT_S if timeout is None else timeout
|
|
1651
|
+
descriptor, why = _open_dispatch_lock(info, lane_id)
|
|
1652
|
+
if descriptor is None:
|
|
1653
|
+
yield f'the dispatch lock is not usable: {why}'
|
|
1654
|
+
return
|
|
1655
|
+
try:
|
|
1656
|
+
deadline = time.monotonic() + timeout
|
|
1657
|
+
while True:
|
|
1658
|
+
try:
|
|
1659
|
+
fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
1660
|
+
break
|
|
1661
|
+
except BlockingIOError:
|
|
1662
|
+
if time.monotonic() >= deadline:
|
|
1663
|
+
yield f'another sender holds the dispatch lock of {lane_id} (waited {timeout:g} s)'
|
|
1664
|
+
return
|
|
1665
|
+
time.sleep(DISPATCH_POLL_S)
|
|
1666
|
+
yield None
|
|
1667
|
+
finally:
|
|
1668
|
+
os.close(descriptor) # releases the lock
|
|
1669
|
+
|
|
1670
|
+
|
|
1671
|
+
def _claude_in_lane(info, socket, session, sessions, proc):
|
|
1672
|
+
"""The live Claude session files bound to a pane of tmux session `session` ON SERVER `socket` (BEY-6838) ->
|
|
1673
|
+
((records, index), None) or (None, failure): `index` = {pane key: the pane's root pid} from ONE `list-panes -a` of
|
|
1674
|
+
that server (only that session's rows), `records` = `agent_state.claude_files` bound by it — each file's process
|
|
1675
|
+
descends from the root process of the pane its `tmux` string names on THIS server. A file of another server whose
|
|
1676
|
+
local key is the same is not among them. tmux not answering is a failure: nothing can be typed."""
|
|
1677
|
+
import agent_state as AS # libexec; agent_state imports nothing of lanes_lib
|
|
1678
|
+
outcome, text = tmux_probe(info, socket, ['list-panes', '-a', '-F', PANE_FORMAT])
|
|
1679
|
+
if outcome != 'ok':
|
|
1680
|
+
return None, ('failed', f'tmux did not answer ({outcome}{": " + text if text else ""}): not typed')
|
|
1681
|
+
index = {}
|
|
1682
|
+
for row in pane_rows(text):
|
|
1683
|
+
if (row['session_name'] == session and PANE_ID.match(row['pane_id']) and row['pane_pid'].isdigit()
|
|
1684
|
+
and row['pane_dead'] != '1'):
|
|
1685
|
+
index[AS.pane_key(row)] = int(row['pane_pid'])
|
|
1686
|
+
return (AS.claude_files(sessions, proc, {socket: index}), index), None
|
|
1687
|
+
|
|
1688
|
+
|
|
1689
|
+
def rename_claude(lane, address, info):
|
|
1690
|
+
"""Type `/rename <address>` and Enter into the Claude session of one tmux `lane` -> (outcome, what happened):
|
|
1691
|
+
'renamed' (typed), 'named' (its name is the address already), 'deferred' (not now: nothing typed) or 'failed'
|
|
1692
|
+
(the container or its tmux did not take it). Decided NOW, from the lane's own tmux server and the container's own
|
|
1693
|
+
session files, never from status.json (up to a cycle old): typed only when exactly one live Claude session file is
|
|
1694
|
+
bound to a pane of the lane's session ON THE LANE'S SOCKET (`_claude_in_lane`: its process descends from that
|
|
1695
|
+
pane's root process — BEY-6838, a server of the same container holding a pane of the same local name no longer
|
|
1696
|
+
counts), that file carries `procStart`, Claude's own word in it is `idle` (at its prompt: never `busy`, never
|
|
1697
|
+
`waiting`, which is a dialog a typed line would answer), its name is not already `address` and its background work
|
|
1698
|
+
is not writing (`agent_state.claude_delegating`). Then, holding the lane's dispatch lock (`dispatch_lock`; not
|
|
1699
|
+
taken within DISPATCH_WAIT_S: deferred), it checks the recipient once more — the same pid with the same
|
|
1700
|
+
`procStart` alive, the same file still `idle` with the same `statusUpdatedAt`, bound to the same pane whose root
|
|
1701
|
+
process is the same — and only then types the text into that pane by its tmux pane id, and the Enter as a second
|
|
1702
|
+
client `lane_core.ENTER_DELAY` seconds later (DEF-1803) if the process is still the same. Never reads anything but
|
|
1703
|
+
the `<pid>.json` session files: the messaging key files beside them are not opened (DEF-1802)."""
|
|
1704
|
+
import agent_state as AS # libexec; agent_state imports nothing of lanes_lib
|
|
1705
|
+
if not info.get('pid'):
|
|
1706
|
+
return 'failed', 'container not running: not typed'
|
|
1707
|
+
tmux = lane.get('tmux') or {}
|
|
1708
|
+
socket, session = tmux.get('socket') or '', tmux.get('session') or ''
|
|
1709
|
+
root = Path(proc_root()) / str(info['pid']) / 'root'
|
|
1710
|
+
sessions, proc = root / CONTAINER_HOME.lstrip('/') / Path(*CLAUDE_SESSIONS), root / 'proc'
|
|
1711
|
+
found, failure = _claude_in_lane(info, socket, session, sessions, proc)
|
|
1712
|
+
if failure:
|
|
1713
|
+
return failure
|
|
1714
|
+
records, index = found
|
|
1715
|
+
if not records:
|
|
1716
|
+
return 'deferred', f'no live Claude session file names a pane of this lane on its tmux socket {socket}: not typed'
|
|
1717
|
+
if len(records) > 1:
|
|
1718
|
+
return 'deferred', f'several Claude sessions run in this lane ({len(records)}): not typed'
|
|
1719
|
+
key, pid, document = records[0]
|
|
1720
|
+
local = key.split('/', 1)[1]
|
|
1721
|
+
pane, word, start = local.rsplit('.', 1)[-1], document.get('status'), document.get('procStart')
|
|
1722
|
+
if word != 'idle':
|
|
1723
|
+
return 'deferred', f'Claude says {word!r} (not idle at its prompt): not typed'
|
|
1724
|
+
if str(document.get('name') or '') == address:
|
|
1725
|
+
return 'named', f'already named {address}'
|
|
1726
|
+
if start is None:
|
|
1727
|
+
return 'deferred', 'its session file carries no procStart (a recycled pid could not be told apart): not typed'
|
|
1728
|
+
if AS.claude_delegating(root, str(document.get('sessionId') or ''), document.get('cwd')):
|
|
1729
|
+
return 'deferred', 'delegating to background work: not typed'
|
|
1730
|
+
with dispatch_lock(info, lane.get('id')) as busy:
|
|
1731
|
+
if busy:
|
|
1732
|
+
return 'deferred', f'{busy}: not typed'
|
|
1733
|
+
found, failure = _claude_in_lane(info, socket, session, sessions, proc)
|
|
1734
|
+
if failure:
|
|
1735
|
+
return failure
|
|
1736
|
+
again, now_index = found
|
|
1737
|
+
if not AS._same_process(proc, str(pid), start):
|
|
1738
|
+
return 'deferred', f'the Claude process {pid} ended or was replaced since the plan: not typed'
|
|
1739
|
+
if now_index.get(local) != index[local]:
|
|
1740
|
+
return 'deferred', f'pane {pane} of {session} on socket {socket} is gone or runs another process: not typed'
|
|
1741
|
+
same = [(k, d) for k, p, d in again if p == pid]
|
|
1742
|
+
if (len(again) != 1 or not same or same[0][0] != key or str(same[0][1].get('procStart')) != str(start)
|
|
1743
|
+
or same[0][1].get('status') != 'idle'
|
|
1744
|
+
or same[0][1].get('statusUpdatedAt') != document.get('statusUpdatedAt')):
|
|
1745
|
+
now_word = same[0][1].get('status') if same else None
|
|
1746
|
+
return 'deferred', f'its Claude session changed since the plan (now {now_word!r}): not typed'
|
|
1747
|
+
outcome, text = tmux_probe(info, socket, ['send-keys', '-t', pane, '-l', '--', f'/rename {address}'])
|
|
1748
|
+
if outcome != 'ok':
|
|
1749
|
+
return 'failed', f'tmux did not answer ({outcome}{": " + text if text else ""}): not typed'
|
|
1750
|
+
names_pause(lane_core().ENTER_DELAY)
|
|
1751
|
+
if not AS._same_process(proc, str(pid), start):
|
|
1752
|
+
return 'failed', f'/rename {address} typed without its Enter (the Claude process {pid} ended before it)'
|
|
1753
|
+
outcome, text = tmux_probe(info, socket, ['send-keys', '-t', pane, 'Enter'])
|
|
1754
|
+
if outcome != 'ok':
|
|
1755
|
+
return 'failed', f'/rename {address} typed without its Enter (tmux {outcome}{": " + text if text else ""})'
|
|
1756
|
+
return 'renamed', f'typed /rename {address}'
|
|
1757
|
+
|
|
1758
|
+
|
|
1371
1759
|
# The proxy's `x-throttle-trace` charset and cap (src/proxy.rs): a lane trace outside it would be dropped there.
|
|
1372
1760
|
TRACE = re.compile(r'[A-Za-z0-9._/-]{1,256}')
|
|
1373
1761
|
|
|
@@ -1553,7 +1941,10 @@ def ssh_workspace_board(workspace):
|
|
|
1553
1941
|
for index, pane in enumerate(workspace['panes'])]}
|
|
1554
1942
|
|
|
1555
1943
|
|
|
1556
|
-
def build_registry(previous=None):
|
|
1944
|
+
def build_registry(previous=None, strict=True):
|
|
1945
|
+
"""The registry from the site catalog, its board manifests and the containers' terminals.json. `strict` False
|
|
1946
|
+
(`lanes migrate addresses`' validation, `lanes doctor`) leaves two lanes claiming one address in place for the
|
|
1947
|
+
caller to report (`apply_addresses`) instead of raising."""
|
|
1557
1948
|
site = read_site_json(workspaces_dir() / 'catalog.json')
|
|
1558
1949
|
remote_tabs = ssh_workspaces(site)
|
|
1559
1950
|
catalog = site['workspaces']
|
|
@@ -1572,13 +1963,21 @@ def build_registry(previous=None):
|
|
|
1572
1963
|
manifest = manifests[workspace['id']]
|
|
1573
1964
|
entry = {'id': _require(IDENT, workspace['id'], 'workspace id'), 'title': workspace['title'],
|
|
1574
1965
|
'cwd': _workspace_cwd(manifest), 'errors': []}
|
|
1966
|
+
coordinator = None
|
|
1575
1967
|
try:
|
|
1576
1968
|
lanes = _workspace_lanes(manifest, containers)
|
|
1969
|
+
# W15 L2/L2b: the board's address overrides and coordinator, checked against its terminals. A bad one is
|
|
1970
|
+
# a board error like a bad displayNames override: this board keeps its previous lanes and settings.
|
|
1971
|
+
overrides, coordinator = board_settings(manifest, entry['id'], lanes)
|
|
1577
1972
|
except (LanesError, OSError, ValueError, KeyError) as error:
|
|
1578
1973
|
# Never lose a working board because one registry is momentarily invalid.
|
|
1579
1974
|
entry['errors'].append(str(error))
|
|
1580
|
-
|
|
1975
|
+
kept = previous_by_id.get(workspace['id']) or {}
|
|
1976
|
+
lanes = kept.get('lanes', [])
|
|
1581
1977
|
entry['stale'] = True
|
|
1978
|
+
overrides = kept.get('address_overrides') if isinstance(kept.get('address_overrides'), dict) else {}
|
|
1979
|
+
entry['coordinator'] = kept.get('coordinator') if any(
|
|
1980
|
+
lane.get('id') == kept.get('coordinator') for lane in lanes) else None
|
|
1582
1981
|
entry['container'] = (lanes[0]['container'] if lanes else
|
|
1583
1982
|
(manifest.get('repositories') or [{}])[0].get('host', ''))
|
|
1584
1983
|
for lane in lanes:
|
|
@@ -1589,6 +1988,10 @@ def build_registry(previous=None):
|
|
|
1589
1988
|
lane_id, n = f'{base}-{n}', n + 1
|
|
1590
1989
|
lane['id'] = lane_id
|
|
1591
1990
|
used_ids.add(lane['id'])
|
|
1991
|
+
if 'coordinator' not in entry: # the terminal name the manifest gives, as the lane id it now has
|
|
1992
|
+
entry['coordinator'] = next((lane['id'] for lane in lanes if coordinator is not None
|
|
1993
|
+
and lane.get('registry_name') == coordinator), None)
|
|
1994
|
+
entry['address_overrides'] = overrides
|
|
1592
1995
|
entry['discovery_roots'] = manifest.get('discoveryRoots') or []
|
|
1593
1996
|
entry['lanes'] = lanes
|
|
1594
1997
|
workspaces.append(entry)
|
|
@@ -1602,8 +2005,14 @@ def build_registry(previous=None):
|
|
|
1602
2005
|
'holder': 'exec', 'exec': 'monitor', 'container': max(set(hosts), key=hosts.count),
|
|
1603
2006
|
'cwd': CONTAINER_HOME, 'color': None, 'icon': '📊'})
|
|
1604
2007
|
import registrations
|
|
1605
|
-
|
|
1606
|
-
|
|
2008
|
+
fleet_admin, names_auto = address_site()
|
|
2009
|
+
registry = registrations.apply({'version': 1, 'generated_at': time.time(), 'containers': containers,
|
|
2010
|
+
'workspaces': workspaces, 'tools': tools, 'ssh_workspaces': remote_tabs,
|
|
2011
|
+
'fleet_admin': fleet_admin, 'names_auto': names_auto})
|
|
2012
|
+
# W15 L2: every lane's address and role. Two lanes claiming one address refuse the whole sync, naming both: a
|
|
2013
|
+
# message to that address could reach either (the previous registry stays published; `lanes doctor` says so).
|
|
2014
|
+
apply_addresses(registry, strict=strict)
|
|
2015
|
+
return registry
|
|
1607
2016
|
|
|
1608
2017
|
|
|
1609
2018
|
def publish_registry(registry):
|
|
@@ -1612,7 +2021,9 @@ def publish_registry(registry):
|
|
|
1612
2021
|
`generated_at` made statusd, notify and every sidebar reload it. An unchanged registry.json therefore keeps its
|
|
1613
2022
|
OLD `generated_at`; the sync itself is recorded in `registry.synced`, which only `lanes doctor` reads.
|
|
1614
2023
|
-> [(container, why)] for each container whose `~/.lz/registry.json` was refused (DEF-1796): it costs only that
|
|
1615
|
-
container, never the other projections; `lanes sync` reports it.
|
|
2024
|
+
container, never the other projections; `lanes sync` reports it. Every lane is (re)addressed first
|
|
2025
|
+
(`apply_addresses`, never raising here: a sync refused a clash before anything was published)."""
|
|
2026
|
+
apply_addresses(registry, strict=False)
|
|
1616
2027
|
write_resolve_files(registry)
|
|
1617
2028
|
_written, refused = export_container_registries(registry)
|
|
1618
2029
|
for workspace in registry['workspaces']:
|
|
@@ -1666,7 +2077,12 @@ def export_container_registries(registry):
|
|
|
1666
2077
|
`source` (the container's spelling of its terminals.json), `repo` (the manifest's repository id) and
|
|
1667
2078
|
`registry_name` (the declared terminal name with the repository prefix — what the id derives from, whatever the
|
|
1668
2079
|
display name), all null for a session adopted through `registered-sessions.json` (`registered_session: true`),
|
|
1669
|
-
plus `container`. Additive within version 1: `lane` and the Studio's registry reader read by key.
|
|
2080
|
+
plus `container`. Additive within version 1: `lane` and the Studio's registry reader read by key.
|
|
2081
|
+
|
|
2082
|
+
W15 L2/L2b (DM-LANES-REGISTRY): each entry's `address` (`<board>.<slug>` or the manifest's override) and `role`
|
|
2083
|
+
(None, 'coordinator' or 'fleet-admin'), and three top-level keys: `boards` ({board: {coordinator: lane id or None,
|
|
2084
|
+
address: board}} for every board of the site), `fleet_admin` (the fleet admin's address or None) and `names_auto`
|
|
2085
|
+
(statusd keeps Claude session names equal to addresses)."""
|
|
1670
2086
|
per_container = {}
|
|
1671
2087
|
for workspace in registry['workspaces']:
|
|
1672
2088
|
for lane in workspace['lanes']:
|
|
@@ -1676,7 +2092,10 @@ def export_container_registries(registry):
|
|
|
1676
2092
|
'name': lane['name'], 'ws': workspace['id'], 'holder': lane['holder'], 'tmux': lane.get('tmux'),
|
|
1677
2093
|
'zmx': lane.get('zmx'), 'create': lane.get('create'), 'folder': lane.get('folder'),
|
|
1678
2094
|
'source': lane.get('source'), 'repo': lane.get('repo'), 'registry_name': lane.get('registry_name'),
|
|
1679
|
-
'container': lane['container'], 'registered_session': bool(lane.get('registered_session'))
|
|
2095
|
+
'container': lane['container'], 'registered_session': bool(lane.get('registered_session')),
|
|
2096
|
+
'address': lane.get('address') or address_of(lane['id'], board=workspace['id']),
|
|
2097
|
+
'role': lane.get('role') if lane.get('role') in ROLES else None}
|
|
2098
|
+
boards = boards_document(registry)
|
|
1680
2099
|
written, refused = [], []
|
|
1681
2100
|
for container, lanes in per_container.items():
|
|
1682
2101
|
home = (registry['containers'].get(container) or {}).get('home')
|
|
@@ -1697,7 +2116,9 @@ def export_container_registries(registry):
|
|
|
1697
2116
|
os.stat('bin/lane', dir_fd=fd)
|
|
1698
2117
|
except FileNotFoundError:
|
|
1699
2118
|
continue # a ~/.lz without `lane`: not installed either
|
|
1700
|
-
document = {'version': 1, 'generated_at': registry['generated_at'], 'lanes': lanes
|
|
2119
|
+
document = {'version': 1, 'generated_at': registry['generated_at'], 'lanes': lanes, 'boards': boards,
|
|
2120
|
+
'fleet_admin': registry.get('fleet_admin'),
|
|
2121
|
+
'names_auto': bool(registry.get('names_auto', True))}
|
|
1701
2122
|
old = read_regular_at(fd, 'registry.json', EXPORT_READ_MAX)
|
|
1702
2123
|
try:
|
|
1703
2124
|
old = json.loads(old) if old is not None else None
|