@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.
- package/package.json +1 -1
- package/payload/lanes/VERSION +1 -1
- package/payload/lanes/bin/lanes +571 -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 +288 -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
|
@@ -35,14 +35,49 @@ sees, and `lane-mcp` may write nothing but protocol frames to its stdout.
|
|
|
35
35
|
* publish requests (plan W10 W4): `publish` writes ~/.lz/state/publish/<lane>/<id>.json for `lane publish` and
|
|
36
36
|
lane-mcp's `lanes_publish` (the file hashed once, the id in docs_store's grammar: `new_publish_id`), and
|
|
37
37
|
`latest_receipt` reads the `<id>.receipt.json` the host's lanes-docsd writes back (`lanes_status`'s `published`).
|
|
38
|
+
* addresses (W15 L2/L2b/L2c, DM-LANES-ADDRESS): every lane's registered messaging address `<board>.<slug>`
|
|
39
|
+
(`address_of`; an alias override from the host's export wins), what a tool's `lane` argument may name
|
|
40
|
+
(`resolve_address`: a lane id, `@<address>`, `@<board>` for its coordinator, `@fleet` for the fleet admin), the
|
|
41
|
+
routing rule lane → coordinator → fleet admin (`routing_check`), how a message reaches a lane's agent (`handle`),
|
|
42
|
+
whether its messaging name is its address (`name_match`), and name parity at launch: a Claude lane's recipe runs
|
|
43
|
+
`claude … --name <address>` (`claude_named`).
|
|
44
|
+
* Codex thread ids without hooks (W15 L3, Linear BEY-6841, DM-LANES-CODEX-THREADS): `codex_threads` asks the
|
|
45
|
+
shared Codex app-server daemon over its control socket (WebSocket over AF_UNIX, MEASURED Codex 0.164.0) for its
|
|
46
|
+
live top-level threads, `codex_assign` joins a lane to one by its Codex process's cwd (the title Codex draws, the
|
|
47
|
+
thread's name, telling several apart), and `handle(agent, lane, root)` falls back to that when no hook recorded
|
|
48
|
+
the thread id.
|
|
49
|
+
* messages (W15 L4, BEY-6842; DM-LANES-MESSAGE/-RECEIPT/-LOG): `message` for `lane message` and lane-mcp's `lanes_message`
|
|
50
|
+
sends one message to one lane of this container through the first adapter that applies — the sender's own
|
|
51
|
+
SendMessage (refused `use_send_message`), `codex queue`, the Throttle bus (LANES_BUS=throttle), typed into an idle
|
|
52
|
+
lane — else the recipient's inbox ~/.lz/state/inbox/<lane>/ (`queued`, typed by the host's lanes-statusd when the
|
|
53
|
+
lane is next idle); every message in ONE envelope (ENVELOPE), every outcome one metadata-only log line, never its
|
|
54
|
+
text. `inbox_summary`/`inbox_pending`/`inbox_counts` read an inbox (every message that is not settled, whatever
|
|
55
|
+
the history holds), `message_ack` takes a message's text out of it, `message_retry` hands a held one back.
|
|
56
|
+
W15 part 2 (the PR #544 review): native input has ONE authority per recipient, `dispatch_lock` (an flock on
|
|
57
|
+
~/.lz/state/dispatch/<lane>.lock, which the host's lanes-statusd takes too through /proc/<init>/root), held across
|
|
58
|
+
the final readiness recheck, the text and its Enter (DM-LANES-DISPATCH-LOCK); a Codex lane is resolved with its
|
|
59
|
+
own context at dispatch (`handle(…, fresh=True)`); an adapter whose answer was lost after the request went out is
|
|
60
|
+
`unknown` — held, never replayed or handed to another adapter — and the Throttle bus is reached on Throttle's
|
|
61
|
+
control listener with the sending harness's own client token (BEY-6869).
|
|
62
|
+
* Claude peers (W15 L6, BEY-6843; DM-LANES-PEER, DM-LANES-PEER-FRAME): Claude Code's cross-session messaging spoken by
|
|
63
|
+
proxy. `container/lane-peerd` registers every lane whose agent is not Claude as a virtual peer (a session entry
|
|
64
|
+
naming a Lanes socket); `virtual_peers` reads what it serves, `peer_frame`/`parse_peer_frame` are the measured wire
|
|
65
|
+
line, and `message`'s `peer_socket` adapter writes that line to a REAL Claude session's socket for a sender that
|
|
66
|
+
is not Claude — only while the recipient's session file passes PEER_PIN (`peer_pin_failed` otherwise).
|
|
38
67
|
"""
|
|
68
|
+
import base64
|
|
69
|
+
import contextlib
|
|
39
70
|
import difflib
|
|
71
|
+
import fcntl
|
|
72
|
+
import hashlib
|
|
40
73
|
import json
|
|
41
74
|
import os
|
|
42
75
|
import pwd
|
|
43
76
|
import re
|
|
44
77
|
import shlex
|
|
78
|
+
import socket
|
|
45
79
|
import stat
|
|
80
|
+
import struct
|
|
46
81
|
import subprocess
|
|
47
82
|
import tempfile
|
|
48
83
|
import time
|
|
@@ -122,22 +157,39 @@ def read_json(path):
|
|
|
122
157
|
return None
|
|
123
158
|
|
|
124
159
|
|
|
125
|
-
def
|
|
126
|
-
"""
|
|
127
|
-
|
|
160
|
+
def registry_export(root):
|
|
161
|
+
"""<root>/registry.json whole — what `lanes sync` places in this container: {'lanes': {lane id: entry}, 'boards':
|
|
162
|
+
{board: {'coordinator': lane id | None, 'address': board}}, 'fleet_admin': address | None, 'names_auto': bool |
|
|
163
|
+
None}. `lanes` holds the declared and registered lanes ({} when there is no registry yet: a zmx-only container
|
|
164
|
+
needs none). `boards`, `fleet_admin` and `names_auto` are W15's additive top-level keys (DM-LANES-ADDRESS; the
|
|
165
|
+
host writes them, an older export lacks them: {}, None, None), as is each entry's `address` and `role`. A
|
|
166
|
+
`fleet_admin` is kept without its `@`, and only when it reads as an address. A newer registry raises NewerVersion."""
|
|
167
|
+
out = {'lanes': {}, 'boards': {}, 'fleet_admin': None, 'names_auto': None}
|
|
128
168
|
data = read_json(Path(root) / 'registry.json')
|
|
129
169
|
if not isinstance(data, dict):
|
|
130
|
-
return
|
|
170
|
+
return out
|
|
131
171
|
try:
|
|
132
172
|
version = int(data.get('version', 1))
|
|
133
173
|
except (TypeError, ValueError):
|
|
134
|
-
return
|
|
174
|
+
return out
|
|
135
175
|
if version > 1:
|
|
136
176
|
raise NewerVersion('the registry is newer than this `lane` — on the host run: lanes install-container <container>')
|
|
137
177
|
lanes = data.get('lanes')
|
|
138
|
-
if
|
|
139
|
-
|
|
140
|
-
|
|
178
|
+
if isinstance(lanes, dict):
|
|
179
|
+
out['lanes'] = {key: value for key, value in lanes.items() if isinstance(value, dict) and LANE_RE.fullmatch(key)}
|
|
180
|
+
boards = data.get('boards')
|
|
181
|
+
if isinstance(boards, dict):
|
|
182
|
+
out['boards'] = {key: value for key, value in boards.items() if isinstance(value, dict) and LANE_RE.fullmatch(key)}
|
|
183
|
+
out['fleet_admin'] = bare_address(data.get('fleet_admin'))
|
|
184
|
+
if isinstance(data.get('names_auto'), bool):
|
|
185
|
+
out['names_auto'] = data['names_auto']
|
|
186
|
+
return out
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def registry_lanes(root):
|
|
190
|
+
"""{lane id: entry} of <root>/registry.json (registry_export's `lanes`): {} when there is none yet. A newer
|
|
191
|
+
registry raises NewerVersion."""
|
|
192
|
+
return registry_export(root)['lanes']
|
|
141
193
|
|
|
142
194
|
|
|
143
195
|
def container_status(root, now=None):
|
|
@@ -310,15 +362,17 @@ def last_lines(text, lines):
|
|
|
310
362
|
return '\n'.join(rows[-lines:]) + '\n' if rows else ''
|
|
311
363
|
|
|
312
364
|
|
|
313
|
-
def new_session_argv(socket, session, cwd, lane_id, ws, command):
|
|
365
|
+
def new_session_argv(socket, session, cwd, lane_id, ws, command, address=None):
|
|
314
366
|
"""The one tmux client lane-mcp runs WITHOUT -N (`lanes_new`): it creates the session, and starts the socket's
|
|
315
367
|
server when none runs. The lane's identity reaches the session only through these `-e` flags, the canonical
|
|
316
368
|
recipe's eight (the client's own environment is creation_env(), an allow-list: whatever client starts a server
|
|
317
369
|
hands its environment to every later session there, DEF-1559, DEF-1802). `command` is one shell-command string,
|
|
318
|
-
run by the server's default shell like the recipe's command
|
|
370
|
+
run by the server's default shell like the recipe's command; a Claude Code command gets `--name <address>` (W15
|
|
371
|
+
L2c, claude_named; `address` defaults to the lane's derived one)."""
|
|
319
372
|
trace = lane_trace(lane_id, ws)
|
|
320
373
|
if trace is None:
|
|
321
374
|
raise LaneError(f'invalid lane trace: lanes/{ws}/{lane_id}', 'invalid_name')
|
|
375
|
+
command = claude_named(command, address or address_of(lane_id, {'ws': ws}))
|
|
322
376
|
return ['tmux', '-L', socket, 'new-session', '-d', '-s', session, '-x', '100', '-y', '30', '-c', cwd,
|
|
323
377
|
'-e', f'LANE_ID={lane_id}', '-e', f'LANE_WS={ws}',
|
|
324
378
|
'-e', f'ANTHROPIC_CUSTOM_HEADERS=x-throttle-trace: {trace}', '-e', f'THROTTLE_TRACE={trace}',
|
|
@@ -394,11 +448,14 @@ def lane_trace(lane_id, ws):
|
|
|
394
448
|
return trace if TRACE.fullmatch(trace) else None
|
|
395
449
|
|
|
396
450
|
|
|
397
|
-
def canonical_recipe(lane_id, ws, socket, session, folder, cmd='bash -l'):
|
|
451
|
+
def canonical_recipe(lane_id, ws, socket, session, folder, cmd='bash -l', address=None):
|
|
398
452
|
"""lanes_lib.canonical_recipe: the create recipe that gives a new tmux lane its identity (LANE_ID, LANE_WS, the
|
|
399
453
|
lanes/<ws>/<id> trace as ANTHROPIC_CUSTOM_HEADERS, THROTTLE_TRACE, KIMI_CODE_CUSTOM_HEADERS, LANES_TRACE and (W13)
|
|
400
454
|
MUSE_CUSTOM_HEADERS, and GROK_HOME) through `-e` flags; `new -A` attaches when the session exists. LaneError where
|
|
401
|
-
the host raises LanesError.
|
|
455
|
+
the host raises LanesError. W15 L2c (name parity): a Claude Code `cmd` is the host's recipe of
|
|
456
|
+
`claude_named(cmd, address)` — `… claude [its own options] --name <address>`, the address the lane's derived one
|
|
457
|
+
unless `address` names it; every other command, and the identity flags, exactly the host's
|
|
458
|
+
(test_lane_mcp_write.HostRules)."""
|
|
402
459
|
trace = lane_trace(lane_id, ws)
|
|
403
460
|
if trace is None:
|
|
404
461
|
raise LaneError(f'Invalid lane trace: lanes/{ws}/{lane_id} (allowed: A-Z a-z 0-9 . _ - /, at most 256)',
|
|
@@ -411,6 +468,7 @@ def canonical_recipe(lane_id, ws, socket, session, folder, cmd='bash -l'):
|
|
|
411
468
|
raise LaneError(f'Invalid lane folder: {folder!r}', 'invalid_cwd')
|
|
412
469
|
if not isinstance(cmd, str) or not cmd.strip():
|
|
413
470
|
raise LaneError('Invalid lane command', 'invalid_command')
|
|
471
|
+
cmd = claude_named(cmd, address or address_of(lane_id, {'ws': ws}))
|
|
414
472
|
header = shlex.quote(f'x-throttle-trace: {trace}')
|
|
415
473
|
return (f'tmux -L {shlex.quote(socket)} new -ADs {shlex.quote(session)} -c {shlex.quote(folder)} '
|
|
416
474
|
f'-e LANE_ID={lane_id} -e LANE_WS={ws} -e ANTHROPIC_CUSTOM_HEADERS={header} '
|
|
@@ -619,6 +677,683 @@ def whoami(root, environ=None, proc=Path('/proc'), parent=None):
|
|
|
619
677
|
'why': 'this tmux session is neither a registry lane nor an unregistered session statusd has seen'}
|
|
620
678
|
|
|
621
679
|
|
|
680
|
+
# ------------------------------------------------------------------------------------------------ addresses (W15 L2)
|
|
681
|
+
# Every lane has a registered messaging address (plan 2026-10-25-lanes-messaging-bus, L2/L2b/L2c; DM-LANES-ADDRESS):
|
|
682
|
+
# `<board>.<slug>`, the lane id `<board>--<slug>` with its `--` turned into `.`, or an alias the host's manifest sets
|
|
683
|
+
# (`<board>.<alias>`), which the registry export then carries as the entry's `address`. MEASURED (Claude Code 2.1.310,
|
|
684
|
+
# 2026-10-25): `/rename` refuses a name containing `--` and takes `worlds.worlds-packages`, and a dotted name is a valid
|
|
685
|
+
# bare `SendMessage` target, so the address is also the lane's Claude session name (name parity: Claude lanes are
|
|
686
|
+
# launched `claude --name <address>`, claude_named). A board is addressed as `@<board>` (its coordinator) and the
|
|
687
|
+
# site's fleet admin as `@fleet`. The display name is cosmetic: renaming a lane never changes its address.
|
|
688
|
+
|
|
689
|
+
FLEET = 'fleet' # `@fleet`: the site's fleet admin lane
|
|
690
|
+
ROLES = ('coordinator', 'fleet-admin') # a lane's `role`, else None
|
|
691
|
+
ADDRESS_RE = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}') # an address without its `@` (IDENT, bounded)
|
|
692
|
+
TARGET_RE = re.compile(r'@?[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}') # a lane id, or an address with an optional `@`
|
|
693
|
+
HANDLE_KINDS = ('claude-session', 'codex-thread', 'lane', 'claude-peer') # claude-peer: lane-peerd's (W15 L6)
|
|
694
|
+
TRANSPORTS = ('send_message', 'codex_queue', 'throttle_turn', 'typed')
|
|
695
|
+
THREAD_RE = re.compile(r'[A-Za-z0-9_.:-]{1,128}') # a Codex thread id as a sidecar records it
|
|
696
|
+
NO_AGENT = ('', 'shell', 'none') # harness words that mean no agent in the pane
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def bare_address(text):
|
|
700
|
+
"""`text` without its leading `@` when it reads as an address, else None."""
|
|
701
|
+
if not isinstance(text, str):
|
|
702
|
+
return None
|
|
703
|
+
text = text[1:] if text.startswith('@') else text
|
|
704
|
+
return text if ADDRESS_RE.fullmatch(text) else None
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def board_of(lane_id):
|
|
708
|
+
"""The board a lane id names (`<board>--…`), or None."""
|
|
709
|
+
board, sep, rest = lane_id.partition('--') if isinstance(lane_id, str) else ('', '', '')
|
|
710
|
+
return board if sep and board and rest else None
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
def address_of(lane_id, *facts):
|
|
714
|
+
"""A lane's registered address, without its `@`: the first of `facts` (its registry entry, its status.json row,
|
|
715
|
+
an unregistered session's row) that carries an `address` (the host's export: an alias override included), else
|
|
716
|
+
derived from the id — `<board>--<slug>` gives `<board>.<slug>`, an adopted `<board>--x-<hash>` gives
|
|
717
|
+
`<board>.x-<hash>` (the board from the facts' `ws`/`workspace` first, else the id's first `--`). None for an id
|
|
718
|
+
without a board (a zmx lane)."""
|
|
719
|
+
ws = None
|
|
720
|
+
for fact in facts:
|
|
721
|
+
if not isinstance(fact, dict):
|
|
722
|
+
continue
|
|
723
|
+
given = bare_address(fact.get('address'))
|
|
724
|
+
if given:
|
|
725
|
+
return given
|
|
726
|
+
ws = ws or fact.get('ws') or fact.get('workspace')
|
|
727
|
+
if not isinstance(lane_id, str):
|
|
728
|
+
return None
|
|
729
|
+
if isinstance(ws, str) and ws and lane_id.startswith(ws + '--') and len(lane_id) > len(ws) + 2:
|
|
730
|
+
return bare_address(f'{ws}.{lane_id[len(ws) + 2:]}')
|
|
731
|
+
board = board_of(lane_id)
|
|
732
|
+
return bare_address(f'{board}.{lane_id[len(board) + 2:]}') if board else None
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def fleet_admin_of(export):
|
|
736
|
+
"""(address, lane id in this container or None) of the site's fleet admin: the export's `fleet_admin`, else the
|
|
737
|
+
one lane whose `role` is `fleet-admin`; (None, None) when the site names none."""
|
|
738
|
+
lanes = export['lanes']
|
|
739
|
+
address = export.get('fleet_admin')
|
|
740
|
+
if address is None:
|
|
741
|
+
named = [lane for lane, entry in lanes.items() if entry.get('role') == 'fleet-admin']
|
|
742
|
+
return (address_of(named[0], lanes[named[0]]), named[0]) if len(named) == 1 else (None, None)
|
|
743
|
+
return address, next((lane for lane, entry in lanes.items() if address_of(lane, entry) == address), None)
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def coordinator_of(export, board):
|
|
747
|
+
"""The lane id of `board`'s coordinator, or None: the export's `boards.<board>.coordinator` (null included — the
|
|
748
|
+
host's word), else the one lane of the board whose `role` is `coordinator`."""
|
|
749
|
+
entry = export['boards'].get(board) if isinstance(board, str) else None
|
|
750
|
+
if isinstance(entry, dict) and 'coordinator' in entry:
|
|
751
|
+
lane = entry['coordinator']
|
|
752
|
+
return lane if isinstance(lane, str) and LANE_RE.fullmatch(lane) else None
|
|
753
|
+
named = [lane for lane, value in export['lanes'].items() if value.get('ws') == board and value.get('role') == 'coordinator']
|
|
754
|
+
return named[0] if len(named) == 1 else None
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def lane_role(lane_id, export, *facts):
|
|
758
|
+
"""`coordinator`, `fleet-admin` or None: the first of `facts` that carries a `role` key (the host's word, null
|
|
759
|
+
included), else derived — the fleet admin's lane is `fleet-admin` (also when it coordinates its board), a board's
|
|
760
|
+
coordinator `coordinator`."""
|
|
761
|
+
ws = None
|
|
762
|
+
for fact in facts:
|
|
763
|
+
if isinstance(fact, dict):
|
|
764
|
+
if 'role' in fact:
|
|
765
|
+
return fact['role'] if fact['role'] in ROLES else None
|
|
766
|
+
ws = ws or fact.get('ws') or fact.get('workspace')
|
|
767
|
+
if lane_id is not None and fleet_admin_of(export)[1] == lane_id:
|
|
768
|
+
return 'fleet-admin'
|
|
769
|
+
if lane_id is not None and coordinator_of(export, ws or board_of(lane_id)) == lane_id:
|
|
770
|
+
return 'coordinator'
|
|
771
|
+
return None
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
def resolve_address(root, text, export=None, status=None):
|
|
775
|
+
"""(lane id, registry entry or None) of what a tool's or verb's `lane` argument names (the entry is None for an
|
|
776
|
+
unregistered session, and for a lane id of another container that a board's coordinator names). Accepted, the
|
|
777
|
+
`@` optional throughout: an exact lane id of this container (the legacy `<board>--<slug>` spelling, also as
|
|
778
|
+
`@<board>--<slug>`); `fleet` → the fleet admin (`no_fleet_admin` when the site names none, `not_in_container`
|
|
779
|
+
when its lane is elsewhere); a registered address (address_of over the registry and the unregistered sessions);
|
|
780
|
+
a board → its coordinator (`no_coordinator` when it has none). Anything else is LaneError `unknown_address`."""
|
|
781
|
+
export = registry_export(root) if export is None else export
|
|
782
|
+
lanes = export['lanes']
|
|
783
|
+
if not isinstance(text, str) or not TARGET_RE.fullmatch(text):
|
|
784
|
+
raise LaneError(f'{text!r} is neither a lane id nor an address (@<board>.<lane>, @<board>, @fleet)',
|
|
785
|
+
'unknown_address')
|
|
786
|
+
name = text[1:] if text.startswith('@') else text
|
|
787
|
+
if name in lanes:
|
|
788
|
+
return name, lanes[name]
|
|
789
|
+
ghosts = (container_status(root) if status is None else status)['unregistered']
|
|
790
|
+
if any(row['id'] == name for row in ghosts):
|
|
791
|
+
return name, None
|
|
792
|
+
if name == FLEET:
|
|
793
|
+
address, lane = fleet_admin_of(export)
|
|
794
|
+
if address is None:
|
|
795
|
+
raise LaneError('this site names no fleet admin (the host\'s site.conf LANES_FLEET_ADMIN)', 'no_fleet_admin')
|
|
796
|
+
if lane is None:
|
|
797
|
+
raise LaneError(f'the fleet admin @{address} is not a lane of this container', 'not_in_container')
|
|
798
|
+
return lane, lanes[lane]
|
|
799
|
+
for lane, entry in lanes.items():
|
|
800
|
+
if address_of(lane, entry) == name:
|
|
801
|
+
return lane, entry
|
|
802
|
+
for row in ghosts:
|
|
803
|
+
if address_of(row['id'], row) == name:
|
|
804
|
+
return row['id'], None
|
|
805
|
+
if name in set(export['boards']) | {entry.get('ws') for entry in lanes.values()}:
|
|
806
|
+
lane = coordinator_of(export, name)
|
|
807
|
+
if lane is None:
|
|
808
|
+
raise LaneError(f'board {name} has no coordinator (its workspace manifest names none)', 'no_coordinator')
|
|
809
|
+
return lane, lanes.get(lane)
|
|
810
|
+
raise LaneError(f'no lane, address or board {text!r} in this container (lanes_list shows each lane\'s address)',
|
|
811
|
+
'unknown_address')
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
def routing_check(sender_lane, recipient_lane, export):
|
|
815
|
+
"""None when `sender_lane` may message `recipient_lane`, else 'use_coordinator' (plan L2b, operator 2026-10-25):
|
|
816
|
+
fleet and infrastructure needs travel lane → its board's coordinator → the fleet admin. So a message to the fleet
|
|
817
|
+
admin's lane is refused from any lane that is not a coordinator or the fleet admin itself, unless the fleet admin
|
|
818
|
+
is on the sender's own board (it is then the sender's coordinator or a board sibling). No sender (an agent outside
|
|
819
|
+
a lane) is no coordinator. Every other pair is allowed — within this container, as every write tool is."""
|
|
820
|
+
_address, admin = fleet_admin_of(export)
|
|
821
|
+
if admin is None or recipient_lane != admin or sender_lane == admin:
|
|
822
|
+
return None
|
|
823
|
+
lanes = export['lanes']
|
|
824
|
+
sender = lanes.get(sender_lane) if sender_lane else None
|
|
825
|
+
if sender_lane and lane_role(sender_lane, export, sender) in ROLES:
|
|
826
|
+
return None
|
|
827
|
+
board = (sender or {}).get('ws') or board_of(sender_lane)
|
|
828
|
+
if board and (board == lanes[admin].get('ws') or coordinator_of(export, board) == admin):
|
|
829
|
+
return None
|
|
830
|
+
return 'use_coordinator'
|
|
831
|
+
|
|
832
|
+
|
|
833
|
+
def handle(agent, lane=None, root=None, home=None, proc=None, fresh=False):
|
|
834
|
+
"""How a message reaches the agent in a lane: {'kind', 'name', 'transport'} (plan L2). A Claude session whose
|
|
835
|
+
messaging name is known — the host's `agent.messaging.name`, else the `name` of the Claude session file the
|
|
836
|
+
verdict came from — is `claude-session`, reached by the sender's own `SendMessage` (`send_message`); a Codex
|
|
837
|
+
agent whose thread id the hooks recorded (`session_id`) is `codex-thread` (`codex_queue`); any other harness, or
|
|
838
|
+
Claude/Codex without that name, is `lane` (`throttle_turn`, Throttle's next-turn delivery); a pane without an
|
|
839
|
+
agent (none, a shell) is `lane` (`typed`). The name is None for `lane`.
|
|
840
|
+
|
|
841
|
+
W15 L3: given the lane's id and this container's ~/.lz (`lane`, `root`; `home` defaults to its parent, `proc` to
|
|
842
|
+
/proc), a Codex agent without a recorded thread id falls back to Codex's own daemon (codex_handles: its cwd and
|
|
843
|
+
title against the live threads). A thread found there is `codex-thread` with the additive `via: 'app-server'` (an
|
|
844
|
+
inference, never the agent's own record); none adds `why` — `handle_ambiguous` when several threads fit, else
|
|
845
|
+
the reason (CODEX_WHY). Without `lane`/`root`, and in a container with no Codex daemon (`no_daemon`: the fallback
|
|
846
|
+
has nothing to ask), the answer is exactly the pre-L3 one. `fresh` (lane_core.message, at dispatch) asks the
|
|
847
|
+
daemon now instead of answering from CODEX_CACHE: a thread a status read saw seconds ago is never sent to."""
|
|
848
|
+
if not isinstance(agent, dict) or not agent.get('status') or agent.get('status') == 'shell' \
|
|
849
|
+
or str(agent.get('harness') or '') in NO_AGENT:
|
|
850
|
+
return {'kind': 'lane', 'name': None, 'transport': 'typed'}
|
|
851
|
+
harness = agent.get('harness')
|
|
852
|
+
messaging = agent.get('messaging') if isinstance(agent.get('messaging'), dict) else {}
|
|
853
|
+
if harness == 'claude':
|
|
854
|
+
name = messaging.get('name')
|
|
855
|
+
if not (isinstance(name, str) and name) and agent.get('source') == 'claude-session-file':
|
|
856
|
+
name = agent.get('name')
|
|
857
|
+
if isinstance(name, str) and name.strip() and len(name) <= NAME_MAX \
|
|
858
|
+
and not any(unicodedata.category(ch) in ('Cc', 'Cs') for ch in name):
|
|
859
|
+
return {'kind': 'claude-session', 'name': name, 'transport': 'send_message'}
|
|
860
|
+
if harness == 'codex' and isinstance(agent.get('session_id'), str) and THREAD_RE.fullmatch(agent['session_id']):
|
|
861
|
+
return {'kind': 'codex-thread', 'name': agent['session_id'], 'transport': 'codex_queue'}
|
|
862
|
+
if harness == 'codex' and lane is not None and root is not None:
|
|
863
|
+
found = codex_handles(root, home, proc, fresh=fresh).get(lane) or {'thread_id': None, 'why': 'no_match'}
|
|
864
|
+
if found['thread_id']:
|
|
865
|
+
return {'kind': 'codex-thread', 'name': found['thread_id'], 'transport': 'codex_queue', 'via': 'app-server'}
|
|
866
|
+
if found['why'] != 'no_daemon':
|
|
867
|
+
return {'kind': 'lane', 'name': None, 'transport': 'throttle_turn', 'why': found['why']}
|
|
868
|
+
return {'kind': 'lane', 'name': None, 'transport': 'throttle_turn'}
|
|
869
|
+
|
|
870
|
+
|
|
871
|
+
def name_match(agent, address):
|
|
872
|
+
"""Does the agent's messaging name equal the lane's address (plan L2c)? The host's `agent.name_match` when it
|
|
873
|
+
published one (a bool), else, for a Claude session whose name handle() knows, that name == `address`; None
|
|
874
|
+
otherwise (no agent, Codex until its sessions can be named, the other harnesses)."""
|
|
875
|
+
if isinstance(agent, dict) and isinstance(agent.get('name_match'), bool):
|
|
876
|
+
return agent['name_match']
|
|
877
|
+
found = handle(agent)
|
|
878
|
+
if found['kind'] == 'claude-session' and address:
|
|
879
|
+
return found['name'] == address
|
|
880
|
+
return None
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
def peer_handle(peer):
|
|
884
|
+
"""The handle a lane served by lane-peerd shows (W15 L6): `claude-peer`, its virtual peer's name (the lane's
|
|
885
|
+
address), reached by a Claude sender's own `SendMessage` (`send_message`) — whatever its agent's own handle is.
|
|
886
|
+
lane_core.message keeps routing a non-Claude sender by handle(), never by this view."""
|
|
887
|
+
return {'kind': 'claude-peer', 'name': peer['name'], 'transport': 'send_message'}
|
|
888
|
+
|
|
889
|
+
|
|
890
|
+
def shown_handle(agent, peer=None, summary=False, lane=None, root=None, home=None, proc=None):
|
|
891
|
+
"""A lane's `handle` as the tools show it: peer_handle() while lane-peerd serves it as a virtual peer, else
|
|
892
|
+
handle(agent); `summary` (a lanes_list row) keeps kind and name only — a virtual peer's transport stays, the one
|
|
893
|
+
thing a row needs to say that a Claude sender's SendMessage reaches it."""
|
|
894
|
+
found = peer_handle(peer) if peer else handle(agent, lane, root, home, proc) # W15 L3: the Codex daemon fallback
|
|
895
|
+
return {'kind': found['kind'], 'name': found['name'], **({'transport': found['transport']} if peer else {})} \
|
|
896
|
+
if summary else found
|
|
897
|
+
|
|
898
|
+
|
|
899
|
+
def addressing(root, lane_id, entry=None, row=None, observed=None, export=None, home=None, proc=None, peers=None):
|
|
900
|
+
"""What lanes_whoami (and `lane address`) say about a lane's addressing: {'address', 'role', 'coordinator',
|
|
901
|
+
'fleet_admin', 'handle', 'name_match'} — addresses without their `@`; `coordinator` is the address of the
|
|
902
|
+
lane's board's coordinator (its own when it is one), `fleet_admin` the site's fleet admin. A lane lane-peerd
|
|
903
|
+
serves (`peers`, else virtual_peers(root)) shows its virtual peer's handle and matches by that name (W15 L6);
|
|
904
|
+
otherwise the handle takes the Codex fallback (W15 L3: handle with the lane, `root`, `home` and `proc`)."""
|
|
905
|
+
export = registry_export(root) if export is None else export
|
|
906
|
+
observed = observed if isinstance(observed, dict) else {}
|
|
907
|
+
agent = observed.get('agent') if isinstance(observed.get('agent'), dict) else None
|
|
908
|
+
address = address_of(lane_id, entry, observed, row)
|
|
909
|
+
board = next((fact.get('ws') or fact.get('workspace') for fact in (entry, row) if isinstance(fact, dict)
|
|
910
|
+
and (fact.get('ws') or fact.get('workspace'))), None) or board_of(lane_id)
|
|
911
|
+
coordinator = coordinator_of(export, board)
|
|
912
|
+
peer = ((virtual_peers(root) if peers is None else peers).get(lane_id)) if lane_id else None
|
|
913
|
+
return {'address': address, 'role': lane_role(lane_id, export, entry, observed, row) if lane_id else None,
|
|
914
|
+
'coordinator': address_of(coordinator, export['lanes'].get(coordinator)) if coordinator else None,
|
|
915
|
+
'fleet_admin': fleet_admin_of(export)[0],
|
|
916
|
+
'handle': shown_handle(agent, peer, lane=lane_id, root=root, home=home, proc=proc) if lane_id else None,
|
|
917
|
+
'name_match': (peer['name'] == address if peer else name_match(agent, address)) if lane_id else None}
|
|
918
|
+
|
|
919
|
+
|
|
920
|
+
NAME_FLAGS = ('--name', '-n') # Claude Code 2.1.310's session-name option (MEASURED: `-n, --name <name>`)
|
|
921
|
+
SHELL_OPERATORS = set('();<>|&')
|
|
922
|
+
|
|
923
|
+
|
|
924
|
+
def claude_named(command, address):
|
|
925
|
+
"""`command` with ` --name <address>` appended when it starts Claude Code (plan L2c, name parity: the address IS
|
|
926
|
+
the lane's messaging name): its first word — after `exec` and `NAME=value` words — is `claude` or a path ending
|
|
927
|
+
`/claude`. Left as it is: any other command, a compound one (a shell operator), one with `--` or a session name
|
|
928
|
+
of its own (`--name`, `-n`, `--name=`), and an address that is not one. The text before the appended option is
|
|
929
|
+
kept byte for byte (the operator's own quoting)."""
|
|
930
|
+
address = bare_address(address)
|
|
931
|
+
if not address or not isinstance(command, str):
|
|
932
|
+
return command
|
|
933
|
+
try:
|
|
934
|
+
lexer = shlex.shlex(command, posix=True, punctuation_chars=True)
|
|
935
|
+
lexer.whitespace_split = True
|
|
936
|
+
words = list(lexer)
|
|
937
|
+
except ValueError:
|
|
938
|
+
return command
|
|
939
|
+
while words and (words[0] == 'exec' or re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*=.*', words[0], re.S)):
|
|
940
|
+
words = words[1:]
|
|
941
|
+
if not words or words[0].rpartition('/')[2] != 'claude':
|
|
942
|
+
return command
|
|
943
|
+
if any(set(word) <= SHELL_OPERATORS for word in words) or '--' in words[1:]:
|
|
944
|
+
return command
|
|
945
|
+
if any(word in NAME_FLAGS or word.startswith('--name=') for word in words[1:]):
|
|
946
|
+
return command
|
|
947
|
+
return f'{command.rstrip()} --name {shlex.quote(address)}'
|
|
948
|
+
|
|
949
|
+
|
|
950
|
+
# ----------------------------------------------------------------------------------------------- Codex threads (W15 L3)
|
|
951
|
+
# Linear BEY-6841 ("Lanes: Codex lanes addressable without hooks").
|
|
952
|
+
# A Codex lane is addressable (`codex queue --thread <id>`) once Lanes knows its thread id. The Codex hooks record it
|
|
953
|
+
# (`lanes hooks install --agent codex`: lane-signal's `session`), but on 2026-10-25 no container had them and 0 of 27
|
|
954
|
+
# Codex lanes had a thread id. MEASURED then (Codex CLI 0.164.0; test_codex_contract pins it, fixtures/codex/
|
|
955
|
+
# thread-list.json records it): every Codex TUI runs its threads on ONE shared app-server daemon whose control socket
|
|
956
|
+
# is ~/.codex/app-server-control/app-server-control.sock — a link Codex plants to /tmp/codex-daemon-<uid>/<sha256>,
|
|
957
|
+
# mode 0600 in a 0700 directory — speaking WebSocket (HTTP/1.1 101, one JSON-RPC message per text frame, no
|
|
958
|
+
# `jsonrpc` member). `thread/list` returns every non-archived thread, live or not (its first 100: 373,939 bytes, 87
|
|
959
|
+
# `notLoaded`), so a bounded read cannot promise to reach every live one; `thread/loaded/list` names the threads the
|
|
960
|
+
# daemon holds (21, 865 bytes) and `thread/read` {includeTurns: false} gives each one's metadata (32,830 bytes in
|
|
961
|
+
# all). A lane's thread is the live top-level thread whose `cwd` is its Codex process's (readlink /proc/<pid>/cwd);
|
|
962
|
+
# several there are told apart by the title Codex draws, which is the thread's `name` (MEASURED: 17 of 17 named live
|
|
963
|
+
# threads equal to their pane's title; an unnamed thread's title says something else). Read-only: initialize,
|
|
964
|
+
# thread/loaded/list, thread/read — never a write, never a turn, nothing typed into a lane.
|
|
965
|
+
|
|
966
|
+
CODEX_CONTROL = ('.codex', 'app-server-control') # real directories under the home: a link is never followed
|
|
967
|
+
CODEX_SOCKET = 'app-server-control.sock' # the socket, or Codex's link to it (codex_socket)
|
|
968
|
+
CODEX_TIMEOUT = 2.0 # seconds for the whole conversation
|
|
969
|
+
CODEX_READ_MAX = 1 << 20 # bytes read from the daemon, at most, per conversation
|
|
970
|
+
CODEX_LOADED_MAX = 256 # loaded threads read, at most (`truncated` beyond)
|
|
971
|
+
CODEX_CACHE_S = 10 # codex_handles answers this long from one conversation
|
|
972
|
+
CODEX_METHODS = ('initialize', 'thread/loaded/list', 'thread/read')
|
|
973
|
+
CODEX_WHY = ('no_daemon', 'unsafe_socket', 'unreachable', 'timeout', 'too_big', 'protocol', 'truncated', 'no_pid',
|
|
974
|
+
'no_match', 'handle_ambiguous')
|
|
975
|
+
CODEX_CLIENT = {'name': 'lanes', 'title': None, 'version': '1'}
|
|
976
|
+
WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' # RFC 6455's accept suffix
|
|
977
|
+
CODEX_CACHE = {} # (root, home, proc) -> (monotonic time, codex_handles answer)
|
|
978
|
+
|
|
979
|
+
|
|
980
|
+
class CodexThreads(list):
|
|
981
|
+
"""codex_threads' answer: a list of {'thread_id', 'name', 'cwd', 'updated_at'}, and `why` — None, or why the list
|
|
982
|
+
is empty (or, for `truncated`, partial): a CODEX_WHY word."""
|
|
983
|
+
|
|
984
|
+
def __init__(self, items=(), why=None):
|
|
985
|
+
super().__init__(items)
|
|
986
|
+
self.why = why
|
|
987
|
+
|
|
988
|
+
|
|
989
|
+
class CodexError(Exception):
|
|
990
|
+
def __init__(self, why):
|
|
991
|
+
super().__init__(why)
|
|
992
|
+
self.why = why
|
|
993
|
+
|
|
994
|
+
|
|
995
|
+
def _private_dir(path, uid):
|
|
996
|
+
"""`path` is a real directory (not a link) owned by `uid` that no one else may enter or write."""
|
|
997
|
+
info = os.lstat(path)
|
|
998
|
+
return stat.S_ISDIR(info.st_mode) and info.st_uid == uid and not info.st_mode & 0o077
|
|
999
|
+
|
|
1000
|
+
|
|
1001
|
+
def codex_socket(home):
|
|
1002
|
+
"""(path, None) of the daemon's control socket under `home`, or (None, why). Neither ~/.codex nor
|
|
1003
|
+
app-server-control may be a link. The entry itself is the socket, or the ONE link Codex plants: read with
|
|
1004
|
+
readlink, never resolved through further links — an absolute normal path to a socket of this uid whose directory
|
|
1005
|
+
is a private one of this uid (/tmp/codex-daemon-<uid>/, 0700). Anything else is `unsafe_socket`; no entry (or no
|
|
1006
|
+
~/.codex) is `no_daemon`."""
|
|
1007
|
+
uid = os.getuid()
|
|
1008
|
+
base = Path(home)
|
|
1009
|
+
try:
|
|
1010
|
+
for part in CODEX_CONTROL:
|
|
1011
|
+
base = base / part
|
|
1012
|
+
if not stat.S_ISDIR(os.lstat(base).st_mode):
|
|
1013
|
+
return None, 'unsafe_socket'
|
|
1014
|
+
entry = base / CODEX_SOCKET
|
|
1015
|
+
info = os.lstat(entry)
|
|
1016
|
+
except FileNotFoundError:
|
|
1017
|
+
return None, 'no_daemon'
|
|
1018
|
+
except OSError:
|
|
1019
|
+
return None, 'unsafe_socket'
|
|
1020
|
+
try:
|
|
1021
|
+
if stat.S_ISSOCK(info.st_mode):
|
|
1022
|
+
return (str(entry), None) if info.st_uid == uid and _private_dir(base, uid) else (None, 'unsafe_socket')
|
|
1023
|
+
if not stat.S_ISLNK(info.st_mode):
|
|
1024
|
+
return None, 'unsafe_socket'
|
|
1025
|
+
target = os.readlink(entry)
|
|
1026
|
+
if not os.path.isabs(target) or os.path.normpath(target) != target:
|
|
1027
|
+
return None, 'unsafe_socket'
|
|
1028
|
+
found = os.lstat(target)
|
|
1029
|
+
if not (stat.S_ISSOCK(found.st_mode) and found.st_uid == uid and _private_dir(os.path.dirname(target), uid)):
|
|
1030
|
+
return None, 'unsafe_socket'
|
|
1031
|
+
except FileNotFoundError:
|
|
1032
|
+
return None, 'unreachable' # Codex's link to a daemon that is gone
|
|
1033
|
+
except OSError:
|
|
1034
|
+
return None, 'unsafe_socket'
|
|
1035
|
+
return target, None
|
|
1036
|
+
|
|
1037
|
+
|
|
1038
|
+
class _CodexSocket:
|
|
1039
|
+
"""One WebSocket conversation with the daemon (RFC 6455 client: masked frames; a ping answered, pongs and
|
|
1040
|
+
notifications skipped), bounded by a deadline and a byte budget for everything read."""
|
|
1041
|
+
|
|
1042
|
+
def __init__(self, path, timeout, limit):
|
|
1043
|
+
self.deadline = time.monotonic() + timeout
|
|
1044
|
+
self.limit, self.read, self.buf, self.answers = limit, 0, b'', {}
|
|
1045
|
+
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
1046
|
+
try:
|
|
1047
|
+
self.sock.settimeout(max(0.01, timeout))
|
|
1048
|
+
self.sock.connect(path)
|
|
1049
|
+
except socket.timeout:
|
|
1050
|
+
self.sock.close()
|
|
1051
|
+
raise CodexError('timeout') from None
|
|
1052
|
+
except OSError:
|
|
1053
|
+
self.sock.close()
|
|
1054
|
+
raise CodexError('unreachable') from None
|
|
1055
|
+
|
|
1056
|
+
def close(self):
|
|
1057
|
+
self.sock.close()
|
|
1058
|
+
|
|
1059
|
+
def _io(self, call, *args):
|
|
1060
|
+
left = self.deadline - time.monotonic()
|
|
1061
|
+
if left <= 0:
|
|
1062
|
+
raise CodexError('timeout')
|
|
1063
|
+
try:
|
|
1064
|
+
self.sock.settimeout(left)
|
|
1065
|
+
return call(*args)
|
|
1066
|
+
except socket.timeout:
|
|
1067
|
+
raise CodexError('timeout') from None
|
|
1068
|
+
except OSError:
|
|
1069
|
+
raise CodexError('protocol') from None # the daemon dropped the conversation
|
|
1070
|
+
|
|
1071
|
+
def _more(self):
|
|
1072
|
+
chunk = self._io(self.sock.recv, 1 << 16)
|
|
1073
|
+
if not chunk:
|
|
1074
|
+
raise CodexError('protocol')
|
|
1075
|
+
self.read += len(chunk)
|
|
1076
|
+
if self.read > self.limit:
|
|
1077
|
+
raise CodexError('too_big')
|
|
1078
|
+
self.buf += chunk
|
|
1079
|
+
|
|
1080
|
+
def _take(self, n):
|
|
1081
|
+
if n > self.limit:
|
|
1082
|
+
raise CodexError('too_big')
|
|
1083
|
+
while len(self.buf) < n:
|
|
1084
|
+
self._more()
|
|
1085
|
+
out, self.buf = self.buf[:n], self.buf[n:]
|
|
1086
|
+
return out
|
|
1087
|
+
|
|
1088
|
+
def handshake(self):
|
|
1089
|
+
key = base64.b64encode(os.urandom(16)).decode()
|
|
1090
|
+
request = ('GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n'
|
|
1091
|
+
f'Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n')
|
|
1092
|
+
self._io(self.sock.sendall, request.encode())
|
|
1093
|
+
while b'\r\n\r\n' not in self.buf:
|
|
1094
|
+
if len(self.buf) > 16 << 10:
|
|
1095
|
+
raise CodexError('protocol')
|
|
1096
|
+
self._more()
|
|
1097
|
+
head, _, self.buf = self.buf.partition(b'\r\n\r\n')
|
|
1098
|
+
lines = head.decode('latin-1').split('\r\n')
|
|
1099
|
+
headers = {line.partition(':')[0].strip().lower(): line.partition(':')[2].strip() for line in lines[1:]}
|
|
1100
|
+
accept = base64.b64encode(hashlib.sha1((key + WS_GUID).encode()).digest()).decode()
|
|
1101
|
+
if not lines[0].startswith('HTTP/1.1 101') or headers.get('sec-websocket-accept') != accept:
|
|
1102
|
+
raise CodexError('protocol')
|
|
1103
|
+
|
|
1104
|
+
def _frame(self, opcode, data):
|
|
1105
|
+
mask = os.urandom(4)
|
|
1106
|
+
n = len(data)
|
|
1107
|
+
head = bytes([0x80 | opcode]) + (bytes([0x80 | n]) if n < 126 else bytes([0x80 | 126]) + struct.pack('!H', n)
|
|
1108
|
+
if n < 1 << 16 else bytes([0x80 | 127]) + struct.pack('!Q', n))
|
|
1109
|
+
masked = bytes(byte ^ mask[i & 3] for i, byte in enumerate(data))
|
|
1110
|
+
self._io(self.sock.sendall, head + mask + masked)
|
|
1111
|
+
|
|
1112
|
+
def send(self, message):
|
|
1113
|
+
self._frame(0x1, json.dumps(message, separators=(',', ':')).encode())
|
|
1114
|
+
|
|
1115
|
+
def _message(self):
|
|
1116
|
+
"""The next complete data message (text or binary; fragments joined) as JSON."""
|
|
1117
|
+
parts = []
|
|
1118
|
+
while True:
|
|
1119
|
+
first, second = self._take(2)
|
|
1120
|
+
opcode, n = first & 0x0f, second & 0x7f
|
|
1121
|
+
if n == 126:
|
|
1122
|
+
n = struct.unpack('!H', self._take(2))[0]
|
|
1123
|
+
elif n == 127:
|
|
1124
|
+
n = struct.unpack('!Q', self._take(8))[0]
|
|
1125
|
+
mask = self._take(4) if second & 0x80 else None
|
|
1126
|
+
data = self._take(n)
|
|
1127
|
+
if mask:
|
|
1128
|
+
data = bytes(byte ^ mask[i & 3] for i, byte in enumerate(data))
|
|
1129
|
+
if opcode == 0x8:
|
|
1130
|
+
raise CodexError('protocol') # the daemon closed the conversation
|
|
1131
|
+
if opcode == 0x9:
|
|
1132
|
+
self._frame(0xa, data) # a ping: its pong
|
|
1133
|
+
continue
|
|
1134
|
+
if opcode == 0xa:
|
|
1135
|
+
continue
|
|
1136
|
+
parts.append(data)
|
|
1137
|
+
if first & 0x80:
|
|
1138
|
+
try:
|
|
1139
|
+
return json.loads(b''.join(parts).decode('utf-8'))
|
|
1140
|
+
except ValueError:
|
|
1141
|
+
raise CodexError('protocol') from None
|
|
1142
|
+
|
|
1143
|
+
def result(self, ident, refused_ok=False):
|
|
1144
|
+
"""The `result` of the response to request `ident`; a JSON-RPC error is None with `refused_ok`, else (and a
|
|
1145
|
+
reply that is not one) `protocol`. Notifications and the daemon's own requests (a `method` beside the `id`)
|
|
1146
|
+
are skipped."""
|
|
1147
|
+
while ident not in self.answers:
|
|
1148
|
+
message = self._message()
|
|
1149
|
+
if isinstance(message, dict) and 'id' in message and 'method' not in message:
|
|
1150
|
+
self.answers[message['id']] = message
|
|
1151
|
+
answer = self.answers.pop(ident)
|
|
1152
|
+
if 'error' in answer and refused_ok:
|
|
1153
|
+
return None
|
|
1154
|
+
if 'error' in answer or not isinstance(answer.get('result'), dict):
|
|
1155
|
+
raise CodexError('protocol')
|
|
1156
|
+
return answer['result']
|
|
1157
|
+
|
|
1158
|
+
|
|
1159
|
+
def _codex_live(thread):
|
|
1160
|
+
"""{'thread_id', 'name', 'cwd', 'updated_at'} of a Thread that is live (loaded: not `notLoaded`) and top level
|
|
1161
|
+
(no parent, not a sub-agent's), else None."""
|
|
1162
|
+
if not isinstance(thread, dict) or (thread.get('status') or {}).get('type') in (None, 'notLoaded'):
|
|
1163
|
+
return None
|
|
1164
|
+
source = thread.get('source')
|
|
1165
|
+
if thread.get('parentThreadId') or (isinstance(source, dict) and 'subAgent' in source):
|
|
1166
|
+
return None
|
|
1167
|
+
ident, cwd, name, updated = thread.get('id'), thread.get('cwd'), thread.get('name'), thread.get('updatedAt')
|
|
1168
|
+
if not (isinstance(ident, str) and THREAD_RE.fullmatch(ident) and isinstance(cwd, str) and cwd.startswith('/')):
|
|
1169
|
+
return None
|
|
1170
|
+
return {'thread_id': ident, 'name': name if isinstance(name, str) and name else None, 'cwd': cwd,
|
|
1171
|
+
'updated_at': updated if isinstance(updated, int) and not isinstance(updated, bool) else None}
|
|
1172
|
+
|
|
1173
|
+
|
|
1174
|
+
def codex_threads(home, timeout=CODEX_TIMEOUT):
|
|
1175
|
+
"""The Codex daemon's live top-level threads (CodexThreads), asked over its control socket under `home`
|
|
1176
|
+
(codex_socket): `initialize`, the `initialized` notification, `thread/loaded/list`, then `thread/read`
|
|
1177
|
+
{includeTurns: false} for each loaded id (at most CODEX_LOADED_MAX, pipelined), within `timeout` seconds and
|
|
1178
|
+
CODEX_READ_MAX bytes. Never raises: any failure is an empty list whose `why` says which (CODEX_WHY)."""
|
|
1179
|
+
path, why = codex_socket(home)
|
|
1180
|
+
if why:
|
|
1181
|
+
return CodexThreads(why=why)
|
|
1182
|
+
try:
|
|
1183
|
+
conversation = _CodexSocket(path, timeout, CODEX_READ_MAX)
|
|
1184
|
+
except CodexError as error:
|
|
1185
|
+
return CodexThreads(why=error.why)
|
|
1186
|
+
try:
|
|
1187
|
+
conversation.handshake()
|
|
1188
|
+
conversation.send({'id': 1, 'method': 'initialize', 'params': {'clientInfo': CODEX_CLIENT}})
|
|
1189
|
+
conversation.result(1)
|
|
1190
|
+
conversation.send({'method': 'initialized'})
|
|
1191
|
+
conversation.send({'id': 2, 'method': 'thread/loaded/list', 'params': {}})
|
|
1192
|
+
ids = conversation.result(2).get('data')
|
|
1193
|
+
if not isinstance(ids, list):
|
|
1194
|
+
raise CodexError('protocol')
|
|
1195
|
+
ids = [ident for ident in ids if isinstance(ident, str) and THREAD_RE.fullmatch(ident)]
|
|
1196
|
+
asked = ids[:CODEX_LOADED_MAX]
|
|
1197
|
+
for index, ident in enumerate(asked):
|
|
1198
|
+
conversation.send({'id': 3 + index, 'method': 'thread/read',
|
|
1199
|
+
'params': {'threadId': ident, 'includeTurns': False}})
|
|
1200
|
+
found = []
|
|
1201
|
+
for index in range(len(asked)):
|
|
1202
|
+
answer = conversation.result(3 + index, refused_ok=True) # refused: unloaded since the list
|
|
1203
|
+
thread = _codex_live(answer.get('thread')) if answer else None
|
|
1204
|
+
if thread:
|
|
1205
|
+
found.append(thread)
|
|
1206
|
+
return CodexThreads(found, 'truncated' if len(ids) > len(asked) else None)
|
|
1207
|
+
except CodexError as error:
|
|
1208
|
+
return CodexThreads(why=error.why)
|
|
1209
|
+
finally:
|
|
1210
|
+
conversation.close()
|
|
1211
|
+
|
|
1212
|
+
|
|
1213
|
+
def codex_assign(lanes, threads, taken=()):
|
|
1214
|
+
"""{lane: (thread id | None, why | None)} for `lanes` {lane: {'cwd', 'name', 'source'}} — the cwd of the lane's
|
|
1215
|
+
Codex process (None: not found) and its agent's name and source — over the live `threads` (codex_threads), the
|
|
1216
|
+
ids in `taken` (recorded by hooks for other lanes) left out. At the lane's cwd: a title (`source: title`, which
|
|
1217
|
+
is the thread's name as Codex draws it) picks the threads named so, else the unnamed ones; without a title every
|
|
1218
|
+
thread there counts. One is the lane's; several are `handle_ambiguous`; none is `no_match`. A thread two lanes
|
|
1219
|
+
would take is neither's (`handle_ambiguous`)."""
|
|
1220
|
+
pool = [thread for thread in threads if thread['thread_id'] not in set(taken)]
|
|
1221
|
+
out = {}
|
|
1222
|
+
for lane, fact in lanes.items():
|
|
1223
|
+
cwd = fact.get('cwd')
|
|
1224
|
+
if not cwd:
|
|
1225
|
+
out[lane] = (None, 'no_pid')
|
|
1226
|
+
continue
|
|
1227
|
+
here = [thread for thread in pool if thread['cwd'] == cwd]
|
|
1228
|
+
title = fact.get('name') if fact.get('source') == 'title' and isinstance(fact.get('name'), str) else ''
|
|
1229
|
+
if title:
|
|
1230
|
+
here = [thread for thread in here if thread['name'] == title] or \
|
|
1231
|
+
[thread for thread in here if not thread['name']]
|
|
1232
|
+
out[lane] = (here[0]['thread_id'], None) if len(here) == 1 else \
|
|
1233
|
+
(None, 'handle_ambiguous') if here else (None, 'no_match')
|
|
1234
|
+
claimed = {}
|
|
1235
|
+
for thread_id, _why in out.values():
|
|
1236
|
+
if thread_id:
|
|
1237
|
+
claimed[thread_id] = claimed.get(thread_id, 0) + 1
|
|
1238
|
+
return {lane: (None, 'handle_ambiguous') if found and claimed[found] > 1 else (found, why)
|
|
1239
|
+
for lane, (found, why) in out.items()}
|
|
1240
|
+
|
|
1241
|
+
|
|
1242
|
+
def _children(proc, pid):
|
|
1243
|
+
"""The children of `pid` (/proc/<pid>/task/*/children), [] when unreadable."""
|
|
1244
|
+
kids = []
|
|
1245
|
+
try:
|
|
1246
|
+
tasks = os.listdir(Path(proc) / str(pid) / 'task')
|
|
1247
|
+
except OSError:
|
|
1248
|
+
return kids
|
|
1249
|
+
for task in tasks:
|
|
1250
|
+
data = read_regular(Path(proc) / str(pid) / 'task' / task / 'children', 1 << 16) if task.isdigit() else None
|
|
1251
|
+
kids.extend(int(word) for word in (data or b'').split() if word.isdigit())
|
|
1252
|
+
return kids
|
|
1253
|
+
|
|
1254
|
+
|
|
1255
|
+
def codex_pid(proc, pid, depth=PARENT_DEPTH, budget=64):
|
|
1256
|
+
"""`pid` or the first of its descendants (breadth first, at most `depth` levels and `budget` processes) that is a
|
|
1257
|
+
Codex client — a `codex` process (process_harness) that is not an `app-server` — else None. MEASURED: a Codex
|
|
1258
|
+
lane is `bash` -> `node` (the npm wrapper) -> `codex`."""
|
|
1259
|
+
level = [pid] if isinstance(pid, int) and pid > 1 else []
|
|
1260
|
+
seen = 0
|
|
1261
|
+
for _step in range(depth + 1):
|
|
1262
|
+
following = []
|
|
1263
|
+
for candidate in level:
|
|
1264
|
+
seen += 1
|
|
1265
|
+
if seen > budget:
|
|
1266
|
+
return None
|
|
1267
|
+
if process_harness(proc, candidate) == 'codex':
|
|
1268
|
+
argv = (read_regular(Path(proc) / str(candidate) / 'cmdline', 1 << 16) or b'').split(b'\0')
|
|
1269
|
+
if b'app-server' not in argv[1:3]:
|
|
1270
|
+
return candidate
|
|
1271
|
+
following.extend(_children(proc, candidate))
|
|
1272
|
+
level = following
|
|
1273
|
+
if not level:
|
|
1274
|
+
return None
|
|
1275
|
+
return None
|
|
1276
|
+
|
|
1277
|
+
|
|
1278
|
+
def _cwd(proc, pid):
|
|
1279
|
+
"""readlink /proc/<pid>/cwd, or None (gone, unreadable, deleted)."""
|
|
1280
|
+
try:
|
|
1281
|
+
cwd = os.readlink(str(Path(proc) / str(pid) / 'cwd'))
|
|
1282
|
+
except OSError:
|
|
1283
|
+
return None
|
|
1284
|
+
return cwd if cwd.startswith('/') and not cwd.endswith(' (deleted)') else None
|
|
1285
|
+
|
|
1286
|
+
|
|
1287
|
+
def _pane_pids(socket_name):
|
|
1288
|
+
"""{session: [pane pid]} of one tmux socket (`list-panes -a`), {} when it does not answer."""
|
|
1289
|
+
result = run_tmux(tmux_argv(socket_name, 'list-panes', '-a', '-F', '#{session_name}\t#{pane_pid}'), timeout=2)
|
|
1290
|
+
panes = {}
|
|
1291
|
+
for line in result.stdout.splitlines() if result.returncode == 0 else ():
|
|
1292
|
+
session, _, pid = line.rpartition('\t')
|
|
1293
|
+
if session and pid.isdigit():
|
|
1294
|
+
panes.setdefault(session, []).append(int(pid))
|
|
1295
|
+
return panes
|
|
1296
|
+
|
|
1297
|
+
|
|
1298
|
+
def _needs_thread(agent):
|
|
1299
|
+
"""A Codex agent in its pane without a thread id a hook recorded."""
|
|
1300
|
+
return isinstance(agent, dict) and agent.get('harness') == 'codex' and agent.get('status') in STATUSES \
|
|
1301
|
+
and agent.get('status') != 'shell' \
|
|
1302
|
+
and not (isinstance(agent.get('session_id'), str) and THREAD_RE.fullmatch(agent['session_id']))
|
|
1303
|
+
|
|
1304
|
+
|
|
1305
|
+
def codex_handles(root, home=None, proc=None, now=None, fresh=False):
|
|
1306
|
+
"""{lane id: {'thread_id', 'why'}} for every Codex lane of this container (status.json) without a recorded
|
|
1307
|
+
thread id — the fallback handle() takes. One daemon conversation (codex_threads, under `home`: the parent of
|
|
1308
|
+
`root` by default) and, only when it named live threads, one `list-panes -a` per tmux socket those lanes live on
|
|
1309
|
+
and a bounded walk of /proc (`proc`) from each pane to its Codex client (an agent's own `pid` first); then
|
|
1310
|
+
codex_assign. Answered from CODEX_CACHE for CODEX_CACHE_S per (root, home, proc) unless `fresh` (asked now, the
|
|
1311
|
+
answer cached for the next reader). Never raises."""
|
|
1312
|
+
root = Path(root)
|
|
1313
|
+
home = root.parent if home is None else Path(home)
|
|
1314
|
+
proc = Path('/proc') if proc is None else Path(proc)
|
|
1315
|
+
key, clock = (str(root), str(home), str(proc)), time.monotonic() if now is None else now
|
|
1316
|
+
cached = CODEX_CACHE.get(key)
|
|
1317
|
+
if cached and not fresh and 0 <= clock - cached[0] < CODEX_CACHE_S:
|
|
1318
|
+
return cached[1]
|
|
1319
|
+
try:
|
|
1320
|
+
answer = _codex_handles(root, home, proc)
|
|
1321
|
+
except (LaneError, OSError, ValueError, TypeError, KeyError):
|
|
1322
|
+
answer = {}
|
|
1323
|
+
CODEX_CACHE[key] = (clock, answer)
|
|
1324
|
+
return answer
|
|
1325
|
+
|
|
1326
|
+
|
|
1327
|
+
def _codex_handles(root, home, proc):
|
|
1328
|
+
status = container_status(root)
|
|
1329
|
+
wanted = {lane: row['agent'] for lane, row in status['lanes'].items() if _needs_thread(row.get('agent'))}
|
|
1330
|
+
if not wanted:
|
|
1331
|
+
return {}
|
|
1332
|
+
threads = codex_threads(home)
|
|
1333
|
+
if not threads:
|
|
1334
|
+
return {lane: {'thread_id': None, 'why': threads.why or 'no_match'} for lane in wanted}
|
|
1335
|
+
lanes = registry_export(root)['lanes']
|
|
1336
|
+
ghosts = {row['id']: row for row in status['unregistered']}
|
|
1337
|
+
taken = {row['agent']['session_id'] for row in status['lanes'].values() if isinstance(row.get('agent'), dict)
|
|
1338
|
+
and row['agent'].get('harness') == 'codex' and isinstance(row['agent'].get('session_id'), str)}
|
|
1339
|
+
panes, facts = {}, {}
|
|
1340
|
+
for lane, agent in wanted.items():
|
|
1341
|
+
pid = codex_pid(proc, agent.get('pid')) if isinstance(agent.get('pid'), int) else None
|
|
1342
|
+
held = tmux_target(lanes[lane]) if lane in lanes else None
|
|
1343
|
+
if held is None and lane in ghosts:
|
|
1344
|
+
tmux = ghosts[lane].get('tmux') or {}
|
|
1345
|
+
held = (str(tmux['socket']), str(tmux['session'])) if tmux.get('socket') and tmux.get('session') else None
|
|
1346
|
+
if pid is None and held:
|
|
1347
|
+
if held[0] not in panes:
|
|
1348
|
+
panes[held[0]] = _pane_pids(held[0])
|
|
1349
|
+
pid = next((found for found in (codex_pid(proc, pane) for pane in panes[held[0]].get(held[1], []))
|
|
1350
|
+
if found), None)
|
|
1351
|
+
facts[lane] = {'cwd': _cwd(proc, pid) if pid else None, 'name': agent.get('name'),
|
|
1352
|
+
'source': agent.get('source')}
|
|
1353
|
+
assigned = codex_assign(facts, threads, taken)
|
|
1354
|
+
return {lane: {'thread_id': found, 'why': why} for lane, (found, why) in assigned.items()}
|
|
1355
|
+
|
|
1356
|
+
|
|
622
1357
|
# ------------------------------------------------------------------------------------------------ atomic files
|
|
623
1358
|
|
|
624
1359
|
def atomic_replace(path, text, mode):
|
|
@@ -1750,3 +2485,1347 @@ def latest_receipt(root, lane):
|
|
|
1750
2485
|
if receipt['outcome'] == 'refused':
|
|
1751
2486
|
out['reason'] = receipt.get('reason')
|
|
1752
2487
|
return out
|
|
2488
|
+
|
|
2489
|
+
|
|
2490
|
+
# ------------------------------------------------------------------------------------------------ messages (W15 L4)
|
|
2491
|
+
# `lane message` / lane-mcp `lanes_message` (plan 2026-10-25-lanes-messaging-bus, L4; Linear BEY-6842; DM-LANES-MESSAGE,
|
|
2492
|
+
# DM-LANES-MESSAGE-RECEIPT, DM-LANES-MESSAGE-LOG). One message to one lane of this container, delivered by the first
|
|
2493
|
+
# adapter that applies, the choice recorded as the receipt's `delivered_by`:
|
|
2494
|
+
# 1. the sender is Claude and the recipient has a Claude messaging socket — a real one, or (W15 L6) the virtual peer
|
|
2495
|
+
# lane-peerd serves for it: refused `use_send_message` with the `to` the sender's own SendMessage takes (Claude's
|
|
2496
|
+
# native path; nothing is written);
|
|
2497
|
+
# 1b. (W15 L6, BEY-6843) the recipient is a Claude session with a messaging socket and the sender is not Claude: one
|
|
2498
|
+
# protocol-1 line (peer_frame) written to the session's own socket, delivered mid-turn (`peer_socket`) — only
|
|
2499
|
+
# while its session file passes PEER_PIN; a pin that fails is no delivery (`peer_pin_failed`) and the next
|
|
2500
|
+
# adapter is tried;
|
|
2501
|
+
# 2. the recipient is a Codex thread — its hooks recorded the id, or (W15 L3) its app-server names the one thread
|
|
2502
|
+
# that fits the lane, asked now with the recipient's own context (handle(…, fresh=True)) — and `codex` is on PATH:
|
|
2503
|
+
# `codex queue --thread <id> --message <envelope>` (served at the thread's next turn). A Codex lane whose
|
|
2504
|
+
# app-server names several threads (`handle_ambiguous`) or cannot be asked (`handle_unavailable`) gets no thread
|
|
2505
|
+
# and nothing typed: refused, or queued with `queue`;
|
|
2506
|
+
# 3. LANES_BUS=throttle in the sender's environment and the recipient runs an agent: POST `{to, from, text, ttl_s}`
|
|
2507
|
+
# to Throttle's CONTROL listener (127.0.0.1:$LANES_THROTTLE_CONTROL_PORT, else 19181) with the sending harness's
|
|
2508
|
+
# own client token (`throttle client-token <pool>`; BEY-6869 — the endpoint is the Throttle lane's, so the
|
|
2509
|
+
# adapter is off unless switched on);
|
|
2510
|
+
# 4. the recipient's handle is `lane` and it is idle — an agent at its prompt (needs_input, idle, done; not
|
|
2511
|
+
# delegating), or a shell at its prompt, which gets the envelope as a comment line (SHELL_COMMENT): typed, under
|
|
2512
|
+
# the recipient's dispatch lock (dispatch_lock), after a final recheck there — a fresh observation, the same agent
|
|
2513
|
+
# as when it was addressed, still idle, no older message waiting in its inbox (those are typed first: FIFO);
|
|
2514
|
+
# 5. else, with `queue`, the message waits in the recipient's inbox (`queued`; lanes-statusd types it when the lane
|
|
2515
|
+
# is next idle with no terminal attached), and without it the call is refused `recipient_busy`.
|
|
2516
|
+
# An adapter that applies and provably took nothing (it could not start, the connection was refused, it answered a
|
|
2517
|
+
# refusal) refuses with its own code (`peer_socket_failed`, `codex_queue_failed`, `bus_unavailable`, a tmux code), or
|
|
2518
|
+
# queues when `queue` is true. An adapter that may have taken it — `codex queue` timed out or exited non-zero (its exit
|
|
2519
|
+
# codes are not measured: its own answer can time out after the app-server queued it), Throttle's answer was lost or
|
|
2520
|
+
# unreadable after the request went out — is `unknown` (the review's 49907f8b): the record keeps its text and an
|
|
2521
|
+
# `attempt` {op, adapter, at, outcome, recipient}, the receipt says `unknown`, and nothing sends it again — no other
|
|
2522
|
+
# adapter, no lanes-statusd drain — until a person retries it (`lane inbox retry <id> --duplicate-risk`, message_retry)
|
|
2523
|
+
# or the recipient acknowledges it. A message from another lane is never a person's consent. A frame lane-peerd takes on a virtual peer's socket comes in as `inbound` (its sender a lane of this
|
|
2524
|
+
# container, else `peer:<name>`): never refused `use_send_message` (it came by SendMessage) and always queued rather
|
|
2525
|
+
# than refused, so a frame its sender already counts as sent is never dropped.
|
|
2526
|
+
|
|
2527
|
+
MESSAGE_MAX = 4000 # = lane-mcp SEND_MAX: the text, before its envelope
|
|
2528
|
+
MESSAGE_TTL_S, MESSAGE_TTL_MIN, MESSAGE_TTL_MAX = 86400, 60, 7 * 86400
|
|
2529
|
+
INBOX_DIR = ('state', 'inbox') # under ~/.lz: <lane>/<id>.json, <lane>/<id>.receipt.json, log
|
|
2530
|
+
INBOX_LOG = 'log'
|
|
2531
|
+
INBOX_LOG_MAX = 1 << 20 # rotated to log.1 past this
|
|
2532
|
+
INBOX_FILE_MAX = 64 << 10 # a record or receipt bigger than this is not ours
|
|
2533
|
+
INBOX_SCAN_MAX = 512 # settled messages (history) a reader lists, the newest; never fewer
|
|
2534
|
+
# than every message that is not settled (settled())
|
|
2535
|
+
MESSAGE_SUFFIX = '.json'
|
|
2536
|
+
# The envelope every adapter delivers (one constant: the receipt, the log and the reply all follow from it). A person's
|
|
2537
|
+
# message (`lanes message` on the host, the sidebar's `m`) has no address to reply to: ENVELOPE_PERSON.
|
|
2538
|
+
ENVELOPE = '[lanes message from @{sender} ({handle}) {hhmm}Z] {text} — reply: lane message @{sender} "…"'
|
|
2539
|
+
ENVELOPE_PERSON = '[lanes message from {sender} (a person) {hhmm}Z] {text}'
|
|
2540
|
+
ENVELOPE_PEER = '[lanes message from {sender} (a Claude session outside the lanes) {hhmm}Z] {text}' # W15 L6
|
|
2541
|
+
SHELL_COMMENT = '# ' # typed into a shell at its prompt: one comment line, nothing runs (bash's `#`)
|
|
2542
|
+
TYPED_SHELLS = ('bash', 'sh', 'dash') # a pane whose foreground command is one of these sits at a prompt
|
|
2543
|
+
IDLE_WORDS = ('needs_input', 'idle', 'done') # an agent at its prompt (= lanes_lib.NAMES_IDLE)
|
|
2544
|
+
BUSY_WORDS = ('working', 'needs_approval') # a hook sidecar saying one of these: not idle, whatever else says
|
|
2545
|
+
# delivered_by -> (picked_up_by, expected_within_s): what lanes_message answers per adapter. `next_turn`: the
|
|
2546
|
+
# recipient's harness serves it at its next turn; `when_idle`: lanes-statusd types it when the lane is next idle.
|
|
2547
|
+
DELIVERY = {'peer_socket': ('the Claude session itself: its transcript, mid-turn', 0),
|
|
2548
|
+
'codex_queue': ('codex queue: the thread\'s next turn', 'next_turn'),
|
|
2549
|
+
'throttle_turn': ('Throttle: the recipient\'s next model request', 'next_turn'),
|
|
2550
|
+
'typed': ('the program in the lane\'s active pane', 0),
|
|
2551
|
+
'queued': ('lanes-statusd: typed when the lane is next idle', 'when_idle')}
|
|
2552
|
+
# A receipt's `delivered_by`: an adapter, `queued` while it waits, `inbox` when the recipient took it from its inbox
|
|
2553
|
+
# itself (`lanes_message_ack`), `expired` when its ttl passed undelivered, `unknown` (W15 part 2, additive) when an
|
|
2554
|
+
# adapter may have taken it and its answer never came: held, never sent again by Lanes on its own.
|
|
2555
|
+
RECEIPT_STATES = tuple(DELIVERY) + ('inbox', 'expired', 'unknown')
|
|
2556
|
+
UNCONFIRMED = ('nobody: it may have arrived (the adapter\'s answer was lost) — held, never sent again by Lanes; a '
|
|
2557
|
+
'person retries it (lane inbox retry <id> --duplicate-risk) or the recipient acknowledges it', None)
|
|
2558
|
+
DELIVERED = ('peer_socket', 'codex_queue', 'throttle_turn', 'typed', 'inbox') # what inbox_summary's `delivered` counts
|
|
2559
|
+
CODEX_QUEUE_TIMEOUT = 10
|
|
2560
|
+
# W15 L3 + the review's 5038f1da: a Codex lane's app-server discovery that names no single thread refuses: several fit
|
|
2561
|
+
# (`handle_ambiguous`) or the daemon could not be asked (`handle_unavailable`). `no_daemon` (no app-server: the pre-L3
|
|
2562
|
+
# answer), `no_match` and `no_pid` (the daemon serves no thread of this lane's process) keep the other adapters.
|
|
2563
|
+
CODEX_UNAVAILABLE = ('unsafe_socket', 'unreachable', 'timeout', 'too_big', 'protocol', 'truncated')
|
|
2564
|
+
BUS_ENV, BUS_THROTTLE = 'LANES_BUS', 'throttle'
|
|
2565
|
+
BUS_PATH = '/v1/lanes/messages'
|
|
2566
|
+
BUS_HOST = '127.0.0.1' # Throttle's control listener binds its own container's loopback
|
|
2567
|
+
BUS_PORT_ENV, BUS_PORT = 'LANES_THROTTLE_CONTROL_PORT', 19181 # = throttle-pulse's: the control listener
|
|
2568
|
+
BUS_TIMEOUT = 5
|
|
2569
|
+
BUS_ANSWER_MAX = 64 << 10
|
|
2570
|
+
BUS_TOKEN_PREFIX = 'throttle_' # a Throttle client token; nothing else is ever sent
|
|
2571
|
+
BUS_TOKEN_RE = re.compile(r'throttle_[A-Za-z0-9._-]{1,512}')
|
|
2572
|
+
BUS_TOKEN_TIMEOUT = 5 # seconds for `throttle client-token <pool>`
|
|
2573
|
+
# The sending harness -> its Throttle pool, whose managed client token is the sender's own (`throttle client-token
|
|
2574
|
+
# <pool>`; BEY-6869: Throttle admits a `from` trace only for the client that served it). Grok has no Throttle pool.
|
|
2575
|
+
BUS_POOLS = {'claude': 'claude', 'codex': 'codex', 'kimi': 'kimi', 'muse': 'muse-code', 'zcode': 'zai'}
|
|
2576
|
+
HOST_SENDER = re.compile(r'host:[A-Za-z0-9._@+-]{1,254}')
|
|
2577
|
+
PEER_SENDER = re.compile(r'peer:[A-Za-z0-9_.-]{1,128}') # W15 L6: a Claude session no lane here answers to
|
|
2578
|
+
LOG_FIELD = re.compile(r'[A-Za-z0-9._:@+-]{1,256}')
|
|
2579
|
+
_DIR_FLAGS = os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0) | getattr(os, 'O_CLOEXEC', 0)
|
|
2580
|
+
|
|
2581
|
+
|
|
2582
|
+
def iso(at):
|
|
2583
|
+
"""`at` (epoch seconds) as the receipts write it: `YYYY-MM-DDTHH:MM:SSZ`."""
|
|
2584
|
+
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(at))
|
|
2585
|
+
|
|
2586
|
+
|
|
2587
|
+
def epoch(text):
|
|
2588
|
+
"""iso()'s inverse -> epoch seconds, or None."""
|
|
2589
|
+
import calendar
|
|
2590
|
+
try:
|
|
2591
|
+
return calendar.timegm(time.strptime(text, '%Y-%m-%dT%H:%M:%SZ'))
|
|
2592
|
+
except (TypeError, ValueError):
|
|
2593
|
+
return None
|
|
2594
|
+
|
|
2595
|
+
|
|
2596
|
+
def check_message(text):
|
|
2597
|
+
"""`text` when it is at most MESSAGE_MAX characters of printable text with something visible in it, else
|
|
2598
|
+
LaneError `message_too_long` / `unprintable` (REFUSED_TEXT: control and format characters, line and paragraph
|
|
2599
|
+
separators — a message is one line)."""
|
|
2600
|
+
if not isinstance(text, str) or not text.strip():
|
|
2601
|
+
raise LaneError('a message holds at least one visible character', 'unprintable')
|
|
2602
|
+
if len(text) > MESSAGE_MAX:
|
|
2603
|
+
raise LaneError(f'a message is at most {MESSAGE_MAX} characters ({len(text)} given)', 'message_too_long')
|
|
2604
|
+
bad = sorted({f'U+{ord(char):04X}' for char in text if unicodedata.category(char) in REFUSED_TEXT})
|
|
2605
|
+
if bad:
|
|
2606
|
+
raise LaneError(f'a message is one line of printable text: it holds {", ".join(bad[:8])}', 'unprintable')
|
|
2607
|
+
return text
|
|
2608
|
+
|
|
2609
|
+
|
|
2610
|
+
def handle_text(found, lane_id):
|
|
2611
|
+
"""`<kind>:<name>` of a handle() answer as the envelope names it; a `lane` handle has no name: the lane id."""
|
|
2612
|
+
found = found or {'kind': 'lane', 'name': None}
|
|
2613
|
+
return f'{found["kind"]}:{found["name"] or lane_id}'
|
|
2614
|
+
|
|
2615
|
+
|
|
2616
|
+
def envelope(sender, sender_handle, text, at):
|
|
2617
|
+
"""The one envelope (ENVELOPE) around `text` from `sender` — a lane's address (without `@`) and its handle_text()
|
|
2618
|
+
— or, for a person's `host:<login>`, ENVELOPE_PERSON, and for a Claude session outside the lanes (`peer:<name>`,
|
|
2619
|
+
W15 L6) ENVELOPE_PEER: neither has an address to reply to."""
|
|
2620
|
+
hhmm = time.strftime('%H:%M', time.gmtime(at))
|
|
2621
|
+
if HOST_SENDER.fullmatch(sender or ''):
|
|
2622
|
+
return ENVELOPE_PERSON.format(sender=sender, hhmm=hhmm, text=text)
|
|
2623
|
+
if PEER_SENDER.fullmatch(sender or ''):
|
|
2624
|
+
return ENVELOPE_PEER.format(sender=sender, hhmm=hhmm, text=text)
|
|
2625
|
+
return ENVELOPE.format(sender=sender, handle=sender_handle, hhmm=hhmm, text=text)
|
|
2626
|
+
|
|
2627
|
+
|
|
2628
|
+
def _open_dir(root, parts, create=False, keep=0):
|
|
2629
|
+
"""fd of root/<parts…>: `root` opened as given (trusted: ~/.lz in the container, the home volume or
|
|
2630
|
+
/proc/<pid>/root on the host), every part a REAL directory — a symbolic link is refused (OSError), never
|
|
2631
|
+
followed: from the host a link planted in the container resolves on the HOST. A missing part is created 0700
|
|
2632
|
+
when `create`, except the first `keep` parts, which must exist (the container's own ~/.lz: no contract, no
|
|
2633
|
+
inbox)."""
|
|
2634
|
+
fd = os.open(str(root), _DIR_FLAGS)
|
|
2635
|
+
try:
|
|
2636
|
+
for index, part in enumerate(parts):
|
|
2637
|
+
if not part or '/' in part or part in ('.', '..'):
|
|
2638
|
+
raise OSError(f'invalid path component {part!r}')
|
|
2639
|
+
try:
|
|
2640
|
+
child = os.open(part, _DIR_FLAGS | os.O_NOFOLLOW, dir_fd=fd)
|
|
2641
|
+
except FileNotFoundError:
|
|
2642
|
+
if not create or index < keep:
|
|
2643
|
+
raise
|
|
2644
|
+
try:
|
|
2645
|
+
os.mkdir(part, 0o700, dir_fd=fd)
|
|
2646
|
+
except FileExistsError:
|
|
2647
|
+
pass
|
|
2648
|
+
child = os.open(part, _DIR_FLAGS | os.O_NOFOLLOW, dir_fd=fd)
|
|
2649
|
+
os.close(fd)
|
|
2650
|
+
fd = child
|
|
2651
|
+
except BaseException:
|
|
2652
|
+
os.close(fd)
|
|
2653
|
+
raise
|
|
2654
|
+
return fd
|
|
2655
|
+
|
|
2656
|
+
|
|
2657
|
+
def inbox_fd(root, lane=None, create=False, prefix=()):
|
|
2658
|
+
"""fd of <root>/<prefix…>/state/inbox[/<lane>] (_open_dir: no link followed; with `create`, what is missing
|
|
2659
|
+
below the prefix is created 0700 — the prefix itself must exist)."""
|
|
2660
|
+
if lane is not None and not (isinstance(lane, str) and LANE_RE.fullmatch(lane)):
|
|
2661
|
+
raise OSError(f'invalid lane id {lane!r}')
|
|
2662
|
+
return _open_dir(root, tuple(prefix) + INBOX_DIR + ((lane,) if lane else ()), create, keep=len(tuple(prefix)))
|
|
2663
|
+
|
|
2664
|
+
|
|
2665
|
+
def _read_at(dir_fd, name, limit=INBOX_FILE_MAX):
|
|
2666
|
+
"""The JSON document of `name` in `dir_fd` when it is a regular file of at most `limit` bytes holding one, else
|
|
2667
|
+
None. Never follows a link, never blocks on a FIFO."""
|
|
2668
|
+
try:
|
|
2669
|
+
fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | getattr(os, 'O_CLOEXEC', 0), dir_fd=dir_fd)
|
|
2670
|
+
except OSError:
|
|
2671
|
+
return None
|
|
2672
|
+
try:
|
|
2673
|
+
info = os.fstat(fd)
|
|
2674
|
+
if not stat.S_ISREG(info.st_mode) or info.st_size > limit:
|
|
2675
|
+
return None
|
|
2676
|
+
data = os.read(fd, limit + 1)
|
|
2677
|
+
except OSError:
|
|
2678
|
+
return None
|
|
2679
|
+
finally:
|
|
2680
|
+
os.close(fd)
|
|
2681
|
+
try:
|
|
2682
|
+
document = json.loads(data.decode('utf-8'))
|
|
2683
|
+
except (UnicodeDecodeError, ValueError):
|
|
2684
|
+
return None
|
|
2685
|
+
return document if isinstance(document, dict) else None
|
|
2686
|
+
|
|
2687
|
+
|
|
2688
|
+
def _write_at(dir_fd, name, document, mode=0o600):
|
|
2689
|
+
"""Replace `name` in `dir_fd` with `document` (JSON, indent 1, a trailing newline) atomically: an O_EXCL |
|
|
2690
|
+
O_NOFOLLOW temp file beside it, fsync, then a rename over whatever the name holds (a planted link is replaced,
|
|
2691
|
+
never followed)."""
|
|
2692
|
+
import secrets
|
|
2693
|
+
data = (json.dumps(document, ensure_ascii=False, indent=1) + '\n').encode('utf-8')
|
|
2694
|
+
temporary = f'.{name}.{secrets.token_hex(6)}'
|
|
2695
|
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | getattr(os, 'O_CLOEXEC', 0), mode,
|
|
2696
|
+
dir_fd=dir_fd)
|
|
2697
|
+
try:
|
|
2698
|
+
with os.fdopen(fd, 'wb') as handle:
|
|
2699
|
+
handle.write(data)
|
|
2700
|
+
handle.flush()
|
|
2701
|
+
os.fsync(handle.fileno())
|
|
2702
|
+
os.fchmod(handle.fileno(), mode)
|
|
2703
|
+
os.replace(temporary, name, src_dir_fd=dir_fd, dst_dir_fd=dir_fd)
|
|
2704
|
+
except BaseException:
|
|
2705
|
+
try:
|
|
2706
|
+
os.unlink(temporary, dir_fd=dir_fd)
|
|
2707
|
+
except OSError:
|
|
2708
|
+
pass
|
|
2709
|
+
raise
|
|
2710
|
+
|
|
2711
|
+
|
|
2712
|
+
def log_line(at, sender, to, message_id, size, outcome):
|
|
2713
|
+
"""One DM-LANES-MESSAGE-LOG line: `<at> <from> <to> <id> <bytes> <outcome>`. Metadata only, never a text: every
|
|
2714
|
+
field that is not one token of LOG_FIELD's characters is written `-`."""
|
|
2715
|
+
fields = [iso(at), sender, to, message_id, str(int(size)), outcome]
|
|
2716
|
+
return ' '.join(field if isinstance(field, str) and LOG_FIELD.fullmatch(field) else '-' for field in fields) + '\n'
|
|
2717
|
+
|
|
2718
|
+
|
|
2719
|
+
def append_log(root, line, prefix=()):
|
|
2720
|
+
"""Append `line` (log_line's) to <root>/<prefix…>/state/inbox/log (0600, O_APPEND, never through a link), rotated
|
|
2721
|
+
to log.1 past INBOX_LOG_MAX. A log that cannot be written is silence, never a failure."""
|
|
2722
|
+
try:
|
|
2723
|
+
fd = inbox_fd(root, create=True, prefix=prefix)
|
|
2724
|
+
except OSError:
|
|
2725
|
+
return False
|
|
2726
|
+
try:
|
|
2727
|
+
try:
|
|
2728
|
+
if os.stat(INBOX_LOG, dir_fd=fd, follow_symlinks=False).st_size > INBOX_LOG_MAX:
|
|
2729
|
+
os.replace(INBOX_LOG, INBOX_LOG + '.1', src_dir_fd=fd, dst_dir_fd=fd)
|
|
2730
|
+
except FileNotFoundError:
|
|
2731
|
+
pass
|
|
2732
|
+
out = os.open(INBOX_LOG, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW | getattr(os, 'O_CLOEXEC', 0),
|
|
2733
|
+
0o600, dir_fd=fd)
|
|
2734
|
+
try:
|
|
2735
|
+
os.write(out, line.encode('utf-8'))
|
|
2736
|
+
finally:
|
|
2737
|
+
os.close(out)
|
|
2738
|
+
return True
|
|
2739
|
+
except OSError:
|
|
2740
|
+
return False
|
|
2741
|
+
finally:
|
|
2742
|
+
os.close(fd)
|
|
2743
|
+
|
|
2744
|
+
|
|
2745
|
+
def message_record(message_id, sender, sender_handle, to, at, text, ttl_s):
|
|
2746
|
+
"""DM-LANES-MESSAGE v1, in this order."""
|
|
2747
|
+
return {'v': 1, 'id': message_id, 'from': sender, 'from_handle': sender_handle, 'to': to, 'at': iso(at),
|
|
2748
|
+
'text': text, 'ttl_s': int(ttl_s)}
|
|
2749
|
+
|
|
2750
|
+
|
|
2751
|
+
def receipt_record(message_id, to, delivered_by, at, cleared=None):
|
|
2752
|
+
"""DM-LANES-MESSAGE-RECEIPT v1, in this order: `expected_within_s` follows from `delivered_by` (DELIVERY; 0 for a
|
|
2753
|
+
message the recipient took itself, null once it expired or while it is `unknown`); `cleared` (additive, last) when
|
|
2754
|
+
the record no longer holds the text (settled())."""
|
|
2755
|
+
within = DELIVERY[delivered_by][1] if delivered_by in DELIVERY else 0 if delivered_by == 'inbox' else None
|
|
2756
|
+
out = {'v': 1, 'id': message_id, 'to': to, 'delivered_by': delivered_by, 'expected_within_s': within,
|
|
2757
|
+
'at': iso(at)}
|
|
2758
|
+
if cleared is not None:
|
|
2759
|
+
out['cleared'] = iso(cleared)
|
|
2760
|
+
return out
|
|
2761
|
+
|
|
2762
|
+
|
|
2763
|
+
def settled(receipt):
|
|
2764
|
+
"""Is `receipt` its message's last word — its record holds no text any more (`cleared`, which message_ack and
|
|
2765
|
+
lanes-statusd's ttl purge write only AFTER the text left the record, so an interrupted cleanup is never settled)?
|
|
2766
|
+
A settled message is history: a reader lists the newest INBOX_SCAN_MAX of them. Every message that is not settled
|
|
2767
|
+
— waiting, held (`unknown`), on its way (no receipt), delivered with its text still there — is always listed."""
|
|
2768
|
+
return isinstance(receipt, dict) and isinstance(receipt.get('cleared'), str)
|
|
2769
|
+
|
|
2770
|
+
|
|
2771
|
+
def cleared_receipt(receipt, record, message_id, at):
|
|
2772
|
+
"""The receipt of a message whose record (`record`, as rewritten) no longer holds its text, stamped `cleared`: one
|
|
2773
|
+
still waiting (`queued`, or no receipt) or held (`unknown`) is `inbox` when its record says the recipient
|
|
2774
|
+
acknowledged it (`acked`); one still waiting is `expired` otherwise; every other word, and its `at`, stays."""
|
|
2775
|
+
receipt = receipt if isinstance(receipt, dict) and receipt.get('v') == 1 else None
|
|
2776
|
+
state = (receipt or {}).get('delivered_by')
|
|
2777
|
+
if state in ('queued', 'unknown', None) and record.get('acked'):
|
|
2778
|
+
state = 'inbox'
|
|
2779
|
+
elif state in ('queued', None):
|
|
2780
|
+
state = 'expired'
|
|
2781
|
+
if receipt is not None and state == receipt.get('delivered_by'):
|
|
2782
|
+
out = dict(receipt)
|
|
2783
|
+
out['cleared'] = iso(at)
|
|
2784
|
+
return out
|
|
2785
|
+
return receipt_record(message_id, record.get('to'), state, at, cleared=at)
|
|
2786
|
+
|
|
2787
|
+
|
|
2788
|
+
ID_ORDER = ''.join(sorted(ID_RANDOM)) # the random characters in the order ids sort by
|
|
2789
|
+
|
|
2790
|
+
|
|
2791
|
+
def _id_after(message_id):
|
|
2792
|
+
"""The id right after `message_id` in sort order: its random part (never the 6 time characters) counted up in
|
|
2793
|
+
ID_ORDER, one character longer when that part is all ID_ORDER's last."""
|
|
2794
|
+
chars = list(message_id)
|
|
2795
|
+
for index in range(len(chars) - 1, 5, -1):
|
|
2796
|
+
position = ID_ORDER.find(chars[index])
|
|
2797
|
+
if 0 <= position < len(ID_ORDER) - 1:
|
|
2798
|
+
chars[index] = ID_ORDER[position + 1]
|
|
2799
|
+
return ''.join(chars)
|
|
2800
|
+
chars[index] = ID_ORDER[0]
|
|
2801
|
+
return message_id + ID_ORDER[0]
|
|
2802
|
+
|
|
2803
|
+
|
|
2804
|
+
def new_message_id(directory_fd, now=None):
|
|
2805
|
+
"""A message id (new_publish_id's grammar, docs_store's [a-z0-9]{10,20}) no record or receipt of this inbox has
|
|
2806
|
+
yet, sorting after every id the inbox holds: ids are an inbox's order, oldest first, so two messages of one second
|
|
2807
|
+
keep the order they were written in (FIFO; W15 part 2) — one that would sort before the newest is the id right
|
|
2808
|
+
after it (_id_after)."""
|
|
2809
|
+
try:
|
|
2810
|
+
newest = max((name.split('.', 1)[0] for name in os.listdir(directory_fd)
|
|
2811
|
+
if PUBLISH_ID.fullmatch(name.split('.', 1)[0])), default='')
|
|
2812
|
+
except OSError:
|
|
2813
|
+
newest = ''
|
|
2814
|
+
message_id = new_publish_id(now)
|
|
2815
|
+
for _ in range(64):
|
|
2816
|
+
if message_id <= newest:
|
|
2817
|
+
message_id = _id_after(newest)
|
|
2818
|
+
if PUBLISH_ID.fullmatch(message_id) and not any(_exists_at(directory_fd, message_id + suffix)
|
|
2819
|
+
for suffix in (MESSAGE_SUFFIX, RECEIPT_SUFFIX)):
|
|
2820
|
+
return message_id
|
|
2821
|
+
newest = message_id
|
|
2822
|
+
raise LaneError('could not mint a free message id', 'refused')
|
|
2823
|
+
|
|
2824
|
+
|
|
2825
|
+
def _exists_at(dir_fd, name):
|
|
2826
|
+
try:
|
|
2827
|
+
os.stat(name, dir_fd=dir_fd, follow_symlinks=False)
|
|
2828
|
+
return True
|
|
2829
|
+
except FileNotFoundError:
|
|
2830
|
+
return False
|
|
2831
|
+
|
|
2832
|
+
|
|
2833
|
+
def _inbox_read(fd, history):
|
|
2834
|
+
"""(entries oldest first, {id: receipt}) of one lane directory: EVERY receipt read (each a small file), then the
|
|
2835
|
+
record of every message that is not settled and of the newest `history` settled ones (None: all; 0: none). Records
|
|
2836
|
+
are the `<id>.json` names, receipts the `<id>.receipt.json` ones: one never stands for the other."""
|
|
2837
|
+
records, named = set(), set()
|
|
2838
|
+
for name in os.listdir(fd):
|
|
2839
|
+
if name.endswith(RECEIPT_SUFFIX):
|
|
2840
|
+
ident, found = name[:-len(RECEIPT_SUFFIX)], named
|
|
2841
|
+
elif name.endswith(MESSAGE_SUFFIX):
|
|
2842
|
+
ident, found = name[:-len(MESSAGE_SUFFIX)], records
|
|
2843
|
+
else:
|
|
2844
|
+
continue
|
|
2845
|
+
if PUBLISH_ID.fullmatch(ident):
|
|
2846
|
+
found.add(ident)
|
|
2847
|
+
receipts = {}
|
|
2848
|
+
for ident in named:
|
|
2849
|
+
receipt = _read_at(fd, ident + RECEIPT_SUFFIX)
|
|
2850
|
+
if isinstance(receipt, dict) and receipt.get('v') == 1 and receipt.get('delivered_by') in RECEIPT_STATES:
|
|
2851
|
+
receipts[ident] = receipt
|
|
2852
|
+
ids = sorted(records | named)
|
|
2853
|
+
done = [ident for ident in ids if settled(receipts.get(ident))]
|
|
2854
|
+
kept = set(done if history is None else done[-history:] if history > 0 else ())
|
|
2855
|
+
out = []
|
|
2856
|
+
for ident in ids:
|
|
2857
|
+
if ident in receipts and settled(receipts[ident]) and ident not in kept:
|
|
2858
|
+
continue
|
|
2859
|
+
record = _read_at(fd, ident + MESSAGE_SUFFIX) if ident in records else None
|
|
2860
|
+
record = record if isinstance(record, dict) and record.get('v') == 1 else None
|
|
2861
|
+
if record or receipts.get(ident):
|
|
2862
|
+
out.append({'id': ident, 'record': record, 'receipt': receipts.get(ident)})
|
|
2863
|
+
return out, receipts
|
|
2864
|
+
|
|
2865
|
+
|
|
2866
|
+
def inbox_entries(root, lane, prefix=(), history=INBOX_SCAN_MAX):
|
|
2867
|
+
"""[{'id', 'record', 'receipt'}] of one lane's inbox, oldest first (ids sort by time), each file read as a regular
|
|
2868
|
+
file only: every message that is not settled (settled(): waiting, held, on its way, delivered with its text) —
|
|
2869
|
+
however much history the inbox holds — and the newest `history` settled ones (the review's 652c1329: a cap on
|
|
2870
|
+
names once hid an older waiting message behind acknowledged ones). A receipt without its record, or a record
|
|
2871
|
+
without a receipt (a message still on its way), is listed with None in its place. [] without an inbox."""
|
|
2872
|
+
try:
|
|
2873
|
+
fd = inbox_fd(root, lane, prefix=prefix)
|
|
2874
|
+
except (OSError, LaneError):
|
|
2875
|
+
return []
|
|
2876
|
+
try:
|
|
2877
|
+
return _inbox_read(fd, history)[0]
|
|
2878
|
+
except OSError:
|
|
2879
|
+
return []
|
|
2880
|
+
finally:
|
|
2881
|
+
os.close(fd)
|
|
2882
|
+
|
|
2883
|
+
|
|
2884
|
+
def expired(entry, now):
|
|
2885
|
+
"""Has `entry`'s ttl passed (its record's `at` + `ttl_s`)? A record that says neither has (it holds nothing a
|
|
2886
|
+
reader may still deliver)."""
|
|
2887
|
+
record = entry.get('record') or {}
|
|
2888
|
+
at, ttl = epoch(record.get('at')), record.get('ttl_s')
|
|
2889
|
+
return at is None or not isinstance(ttl, int) or at + ttl <= now
|
|
2890
|
+
|
|
2891
|
+
|
|
2892
|
+
def pending(entry, now):
|
|
2893
|
+
"""Is `entry` a message still waiting in the inbox: its receipt `queued`, its text there, its ttl not passed."""
|
|
2894
|
+
receipt = entry.get('receipt') or {}
|
|
2895
|
+
return (receipt.get('delivered_by') == 'queued' and isinstance((entry.get('record') or {}).get('text'), str)
|
|
2896
|
+
and not expired(entry, now))
|
|
2897
|
+
|
|
2898
|
+
|
|
2899
|
+
def held(entry):
|
|
2900
|
+
"""Is `entry` a message whose delivery is unknown (receipt `unknown`, not settled): an adapter may have taken it,
|
|
2901
|
+
so Lanes never sends it again on its own — a person retries it (message_retry) or the recipient acknowledges it."""
|
|
2902
|
+
receipt = entry.get('receipt') or {}
|
|
2903
|
+
return receipt.get('delivered_by') == 'unknown' and not settled(receipt)
|
|
2904
|
+
|
|
2905
|
+
|
|
2906
|
+
def inbox_counts(root, lane, now=None, prefix=()):
|
|
2907
|
+
"""{'pending', 'unknown'}: how many messages wait in `lane`'s inbox (pending()) and how many are held (held()) —
|
|
2908
|
+
counted over every message that is not settled, never over a window of the history."""
|
|
2909
|
+
now = time.time() if now is None else now
|
|
2910
|
+
entries = inbox_entries(root, lane, prefix, history=0)
|
|
2911
|
+
return {'pending': sum(1 for entry in entries if pending(entry, now)),
|
|
2912
|
+
'unknown': sum(1 for entry in entries if held(entry))}
|
|
2913
|
+
|
|
2914
|
+
|
|
2915
|
+
def inbox_summary(root, lane, now=None, prefix=()):
|
|
2916
|
+
"""lanes_status's `inbox` for `lane` -> {pending, delivered, last: {id, from, at, delivered_by}, unknown?} or None
|
|
2917
|
+
when the inbox holds nothing. `delivered` counts every receipt an adapter or the recipient answered (DELIVERED);
|
|
2918
|
+
`last` is the newest message; `unknown` (additive, absent at 0) the held ones."""
|
|
2919
|
+
now = time.time() if now is None else now
|
|
2920
|
+
try:
|
|
2921
|
+
fd = inbox_fd(root, lane, prefix=prefix)
|
|
2922
|
+
except (OSError, LaneError):
|
|
2923
|
+
return None
|
|
2924
|
+
try:
|
|
2925
|
+
entries, receipts = _inbox_read(fd, 1)
|
|
2926
|
+
except OSError:
|
|
2927
|
+
return None
|
|
2928
|
+
finally:
|
|
2929
|
+
os.close(fd)
|
|
2930
|
+
if not entries:
|
|
2931
|
+
return None
|
|
2932
|
+
newest = entries[-1]
|
|
2933
|
+
record, receipt = newest.get('record') or {}, newest.get('receipt') or {}
|
|
2934
|
+
out = {'pending': sum(1 for entry in entries if pending(entry, now)),
|
|
2935
|
+
'delivered': sum(1 for found in receipts.values() if found.get('delivered_by') in DELIVERED),
|
|
2936
|
+
'last': {'id': newest['id'], 'from': record.get('from'), 'at': record.get('at') or receipt.get('at'),
|
|
2937
|
+
'delivered_by': receipt.get('delivered_by')}}
|
|
2938
|
+
unknown = sum(1 for entry in entries if held(entry))
|
|
2939
|
+
if unknown:
|
|
2940
|
+
out['unknown'] = unknown
|
|
2941
|
+
return out
|
|
2942
|
+
|
|
2943
|
+
|
|
2944
|
+
def inbox_pending(root, lane, now=None, prefix=()):
|
|
2945
|
+
"""How many messages wait in `lane`'s inbox (pending())."""
|
|
2946
|
+
return inbox_counts(root, lane, now, prefix)['pending']
|
|
2947
|
+
|
|
2948
|
+
|
|
2949
|
+
def message_ack(root, lane, message_id, now=None):
|
|
2950
|
+
"""`lanes_message_ack` / `lane inbox ack <id>`: the recipient has the message -> {id, lane, from, delivered_by,
|
|
2951
|
+
acked, changed}. Its record keeps its metadata and loses its text (`acked` added) FIRST; then its receipt says so
|
|
2952
|
+
(cleared_receipt: `cleared`, and a message still `queued` or held `unknown` is the recipient's own take, `inbox`, so
|
|
2953
|
+
lanes-statusd never types it). Refused `unknown_message` for an id this lane's inbox does not hold. Acking twice
|
|
2954
|
+
changes nothing — except finishing an ack that stopped between its two writes."""
|
|
2955
|
+
now = time.time() if now is None else now
|
|
2956
|
+
if not isinstance(message_id, str) or not PUBLISH_ID.fullmatch(message_id):
|
|
2957
|
+
raise LaneError(f'{message_id!r} is not a message id', 'unknown_message')
|
|
2958
|
+
try:
|
|
2959
|
+
fd = inbox_fd(root, lane)
|
|
2960
|
+
except (OSError, LaneError):
|
|
2961
|
+
raise LaneError(f'{lane} has no inbox: no message {message_id}', 'unknown_message') from None
|
|
2962
|
+
try:
|
|
2963
|
+
record, receipt = _read_at(fd, message_id + MESSAGE_SUFFIX), _read_at(fd, message_id + RECEIPT_SUFFIX)
|
|
2964
|
+
if not (isinstance(record, dict) and record.get('v') == 1 and isinstance(receipt, dict)):
|
|
2965
|
+
raise LaneError(f'{lane}\'s inbox holds no message {message_id}', 'unknown_message')
|
|
2966
|
+
if 'text' not in record:
|
|
2967
|
+
changed = 'nothing: acknowledged already'
|
|
2968
|
+
if not settled(receipt): # an ack (or a purge) that stopped between its two writes: finished here
|
|
2969
|
+
receipt = cleared_receipt(receipt, record, message_id, now)
|
|
2970
|
+
_write_at(fd, message_id + RECEIPT_SUFFIX, receipt)
|
|
2971
|
+
changed = 'its receipt only: an earlier acknowledgement is finished (cleared)'
|
|
2972
|
+
return {'id': message_id, 'lane': lane, 'from': record.get('from'), 'delivered_by':
|
|
2973
|
+
receipt.get('delivered_by'), 'acked': record.get('acked'), 'changed': changed}
|
|
2974
|
+
kept = {key: value for key, value in record.items() if key != 'text'}
|
|
2975
|
+
kept['acked'] = iso(now)
|
|
2976
|
+
_write_at(fd, message_id + MESSAGE_SUFFIX, kept) # the text leaves first …
|
|
2977
|
+
receipt = cleared_receipt(receipt, kept, message_id, now)
|
|
2978
|
+
_write_at(fd, message_id + RECEIPT_SUFFIX, receipt) # … then the receipt says so
|
|
2979
|
+
state = receipt['delivered_by']
|
|
2980
|
+
finally:
|
|
2981
|
+
os.close(fd)
|
|
2982
|
+
append_log(root, log_line(now, record.get('from'), record.get('to'), message_id,
|
|
2983
|
+
len(record['text'].encode('utf-8')), 'acked'))
|
|
2984
|
+
return {'id': message_id, 'lane': lane, 'from': record.get('from'), 'delivered_by': state, 'acked': kept['acked'],
|
|
2985
|
+
'changed': f'{LZ}/{"/".join(INBOX_DIR)}/{lane}/{message_id}{MESSAGE_SUFFIX}: the text removed, its '
|
|
2986
|
+
'metadata and receipt kept'}
|
|
2987
|
+
|
|
2988
|
+
|
|
2989
|
+
def message_retry(root, lane, message_id, duplicate_risk=False, now=None):
|
|
2990
|
+
"""`lane inbox retry <id> --duplicate-risk` (W15 part 2): a person hands a held message (receipt `unknown`) back to
|
|
2991
|
+
the inbox -> {id, lane, from, delivered_by: queued, retry, changed}. Its receipt becomes `queued` — lanes-statusd
|
|
2992
|
+
types it when the lane is next idle — and its record gains `retry: {at, duplicate_risk: true}`: the adapter may
|
|
2993
|
+
have delivered it already, so it may arrive twice, which `duplicate_risk` says the person accepts. Refused
|
|
2994
|
+
`unknown_message` (no such message), `not_held` (it is not `unknown`, or its text is gone or its ttl passed) and
|
|
2995
|
+
`duplicate_risk` (without the person's word)."""
|
|
2996
|
+
now = time.time() if now is None else now
|
|
2997
|
+
if not isinstance(message_id, str) or not PUBLISH_ID.fullmatch(message_id):
|
|
2998
|
+
raise LaneError(f'{message_id!r} is not a message id', 'unknown_message')
|
|
2999
|
+
try:
|
|
3000
|
+
fd = inbox_fd(root, lane)
|
|
3001
|
+
except (OSError, LaneError):
|
|
3002
|
+
raise LaneError(f'{lane} has no inbox: no message {message_id}', 'unknown_message') from None
|
|
3003
|
+
try:
|
|
3004
|
+
record, receipt = _read_at(fd, message_id + MESSAGE_SUFFIX), _read_at(fd, message_id + RECEIPT_SUFFIX)
|
|
3005
|
+
if not (isinstance(record, dict) and record.get('v') == 1 and isinstance(receipt, dict)):
|
|
3006
|
+
raise LaneError(f'{lane}\'s inbox holds no message {message_id}', 'unknown_message')
|
|
3007
|
+
entry = {'id': message_id, 'record': record, 'receipt': receipt}
|
|
3008
|
+
if not held(entry):
|
|
3009
|
+
raise LaneError(f'{message_id} is not held: its receipt says {receipt.get("delivered_by")}', 'not_held')
|
|
3010
|
+
if not isinstance(record.get('text'), str) or expired(entry, now):
|
|
3011
|
+
raise LaneError(f'{message_id} can no longer be retried: its text is gone or its ttl passed', 'not_held')
|
|
3012
|
+
if not duplicate_risk:
|
|
3013
|
+
adapter = (record.get('attempt') or {}).get('adapter') if isinstance(record.get('attempt'), dict) else None
|
|
3014
|
+
raise LaneError(f'{message_id} may have arrived already ({adapter or "an adapter"} did not answer): '
|
|
3015
|
+
'retried, it may arrive twice — say you accept that (--duplicate-risk)', 'duplicate_risk')
|
|
3016
|
+
record['retry'] = {'at': iso(now), 'duplicate_risk': True}
|
|
3017
|
+
_write_at(fd, message_id + MESSAGE_SUFFIX, record)
|
|
3018
|
+
_write_at(fd, message_id + RECEIPT_SUFFIX, receipt_record(message_id, record.get('to'), 'queued', now))
|
|
3019
|
+
finally:
|
|
3020
|
+
os.close(fd)
|
|
3021
|
+
append_log(root, log_line(now, record.get('from'), record.get('to'), message_id,
|
|
3022
|
+
len(record['text'].encode('utf-8')), 'retried'))
|
|
3023
|
+
return {'id': message_id, 'lane': lane, 'from': record.get('from'), 'delivered_by': 'queued',
|
|
3024
|
+
'retry': record['retry'],
|
|
3025
|
+
'changed': f'{LZ}/{"/".join(INBOX_DIR)}/{lane}/{message_id}{RECEIPT_SUFFIX}: queued again — '
|
|
3026
|
+
f'{DELIVERY["queued"][0]} (it may arrive twice)'}
|
|
3027
|
+
|
|
3028
|
+
|
|
3029
|
+
class Unconfirmed(LaneError):
|
|
3030
|
+
"""An adapter that may have taken the message and whose answer never came: `codex queue` timed out or exited
|
|
3031
|
+
non-zero, Throttle's answer was lost or unreadable after the request went out. lane_core.message holds it
|
|
3032
|
+
(`unknown`) — never sent again by another adapter or a drain (the review's 49907f8b). Its code is the adapter's."""
|
|
3033
|
+
|
|
3034
|
+
|
|
3035
|
+
def codex_queue(thread, text, home, environ=None, timeout=None):
|
|
3036
|
+
"""Adapter 2: `codex queue --thread <thread> --message <text>` -> None when codex took it. A codex that could not
|
|
3037
|
+
start took nothing: LaneError `codex_queue_failed`. One that did not finish within `timeout` s (default
|
|
3038
|
+
CODEX_QUEUE_TIMEOUT) or exited non-zero MAY have queued it — its exit codes are not measured, and its own answer
|
|
3039
|
+
from the app-server can time out after the thread queued the text — so that is Unconfirmed (code
|
|
3040
|
+
`codex_queue_failed`), naming the exit code only (its output is never shown). Run in creation_env()'s allow-list
|
|
3041
|
+
(never the agent's environment: no token, no lane identity) with HOME = `home`, stdin closed."""
|
|
3042
|
+
import shutil
|
|
3043
|
+
timeout = CODEX_QUEUE_TIMEOUT if timeout is None else timeout
|
|
3044
|
+
environ = os.environ if environ is None else environ
|
|
3045
|
+
env = creation_env({**os.environ, **environ})
|
|
3046
|
+
env['HOME'] = str(home)
|
|
3047
|
+
binary = shutil.which('codex', path=env.get('PATH'))
|
|
3048
|
+
if not binary:
|
|
3049
|
+
raise LaneError('codex is not on PATH', 'codex_queue_failed')
|
|
3050
|
+
try:
|
|
3051
|
+
done = subprocess.run([binary, 'queue', '--thread', thread, '--message', text], env=env,
|
|
3052
|
+
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
3053
|
+
timeout=timeout)
|
|
3054
|
+
except subprocess.TimeoutExpired:
|
|
3055
|
+
raise Unconfirmed(f'codex queue did not finish within {timeout:g} s: it may have queued the message',
|
|
3056
|
+
'codex_queue_failed') from None
|
|
3057
|
+
except OSError as error:
|
|
3058
|
+
raise LaneError(f'codex queue could not start: {error.strerror or error}', 'codex_queue_failed') from None
|
|
3059
|
+
if done.returncode:
|
|
3060
|
+
raise Unconfirmed(f'codex queue exited {done.returncode}: it may have queued the message (its exit codes are '
|
|
3061
|
+
'not measured)', 'codex_queue_failed')
|
|
3062
|
+
return None
|
|
3063
|
+
|
|
3064
|
+
|
|
3065
|
+
def bus_configured(environ):
|
|
3066
|
+
"""Is the Throttle bus switched on for this sender (LANES_BUS=throttle in its environment)? Off by default: the
|
|
3067
|
+
endpoint is the Throttle lane's (T2)."""
|
|
3068
|
+
return (environ or {}).get(BUS_ENV) == BUS_THROTTLE
|
|
3069
|
+
|
|
3070
|
+
|
|
3071
|
+
def bus_port(environ):
|
|
3072
|
+
"""Throttle's control port: $LANES_THROTTLE_CONTROL_PORT of the sender's environment, else BUS_PORT (19181, the
|
|
3073
|
+
one throttle-pulse asks) -> int, or LaneError `bus_unavailable` for a value that is no port."""
|
|
3074
|
+
raw = str((environ or {}).get(BUS_PORT_ENV) or BUS_PORT)
|
|
3075
|
+
if not raw.isdigit() or not 0 < int(raw) < 65536:
|
|
3076
|
+
raise LaneError(f'LANES_BUS=throttle, but {BUS_PORT_ENV} is no port number', 'bus_unavailable')
|
|
3077
|
+
return int(raw)
|
|
3078
|
+
|
|
3079
|
+
|
|
3080
|
+
def bus_token(harness, environ, home, timeout=None):
|
|
3081
|
+
"""The sending harness's own Throttle client token (BEY-6869): `throttle client-token <pool>` for its pool
|
|
3082
|
+
(BUS_POOLS), run like codex_queue (creation_env()'s allow-list, HOME = `home`, stdin closed, `timeout` s, default
|
|
3083
|
+
BUS_TOKEN_TIMEOUT), its one line a `throttle_` token — never the Claude key of a lane that is not Claude, never
|
|
3084
|
+
shown. Every failure is LaneError `bus_unavailable` (nothing was sent to the bus yet)."""
|
|
3085
|
+
import shutil
|
|
3086
|
+
pool = BUS_POOLS.get(harness or '')
|
|
3087
|
+
if pool is None:
|
|
3088
|
+
raise LaneError(f'LANES_BUS=throttle, but the sender\'s harness ({harness or "none"}) has no Throttle pool and '
|
|
3089
|
+
'so no client token of its own', 'bus_unavailable')
|
|
3090
|
+
env = creation_env({**os.environ, **(environ or {})})
|
|
3091
|
+
env['HOME'] = str(home)
|
|
3092
|
+
binary = shutil.which('throttle', path=env.get('PATH'))
|
|
3093
|
+
if not binary:
|
|
3094
|
+
raise LaneError('LANES_BUS=throttle, but `throttle` is not on PATH (its client token comes from `throttle '
|
|
3095
|
+
f'client-token {pool}`)', 'bus_unavailable')
|
|
3096
|
+
try:
|
|
3097
|
+
done = subprocess.run([binary, 'client-token', pool], env=env, stdin=subprocess.DEVNULL,
|
|
3098
|
+
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
|
3099
|
+
timeout=BUS_TOKEN_TIMEOUT if timeout is None else timeout)
|
|
3100
|
+
except (subprocess.TimeoutExpired, OSError):
|
|
3101
|
+
raise LaneError(f'`throttle client-token {pool}` did not answer', 'bus_unavailable') from None
|
|
3102
|
+
token = done.stdout.decode('ascii', 'replace').strip() if done.returncode == 0 else ''
|
|
3103
|
+
if not BUS_TOKEN_RE.fullmatch(token):
|
|
3104
|
+
raise LaneError(f'`throttle client-token {pool}` gave no Throttle client token'
|
|
3105
|
+
+ (f' (exit {done.returncode})' if done.returncode else ''), 'bus_unavailable')
|
|
3106
|
+
return token
|
|
3107
|
+
|
|
3108
|
+
|
|
3109
|
+
def bus_post(environ, home, harness, sender_trace, to_trace, text, ttl_s, timeout=None):
|
|
3110
|
+
"""Adapter 3, the client of Throttle's lane bus (BEY-6869, `src/lane_bus/http.rs`): POST
|
|
3111
|
+
`http://127.0.0.1:<bus_port>/v1/lanes/messages` — Throttle's CONTROL listener, never ANTHROPIC_BASE_URL (its data
|
|
3112
|
+
plane answers every `/v1/lanes*` 404 `lane_bus_control_only`) — with the body `{to, from, text, ttl_s}` (`from` the
|
|
3113
|
+
sender's lane trace: the sender is the body's, never a header) and `Authorization: Bearer <bus_token(harness)>` ->
|
|
3114
|
+
Throttle's answer {id, state: queued} (it answers 202 `{v, id, state, expires_at}`). No proxy, no redirect followed.
|
|
3115
|
+
Definite failures are LaneError `bus_unavailable`: no token, no port, a connection refused (nothing was sent), an
|
|
3116
|
+
HTTP answer that is not 2xx (Throttle refused it). Once the request went out, a lost answer (a timeout, a reset)
|
|
3117
|
+
or a 2xx that is not {id, state: queued} is Unconfirmed: Throttle may have queued it. No sentence holds the
|
|
3118
|
+
token."""
|
|
3119
|
+
import http.client
|
|
3120
|
+
timeout = BUS_TIMEOUT if timeout is None else timeout
|
|
3121
|
+
port = bus_port(environ)
|
|
3122
|
+
token = bus_token(harness, environ, home)
|
|
3123
|
+
body = json.dumps({'to': to_trace, 'from': sender_trace, 'text': text, 'ttl_s': int(ttl_s)}).encode('utf-8')
|
|
3124
|
+
connection = http.client.HTTPConnection(BUS_HOST, port, timeout=timeout)
|
|
3125
|
+
try:
|
|
3126
|
+
try:
|
|
3127
|
+
connection.connect()
|
|
3128
|
+
except OSError as error:
|
|
3129
|
+
raise LaneError(f'Throttle\'s control listener {BUS_HOST}:{port} took no connection '
|
|
3130
|
+
f'({type(error).__name__}): nothing was sent', 'bus_unavailable') from None
|
|
3131
|
+
try:
|
|
3132
|
+
connection.request('POST', BUS_PATH, body=body, headers={'content-type': 'application/json',
|
|
3133
|
+
'authorization': f'Bearer {token}'})
|
|
3134
|
+
response = connection.getresponse()
|
|
3135
|
+
except (OSError, http.client.HTTPException) as error:
|
|
3136
|
+
raise Unconfirmed(f'the request went out to Throttle\'s {BUS_PATH} and no answer came back '
|
|
3137
|
+
f'({type(error).__name__}): it may have queued it', 'bus_unavailable') from None
|
|
3138
|
+
if not 200 <= response.status < 300:
|
|
3139
|
+
raise LaneError(f'Throttle answered HTTP {response.status} at {BUS_PATH}', 'bus_unavailable')
|
|
3140
|
+
try:
|
|
3141
|
+
data = response.read(BUS_ANSWER_MAX + 1)
|
|
3142
|
+
except (OSError, http.client.HTTPException) as error:
|
|
3143
|
+
raise Unconfirmed(f'Throttle answered HTTP {response.status} at {BUS_PATH} and its body was lost '
|
|
3144
|
+
f'({type(error).__name__}): it may have queued it', 'bus_unavailable') from None
|
|
3145
|
+
finally:
|
|
3146
|
+
connection.close()
|
|
3147
|
+
try:
|
|
3148
|
+
answer = json.loads(data.decode('utf-8')) if len(data) <= BUS_ANSWER_MAX else None
|
|
3149
|
+
except (UnicodeDecodeError, ValueError):
|
|
3150
|
+
answer = None
|
|
3151
|
+
if not (isinstance(answer, dict) and isinstance(answer.get('id'), str) and answer.get('state') == 'queued'):
|
|
3152
|
+
raise Unconfirmed(f'Throttle answered HTTP {response.status} at {BUS_PATH} without {{id, state: queued}}: it '
|
|
3153
|
+
'may have queued it', 'bus_unavailable')
|
|
3154
|
+
return {'id': answer['id'][:128], 'state': 'queued'}
|
|
3155
|
+
|
|
3156
|
+
|
|
3157
|
+
# ------------------------------------------------------------------------------------------------ dispatch lock
|
|
3158
|
+
# W15 part 2 (the PR #544 review 8d91d073; Linear BEY-6842, BEY-6843; DM-LANES-DISPATCH-LOCK). Native input — a text and
|
|
3159
|
+
# its Enter typed into a lane's pane, ENTER_DELAY s apart — has ONE authority per recipient: an exclusive flock(2) on
|
|
3160
|
+
# the container file ~/.lz/state/dispatch/<lane id>.lock (the directory 0700, the file 0600, both created when absent
|
|
3161
|
+
# and owned like ~/.lz/state, no component a link). Every writer takes it: lane_core.message's typed adapter (`lane
|
|
3162
|
+
# message`, lanes_message, lane-peerd's handler threads — flock conflicts between two opens of one file in one process
|
|
3163
|
+
# too), lanes_send and `lane send`, and on the host lanes-statusd (the inbox drain, `lanes message`; the automatic
|
|
3164
|
+
# `/rename` of W15 part 1 follows the same convention), which reaches the same inode through
|
|
3165
|
+
# /proc/<init pid>/root/home/coder/.lz/state/dispatch/<lane id>.lock.
|
|
3166
|
+
# A writer waits at most DISPATCH_WAIT_S, then refuses `recipient_busy` (or queues), and holds it across its final
|
|
3167
|
+
# readiness recheck, the text, the Enter and — for a waiting message — its settled receipt. The lock is the file's
|
|
3168
|
+
# flock, never its content: nothing is written into it and it is never removed; closing the fd releases it.
|
|
3169
|
+
DISPATCH_DIR = ('state', 'dispatch')
|
|
3170
|
+
DISPATCH_SUFFIX = '.lock'
|
|
3171
|
+
DISPATCH_WAIT_S = 5
|
|
3172
|
+
DISPATCH_POLL_S = 0.05
|
|
3173
|
+
|
|
3174
|
+
|
|
3175
|
+
class DispatchBusy(LaneError):
|
|
3176
|
+
"""Another writer held the recipient's dispatch lock longer than the wait: code `recipient_busy`."""
|
|
3177
|
+
|
|
3178
|
+
|
|
3179
|
+
def _owned_like(fd, parent_fd):
|
|
3180
|
+
"""`fd` given the owner of `parent_fd` when they differ and this process may (lanes-statusd on the host creating it
|
|
3181
|
+
for the container's user); silence when it may not."""
|
|
3182
|
+
try:
|
|
3183
|
+
want, have = os.fstat(parent_fd), os.fstat(fd)
|
|
3184
|
+
if (have.st_uid, have.st_gid) != (want.st_uid, want.st_gid):
|
|
3185
|
+
os.fchown(fd, want.st_uid, want.st_gid)
|
|
3186
|
+
except OSError:
|
|
3187
|
+
pass
|
|
3188
|
+
|
|
3189
|
+
|
|
3190
|
+
def dispatch_fd(root, lane, prefix=()):
|
|
3191
|
+
"""fd of <root>/<prefix…>/state/dispatch/<lane>.lock, opened read-write and created 0600 when absent (the directory
|
|
3192
|
+
0700), every component a REAL directory and the file a regular one — OSError otherwise (a link is never followed:
|
|
3193
|
+
from the host one planted in the container resolves on the HOST)."""
|
|
3194
|
+
if not (isinstance(lane, str) and LANE_RE.fullmatch(lane)):
|
|
3195
|
+
raise OSError(f'invalid lane id {lane!r}')
|
|
3196
|
+
state = _open_dir(root, tuple(prefix) + DISPATCH_DIR[:1], create=True, keep=len(tuple(prefix)))
|
|
3197
|
+
try:
|
|
3198
|
+
try:
|
|
3199
|
+
directory = os.open(DISPATCH_DIR[1], _DIR_FLAGS | os.O_NOFOLLOW, dir_fd=state)
|
|
3200
|
+
except FileNotFoundError:
|
|
3201
|
+
try:
|
|
3202
|
+
os.mkdir(DISPATCH_DIR[1], 0o700, dir_fd=state)
|
|
3203
|
+
except FileExistsError:
|
|
3204
|
+
pass
|
|
3205
|
+
directory = os.open(DISPATCH_DIR[1], _DIR_FLAGS | os.O_NOFOLLOW, dir_fd=state)
|
|
3206
|
+
_owned_like(directory, state)
|
|
3207
|
+
finally:
|
|
3208
|
+
os.close(state)
|
|
3209
|
+
try:
|
|
3210
|
+
fd = os.open(lane + DISPATCH_SUFFIX, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK
|
|
3211
|
+
| getattr(os, 'O_CLOEXEC', 0), 0o600, dir_fd=directory)
|
|
3212
|
+
try:
|
|
3213
|
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
|
3214
|
+
raise OSError(f'{lane}{DISPATCH_SUFFIX} is not a regular file')
|
|
3215
|
+
_owned_like(fd, directory)
|
|
3216
|
+
except BaseException:
|
|
3217
|
+
os.close(fd)
|
|
3218
|
+
raise
|
|
3219
|
+
finally:
|
|
3220
|
+
os.close(directory)
|
|
3221
|
+
return fd
|
|
3222
|
+
|
|
3223
|
+
|
|
3224
|
+
@contextlib.contextmanager
|
|
3225
|
+
def dispatch_lock(root, lane, prefix=(), wait=None):
|
|
3226
|
+
"""Hold `lane`'s dispatch lock (<root>/<prefix…>/state/dispatch/<lane>.lock, dispatch_fd) for the block: an
|
|
3227
|
+
exclusive flock, waited for at most `wait` s (default DISPATCH_WAIT_S) — then DispatchBusy (`recipient_busy`), and
|
|
3228
|
+
nothing of the block ran; a lock file that cannot be opened (a link planted, no ~/.lz) is DispatchBusy too: no
|
|
3229
|
+
writer types without it. Released when the block ends, however it ends."""
|
|
3230
|
+
wait = DISPATCH_WAIT_S if wait is None else wait
|
|
3231
|
+
try:
|
|
3232
|
+
fd = dispatch_fd(root, lane, prefix)
|
|
3233
|
+
except OSError as error:
|
|
3234
|
+
raise DispatchBusy(f'{lane}: its dispatch lock cannot be opened ({error.strerror or error}) — nothing is typed '
|
|
3235
|
+
'without it', 'recipient_busy') from None
|
|
3236
|
+
try:
|
|
3237
|
+
deadline = time.monotonic() + wait
|
|
3238
|
+
while True:
|
|
3239
|
+
try:
|
|
3240
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
3241
|
+
break
|
|
3242
|
+
except BlockingIOError:
|
|
3243
|
+
if time.monotonic() >= deadline:
|
|
3244
|
+
raise DispatchBusy(f'{lane}: another sender is typing into it (its dispatch lock stayed taken for '
|
|
3245
|
+
f'{wait:g} s)', 'recipient_busy') from None
|
|
3246
|
+
time.sleep(DISPATCH_POLL_S)
|
|
3247
|
+
yield fd
|
|
3248
|
+
finally:
|
|
3249
|
+
os.close(fd)
|
|
3250
|
+
|
|
3251
|
+
|
|
3252
|
+
def generation(row):
|
|
3253
|
+
"""Who answers in a lane, as a status.json row says: (harness, pid, session id) of its agent, Nones without one. A
|
|
3254
|
+
writer that waited for the dispatch lock types nothing when this moved (the agent was replaced meanwhile)."""
|
|
3255
|
+
agent = row.get('agent') if isinstance(row, dict) and isinstance(row.get('agent'), dict) else {}
|
|
3256
|
+
return agent.get('harness'), agent.get('pid'), agent.get('session_id')
|
|
3257
|
+
|
|
3258
|
+
|
|
3259
|
+
def recipient_idle(found, observed, hook, status_fresh):
|
|
3260
|
+
"""Adapter 4's rule -> (idle, why not). Never on an observation that is not fresh or a kept (`stale`) row, never
|
|
3261
|
+
while the lane's hook sidecar says working or needs_approval. An agent: its status one of IDLE_WORDS and not
|
|
3262
|
+
delegating. No agent (a `typed` handle): no output within statusd's active window (state not `active`); the shell
|
|
3263
|
+
at its prompt is asked of tmux when typing."""
|
|
3264
|
+
if not status_fresh or observed.get('stale'):
|
|
3265
|
+
return False, 'the host\'s observation of it is not fresh'
|
|
3266
|
+
if isinstance(hook, dict) and hook.get('status') in BUSY_WORDS:
|
|
3267
|
+
return False, f'its lane-signal hook says {hook["status"]}'
|
|
3268
|
+
agent = observed.get('agent') if isinstance(observed.get('agent'), dict) else {}
|
|
3269
|
+
if found['transport'] == 'typed':
|
|
3270
|
+
if observed.get('state') != 'quiet':
|
|
3271
|
+
return False, f'its pane is {observed.get("state") or "unknown"}'
|
|
3272
|
+
return True, None
|
|
3273
|
+
if agent.get('activity') == 'delegating':
|
|
3274
|
+
return False, 'its agent is delegating to background work'
|
|
3275
|
+
if agent.get('status') not in IDLE_WORDS:
|
|
3276
|
+
return False, f'its agent is {agent.get("status") or "not observed"}'
|
|
3277
|
+
return True, None
|
|
3278
|
+
|
|
3279
|
+
|
|
3280
|
+
def pane_command(socket, session, run=None):
|
|
3281
|
+
"""The foreground command of the session's active pane (`#{pane_current_command}`), or None (no answer)."""
|
|
3282
|
+
run = run or run_tmux
|
|
3283
|
+
result = run(tmux_argv(socket, 'display', '-p', '-t', target(session), '#{pane_current_command}'))
|
|
3284
|
+
return result.stdout.strip() if result.returncode == 0 else None
|
|
3285
|
+
|
|
3286
|
+
|
|
3287
|
+
def messaging_name(row):
|
|
3288
|
+
"""The Claude messaging name a status.json row's agent{} carries (`messaging.name`), or None."""
|
|
3289
|
+
agent = row.get('agent') if isinstance(row, dict) else None
|
|
3290
|
+
messaging = agent.get('messaging') if isinstance(agent, dict) else None
|
|
3291
|
+
name = messaging.get('name') if isinstance(messaging, dict) else None
|
|
3292
|
+
return name if isinstance(name, str) and name else None
|
|
3293
|
+
|
|
3294
|
+
|
|
3295
|
+
# ------------------------------------------------------------------------------------------------ Claude peers (W15 L6)
|
|
3296
|
+
# Claude Code's cross-session messaging, spoken by proxy in both directions (plan 2026-10-25-lanes-messaging-bus, L6 and
|
|
3297
|
+
# D3; Linear BEY-6843; DM-LANES-PEER, DM-LANES-PEER-FRAME). MEASURED 2026-10-25 on Claude Code 2.1.310 (plan
|
|
3298
|
+
# "Measured 2026-10-25 — M9 and M10"; the raw frames in lanes/tests/unit/fixtures/peer/):
|
|
3299
|
+
# * discovery: a `~/.claude/sessions/<pid>.json` whose `pid` is ANY live process with `procStart` = field 22 of
|
|
3300
|
+
# /proc/<pid>/stat, carrying the keys a real entry has, is listed at once by a real session's ListAgents as
|
|
3301
|
+
# `<name> [ref] · interactive · idle · tmux <pane>`; removing it removes it;
|
|
3302
|
+
# * inbound (what SendMessage writes to a peer's socket): one connection, ONE JSON line (PEER_FRAME's shape), no auth
|
|
3303
|
+
# line; the receiver must send NO byte back (any reply makes the sender's tool report "Failed to send"); a probe
|
|
3304
|
+
# connection carrying no line may come first;
|
|
3305
|
+
# * outbound: the same line, `from`/`from-name`/`from-mode` set by the writer, written to a REAL session's socket by a
|
|
3306
|
+
# plain client is delivered mid-turn; no auth, no reply, the writer closes after the line. The receiver's holds
|
|
3307
|
+
# follow the declared `from-mode`: a writer declares its sender's real mode (sender_mode), never one that lifts a
|
|
3308
|
+
# hold.
|
|
3309
|
+
# Read statically in the 2.1.310 binary (INFERRED, not measured): a sender checks only that a live session file (pid +
|
|
3310
|
+
# procStart) names the socket — never `updatedAt` — and `notify_idle` is a subscription a sender makes with its own
|
|
3311
|
+
# frame, whose shape is unmeasured: virtual peers omit it from `peerFeatures` (PEER_FEATURES) rather than claim it.
|
|
3312
|
+
|
|
3313
|
+
PEER_PIN = {'claude': '2.1.310', 'peerProtocol': 1} # = lanes/tests/unit/fixtures/peer/pin.json (test_lane_peerd.Pin)
|
|
3314
|
+
PEERS_DIR = ('state', 'peers') # under ~/.lz (0700): <lane>.sock (0600), peers.json (lane-peerd's, DM-LANES-PEER)
|
|
3315
|
+
PEERS_STATE = 'peers.json'
|
|
3316
|
+
PEER_FRESH = 90 # peers.json is renewed at least every 30 s while lane-peerd runs: older = stopped
|
|
3317
|
+
# What virtual peers honour of Claude's peerFeatures: nothing measured yet. TODO(BEY-6843): notify_idle — measure the
|
|
3318
|
+
# idle-subscription frame a sender writes (SendMessage notify_when_idle) and the notice Claude sends when it goes idle,
|
|
3319
|
+
# then honour it from lane-peerd when a lane leaves `working` and only then list it here.
|
|
3320
|
+
PEER_FEATURES = []
|
|
3321
|
+
SOCKET_PATH_MAX = 107 # a unix socket address holds 108 bytes, its NUL included
|
|
3322
|
+
PEER_CONNECT_TIMEOUT = 2 # seconds: connect + write of one line to a real session's socket
|
|
3323
|
+
PEER_FILE_MAX = 64 << 10 # a session file bigger than this is not Claude's
|
|
3324
|
+
PEER_SCAN_MAX = 4096 # session files looked at, at most, to find one by its name
|
|
3325
|
+
PEER_MODES = ('bypass', 'prompting')
|
|
3326
|
+
PEER_TAG = 'cross-session-message'
|
|
3327
|
+
PEER_OPEN = re.compile(r'^<cross-session-message\b([^>]*)>\n?')
|
|
3328
|
+
PEER_ATTR = re.compile(r'(?:^|\s)(from-name|from-mode|from)="([^"]*)"')
|
|
3329
|
+
PEER_SAFE = re.compile(r'[A-Za-z0-9_./:@+-]{1,512}') # what a frame's `from` and `from-name` may hold when we write one
|
|
3330
|
+
PEER_LINE_BREAK = ' ↵ ' # a frame's line breaks, in the one line a message is
|
|
3331
|
+
CLAUDE_SESSIONS = ('.claude', 'sessions')
|
|
3332
|
+
BYPASS_FLAGS = ('--dangerously-skip-permissions',)
|
|
3333
|
+
|
|
3334
|
+
|
|
3335
|
+
class PeerPinFailed(LaneError):
|
|
3336
|
+
"""The recipient's Claude session is not the protocol Lanes measured (PEER_PIN): no line is written."""
|
|
3337
|
+
|
|
3338
|
+
def __init__(self, message):
|
|
3339
|
+
super().__init__(message, 'peer_pin_failed')
|
|
3340
|
+
|
|
3341
|
+
|
|
3342
|
+
def peers_root(home):
|
|
3343
|
+
"""<home>/.lz/state/peers as a string (the directory lane-peerd owns)."""
|
|
3344
|
+
return f'{home}/.lz/{"/".join(PEERS_DIR)}'
|
|
3345
|
+
|
|
3346
|
+
|
|
3347
|
+
def peer_socket_name(lane, home=CONTAINER_HOME):
|
|
3348
|
+
"""The file name of `lane`'s virtual peer socket in peers_root(home): `<lane>.sock`, or `x-<sha256 prefix>.sock`
|
|
3349
|
+
when the whole path would not fit a unix socket address (SOCKET_PATH_MAX bytes)."""
|
|
3350
|
+
import hashlib
|
|
3351
|
+
name = f'{lane}.sock'
|
|
3352
|
+
if len(f'{peers_root(home)}/{name}'.encode('utf-8')) <= SOCKET_PATH_MAX:
|
|
3353
|
+
return name
|
|
3354
|
+
return 'x-' + hashlib.sha256(lane.encode('utf-8')).hexdigest()[:24] + '.sock'
|
|
3355
|
+
|
|
3356
|
+
|
|
3357
|
+
def peer_socket_path(lane, home=CONTAINER_HOME):
|
|
3358
|
+
"""Where `lane`'s virtual peer socket is: the `from` of every line written for it (its replies come back there)."""
|
|
3359
|
+
return f'{peers_root(home)}/{peer_socket_name(lane, home)}'
|
|
3360
|
+
|
|
3361
|
+
|
|
3362
|
+
def is_virtual_entry(document, home=CONTAINER_HOME):
|
|
3363
|
+
"""Is this Claude session document one lane-peerd wrote (its `messagingSocketPath` is in peers_root(home))?"""
|
|
3364
|
+
path = document.get('messagingSocketPath') if isinstance(document, dict) else None
|
|
3365
|
+
return isinstance(path, str) and path.startswith(peers_root(home) + '/')
|
|
3366
|
+
|
|
3367
|
+
|
|
3368
|
+
def virtual_peers(root, now=None):
|
|
3369
|
+
"""{lane id: {'name', 'socket', 'pid'}} of the virtual peers lane-peerd serves now: <root>/state/peers/peers.json
|
|
3370
|
+
(DM-LANES-PEER) while its `at` is at most PEER_FRESH seconds old, each entry only while its socket is a socket in
|
|
3371
|
+
that directory. {} when no lane-peerd runs. Never raises."""
|
|
3372
|
+
now = time.time() if now is None else now
|
|
3373
|
+
directory = Path(root).joinpath(*PEERS_DIR)
|
|
3374
|
+
data = read_json(directory / PEERS_STATE)
|
|
3375
|
+
if not isinstance(data, dict) or data.get('v') != 1 or not isinstance(data.get('peers'), dict):
|
|
3376
|
+
return {}
|
|
3377
|
+
at = data.get('at')
|
|
3378
|
+
if isinstance(at, bool) or not isinstance(at, (int, float)) or not 0 <= now - at <= PEER_FRESH:
|
|
3379
|
+
return {}
|
|
3380
|
+
out = {}
|
|
3381
|
+
for lane, peer in data['peers'].items():
|
|
3382
|
+
if not (isinstance(lane, str) and LANE_RE.fullmatch(lane) and isinstance(peer, dict)
|
|
3383
|
+
and isinstance(peer.get('name'), str) and ADDRESS_RE.fullmatch(peer['name'])
|
|
3384
|
+
and isinstance(peer.get('socket'), str)):
|
|
3385
|
+
continue
|
|
3386
|
+
base = peer['socket'].rpartition('/')[2]
|
|
3387
|
+
try:
|
|
3388
|
+
if base and not stat.S_ISSOCK(os.lstat(str(directory / base)).st_mode):
|
|
3389
|
+
continue
|
|
3390
|
+
except OSError:
|
|
3391
|
+
continue
|
|
3392
|
+
out[lane] = {'name': peer['name'], 'socket': peer['socket'], 'pid': peer.get('pid')}
|
|
3393
|
+
return out
|
|
3394
|
+
|
|
3395
|
+
|
|
3396
|
+
def peer_frame(sender_socket, sender_name, sender_mode, text, msg_id=None):
|
|
3397
|
+
"""DM-LANES-PEER-FRAME: the ONE line (UTF-8, `\\n`-terminated) Claude Code 2.1.310 writes to a peer's socket, key
|
|
3398
|
+
for key and in its order — {msgV: 1, msg_id, type: user, message: {role: user, content: <cross-session-message
|
|
3399
|
+
from="uds:<sender socket>" from-name="<sender name>" from-mode="<mode>">\\n<text>\\n</cross-session-message>},
|
|
3400
|
+
priority: next, from: uds:<sender socket>} — compact JSON, non-ASCII kept. ValueError for a mode outside PEER_MODES
|
|
3401
|
+
or a socket or name a quote could break out of."""
|
|
3402
|
+
import uuid
|
|
3403
|
+
if sender_mode not in PEER_MODES:
|
|
3404
|
+
raise ValueError(f'from-mode {sender_mode!r} is none of {PEER_MODES}')
|
|
3405
|
+
if not (PEER_SAFE.fullmatch(sender_socket or '') and (sender_socket or '').startswith('/')
|
|
3406
|
+
and PEER_SAFE.fullmatch(sender_name or '')):
|
|
3407
|
+
raise ValueError('a frame names its sender by a plain socket path and name')
|
|
3408
|
+
origin = f'uds:{sender_socket}'
|
|
3409
|
+
content = (f'<{PEER_TAG} from="{origin}" from-name="{sender_name}" from-mode="{sender_mode}">\n{text}\n'
|
|
3410
|
+
f'</{PEER_TAG}>')
|
|
3411
|
+
frame = {'msgV': 1, 'msg_id': msg_id or str(uuid.uuid4()), 'type': 'user',
|
|
3412
|
+
'message': {'role': 'user', 'content': content}, 'priority': 'next', 'from': origin}
|
|
3413
|
+
return (json.dumps(frame, ensure_ascii=False, separators=(',', ':')) + '\n').encode('utf-8')
|
|
3414
|
+
|
|
3415
|
+
|
|
3416
|
+
def parse_peer_frame(line):
|
|
3417
|
+
"""One protocol-1 line (bytes or str, its `\\n` optional) -> {'msg_id', 'from', 'from_name', 'from_mode', 'text'}
|
|
3418
|
+
— the text between the `<cross-session-message …>` tags (Claude's own rule: the opening tag and one newline at the
|
|
3419
|
+
start, the LAST closing tag and the newline before it at the end), the attributes as written (None when absent).
|
|
3420
|
+
ValueError naming why it is not one: not JSON, another `msgV`, a `type` other than `user` (a control frame), no
|
|
3421
|
+
string `content`, no wrapper."""
|
|
3422
|
+
if isinstance(line, bytes):
|
|
3423
|
+
line = line.decode('utf-8')
|
|
3424
|
+
frame = json.loads(line)
|
|
3425
|
+
if not isinstance(frame, dict):
|
|
3426
|
+
raise ValueError('not a JSON object')
|
|
3427
|
+
if frame.get('msgV') != 1:
|
|
3428
|
+
raise ValueError(f'msgV {frame.get("msgV")!r}, not 1')
|
|
3429
|
+
if frame.get('type') != 'user':
|
|
3430
|
+
raise ValueError(f'type {str(frame.get("type"))[:32]!r}, not user')
|
|
3431
|
+
message = frame.get('message')
|
|
3432
|
+
content = message.get('content') if isinstance(message, dict) and message.get('role') == 'user' else None
|
|
3433
|
+
if not isinstance(content, str):
|
|
3434
|
+
raise ValueError('no user message with a string content')
|
|
3435
|
+
opened = PEER_OPEN.match(content)
|
|
3436
|
+
if not opened:
|
|
3437
|
+
raise ValueError('no <cross-session-message> wrapper')
|
|
3438
|
+
attributes = {}
|
|
3439
|
+
for key, value in PEER_ATTR.findall(opened.group(1)):
|
|
3440
|
+
attributes.setdefault(key, value)
|
|
3441
|
+
body = content[opened.end():]
|
|
3442
|
+
end = body.rfind(f'</{PEER_TAG}>')
|
|
3443
|
+
if end >= 0:
|
|
3444
|
+
body = body[:end]
|
|
3445
|
+
body = body[:-1] if body.endswith('\n') else body
|
|
3446
|
+
origin = attributes.get('from') or (frame.get('from') if isinstance(frame.get('from'), str) else None)
|
|
3447
|
+
msg_id = frame.get('msg_id') if isinstance(frame.get('msg_id'), str) else None
|
|
3448
|
+
return {'msg_id': msg_id, 'from': origin, 'from_name': attributes.get('from-name') or None,
|
|
3449
|
+
'from_mode': attributes.get('from-mode') or None, 'text': body}
|
|
3450
|
+
|
|
3451
|
+
|
|
3452
|
+
def peer_text(body):
|
|
3453
|
+
"""A frame's text as the one line a message is (check_message) -> (text, cut): its line breaks as PEER_LINE_BREAK,
|
|
3454
|
+
every other refused character (REFUSED_TEXT) a space, trimmed, cut to MESSAGE_MAX ending in `…` when longer. A
|
|
3455
|
+
sender already counts its message as sent, so a frame is reshaped, never refused for its form."""
|
|
3456
|
+
text = re.sub(r'\r\n|\r|\n', PEER_LINE_BREAK, body or '')
|
|
3457
|
+
text = ''.join(' ' if unicodedata.category(char) in REFUSED_TEXT else char for char in text).strip()
|
|
3458
|
+
if len(text) <= MESSAGE_MAX:
|
|
3459
|
+
return text, False
|
|
3460
|
+
return text[:MESSAGE_MAX - 1] + '…', True
|
|
3461
|
+
|
|
3462
|
+
|
|
3463
|
+
def proc_start(proc, pid):
|
|
3464
|
+
"""Field 22 (starttime) of /proc/<pid>/stat as Claude writes it into `procStart` (a string), or None."""
|
|
3465
|
+
data = read_regular(Path(proc) / str(pid) / 'stat', 1 << 16)
|
|
3466
|
+
if data is None:
|
|
3467
|
+
return None
|
|
3468
|
+
fields = data.decode('utf-8', 'replace').rsplit(')', 1)[-1].split()
|
|
3469
|
+
return fields[19] if len(fields) > 19 else None
|
|
3470
|
+
|
|
3471
|
+
|
|
3472
|
+
def version_tuple(text):
|
|
3473
|
+
"""`2.1.310` -> (2, 1, 310); None for anything that is not dotted numbers."""
|
|
3474
|
+
if not isinstance(text, str) or not re.fullmatch(r'[0-9]{1,6}(?:\.[0-9]{1,6}){0,3}', text):
|
|
3475
|
+
return None
|
|
3476
|
+
return tuple(int(part) for part in text.split('.'))
|
|
3477
|
+
|
|
3478
|
+
|
|
3479
|
+
def peer_pin_problem(document):
|
|
3480
|
+
"""Why a Claude session file is not the protocol Lanes measured (PEER_PIN: `peerProtocol` equal, `version` at
|
|
3481
|
+
most the measured one), or None."""
|
|
3482
|
+
if not isinstance(document, dict):
|
|
3483
|
+
return 'no session file'
|
|
3484
|
+
if document.get('peerProtocol') != PEER_PIN['peerProtocol']:
|
|
3485
|
+
return f'peerProtocol {document.get("peerProtocol")!r}, pinned {PEER_PIN["peerProtocol"]}'
|
|
3486
|
+
version = version_tuple(document.get('version'))
|
|
3487
|
+
if version is None:
|
|
3488
|
+
return 'its session file names no Claude Code version'
|
|
3489
|
+
if version > version_tuple(PEER_PIN['claude']):
|
|
3490
|
+
return (f'Claude Code {document["version"]} is newer than the measured {PEER_PIN["claude"]} (re-measure: '
|
|
3491
|
+
'RUNBOOK "Claude peers")')
|
|
3492
|
+
return None
|
|
3493
|
+
|
|
3494
|
+
|
|
3495
|
+
def _session_document(directory, pid, proc):
|
|
3496
|
+
"""<directory>/<pid>.json as a dict when it is a LIVE Claude session's: a regular file of at most PEER_FILE_MAX
|
|
3497
|
+
bytes whose `pid` is the file's and whose `procStart` is the process's now. None otherwise."""
|
|
3498
|
+
document = None
|
|
3499
|
+
data = read_regular(Path(directory) / f'{pid}.json', PEER_FILE_MAX)
|
|
3500
|
+
try:
|
|
3501
|
+
document = json.loads(data.decode('utf-8')) if data is not None else None
|
|
3502
|
+
except (UnicodeDecodeError, ValueError):
|
|
3503
|
+
return None
|
|
3504
|
+
if not isinstance(document, dict) or document.get('pid') != pid:
|
|
3505
|
+
return None
|
|
3506
|
+
started = proc_start(proc, pid)
|
|
3507
|
+
return document if started is not None and str(document.get('procStart')) == started else None
|
|
3508
|
+
|
|
3509
|
+
|
|
3510
|
+
def claude_session(home, agent, name, proc=Path('/proc')):
|
|
3511
|
+
"""The live Claude session file of a lane's agent (a dict), or None: `<home>/.claude/sessions/<agent pid>.json`,
|
|
3512
|
+
else the one live file (of the newest PEER_SCAN_MAX) whose `name` is the lane's messaging name `name`. A file
|
|
3513
|
+
lane-peerd wrote is never one (is_virtual_entry)."""
|
|
3514
|
+
directory = Path(home).joinpath(*CLAUDE_SESSIONS)
|
|
3515
|
+
pid = agent.get('pid') if isinstance(agent, dict) else None
|
|
3516
|
+
if isinstance(pid, int) and not isinstance(pid, bool) and pid > 1:
|
|
3517
|
+
document = _session_document(directory, pid, proc)
|
|
3518
|
+
if document is not None and not is_virtual_entry(document, home) \
|
|
3519
|
+
and (not name or document.get('name') == name):
|
|
3520
|
+
return document
|
|
3521
|
+
if not name:
|
|
3522
|
+
return None
|
|
3523
|
+
try:
|
|
3524
|
+
names = sorted((entry for entry in os.listdir(str(directory)) if re.fullmatch(r'[1-9][0-9]{0,9}\.json', entry)),
|
|
3525
|
+
key=lambda entry: int(entry[:-5]))[-PEER_SCAN_MAX:]
|
|
3526
|
+
except OSError:
|
|
3527
|
+
return None
|
|
3528
|
+
found = []
|
|
3529
|
+
for entry in names:
|
|
3530
|
+
document = _session_document(directory, int(entry[:-5]), proc)
|
|
3531
|
+
if document is not None and not is_virtual_entry(document, home) and document.get('name') == name:
|
|
3532
|
+
found.append(document)
|
|
3533
|
+
return found[0] if len(found) == 1 else None
|
|
3534
|
+
|
|
3535
|
+
|
|
3536
|
+
def sender_mode(harness, pid=None, proc=Path('/proc')):
|
|
3537
|
+
"""The `from-mode` a line written for a sender declares (M10: the receiver's holds follow it): `bypass` only for a
|
|
3538
|
+
Claude Code process run with --dangerously-skip-permissions (its /proc/<pid>/cmdline), `prompting` for anything
|
|
3539
|
+
else — every other harness, a shell, a pid that cannot be read. Never a mode that lifts a hold it is not owed."""
|
|
3540
|
+
if harness != 'claude' or not isinstance(pid, int) or pid <= 1:
|
|
3541
|
+
return 'prompting'
|
|
3542
|
+
data = read_regular(Path(proc) / str(pid) / 'cmdline', ENVIRON_MAX) or b''
|
|
3543
|
+
words = [word.decode('utf-8', 'replace') for word in data.split(b'\0')]
|
|
3544
|
+
return 'bypass' if any(word in BYPASS_FLAGS for word in words) else 'prompting'
|
|
3545
|
+
|
|
3546
|
+
|
|
3547
|
+
def peer_send(document, sender_socket, sender_name, mode, text, timeout=PEER_CONNECT_TIMEOUT, home=CONTAINER_HOME):
|
|
3548
|
+
"""Adapter 1b: write ONE protocol-1 line (peer_frame) to the real Claude session `document` names, then close —
|
|
3549
|
+
nothing is read back -> {'msg_id'}. PeerPinFailed (`peer_pin_failed`) when the session is not the protocol Lanes
|
|
3550
|
+
measured; LaneError `peer_socket_failed` when its socket is no socket, is a virtual peer's, or does not take the
|
|
3551
|
+
line within `timeout` s."""
|
|
3552
|
+
import socket
|
|
3553
|
+
problem = peer_pin_problem(document)
|
|
3554
|
+
if problem:
|
|
3555
|
+
raise PeerPinFailed(f'the recipient\'s Claude session is not the measured protocol: {problem}')
|
|
3556
|
+
path = document.get('messagingSocketPath')
|
|
3557
|
+
if (not isinstance(path, str) or not path.startswith('/') or len(path.encode('utf-8')) > SOCKET_PATH_MAX
|
|
3558
|
+
or REFUSED_TEXT.intersection(unicodedata.category(char) for char in path)):
|
|
3559
|
+
raise LaneError('the recipient\'s session file names no usable messaging socket', 'peer_socket_failed')
|
|
3560
|
+
if is_virtual_entry(document, home):
|
|
3561
|
+
raise LaneError('the recipient\'s socket is a virtual peer\'s, not a Claude session\'s', 'peer_socket_failed')
|
|
3562
|
+
try:
|
|
3563
|
+
if not stat.S_ISSOCK(os.lstat(path).st_mode):
|
|
3564
|
+
raise LaneError('the recipient\'s messaging socket is not a socket', 'peer_socket_failed')
|
|
3565
|
+
except OSError:
|
|
3566
|
+
raise LaneError('the recipient\'s messaging socket is gone', 'peer_socket_failed') from None
|
|
3567
|
+
import uuid
|
|
3568
|
+
msg_id = str(uuid.uuid4())
|
|
3569
|
+
try:
|
|
3570
|
+
frame = peer_frame(sender_socket, sender_name, mode, text, msg_id)
|
|
3571
|
+
except ValueError as error:
|
|
3572
|
+
raise LaneError(f'no line can name this sender ({error})', 'peer_socket_failed') from None
|
|
3573
|
+
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
3574
|
+
try:
|
|
3575
|
+
client.settimeout(timeout)
|
|
3576
|
+
client.connect(path)
|
|
3577
|
+
client.sendall(frame)
|
|
3578
|
+
except OSError as error:
|
|
3579
|
+
raise LaneError(f'the recipient\'s messaging socket did not take the line ({type(error).__name__})',
|
|
3580
|
+
'peer_socket_failed') from None
|
|
3581
|
+
finally:
|
|
3582
|
+
client.close()
|
|
3583
|
+
return {'msg_id': msg_id}
|
|
3584
|
+
|
|
3585
|
+
|
|
3586
|
+
def peer_origin(inbound):
|
|
3587
|
+
"""DM-LANES-MESSAGE's additive `origin` for a frame lane-peerd took (W15 L6): {via: send_message, name, mode,
|
|
3588
|
+
msg_id} — each a short token of LOG_FIELD's characters or null, so no free text rides in it."""
|
|
3589
|
+
def token(value):
|
|
3590
|
+
return value[:128] if isinstance(value, str) and LOG_FIELD.fullmatch(value[:128]) else None
|
|
3591
|
+
mode = inbound.get('mode') if isinstance(inbound, dict) else None
|
|
3592
|
+
return {'via': 'send_message', 'name': token((inbound or {}).get('name')),
|
|
3593
|
+
'mode': mode if mode in PEER_MODES else None, 'msg_id': token((inbound or {}).get('msg_id'))}
|
|
3594
|
+
|
|
3595
|
+
|
|
3596
|
+
def _refusal(message_text, code, **extra):
|
|
3597
|
+
"""A LaneError carrying `extra` (lane-mcp answers it beside {refused, why, human})."""
|
|
3598
|
+
error = LaneError(message_text, code)
|
|
3599
|
+
error.extra = extra
|
|
3600
|
+
return error
|
|
3601
|
+
|
|
3602
|
+
|
|
3603
|
+
def message(root, home, sender_lane, to, text, ttl_s=MESSAGE_TTL_S, queue=False, harness=None, environ=None,
|
|
3604
|
+
now=None, proc=Path('/proc'), inbound=None):
|
|
3605
|
+
"""Send `text` from `sender_lane` (a lane of this container: its address is the reply address) to the lane `to`
|
|
3606
|
+
names (resolve_address) -> {id, lane, to, from, delivered_by, expected_within_s, picked_up_by, ttl_s, bytes, at,
|
|
3607
|
+
message, receipt, …what the adapter adds}. The adapters, first that applies, are this section's head comment.
|
|
3608
|
+
`root` is ~/.lz and `home` /home/coder as this process reaches them; `harness` the sender's own (lane-mcp's
|
|
3609
|
+
client), else its lane's observed agent's; `environ` the sender's environment (PATH for codex and `throttle`,
|
|
3610
|
+
LANES_BUS and LANES_THROTTLE_CONTROL_PORT for the bus). Every accepted message writes DM-LANES-MESSAGE (with its
|
|
3611
|
+
text, 0600) and DM-LANES-MESSAGE-RECEIPT in the recipient's inbox, and every outcome one DM-LANES-MESSAGE-LOG line
|
|
3612
|
+
(metadata only). A remote adapter (codex_queue, the bus) is recorded on the record as `attempt` before it is asked
|
|
3613
|
+
and after it answered; one whose answer was lost answers `delivered_by: unknown` with `not_confirmed` and the
|
|
3614
|
+
`attempt` (held: never sent again on its own). `inbound` is lane-peerd's alone (W15 L6): {'name', 'mode',
|
|
3615
|
+
'msg_id'} of a frame a virtual peer's socket took — the record then carries it as `origin` (metadata),
|
|
3616
|
+
`sender_lane` may be `peer:<name>`, no `use_send_message` refusal applies and `queue` is implied.
|
|
3617
|
+
Refusals (LaneError; some carry `extra`): `message_too_long`, `unprintable`, `invalid_arguments`, `not_in_lane`,
|
|
3618
|
+
the address codes, `not_in_container`, `use_coordinator`, `use_send_message`, `handle_ambiguous`,
|
|
3619
|
+
`handle_unavailable`, `peer_pin_failed`, `peer_socket_failed`, `codex_queue_failed`, `bus_unavailable`,
|
|
3620
|
+
`tmux_failed`, `tmux_unanswered`, `recipient_busy`."""
|
|
3621
|
+
import shutil
|
|
3622
|
+
now = time.time() if now is None else now
|
|
3623
|
+
environ = os.environ if environ is None else environ
|
|
3624
|
+
check_message(text)
|
|
3625
|
+
if not isinstance(ttl_s, int) or isinstance(ttl_s, bool) or not MESSAGE_TTL_MIN <= ttl_s <= MESSAGE_TTL_MAX:
|
|
3626
|
+
raise LaneError(f'ttl_s is {MESSAGE_TTL_MIN} to {MESSAGE_TTL_MAX} seconds', 'invalid_arguments')
|
|
3627
|
+
peer_sender = bool(inbound) and isinstance(sender_lane, str) and bool(PEER_SENDER.fullmatch(sender_lane))
|
|
3628
|
+
if not peer_sender and (not isinstance(sender_lane, str) or not LANE_RE.fullmatch(sender_lane)):
|
|
3629
|
+
raise LaneError('a message comes from a lane: its address is the reply address', 'not_in_lane')
|
|
3630
|
+
queue = queue or bool(inbound)
|
|
3631
|
+
export, status = registry_export(root), container_status(root, now)
|
|
3632
|
+
lanes = export['lanes']
|
|
3633
|
+
sender_row = {} if peer_sender else status['lanes'].get(sender_lane) or {}
|
|
3634
|
+
sender_ghost = None if peer_sender else next((row for row in status['unregistered'] if row['id'] == sender_lane),
|
|
3635
|
+
None)
|
|
3636
|
+
sender = sender_lane if peer_sender else \
|
|
3637
|
+
address_of(sender_lane, lanes.get(sender_lane), sender_row, sender_ghost) or sender_lane
|
|
3638
|
+
sender_agent = sender_row.get('agent') if isinstance(sender_row.get('agent'), dict) else None
|
|
3639
|
+
sender_handle = 'claude-session' if peer_sender else handle_text(handle(sender_agent), sender_lane)
|
|
3640
|
+
harness = 'claude' if peer_sender else harness or (sender_agent or {}).get('harness')
|
|
3641
|
+
size = len(text.encode('utf-8'))
|
|
3642
|
+
address = '-'
|
|
3643
|
+
|
|
3644
|
+
def refused(error):
|
|
3645
|
+
append_log(root, log_line(now, sender, address, '-', size, 'refused:' + (error.code or 'refused')))
|
|
3646
|
+
raise error
|
|
3647
|
+
|
|
3648
|
+
try:
|
|
3649
|
+
lane, entry = resolve_address(root, to, export, status)
|
|
3650
|
+
except LaneError as error:
|
|
3651
|
+
refused(error)
|
|
3652
|
+
ghost = None if entry else next((row for row in status['unregistered'] if row['id'] == lane), None)
|
|
3653
|
+
observed = status['lanes'].get(lane) or {}
|
|
3654
|
+
address = address_of(lane, entry, observed, ghost) or lane
|
|
3655
|
+
if entry is None and ghost is None:
|
|
3656
|
+
refused(LaneError(f'{to} names {lane}, a lane of another container: out of reach from here',
|
|
3657
|
+
'not_in_container'))
|
|
3658
|
+
if routing_check(None if peer_sender else sender_lane, lane, export):
|
|
3659
|
+
board = (lanes.get(sender_lane) or {}).get('ws') or board_of(sender_lane)
|
|
3660
|
+
coordinator = coordinator_of(export, board)
|
|
3661
|
+
refused(_refusal(f'{lane} is the fleet admin: it takes messages from coordinators, and {sender_lane} is none',
|
|
3662
|
+
'use_coordinator', fleet_admin=fleet_admin_of(export)[0],
|
|
3663
|
+
coordinator=address_of(coordinator, lanes.get(coordinator)) if coordinator else None))
|
|
3664
|
+
agent = observed.get('agent') if isinstance(observed.get('agent'), dict) else None
|
|
3665
|
+
# The recipient's handle with its own context (W15 L3; the review's 5038f1da): a Codex lane without a thread its
|
|
3666
|
+
# hooks recorded is asked of its app-server NOW, as lanes_status shows it — never a thread a cache kept.
|
|
3667
|
+
found = handle(agent, lane, root, home, proc, fresh=True)
|
|
3668
|
+
messaging = (agent or {}).get('messaging') if isinstance((agent or {}).get('messaging'), dict) else {}
|
|
3669
|
+
hook = hook_agent(Path(root) / 'state' / 'hooks', lane, proc)
|
|
3670
|
+
via, extra, skipped = None, {}, None
|
|
3671
|
+
# 1. Claude to a Claude session with a messaging socket: the sender's own SendMessage, never ours.
|
|
3672
|
+
name = messaging_name(observed) if harness == 'claude' and messaging.get('socket_present') is True else None
|
|
3673
|
+
peer = None if inbound or name or harness != 'claude' else virtual_peers(root, now).get(lane)
|
|
3674
|
+
if peer: # W15 L6: a lane lane-peerd serves is a Claude peer too — the sender's SendMessage reaches it natively
|
|
3675
|
+
refused(_refusal(f'{lane} is a Claude peer ({peer["name"]}, served by lane-peerd): send it with your own '
|
|
3676
|
+
'SendMessage', 'use_send_message', to=peer['name'], tool='SendMessage', address=address))
|
|
3677
|
+
if name and not inbound:
|
|
3678
|
+
twins = sorted(other for other, row in status['lanes'].items() if other != lane and messaging_name(row) == name)
|
|
3679
|
+
if not twins:
|
|
3680
|
+
refused(_refusal(f'{lane} is a Claude session ({name}): send it with your own SendMessage, which reaches '
|
|
3681
|
+
'its transcript mid-turn', 'use_send_message', to=name, tool='SendMessage',
|
|
3682
|
+
address=address))
|
|
3683
|
+
if not queue:
|
|
3684
|
+
refused(_refusal(f'{lane}\'s messaging name {name!r} is also the name of {", ".join(twins)}: a SendMessage '
|
|
3685
|
+
'by that name could reach either', 'handle_ambiguous', name=name, lanes=[lane] + twins))
|
|
3686
|
+
via = 'queued' # `queue` given: the inbox is keyed by the lane, never by a name
|
|
3687
|
+
# A Codex lane whose app-server names no single thread for it: several fit, or the daemon could not be asked. No
|
|
3688
|
+
# thread is picked for it and nothing is typed (the review's 5038f1da); with `queue` it waits in its inbox.
|
|
3689
|
+
if via is None and found.get('why') in ('handle_ambiguous',) + CODEX_UNAVAILABLE:
|
|
3690
|
+
ambiguous = found['why'] == 'handle_ambiguous'
|
|
3691
|
+
problem = _refusal(f'{lane} is Codex without a thread its hooks recorded, and its app-server '
|
|
3692
|
+
+ ('names several threads that fit it' if ambiguous else f'could not be asked ({found["why"]})')
|
|
3693
|
+
+ ': no thread is picked and nothing is typed', 'handle_ambiguous' if ambiguous
|
|
3694
|
+
else 'handle_unavailable', lane=lane, address=address, discovery=found['why'])
|
|
3695
|
+
if not queue:
|
|
3696
|
+
refused(problem)
|
|
3697
|
+
via, extra = 'queued', {'not_delivered': f'{problem.code}: {problem}'}
|
|
3698
|
+
directory = inbox_fd(root, lane, create=True)
|
|
3699
|
+
try:
|
|
3700
|
+
message_id = new_message_id(directory, now)
|
|
3701
|
+
record = message_record(message_id, sender, sender_handle, address, now, text, ttl_s)
|
|
3702
|
+
if inbound: # W15 L6: how it came — by SendMessage, from which session name, in which declared mode
|
|
3703
|
+
record['origin'] = peer_origin(inbound)
|
|
3704
|
+
_write_at(directory, message_id + MESSAGE_SUFFIX, record)
|
|
3705
|
+
body, why_not = envelope(sender, sender_handle, text, now), None
|
|
3706
|
+
pid = (agent or {}).get('pid') if isinstance((agent or {}).get('pid'), int) else None
|
|
3707
|
+
recipient = {'lane': lane, 'harness': (agent or {}).get('harness'), 'pid': pid,
|
|
3708
|
+
'start': proc_start(proc, pid) if pid else None}
|
|
3709
|
+
|
|
3710
|
+
def attempt(adapter, outcome, **seen):
|
|
3711
|
+
"""DM-LANES-MESSAGE's additive `attempt`, written onto the record BEFORE a remote adapter is asked
|
|
3712
|
+
(`sending`: a crash leaves it on its way, never `queued`) and again once it answered (`accepted`, `unsent`,
|
|
3713
|
+
`unknown`): the operation, the adapter, who was meant (the lane's agent pid and start; the thread or the
|
|
3714
|
+
bus message once known)."""
|
|
3715
|
+
meant = dict(recipient)
|
|
3716
|
+
meant.update((record.get('attempt') or {}).get('recipient') or {})
|
|
3717
|
+
meant.update(seen)
|
|
3718
|
+
record['attempt'] = {'op': f'{message_id}.1', 'adapter': adapter, 'at': iso(now), 'outcome': outcome,
|
|
3719
|
+
'recipient': meant}
|
|
3720
|
+
_write_at(directory, message_id + MESSAGE_SUFFIX, record)
|
|
3721
|
+
try:
|
|
3722
|
+
# 1b. (W15 L6) a Claude session with a messaging socket, a sender that is not Claude: one protocol-1 line
|
|
3723
|
+
# on the session's own socket, its `from` the sender's virtual peer socket (a reply comes back there).
|
|
3724
|
+
if via is None and harness != 'claude' and (agent or {}).get('harness') == 'claude' \
|
|
3725
|
+
and messaging.get('socket_present') is True:
|
|
3726
|
+
document = claude_session(home, agent, messaging_name(observed), proc)
|
|
3727
|
+
if document is not None:
|
|
3728
|
+
try:
|
|
3729
|
+
via = 'peer_socket'
|
|
3730
|
+
extra = peer_send(document, peer_socket_path(sender_lane, home), sender,
|
|
3731
|
+
sender_mode(harness, (sender_agent or {}).get('pid'), proc), body,
|
|
3732
|
+
home=home)
|
|
3733
|
+
except PeerPinFailed as error:
|
|
3734
|
+
via, extra, skipped = None, {}, error
|
|
3735
|
+
# 2. a Codex thread — its hooks recorded it, or its app-server named it just now — `codex` on PATH.
|
|
3736
|
+
if via is None and found['kind'] == 'codex-thread' \
|
|
3737
|
+
and shutil.which('codex', path=({**os.environ, **environ}).get('PATH')):
|
|
3738
|
+
via, extra = 'codex_queue', {'thread': found['name']}
|
|
3739
|
+
attempt('codex_queue', 'sending', thread=found['name'])
|
|
3740
|
+
codex_queue(found['name'], body, home, environ)
|
|
3741
|
+
attempt('codex_queue', 'accepted')
|
|
3742
|
+
# 3. the Throttle bus, switched on, for a lane whose agent calls a model.
|
|
3743
|
+
if via is None and bus_configured(environ) and found['transport'] != 'typed' and not peer_sender:
|
|
3744
|
+
via = 'throttle_turn'
|
|
3745
|
+
ws = (entry or {}).get('ws') or (ghost or {}).get('workspace') or board_of(lane)
|
|
3746
|
+
sender_ws = (lanes.get(sender_lane) or {}).get('ws') or (sender_ghost or {}).get('workspace') \
|
|
3747
|
+
or board_of(sender_lane)
|
|
3748
|
+
attempt('throttle_turn', 'sending', trace=lane_trace(lane, ws))
|
|
3749
|
+
extra = {'bus': bus_post(environ, home, harness, lane_trace(sender_lane, sender_ws) or '',
|
|
3750
|
+
lane_trace(lane, ws) or '', body, ttl_s)}
|
|
3751
|
+
attempt('throttle_turn', 'accepted', bus_id=extra['bus']['id'])
|
|
3752
|
+
# 4. typed into an idle lane whose handle is `lane`: an agent at its prompt, or a shell at its prompt.
|
|
3753
|
+
if via is None and found['kind'] == 'lane':
|
|
3754
|
+
tmux = (ghost or {}).get('tmux') if isinstance((ghost or {}).get('tmux'), dict) else {}
|
|
3755
|
+
pair = tmux_target(entry) if entry else ((tmux['socket'], tmux['session'])
|
|
3756
|
+
if tmux.get('socket') and tmux.get('session') else None)
|
|
3757
|
+
idle, why_not = recipient_idle(found, observed, hook, status['fresh'])
|
|
3758
|
+
if idle and not pair:
|
|
3759
|
+
idle, why_not = False, 'it has no tmux session to type into'
|
|
3760
|
+
if idle:
|
|
3761
|
+
with dispatch_lock(root, lane):
|
|
3762
|
+
# The final recheck, under the recipient's dispatch lock (the review's 8d91d073): observed
|
|
3763
|
+
# now, the same agent as when it was addressed, still idle, no older message waiting.
|
|
3764
|
+
now_status = container_status(root)
|
|
3765
|
+
now_observed = now_status['lanes'].get(lane) or {}
|
|
3766
|
+
idle, why_not = recipient_idle(found, now_observed,
|
|
3767
|
+
hook_agent(Path(root) / 'state' / 'hooks', lane, proc),
|
|
3768
|
+
now_status['fresh'])
|
|
3769
|
+
if idle and generation(now_observed) != generation(observed):
|
|
3770
|
+
idle, why_not = False, 'its agent changed since it was addressed (replaced)'
|
|
3771
|
+
older = [other for other in inbox_entries(root, lane, history=0)
|
|
3772
|
+
if other['id'] != message_id and pending(other, now)] if idle else []
|
|
3773
|
+
if older:
|
|
3774
|
+
idle, why_not = False, (f'{len(older)} older message' + (
|
|
3775
|
+
's wait in its inbox: they are' if len(older) > 1 else ' waits in its inbox: it is')
|
|
3776
|
+
+ ' typed first')
|
|
3777
|
+
typed = body
|
|
3778
|
+
if idle and found['transport'] == 'typed':
|
|
3779
|
+
command = pane_command(*pair)
|
|
3780
|
+
idle = command in TYPED_SHELLS
|
|
3781
|
+
why_not = f'its pane runs {command or "what tmux did not name"}, not a shell at its prompt'
|
|
3782
|
+
typed = SHELL_COMMENT + body
|
|
3783
|
+
if idle:
|
|
3784
|
+
via, extra = 'typed', {'typed': len(typed)}
|
|
3785
|
+
results = send_keys(pair[0], pair[1], typed)
|
|
3786
|
+
if results[-1].returncode:
|
|
3787
|
+
said = (results[-1].stderr or '').strip().splitlines()
|
|
3788
|
+
said = said[0] if said else f'tmux exit {results[-1].returncode}'
|
|
3789
|
+
code = 'tmux_unanswered' if results[-1].returncode in (124, 127) else 'tmux_failed'
|
|
3790
|
+
if len(results) == 2:
|
|
3791
|
+
raise _refusal(f'{lane}: {said} — the message was typed, its Enter was not', code,
|
|
3792
|
+
changed=f'typed the message into {lane}, without Enter')
|
|
3793
|
+
raise LaneError(f'{lane}: {said} — nothing was typed', code)
|
|
3794
|
+
except LaneError as error:
|
|
3795
|
+
if isinstance(error, Unconfirmed): # it may have arrived: held, never handed to another adapter
|
|
3796
|
+
attempt(record['attempt']['adapter'], 'unknown')
|
|
3797
|
+
via, extra = 'unknown', {'not_confirmed': f'{error.code}: {error}', 'attempt': record['attempt']}
|
|
3798
|
+
elif not queue or getattr(error, 'extra', {}).get('changed'):
|
|
3799
|
+
_unlink_at(directory, message_id + MESSAGE_SUFFIX)
|
|
3800
|
+
refused(error)
|
|
3801
|
+
else:
|
|
3802
|
+
if record.get('attempt'): # the remote adapter provably took nothing: the inbox may type it later
|
|
3803
|
+
attempt(record['attempt']['adapter'], 'unsent')
|
|
3804
|
+
via, extra = 'queued', {'not_delivered': f'{error.code}: {error}'}
|
|
3805
|
+
if via is None:
|
|
3806
|
+
if not queue:
|
|
3807
|
+
_unlink_at(directory, message_id + MESSAGE_SUFFIX)
|
|
3808
|
+
if skipped is not None: # W15 L6: the pin failed and nothing after it applied — say the pin
|
|
3809
|
+
refused(_refusal(f'{lane}: {skipped}', skipped.code, lane=lane, address=address))
|
|
3810
|
+
refused(_refusal(f'{lane} cannot take a message now: '
|
|
3811
|
+
+ (why_not or f'no adapter reaches its {found["kind"]} handle from here'),
|
|
3812
|
+
'recipient_busy', lane=lane, address=address))
|
|
3813
|
+
via = 'queued'
|
|
3814
|
+
if skipped is not None:
|
|
3815
|
+
extra = {'not_delivered': f'{skipped.code}: {skipped}'}
|
|
3816
|
+
_write_at(directory, message_id + RECEIPT_SUFFIX, receipt_record(message_id, address, via, now))
|
|
3817
|
+
finally:
|
|
3818
|
+
os.close(directory)
|
|
3819
|
+
append_log(root, log_line(now, sender, address, message_id, size, via))
|
|
3820
|
+
where = f'{LZ}/{"/".join(INBOX_DIR)}/{lane}/{message_id}'
|
|
3821
|
+
picked_up_by, within = DELIVERY.get(via) or UNCONFIRMED
|
|
3822
|
+
return {'id': message_id, 'lane': lane, 'to': address, 'from': sender, 'delivered_by': via,
|
|
3823
|
+
'expected_within_s': within, 'picked_up_by': picked_up_by, 'ttl_s': ttl_s, 'bytes': size, 'at': iso(now),
|
|
3824
|
+
'message': where + MESSAGE_SUFFIX, 'receipt': where + RECEIPT_SUFFIX, **extra}
|
|
3825
|
+
|
|
3826
|
+
|
|
3827
|
+
def _unlink_at(dir_fd, name):
|
|
3828
|
+
try:
|
|
3829
|
+
os.unlink(name, dir_fd=dir_fd)
|
|
3830
|
+
except OSError:
|
|
3831
|
+
pass
|