@vibelord/lanes 1.6.1 → 1.7.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.
@@ -0,0 +1,704 @@
1
+ #!/usr/bin/env python3
2
+ """lane-peerd --once|--loop [--home DIR] [--serve S] [--lanes agents|all] — every lane of this container whose agent is
3
+ not Claude, as a
4
+ Claude peer (W15 L6; Linear BEY-6843; plan docs/superpowers/plans/2026-10-25-lanes-messaging-bus.md L6 and D3;
5
+ DM-LANES-PEER, DM-LANES-PEER-FRAME).
6
+
7
+ Claude Code 2.1.310 lists every `~/.claude/sessions/<pid>.json` whose pid is a live process with the matching
8
+ `procStart` in its sessions' ListAgents, and SendMessage writes ONE JSON line to the `messagingSocketPath` such a file
9
+ names (MEASURED 2026-10-25, M9/M10; lane_core's "Claude peers" section). So, every CYCLE_S seconds, this daemon:
10
+
11
+ * reads ~/.lz/status.json (lanes-statusd's slice of this container) and ~/.lz/registry.json, and for every lane
12
+ observed live (`active`/`quiet`, not stale) whose agent is not Claude — Codex, Kimi, Grok, Muse, ZCode; with
13
+ `--lanes all` (site.conf LANES_PEERS=all) a shell or an empty lane too — keeps a VIRTUAL PEER: a socket ~/.lz/state/peers/<lane>.sock (0600, the directory 0700) and a session
14
+ entry ~/.claude/sessions/<pid>.json with the keys a real entry has: `pid` the lane's agent process (found under the
15
+ pane's process, `tmux list-panes`; the pane's own shell for a lane without an agent), `procStart` its field 22,
16
+ `name` the lane's registered address, `tmux` its pane, `cwd` the lane folder, `status` busy while the agent works
17
+ (idle otherwise), `sessionId` a uuid5 of the lane id, `kind` interactive, `entrypoint` cli, `peerProtocol`
18
+ and `version` lane_core.PEER_PIN's, `peerFeatures` lane_core.PEER_FEATURES (notify_idle is not honoured: its
19
+ subscribe frame is unmeasured, so it is never claimed). The entry is rewritten on a change and every HEARTBEAT_S;
20
+ a session file whose `messagingSocketPath` is not ours is never touched, and a pane where a Claude process runs
21
+ gets no peer (Claude's own entry speaks for it);
22
+ * removes an entry and its socket when the lane ends, its process ends, or its agent becomes Claude;
23
+ * serves the sockets: each connection is read for one line (READ_TIMEOUT_S, FRAME_MAX), closed, and NOTHING is ever
24
+ written back (any reply byte makes the sender's SendMessage report a failure, M10); a connection without a line
25
+ (Claude's probe) is closed quietly. The line is lane_core.parse_peer_frame's; its text goes to lane_core.message for
26
+ the lane as `inbound` — sender the lane whose address (else Claude messaging name) is the frame's `from-name`,
27
+ else `peer:<from-name>` — which delivers it by the first adapter that applies (codex_queue, typed, …) or leaves
28
+ it in the lane's inbox (`queued`), or holds it (`unknown`: an adapter that may have taken it and never answered).
29
+ Handler threads run concurrently, but a typed delivery takes the lane's dispatch lock (lane_core.dispatch_lock),
30
+ the one every other writer of that lane takes too: two frames, a `lane message` and lanes-statusd's drain never
31
+ interleave their texts and Enters. The text's line breaks become ` ↵ `; one longer than 4000 characters is cut.
32
+ * writes ~/.lz/state/peers/peers.json — {v: 1, at, pid, pin, peers: {lane: {name, socket, pid, session, harness,
33
+ status, tmux}}, blocked: {lane: why}, frames: {…counts}} — on a change and every STATE_HEARTBEAT_S: its `at` is
34
+ the liveness lanes-statusd re-arms the loop by, and what lane_core.virtual_peers (lanes_whoami/lanes_list's
35
+ `claude-peer` handle, the `use_send_message` refusal) reads.
36
+
37
+ It never reads or prints a message's text into a log: the journal (stderr: the tmux pane) holds lane ids, message ids,
38
+ codes and adapters. One loop per container (a lock in the peers directory); started by lanes-statusd as
39
+ `tmux -L lanes-peers new -d -s peerd ~/.lz/bin/lane-peerd --loop` (statusd.peerd_rearm_argv) and stopped by SIGTERM,
40
+ SIGHUP or SIGINT, which removes every entry and socket it made. `--once`: one cycle, the document printed, the
41
+ sockets served for --serve seconds (default 0), then everything it registered removed again (a check, not a service).
42
+ Exit 0; 1 when another loop holds the lock (--once); 2 on a usage error.
43
+ """
44
+ import argparse
45
+ import fcntl
46
+ import json
47
+ import os
48
+ import re
49
+ import selectors
50
+ import signal
51
+ import socket
52
+ import stat
53
+ import sys
54
+ import threading
55
+ import time
56
+ import uuid
57
+ from pathlib import Path
58
+
59
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
60
+ import lane_core as C # noqa: E402
61
+
62
+ CYCLE_S = 3 # seconds between two reconciliations; the sockets are served in between
63
+ READ_TIMEOUT_S = 5 # a connection that sends no full line within this is closed
64
+ FRAME_MAX = 1 << 20 # bytes: a longer line is no frame
65
+ HEARTBEAT_S = 60 # a session entry is rewritten at least this often (its updatedAt), at once on a change
66
+ STATE_HEARTBEAT_S = 30 # peers.json renewed at least this often (lane_core.PEER_FRESH, 90 s, judges it)
67
+ HANDLERS = 16 # connections read and delivered at once; more wait in the listen backlog
68
+ BACKLOG = 16
69
+ BLOCKED_RETRY_S = 60 # a lane that could not be registered is looked at again after this
70
+ SOCKETS_PER_CYCLE = 16 # tmux servers asked for their panes in one cycle, at most
71
+ WALK_DEPTH = 4 # the pane's process tree, this deep (Codex: bash -> node -> codex)
72
+ WALK_MAX = 64 # processes looked at per pane, at most
73
+ LIVE_STATES = ('active', 'quiet')
74
+ NO_AGENT = ('none', 'shell')
75
+ PANE_FORMAT = '\t'.join('#{' + key + '}' for key in ('session_name', 'window_active', 'pane_active', 'pane_pid',
76
+ 'window_id', 'pane_id', 'pane_current_path'))
77
+ SESSION_NAMESPACE = uuid.UUID('6f1d7a52-3b0e-5c55-9a4e-1b2f6e0c0d15') # sessionId = uuid5(this, 'lanes-peer:<lane>')
78
+ LOCK = 'lock'
79
+ # The loop starts from `docker exec` with the image's PATH, which holds none of the user's own bin directories — where
80
+ # `codex` lives in a workspace (MEASURED here: ~/.local/bin/codex). lane_core.message's codex_queue adapter looks it up
81
+ # on the PATH it is given, so the loop puts these first (each only when it is a directory).
82
+ USER_BINS = ('.local/bin', '.npm-global/bin', '.n/bin', '.cargo/bin')
83
+
84
+
85
+ def loop_environ(environ, home):
86
+ """`environ` with USER_BINS (under `home`, those that exist) in front of its PATH."""
87
+ out = dict(environ)
88
+ found = [f'{home}/{part}' for part in USER_BINS if os.path.isdir(f'{home}/{part}')]
89
+ rest = [part for part in (out.get('PATH') or '/usr/local/bin:/usr/bin:/bin').split(':') if part and part not in found]
90
+ out['PATH'] = ':'.join(found + rest)
91
+ return out
92
+
93
+
94
+ def ms(at):
95
+ return int(at * 1000)
96
+
97
+
98
+ def session_id(lane):
99
+ """The stable sessionId of `lane`'s virtual peer."""
100
+ return str(uuid.uuid5(SESSION_NAMESPACE, f'lanes-peer:{lane}'))
101
+
102
+
103
+ def pid_domain(proc=Path('/proc'), machine_id=Path('/etc/machine-id')):
104
+ """`linux:<machine id>:pid:[<pid namespace inode>]`, the `pidDomain` a real entry of this container carries
105
+ (MEASURED: 69/69 live entries here), or None when either part cannot be read (the key is then left out)."""
106
+ try:
107
+ machine = machine_id.read_text().strip()
108
+ namespace = os.readlink(str(Path(proc) / 'self' / 'ns' / 'pid'))
109
+ except OSError:
110
+ return None
111
+ return f'linux:{machine}:{namespace}' if re.fullmatch(r'[0-9a-f]{32}', machine) else None
112
+
113
+
114
+ def children(proc, pid):
115
+ """The child pids of `pid`: /proc/<pid>/task/*/children (CONFIG_PROC_CHILDREN), else — a kernel without that
116
+ file — the processes whose parent (field 4 of /proc/<n>/stat) is `pid`. [] when unreadable."""
117
+ out, readable = [], False
118
+ try:
119
+ tasks = os.listdir(str(Path(proc) / str(pid) / 'task'))
120
+ except OSError:
121
+ return out
122
+ for task in tasks:
123
+ data = C.read_regular(Path(proc) / str(pid) / 'task' / task / 'children', 1 << 16)
124
+ readable = readable or data is not None
125
+ out.extend(int(word) for word in (data or b'').split() if word.isdigit())
126
+ if readable:
127
+ return out
128
+ for name in os.listdir(str(proc)):
129
+ if name.isdigit():
130
+ data = C.read_regular(Path(proc) / name / 'stat', 1 << 16)
131
+ fields = (data or b'').decode('utf-8', 'replace').rsplit(')', 1)[-1].split()
132
+ if len(fields) > 1 and fields[1] == str(pid):
133
+ out.append(int(name))
134
+ return out
135
+
136
+
137
+ def walk(proc, root):
138
+ """[(pid, harness or None)] of `root` and its descendants, breadth first, WALK_DEPTH levels, WALK_MAX processes."""
139
+ out, level = [], [root]
140
+ for _depth in range(WALK_DEPTH + 1):
141
+ following = []
142
+ for pid in level:
143
+ if len(out) >= WALK_MAX:
144
+ return out
145
+ out.append((pid, C.process_harness(proc, pid)))
146
+ following.extend(children(proc, pid))
147
+ level = following
148
+ if not level:
149
+ break
150
+ return out
151
+
152
+
153
+ class Peerd:
154
+ """The daemon's state. `cycle()` reconciles the virtual peers with the host's observation; `serve(seconds)` serves
155
+ their sockets until then; `shutdown()` removes every entry and socket it made. Everything it touches is under
156
+ `home` (the container's /home/coder; a test's own directory)."""
157
+
158
+ def __init__(self, home, proc=Path('/proc'), clock=time.time, run=None, deliver=None, environ=None, say=None,
159
+ machine_id=Path('/etc/machine-id'), lanes='agents'):
160
+ self.home, self.proc = Path(home), Path(proc)
161
+ self.lanes = lanes # 'agents' (Codex, Kimi, Grok, Muse, ZCode lanes) or 'all' (shells and empty lanes too)
162
+ self.lz = self.home / '.lz'
163
+ self.sessions = self.home.joinpath(*C.CLAUDE_SESSIONS)
164
+ self.directory = Path(C.peers_root(str(self.home)))
165
+ self.clock, self.run = clock, run or C.run_tmux
166
+ self.deliver = deliver or C.message
167
+ self.environ = dict(os.environ if environ is None else environ)
168
+ self.say_line = say or (lambda line: print(line, file=sys.stderr, flush=True))
169
+ self.domain = pid_domain(self.proc, machine_id)
170
+ self.peers, self.blocked = {}, {}
171
+ self.state = None # (the peers.json content without `at`, its `at`)
172
+ self.counts = {'frames': 0, 'delivered': 0, 'queued': 0, 'ignored': 0, 'refused': 0, 'unknown': 0}
173
+ self.counts_lock = threading.Lock()
174
+ self.handlers = threading.BoundedSemaphore(HANDLERS)
175
+ self.selector = selectors.DefaultSelector()
176
+ self.threads = []
177
+ self.lock_fd = None
178
+
179
+ # ------------------------------------------------------------------ journal
180
+
181
+ def say(self, line):
182
+ self.say_line(f'{C.iso(self.clock())} lane-peerd {line}')
183
+
184
+ def count(self, key):
185
+ with self.counts_lock:
186
+ self.counts[key] += 1
187
+
188
+ # ------------------------------------------------------------------ the one loop
189
+
190
+ def own_directory(self):
191
+ """fd of ~/.lz/state/peers, created when missing (no component a link) and kept 0700."""
192
+ fd = C._open_dir(self.lz, C.PEERS_DIR, create=True)
193
+ try:
194
+ os.fchmod(fd, 0o700)
195
+ except BaseException:
196
+ os.close(fd)
197
+ raise
198
+ return fd
199
+
200
+ def acquire(self):
201
+ """Take the one-loop-per-container lock -> True; False when another lane-peerd holds it."""
202
+ fd = self.own_directory()
203
+ try:
204
+ lock = os.open(LOCK, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | getattr(os, 'O_CLOEXEC', 0), 0o600,
205
+ dir_fd=fd)
206
+ finally:
207
+ os.close(fd)
208
+ try:
209
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
210
+ except OSError:
211
+ os.close(lock)
212
+ return False
213
+ self.lock_fd = lock
214
+ return True
215
+
216
+ def sweep(self):
217
+ """At start: what an earlier loop that did not stop cleanly left — its entries (session files whose socket is
218
+ in our directory; the newest lane_core.PEER_SCAN_MAX names looked at) and its sockets — removed."""
219
+ removed = 0
220
+ try:
221
+ names = sorted((n for n in os.listdir(str(self.sessions)) if re.fullmatch(r'[1-9][0-9]{0,9}\.json', n)),
222
+ key=lambda n: int(n[:-5]))[-C.PEER_SCAN_MAX:]
223
+ except OSError:
224
+ names = []
225
+ for name in names:
226
+ if C.is_virtual_entry(self.read_entry(self.sessions / name), str(self.home)):
227
+ removed += self.unlink_entry(self.sessions / name)
228
+ try:
229
+ leftovers = [n for n in os.listdir(str(self.directory)) if n.endswith('.sock')]
230
+ except OSError:
231
+ leftovers = []
232
+ for name in leftovers:
233
+ self.unlink_socket(str(self.directory / name))
234
+ if removed or leftovers:
235
+ self.say(f'swept {removed} entries and {len(leftovers)} sockets an earlier loop left')
236
+
237
+ # ------------------------------------------------------------------ what to serve
238
+
239
+ def observed(self, now):
240
+ """(want, keep) from the host's two projections — want: {lane: {name, harness, pair, folder, busy,
241
+ agent_pid}} of the lanes to serve now; keep: the lanes whose row is stale (left as they are) — or None while
242
+ the observation is not fresh (nothing is added or removed then, but for an ended process)."""
243
+ try:
244
+ export, status = C.registry_export(self.lz), C.container_status(self.lz, now)
245
+ except C.LaneError as error:
246
+ self.say(f'contract: {error.code}')
247
+ return None
248
+ if not status['available'] or not status['fresh']:
249
+ return None
250
+ ghosts = {row['id']: row for row in status['unregistered']}
251
+ want, keep = {}, set()
252
+ for lane in list(export['lanes']) + [ghost for ghost in ghosts if ghost not in export['lanes']]:
253
+ entry, ghost, row = export['lanes'].get(lane), ghosts.get(lane), status['lanes'].get(lane) or {}
254
+ if row.get('stale'):
255
+ keep.add(lane)
256
+ continue
257
+ if row.get('state') not in LIVE_STATES or not C.LANE_RE.fullmatch(lane):
258
+ continue
259
+ agent = row.get('agent') if isinstance(row.get('agent'), dict) else {}
260
+ harness = str(agent.get('harness') or '') if agent.get('status') else ''
261
+ if harness == 'claude':
262
+ continue
263
+ if agent.get('status') == 'shell' or harness in C.NO_AGENT:
264
+ harness = 'shell' if agent.get('status') == 'shell' else 'none'
265
+ if self.lanes != 'all':
266
+ continue # LANES_PEERS=agents (the default): a shell is no agent and would only crowd ListAgents
267
+ name = C.address_of(lane, entry, row, ghost)
268
+ tmux = (ghost or {}).get('tmux') if isinstance((ghost or {}).get('tmux'), dict) else {}
269
+ pair = C.tmux_target(entry) if entry else ((str(tmux['socket']), str(tmux['session']))
270
+ if tmux.get('socket') and tmux.get('session') else None)
271
+ if not name or not pair or not C.IDENT.match(pair[0]):
272
+ continue
273
+ pid, folder = agent.get('pid'), (entry or {}).get('folder')
274
+ want[lane] = {'name': name, 'harness': harness, 'pair': pair,
275
+ 'folder': folder if isinstance(folder, str) and folder.startswith('/') else None,
276
+ 'busy': agent.get('status') == 'working',
277
+ 'agent_pid': pid if isinstance(pid, int) and not isinstance(pid, bool) else None}
278
+ return want, keep
279
+
280
+ def panes(self, sockets):
281
+ """({(socket, session): {pid, window, pane, cwd}} of each session's active pane, the sockets that answered):
282
+ one `list-panes -a` per tmux server, at most SOCKETS_PER_CYCLE of them (the rest are asked next cycle)."""
283
+ out, answered = {}, set()
284
+ for socket_name in sorted(sockets)[:SOCKETS_PER_CYCLE]:
285
+ result = self.run(C.tmux_argv(socket_name, 'list-panes', '-a', '-F', PANE_FORMAT))
286
+ if result.returncode:
287
+ continue
288
+ answered.add(socket_name)
289
+ for line in result.stdout.splitlines():
290
+ fields = line.split('\t', 6)
291
+ if len(fields) != 7 or fields[1] != '1' or fields[2] != '1' or not fields[3].isdigit():
292
+ continue
293
+ if not re.fullmatch(r'@[0-9]+', fields[4]) or not re.fullmatch(r'%[0-9]+', fields[5]):
294
+ continue
295
+ out[(socket_name, fields[0])] = {'pid': int(fields[3]), 'window': fields[4], 'pane': fields[5],
296
+ 'cwd': fields[6] if fields[6].startswith('/') else None}
297
+ return out, answered
298
+
299
+ def agent_pid(self, want, pane_pid):
300
+ """The process a lane's virtual peer names, or None when a Claude process runs in the pane (its own entry
301
+ speaks for it): the first harness process under the pane (walk), else the agent pid the host published when
302
+ that process lives, else the pane's own process (a shell lane: always that one)."""
303
+ tree = walk(self.proc, pane_pid)
304
+ if any(harness == 'claude' for _pid, harness in tree):
305
+ return None
306
+ if want['harness'] in NO_AGENT:
307
+ return pane_pid
308
+ found = next((pid for pid, harness in tree if harness), None)
309
+ if found:
310
+ return found
311
+ published = want.get('agent_pid')
312
+ if published and C.proc_start(self.proc, published) and C.process_harness(self.proc, published) != 'claude':
313
+ return published
314
+ return pane_pid
315
+
316
+ # ------------------------------------------------------------------ entries and sockets
317
+
318
+ def read_entry(self, path):
319
+ """A session file as a dict: None when it is absent; {} when it exists but is not a readable JSON object
320
+ (a file that is not ours either way)."""
321
+ if not os.path.lexists(str(path)):
322
+ return None
323
+ data = C.read_regular(path, C.PEER_FILE_MAX)
324
+ try:
325
+ document = json.loads(data.decode('utf-8')) if data is not None else {}
326
+ except (UnicodeDecodeError, ValueError):
327
+ return {}
328
+ return document if isinstance(document, dict) else {}
329
+
330
+ def ours(self, document):
331
+ return C.is_virtual_entry(document, str(self.home))
332
+
333
+ def entry(self, peer):
334
+ """DM-LANES-PEER's session entry: the keys and order of a real 2.1.310 entry (MEASURED)."""
335
+ document = {'pid': peer['pid'], 'sessionId': session_id(peer['lane'])}
336
+ if peer['cwd']: # optional in Claude's own schema: absent, never null
337
+ document['cwd'] = peer['cwd']
338
+ document.update({'startedAt': peer['started'], 'procStart': peer['proc_start'],
339
+ 'version': C.PEER_PIN['claude'], 'peerProtocol': C.PEER_PIN['peerProtocol'],
340
+ 'peerFeatures': list(C.PEER_FEATURES), 'kind': 'interactive', 'entrypoint': 'cli'})
341
+ if self.domain:
342
+ document['pidDomain'] = self.domain
343
+ document.update({'tmux': peer['tmux'], 'messagingSocketPath': peer['socket'], 'name': peer['name'],
344
+ 'nameSource': 'user', 'nameSince': peer['name_since'], 'updatedAt': peer['updated'],
345
+ 'status': peer['status'], 'statusUpdatedAt': peer['status_since']})
346
+ return document
347
+
348
+ def write_entry(self, peer):
349
+ """Write the peer's session entry by rename -> True; False (nothing written) when the file at its name is not
350
+ ours — a real session took the pid's name meanwhile."""
351
+ path = self.sessions / f'{peer["pid"]}.json'
352
+ existing = self.read_entry(path)
353
+ if existing is not None and not self.ours(existing):
354
+ return False
355
+ C.atomic_replace(path, json.dumps(self.entry(peer), ensure_ascii=False) + '\n', 0o600)
356
+ return True
357
+
358
+ def unlink_entry(self, path):
359
+ """Remove a session file only while it is ours (re-read first) -> 1 when removed."""
360
+ if self.ours(self.read_entry(path)):
361
+ try:
362
+ os.unlink(str(path))
363
+ return 1
364
+ except OSError:
365
+ pass
366
+ return 0
367
+
368
+ def unlink_socket(self, path):
369
+ try:
370
+ if stat.S_ISSOCK(os.lstat(path).st_mode):
371
+ os.unlink(path)
372
+ except OSError:
373
+ pass
374
+
375
+ def listen(self, path):
376
+ """A listening unix socket at `path` (0600; a socket already there is replaced, anything else refused)."""
377
+ if os.path.lexists(path):
378
+ if not stat.S_ISSOCK(os.lstat(path).st_mode):
379
+ raise OSError(f'{os.path.basename(path)} exists and is not a socket')
380
+ os.unlink(path)
381
+ server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
382
+ try:
383
+ # No umask change (it is process-wide, and handler threads create inbox directories): the directory is
384
+ # 0700, so nobody else reaches the socket in the instant before its chmod.
385
+ server.bind(path)
386
+ os.chmod(path, 0o600)
387
+ server.listen(BACKLOG)
388
+ server.setblocking(False)
389
+ except BaseException:
390
+ server.close()
391
+ raise
392
+ return server
393
+
394
+ def block(self, lane, now, why):
395
+ if self.blocked.get(lane, (None, 0))[0] != why:
396
+ self.say(f'{lane}: no peer ({why})')
397
+ self.blocked[lane] = (why, now + BLOCKED_RETRY_S)
398
+
399
+ def add(self, lane, want, pane, now):
400
+ """Register `lane` as a virtual peer -> True when it now has one."""
401
+ if pane is None:
402
+ self.block(lane, now, 'tmux names no active pane for its session')
403
+ return False
404
+ pid = self.agent_pid(want, pane['pid'])
405
+ if pid is None:
406
+ self.block(lane, now, 'a Claude process runs in its pane')
407
+ return False
408
+ started = C.proc_start(self.proc, pid)
409
+ if started is None:
410
+ return False
411
+ if not os.path.isdir(str(self.sessions.parent)):
412
+ self.block(lane, now, 'no ~/.claude here: no Claude session to list it')
413
+ return False
414
+ try:
415
+ self.sessions.mkdir(mode=0o700, exist_ok=True)
416
+ except OSError:
417
+ self.block(lane, now, '~/.claude/sessions cannot be created')
418
+ return False
419
+ existing = self.read_entry(self.sessions / f'{pid}.json')
420
+ if existing is not None and not self.ours(existing):
421
+ self.block(lane, now, f'{pid}.json is a session file of its own')
422
+ return False
423
+ path = C.peer_socket_path(lane, str(self.home))
424
+ try:
425
+ server = self.listen(path)
426
+ except OSError as error:
427
+ self.block(lane, now, f'its socket cannot listen ({error.strerror or error})')
428
+ return False
429
+ at = ms(now)
430
+ peer = {'lane': lane, 'name': want['name'], 'harness': want['harness'], 'pid': pid, 'proc_start': started,
431
+ 'tmux': f'{want["pair"][1]}:{pane["window"]}.{pane["pane"]}', 'cwd': want['folder'] or pane['cwd'],
432
+ 'socket': path, 'server': server, 'status': 'busy' if want['busy'] else 'idle', 'started': at,
433
+ 'name_since': at, 'updated': at, 'status_since': at, 'written': now}
434
+ try:
435
+ written = self.write_entry(peer)
436
+ except OSError as error:
437
+ written, why = False, f'its entry cannot be written ({error.strerror or error})'
438
+ else:
439
+ why = f'{pid}.json is a session file of its own'
440
+ if not written:
441
+ server.close()
442
+ self.unlink_socket(path)
443
+ self.block(lane, now, why)
444
+ return False
445
+ self.blocked.pop(lane, None)
446
+ self.peers[lane] = peer
447
+ self.selector.register(server, selectors.EVENT_READ, lane)
448
+ self.say(f'{lane}: peer {want["name"]} (pid {pid}, {want["harness"]})')
449
+ return True
450
+
451
+ def refresh(self, lane, want, now):
452
+ """A peer's name and status follow the lane; its entry is rewritten on a change and every HEARTBEAT_S."""
453
+ peer = self.peers[lane]
454
+ status = 'busy' if want['busy'] else 'idle'
455
+ changed = peer['name'] != want['name'] or peer['status'] != status
456
+ if peer['name'] != want['name']:
457
+ peer['name'], peer['name_since'] = want['name'], ms(now)
458
+ if peer['status'] != status:
459
+ peer['status'], peer['status_since'] = status, ms(now)
460
+ if not changed and now - peer['written'] < HEARTBEAT_S:
461
+ return
462
+ peer['updated'], peer['written'] = ms(now), now
463
+ try:
464
+ if not self.write_entry(peer):
465
+ self.remove(lane, 'its pid has a session file of its own now')
466
+ except OSError as error:
467
+ self.say(f'{lane}: entry not refreshed ({error.strerror or type(error).__name__})')
468
+
469
+ def remove(self, lane, why):
470
+ peer = self.peers.pop(lane, None)
471
+ if peer is None:
472
+ return
473
+ try:
474
+ self.selector.unregister(peer['server'])
475
+ except (KeyError, ValueError):
476
+ pass
477
+ peer['server'].close()
478
+ self.unlink_socket(peer['socket'])
479
+ self.unlink_entry(self.sessions / f'{peer["pid"]}.json')
480
+ self.say(f'{lane}: peer removed ({why})')
481
+
482
+ # ------------------------------------------------------------------ one cycle
483
+
484
+ def cycle(self, now=None):
485
+ """One reconciliation -> the peers.json document it stands on."""
486
+ now = self.clock() if now is None else now
487
+ os.close(self.own_directory()) # the sockets' directory, there and 0700 before any socket is bound in it
488
+ found = self.observed(now)
489
+ for lane, peer in list(self.peers.items()):
490
+ if C.proc_start(self.proc, peer['pid']) != peer['proc_start']:
491
+ self.remove(lane, 'its process ended')
492
+ elif found is not None and lane not in found[0] and lane not in found[1]:
493
+ self.remove(lane, 'the lane ended, or its agent is Claude now')
494
+ elif found is not None and lane in found[0] and found[0][lane]['harness'] != peer['harness']:
495
+ self.remove(lane, f'its agent is {found[0][lane]["harness"]} now')
496
+ if found is not None:
497
+ want = found[0]
498
+ for lane in [lane for lane in self.blocked if lane not in want]:
499
+ del self.blocked[lane]
500
+ new = [lane for lane in want if lane not in self.peers and self.blocked.get(lane, (None, 0))[1] <= now]
501
+ panes, answered = self.panes({want[lane]['pair'][0] for lane in new}) if new else ({}, set())
502
+ for lane in new:
503
+ if want[lane]['pair'][0] in answered: # a server that did not answer is asked again next cycle
504
+ self.add(lane, want[lane], panes.get(want[lane]['pair']), now)
505
+ for lane in list(self.peers):
506
+ if lane in want:
507
+ self.refresh(lane, want[lane], now)
508
+ return self.write_state(now)
509
+
510
+ def document(self, now):
511
+ with self.counts_lock:
512
+ frames = dict(self.counts)
513
+ return {'v': 1, 'at': int(now), 'pid': os.getpid(), 'pin': dict(C.PEER_PIN),
514
+ 'peers': {lane: {'name': peer['name'], 'socket': peer['socket'], 'pid': peer['pid'],
515
+ 'session': f'{peer["pid"]}.json', 'harness': peer['harness'],
516
+ 'status': peer['status'], 'tmux': peer['tmux']}
517
+ for lane, peer in sorted(self.peers.items())},
518
+ 'blocked': {lane: why for lane, (why, _until) in sorted(self.blocked.items())}, 'frames': frames}
519
+
520
+ def write_state(self, now):
521
+ """peers.json (DM-LANES-PEER) on a change and every STATE_HEARTBEAT_S -> the document."""
522
+ document = self.document(now)
523
+ content = {key: value for key, value in document.items() if key != 'at'}
524
+ if self.state and self.state[0] == content and now - self.state[1] < STATE_HEARTBEAT_S:
525
+ return dict(content, at=int(self.state[1]))
526
+ try:
527
+ fd = self.own_directory()
528
+ except OSError as error:
529
+ self.say(f'peers.json not written ({error.strerror or type(error).__name__})')
530
+ return document
531
+ try:
532
+ C._write_at(fd, C.PEERS_STATE, document, mode=0o600)
533
+ self.state = (content, now)
534
+ except OSError as error:
535
+ self.say(f'peers.json not written ({error.strerror or type(error).__name__})')
536
+ finally:
537
+ os.close(fd)
538
+ return document
539
+
540
+ # ------------------------------------------------------------------ the sockets
541
+
542
+ def serve(self, seconds, stop=None):
543
+ """Serve the peers' sockets for `seconds` (or until the threading.Event `stop` is set): each connection read
544
+ and delivered on its own thread (at most HANDLERS at once; more wait in the backlog)."""
545
+ deadline = time.monotonic() + seconds
546
+ while True:
547
+ left = deadline - time.monotonic()
548
+ if left <= 0 or (stop is not None and stop.is_set()):
549
+ return
550
+ if not self.selector.get_map():
551
+ time.sleep(min(left, 0.25))
552
+ continue
553
+ for key, _events in self.selector.select(timeout=min(left, 0.5)):
554
+ if not self.handlers.acquire(timeout=min(max(left, 0), 0.25)):
555
+ break
556
+ try:
557
+ connection, _address = key.fileobj.accept()
558
+ except OSError:
559
+ self.handlers.release()
560
+ continue
561
+ thread = threading.Thread(target=self.handle, args=(key.data, connection), daemon=True)
562
+ self.threads = [t for t in self.threads if t.is_alive()] + [thread]
563
+ thread.start()
564
+
565
+ def read_line(self, connection):
566
+ """The first line a connection carries (without its `\\n`; the bytes up to EOF when it ends without one), or
567
+ None: nothing within READ_TIMEOUT_S, more than FRAME_MAX bytes, or a closed connection. Reads only."""
568
+ deadline = time.monotonic() + READ_TIMEOUT_S
569
+ chunks, size = [], 0
570
+ try:
571
+ while True:
572
+ left = deadline - time.monotonic()
573
+ if left <= 0:
574
+ return None
575
+ connection.settimeout(left)
576
+ chunk = connection.recv(65536)
577
+ if not chunk:
578
+ data = b''.join(chunks)
579
+ return data if data.strip() else None
580
+ newline = chunk.find(b'\n')
581
+ if newline >= 0:
582
+ chunks.append(chunk[:newline])
583
+ return b''.join(chunks)
584
+ chunks.append(chunk)
585
+ size += len(chunk)
586
+ if size > FRAME_MAX:
587
+ return None
588
+ except OSError:
589
+ return None
590
+
591
+ def handle(self, lane, connection):
592
+ """One connection: read its line, close it — nothing is ever sent back (M10) — then take the frame."""
593
+ try:
594
+ try:
595
+ line = self.read_line(connection)
596
+ finally:
597
+ connection.close()
598
+ if line:
599
+ self.take(lane, line)
600
+ except Exception as error: # one connection's defect never ends the daemon
601
+ self.say(f'{lane}: a connection failed ({type(error).__name__})')
602
+ finally:
603
+ self.handlers.release()
604
+
605
+ def sender_of(self, name):
606
+ """The sender of a frame whose `from-name` is `name`: the lane of this container whose address it is, else
607
+ the one whose Claude messaging name it is, else `peer:<name>` (a Claude session outside the lanes)."""
608
+ try:
609
+ export, status = C.registry_export(self.lz), C.container_status(self.lz)
610
+ except C.LaneError:
611
+ export, status = {'lanes': {}}, {'lanes': {}, 'unregistered': []}
612
+ if name:
613
+ for lane, entry in export['lanes'].items():
614
+ if C.address_of(lane, entry, status['lanes'].get(lane)) == name:
615
+ return lane
616
+ for row in status['unregistered']:
617
+ if C.address_of(row['id'], status['lanes'].get(row['id']), row) == name:
618
+ return row['id']
619
+ named = [lane for lane, row in status['lanes'].items() if C.messaging_name(row) == name]
620
+ if len(named) == 1 and C.LANE_RE.fullmatch(named[0]):
621
+ return named[0]
622
+ cleaned = re.sub(r'[^A-Za-z0-9_.-]+', '-', name or '').strip('-')[:128]
623
+ return 'peer:' + (cleaned or 'unnamed')
624
+
625
+ def take(self, lane, line):
626
+ """Hand one frame's text to lane_core.message for `lane` (inbound, queued when nothing delivers it now)."""
627
+ self.count('frames')
628
+ try:
629
+ frame = C.parse_peer_frame(line)
630
+ except (ValueError, UnicodeDecodeError) as error:
631
+ self.count('ignored')
632
+ self.say(f'{lane}: a line that is no protocol-1 message, ignored ({str(error)[:80]})')
633
+ return None
634
+ text, cut = C.peer_text(frame['text'])
635
+ if not text:
636
+ self.count('ignored')
637
+ self.say(f'{lane}: an empty message, ignored')
638
+ return None
639
+ sender = self.sender_of(frame['from_name'])
640
+ inbound = {'name': frame['from_name'], 'mode': frame['from_mode'], 'msg_id': frame['msg_id']}
641
+ try:
642
+ out = self.deliver(self.lz, self.home, sender, lane, text, queue=True, harness='claude',
643
+ environ=self.environ, inbound=inbound)
644
+ except C.LaneError as error:
645
+ self.count('refused')
646
+ self.say(f'{lane}: a message from {sender} refused {error.code}')
647
+ return None
648
+ state = out.get('delivered_by')
649
+ self.count(state if state in ('queued', 'unknown') else 'delivered')
650
+ self.say(f'{lane}: {out.get("id")} from {sender} {out.get("delivered_by")}' + (' (cut)' if cut else ''))
651
+ return out
652
+
653
+ # ------------------------------------------------------------------ the end
654
+
655
+ def shutdown(self, now=None):
656
+ """Every entry and socket this loop made removed, peers.json emptied."""
657
+ for lane in list(self.peers):
658
+ self.remove(lane, 'lane-peerd stops')
659
+ for thread in self.threads:
660
+ thread.join(timeout=READ_TIMEOUT_S + 1)
661
+ self.write_state(self.clock() if now is None else now)
662
+ self.selector.close()
663
+
664
+
665
+ def main(argv=None, environ=None):
666
+ environ = os.environ if environ is None else environ
667
+ parser = argparse.ArgumentParser(prog='lane-peerd', description=__doc__.split('\n\n', 1)[0])
668
+ mode = parser.add_mutually_exclusive_group(required=True)
669
+ mode.add_argument('--once', action='store_true', help='one cycle, the document printed, then removed again')
670
+ mode.add_argument('--loop', action='store_true', help=f'a cycle every {CYCLE_S} s until SIGTERM')
671
+ parser.add_argument('--home', default=environ.get('HOME') or C.CONTAINER_HOME)
672
+ parser.add_argument('--serve', type=float, default=0.0, help='--once: seconds to serve the sockets (default 0)')
673
+ parser.add_argument('--lanes', choices=('agents', 'all'), default='agents',
674
+ help='which lanes become peers: agents (Codex, Kimi, Grok, Muse, ZCode; the default) or all (shells too)')
675
+ args = parser.parse_args(argv)
676
+ daemon = Peerd(args.home, environ=loop_environ(environ, args.home), lanes=args.lanes)
677
+ if not daemon.acquire():
678
+ daemon.say('another lane-peerd runs here (its lock is held): nothing done')
679
+ return 1 if args.once else 0
680
+
681
+ def stop(*_args):
682
+ raise SystemExit(0)
683
+ for signum in (signal.SIGTERM, signal.SIGHUP, signal.SIGINT):
684
+ signal.signal(signum, stop)
685
+ try:
686
+ daemon.sweep()
687
+ if args.once:
688
+ print(json.dumps(daemon.cycle(), indent=1))
689
+ daemon.serve(max(0.0, args.serve))
690
+ return 0
691
+ daemon.say(f'serving (pin Claude Code {C.PEER_PIN["claude"]}, peerProtocol {C.PEER_PIN["peerProtocol"]})')
692
+ while True:
693
+ started = time.monotonic()
694
+ try:
695
+ daemon.cycle()
696
+ except OSError as error: # an unwritable directory is journalled; the loop keeps going
697
+ daemon.say(f'cycle failed ({error.strerror or type(error).__name__})')
698
+ daemon.serve(max(0.5, CYCLE_S - (time.monotonic() - started)))
699
+ finally:
700
+ daemon.shutdown()
701
+
702
+
703
+ if __name__ == '__main__':
704
+ sys.exit(main())