@vibelord/lanes 1.7.2 → 1.7.4

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.
Files changed (50) hide show
  1. package/README.md +9 -0
  2. package/package.json +1 -1
  3. package/payload/lanes/VERSION +1 -1
  4. package/payload/lanes/bin/lanes +97 -17
  5. package/payload/lanes/bin/lanes-site-serve +15 -0
  6. package/payload/lanes/bin-rs/BINARIES.json +5 -0
  7. package/payload/lanes/container/lane-mcp +105 -5
  8. package/payload/lanes/container/lane_core.py +110 -0
  9. package/payload/lanes/container/throttle-pulse +159 -14
  10. package/payload/lanes/docs/ARCHITECTURE.md +108 -11
  11. package/payload/lanes/docs/DESIGN.md +10 -8
  12. package/payload/lanes/docs/INSTALL.md +1 -1
  13. package/payload/lanes/docs/RUNBOOK.md +297 -5
  14. package/payload/lanes/docs/USERGUIDE.md +11 -6
  15. package/payload/lanes/install/host-install.sh +14 -3
  16. package/payload/lanes/libexec/adopt.py +325 -0
  17. package/payload/lanes/libexec/cutover.py +656 -0
  18. package/payload/lanes/libexec/docsd.py +12 -8
  19. package/payload/lanes/libexec/doctor_lanes2.py +213 -0
  20. package/payload/lanes/libexec/economy_poll.py +87 -2
  21. package/payload/lanes/libexec/lanes_lib.py +465 -2
  22. package/payload/lanes/libexec/native.sh +38 -0
  23. package/payload/lanes/libexec/native_bin.py +668 -0
  24. package/payload/lanes/libexec/shadow.py +1311 -0
  25. package/payload/lanes/libexec/sidebar.py +269 -28
  26. package/payload/lanes/libexec/sidebar_status.py +373 -25
  27. package/payload/lanes/libexec/statusd.py +67 -3
  28. package/payload/lanes/libexec/tokens.py +99 -131
  29. package/payload/lanes/libexec/tokens.sh +1 -1
  30. package/payload/lanes/libexec/update.py +48 -5
  31. package/payload/lanes/libexec/users.py +282 -0
  32. package/payload/lanes/site/README.md +9 -0
  33. package/payload/lanes/site/conformance.py +280 -0
  34. package/payload/lanes/site/protocol.py +368 -0
  35. package/payload/lanes/site/server.py +314 -0
  36. package/payload/lanes/tokens/README.md +156 -0
  37. package/payload/lanes/tokens/generate.py +930 -0
  38. package/payload/lanes/tokens/generated/parity.v1.tsv +489 -0
  39. package/payload/lanes/tokens/generated/tokens.resolved.json +835 -0
  40. package/payload/lanes/tokens/tokens.v1.json +763 -0
  41. package/payload/lanes/tokens/tokens.v1.schema.json +143 -0
  42. package/payload/lanes/web/README.md +132 -4
  43. package/payload/lanes/web/directory.css +95 -0
  44. package/payload/lanes/web/directory.js +951 -0
  45. package/payload/lanes/web/generated/README.md +107 -0
  46. package/payload/lanes/web/generated/lanes2_protocol.d.mts +1162 -0
  47. package/payload/lanes/web/generated/lanes2_protocol.mjs +2333 -0
  48. package/payload/lanes/web/mobile.js +17 -21
  49. package/payload/lanes/web/tokens.css +137 -0
  50. package/payload/manifest.json +7 -4
@@ -0,0 +1,368 @@
1
+ """lanes-site/1 — the federation protocol a guest serves to its aggregator over one ssh stdio channel.
2
+
3
+ Python 3 stdlib only; shared by the reference server (`site/server.py`), the host client (`libexec/lanes_lib.py`,
4
+ transport section) and the conformance kit (`site/conformance.py`). Specification: Lanes2 architecture §3.32 and §7.5
5
+ (docs/superpowers/specs/2026-10-28-lanes2-architecture.md), fan-out plan row H1, DM-LANES-SITE-ADAPTER.
6
+
7
+ Framing: newline-delimited UTF-8 JSON, one object per line, at most FRAME_MAX bytes, separators (',', ':').
8
+ request {"id": N, "op": "<op>", "args": {...}} (hello also carries "lanes_site": 1)
9
+ reply {"id": N, "ok": {...}} | {"id": N, "err": {"code": "<code>", "human": "<text>"}}
10
+ The first request of a connection is `hello`; every other op before it is refused `hello_required`.
11
+
12
+ Ops in v1 (this module is their one definition). They are plan row H1's interim ops (the W16-H seam): transport,
13
+ framing, hello and versioning are AR §3.32's; AR's fs.*, exec.run, msg.deliver/msg.status, holder.* and the streams
14
+ arrive additively with the owner runtime (W17/W20).
15
+ hello{client, proto} -> {lanes_site, proto, guest_id, boot_id, versions, capabilities, ops, epochs}
16
+ (`epochs` {workspace: N} is {} until an owner lanesd fences a workspace)
17
+ boards.list{} -> {boards: [{id, title, container, lanes, stale}]}
18
+ boards.lanes{board} -> {board, lanes: [{id, name, holder, container, address, role, tmux}]}
19
+ tmux_read{container, socket, args} -> {outcome, text, truncated}; args pass `check_tmux_read` (a read-only verb
20
+ allowlist, no format job `#(` nor an E:/T: modifier that expands a value as a
21
+ format again, no `pane_start_command` and no `@` user option inside a format,
22
+ no command separator) and the socket is one a registered lane of that container
23
+ uses; `text` is at most READ_BYTES_MAX bytes once JSON-escaped (`fit_text`:
24
+ capture-pane keeps its newest lines, the other verbs their first)
25
+ tmux_write{lane, text, enter, [intent], [epoch]} -> {lane, typed, enter, [intent]}; the ONE write: send-keys only,
26
+ into the active pane of a lane registered to that guest, `check_text`-bounded,
27
+ under the recipient's dispatch lock ~/.lz/state/dispatch/<lane>.lock
28
+ exec{template, args{container}, [intent], [epoch]} -> {template, container, rc, outcome, out, err, detail,
29
+ [intent]}; by template id only (EXEC_TEMPLATES: the pulse and lane-peerd re-arms),
30
+ never an argv; the guest decides whether it is due (`skipped` with `detail`) and
31
+ refuses `busy` while its own health is critical
32
+ A mutating op (tmux_write, exec) takes an optional `intent` (INTENT: the caller's id of this one attempt, echoed in
33
+ the reply, never reused) and an optional `epoch` (an integer >= 0). v1 enforces neither; the codes an owner fence will
34
+ answer with (RESERVED_ERRORS) are reserved now so that turning the fence on stays additive within v1 (AR §3.32).
35
+
36
+ Check order (normative, every adapter): a request's shape, then its verb allowlist and its text bound, and only then
37
+ the recipient (socket, lane, container) in the guest's registry. A probe aimed at an unregistered target therefore
38
+ still learns whether its verb or text is refused, and a conforming server never looks a recipient up for a request it
39
+ refuses anyway — the conformance kit sends its refused writes to unregistered targets only.
40
+
41
+ No op returns or accepts a secret (`secret_keys` finds a key that looks like one) and no op serves a lane's create
42
+ recipe; tmux_read returns what tmux shows of a registered socket (a pane's screen can hold anything typed into it).
43
+ Errors are typed (ERRORS)."""
44
+ import json
45
+ import os
46
+ import re
47
+ import select
48
+ import time
49
+ import unicodedata
50
+
51
+ PROTO = 1
52
+ FRAME_MAX = 1 << 20 # bytes of one frame, its newline included
53
+ READ_BYTES_MAX = FRAME_MAX - 4096 # bytes of tmux output one tmux_read reply carries, JSON-escaped (`fit_text`)
54
+ TAIL_MAX = 2048 # characters of an exec's stdout/stderr tail in its reply
55
+ TEXT_MAX = 4000 # = lane_core.MESSAGE_MAX: the characters one tmux_write types
56
+ ARGS_MAX = 16 # words of one tmux_read argv
57
+ ARG_MAX = 1024 # characters of one of them
58
+ DEADLINE_S = 5.0 # client-side default per request
59
+ # tmux_write: DISPATCH_WAIT_S 5 + 2 x TMUX_TIMEOUT 5 + ENTER_DELAY 0.5 + a round trip (AR §3.32, msg.deliver's bound)
60
+ WRITE_DEADLINE_S = 16.0
61
+ TMUX_TIMEOUT = 5 # = lane_core.TMUX_TIMEOUT
62
+ ENTER_DELAY = 0.5 # = lane_core.ENTER_DELAY: the Enter is a second client (DEF-1803)
63
+
64
+ OPS = ('hello', 'boards.list', 'boards.lanes', 'tmux_read', 'tmux_write', 'exec')
65
+ CAPABILITIES = ('boards', 'tmux_read', 'tmux_write', 'exec')
66
+ # template id -> the seconds its one bounded spawn may take (= statusd PULSE_REARM_TIMEOUT / PEERD_REARM_TIMEOUT: each
67
+ # is one `docker exec -d`). Plan row H1 bounds exec to these two; a new template is a new op version's business.
68
+ EXEC_TEMPLATES = {'pulse.rearm': 10, 'peerd.rearm': 10}
69
+ EXEC_ARGS = ('container',) # the only key an exec's args may carry
70
+ MUTATING = ('tmux_write', 'exec') # the ops that take `intent` and `epoch`
71
+ INTENT = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_.:-]{0,63}\Z') # a mutating request's own id (the client's uuid4 hex)
72
+ ERRORS = (
73
+ 'hello_required', # an op before hello
74
+ 'version_unsupported', # hello asked for another major
75
+ 'frame_invalid', # not one JSON object on one UTF-8 line
76
+ 'frame_too_large', # a frame over FRAME_MAX (skipped up to its newline)
77
+ 'op_unknown', # not one of OPS
78
+ 'args_invalid', # args missing, of the wrong type, or out of their pattern
79
+ 'registry_unavailable', # the guest has no readable registry.json (or a newer one)
80
+ 'board_unknown', # boards.lanes of a board the registry does not hold
81
+ 'lane_unregistered', # tmux_write to a lane that is not a registered tmux lane of this guest
82
+ 'socket_unregistered', # tmux_read of a (container, socket) no registered lane uses
83
+ 'container_unknown', # exec into a container the registry does not name
84
+ 'container_unavailable', # the container has no local init pid on the guest (not running, or not local)
85
+ 'verb_refused', # tmux_read of a verb or flag outside the read-only allowlist
86
+ 'text_too_long', # tmux_write text over TEXT_MAX
87
+ 'text_unprintable', # tmux_write text empty or holding a control/format/separator character
88
+ 'busy', # another sender held the recipient's dispatch lock past DISPATCH_WAIT_S
89
+ 'tmux_failed', # tmux did not take the keys (outcome in `human`)
90
+ 'template_unknown', # exec of a template id not in EXEC_TEMPLATES
91
+ 'argv_refused', # exec carrying anything but a template id and its container (a free-form argv)
92
+ 'adapter_unavailable', # the forced command cannot start the adapter its flag names (rs-site before lanesd, W20)
93
+ 'internal', # the server failed; `human` says how, never with a secret
94
+ )
95
+ # Reserved in v1, sent by no v1 server: the owner fence of AR §3.32 (W17 on: every mutating op carries the workspace
96
+ # epoch and an intent id) and the relay's refusals. A v1 client treats each as a refusal of that request.
97
+ RESERVED_ERRORS = ('epoch_required', 'intent_required', 'stale_epoch', 'owner_unclaimed', 'owner_unavailable',
98
+ 'store_unavailable')
99
+ IDENT = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_.-]*\Z') # = lanes_lib.IDENT
100
+ TMUX_SESSION = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_. -]*\Z') # = lanes_lib.TMUX_SESSION
101
+ ALIAS = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_.-]{0,62}\Z') # an ssh alias in `guest:<alias>`
102
+ REFUSED_TEXT = frozenset(('Cc', 'Cf', 'Cs', 'Co', 'Cn', 'Zl', 'Zp')) # = lane_core.REFUSED_TEXT
103
+ SECRET_KEY = re.compile(r'token|secret|passw|credential|api.?key|authori[sz]ation|cookie|private', re.I)
104
+ # In a word holding a format (`#{`): tmux's E: and T: modifiers expand a variable's VALUE as a format once more, and a
105
+ # value such as a pane title (any program in the pane sets it, OSC 2) can hold a `#(` job. tmux takes a one-letter
106
+ # modifier wherever a `;` or `:` follows it in a modifier list (after `#{`, `;`, or another modifier's arguments), so
107
+ # any E or T followed by one of them refuses the word: conservative, and no format the host asks holds one.
108
+ FORMAT_REEXPAND = re.compile(r'[ET][;:]')
109
+ # Also refused inside a format: `pane_start_command` (the command line a pane was started with, which can carry an
110
+ # environment such as `env API_TOKEN=... claude`) and any `@` (a user option, set by anyone with the socket). No format
111
+ # the host asks holds either.
112
+ FORMAT_PRIVATE = re.compile(r'pane_start_command|@')
113
+
114
+ # The read-only tmux verbs and their flags: flag -> True when it takes a value. A verb's positional words are counted
115
+ # by READ_POSITIONALS; REQUIRED_FLAGS names a flag without which the verb would write (display-message without -p
116
+ # writes into a client's status line, capture-pane without -p into a paste buffer).
117
+ READ_VERBS = {
118
+ 'list-sessions': {'-F': True, '-f': True},
119
+ 'list-panes': {'-a': False, '-s': False, '-F': True, '-f': True, '-t': True},
120
+ 'list-windows': {'-a': False, '-F': True, '-f': True, '-t': True},
121
+ 'list-clients': {'-F': True, '-t': True},
122
+ 'has-session': {'-t': True},
123
+ 'display-message': {'-p': False, '-t': True, '-F': True},
124
+ 'capture-pane': {'-p': False, '-t': True, '-S': True, '-E': True, '-e': False, '-J': False, '-N': False},
125
+ }
126
+ READ_POSITIONALS = {'display-message': 1}
127
+ REQUIRED_FLAGS = {'display-message': '-p', 'capture-pane': '-p'}
128
+
129
+
130
+ class ProtocolError(Exception):
131
+ """A typed refusal: `code` is one of ERRORS, `human` one line for a person."""
132
+
133
+ def __init__(self, code, human):
134
+ super().__init__(f'{code}: {human}')
135
+ self.code, self.human = code, human
136
+
137
+
138
+ def encode(message):
139
+ """One frame: the object as compact UTF-8 JSON plus a newline. ProtocolError frame_too_large over FRAME_MAX."""
140
+ data = json.dumps(message, separators=(',', ':'), ensure_ascii=False).encode('utf-8') + b'\n'
141
+ if len(data) > FRAME_MAX:
142
+ raise ProtocolError('frame_too_large', f'a frame is at most {FRAME_MAX} bytes ({len(data)})')
143
+ return data
144
+
145
+
146
+ def decode(line):
147
+ """The object of one frame (its newline optional) -> dict, else ProtocolError frame_invalid."""
148
+ try:
149
+ message = json.loads(bytes(line).decode('utf-8'))
150
+ except (UnicodeDecodeError, ValueError):
151
+ raise ProtocolError('frame_invalid', 'a frame is one JSON object on one UTF-8 line') from None
152
+ if not isinstance(message, dict):
153
+ raise ProtocolError('frame_invalid', 'a frame is one JSON object')
154
+ return message
155
+
156
+
157
+ def reply_ok(request_id, result):
158
+ return {'id': request_id, 'ok': result}
159
+
160
+
161
+ def reply_err(request_id, code, human):
162
+ return {'id': request_id, 'err': {'code': code, 'human': str(human)[:400]}}
163
+
164
+
165
+ class FrameReader:
166
+ """Frames from one file descriptor, read with a deadline (select + os.read; never a blocking readline that could
167
+ outlive its caller). `read(timeout)` -> the next frame's dict, None at end of file; TimeoutError when nothing
168
+ complete arrived in `timeout` seconds (None: wait); ProtocolError frame_invalid for a line that is no object, and
169
+ frame_too_large once for a line over FRAME_MAX, whose remainder is then skipped up to its newline."""
170
+
171
+ def __init__(self, fd):
172
+ self.fd, self.buffer, self.skipping, self.eof = fd, bytearray(), False, False
173
+
174
+ def _line(self):
175
+ while True:
176
+ end = self.buffer.find(b'\n')
177
+ if self.skipping:
178
+ if end < 0:
179
+ self.buffer.clear()
180
+ return None
181
+ del self.buffer[:end + 1]
182
+ self.skipping = False
183
+ continue
184
+ if end >= 0:
185
+ line = bytes(self.buffer[:end])
186
+ del self.buffer[:end + 1]
187
+ if len(line) + 1 > FRAME_MAX:
188
+ raise ProtocolError('frame_too_large', f'a frame is at most {FRAME_MAX} bytes')
189
+ return line
190
+ if len(self.buffer) >= FRAME_MAX:
191
+ self.buffer.clear()
192
+ self.skipping = True
193
+ raise ProtocolError('frame_too_large', f'a frame is at most {FRAME_MAX} bytes')
194
+ return None
195
+
196
+ def read(self, timeout=None):
197
+ deadline = None if timeout is None else time.monotonic() + timeout
198
+ while True:
199
+ line = self._line()
200
+ if line is not None:
201
+ if not line.strip():
202
+ continue
203
+ return decode(line)
204
+ if self.eof:
205
+ return None
206
+ remaining = None if deadline is None else max(0.0, deadline - time.monotonic())
207
+ ready, _w, _x = select.select([self.fd], [], [], remaining)
208
+ if not ready:
209
+ raise TimeoutError('no complete frame in time')
210
+ chunk = os.read(self.fd, 65536)
211
+ if not chunk:
212
+ self.eof = True
213
+ if self.buffer and not self.skipping:
214
+ line, self.buffer = bytes(self.buffer), bytearray()
215
+ if len(line) + 1 > FRAME_MAX:
216
+ raise ProtocolError('frame_too_large', f'a frame is at most {FRAME_MAX} bytes')
217
+ return decode(line) if line.strip() else None
218
+ return None
219
+ self.buffer += chunk
220
+
221
+
222
+ def write_frame(fd, message):
223
+ """Write one frame completely (os.write until every byte left)."""
224
+ data = memoryview(encode(message))
225
+ while data:
226
+ written = os.write(fd, data)
227
+ data = data[written:]
228
+
229
+
230
+ def check_tmux_read(args):
231
+ """`args` (a tmux argv after the socket) when it is a read: a list of 1..ARGS_MAX strings of at most ARG_MAX
232
+ characters, none holding a NUL or a line break, none ending in `;` (tmux ends a command there and starts the next
233
+ one), none holding `#(` (a format job runs a shell command), none holding a format (`#{`) with an E: or T:
234
+ modifier (FORMAT_REEXPAND: it expands a value, which a pane may set to a `#(` job, as a format again), none holding
235
+ a format that reads `pane_start_command` or an `@` user option (FORMAT_PRIVATE), its verb one of READ_VERBS with
236
+ only that verb's flags,
237
+ each flag a word of its own, a value flag followed by its value, at most READ_POSITIONALS words that are no flag,
238
+ and the verb's REQUIRED_FLAGS present -> the list. ProtocolError args_invalid / verb_refused otherwise."""
239
+ if not isinstance(args, list) or not 1 <= len(args) <= ARGS_MAX:
240
+ raise ProtocolError('args_invalid', f'args is a list of 1 to {ARGS_MAX} words')
241
+ for word in args:
242
+ if not isinstance(word, str) or len(word) > ARG_MAX or any(c in word for c in '\x00\n\r'):
243
+ raise ProtocolError('args_invalid', f'each word is a string of at most {ARG_MAX} characters on one line')
244
+ if word.endswith(';'):
245
+ raise ProtocolError('verb_refused', "a word ending in ';' starts another tmux command")
246
+ if '#(' in word:
247
+ raise ProtocolError('verb_refused', "a format job '#(' runs a shell command")
248
+ if '#{' in word and FORMAT_REEXPAND.search(word):
249
+ raise ProtocolError('verb_refused', "a format modifier E: or T: expands a value as a format again "
250
+ "(a pane title can hold a '#(' job)")
251
+ if '#{' in word and FORMAT_PRIVATE.search(word):
252
+ raise ProtocolError('verb_refused', "a format reads no pane_start_command (it can carry an environment) "
253
+ "and no '@' user option")
254
+ verb, flags = args[0], READ_VERBS.get(args[0])
255
+ if flags is None:
256
+ raise ProtocolError('verb_refused', f'{verb!r} is not a read-only tmux verb ({", ".join(sorted(READ_VERBS))})')
257
+ seen, positionals, index, literal = set(), 0, 1, False
258
+ while index < len(args):
259
+ word = args[index]
260
+ if not literal and word == '--':
261
+ literal = True
262
+ elif not literal and word.startswith('-') and len(word) > 1:
263
+ if word not in flags:
264
+ raise ProtocolError('verb_refused', f'{verb} takes no {word} here (only {", ".join(sorted(flags))})')
265
+ seen.add(word)
266
+ if flags[word]:
267
+ index += 1
268
+ if index >= len(args):
269
+ raise ProtocolError('args_invalid', f'{word} needs a value')
270
+ else:
271
+ positionals += 1
272
+ index += 1
273
+ if positionals > READ_POSITIONALS.get(verb, 0):
274
+ raise ProtocolError('verb_refused', f'{verb} takes at most {READ_POSITIONALS.get(verb, 0)} words that are no flag')
275
+ required = REQUIRED_FLAGS.get(verb)
276
+ if required and required not in seen:
277
+ raise ProtocolError('verb_refused', f'{verb} is a read only with {required}')
278
+ return list(args)
279
+
280
+
281
+ def check_text(text):
282
+ """`text` when it is 1..TEXT_MAX characters of printable text with something visible in it, on one line (Enter is
283
+ the `enter` flag, never a character) -> text. ProtocolError text_too_long / text_unprintable otherwise."""
284
+ if not isinstance(text, str) or not text.strip():
285
+ raise ProtocolError('text_unprintable', 'the text holds at least one visible character')
286
+ if len(text) > TEXT_MAX:
287
+ raise ProtocolError('text_too_long', f'the text is at most {TEXT_MAX} characters ({len(text)} given)')
288
+ bad = sorted({f'U+{ord(c):04X}' for c in text if unicodedata.category(c) in REFUSED_TEXT})
289
+ if bad:
290
+ raise ProtocolError('text_unprintable', f'the text is one line of printable characters: it holds {", ".join(bad[:8])}')
291
+ return text
292
+
293
+
294
+ def fit_text(text, budget=None, tail=False):
295
+ """(text, truncated): `text` cut to the longest head (or, with `tail`, the longest end) whose JSON-escaped UTF-8
296
+ form is at most `budget` bytes (READ_BYTES_MAX), so a reply holding it always fits one frame — whatever its
297
+ characters (a CJK or escape-heavy screen is several bytes per character once escaped)."""
298
+ budget = READ_BYTES_MAX if budget is None else budget
299
+
300
+ def size(part):
301
+ return len(json.dumps(part, ensure_ascii=False).encode('utf-8'))
302
+
303
+ if size(text) <= budget:
304
+ return text, False
305
+ low, high = 0, len(text) # the longest n whose cut fits: size grows with n
306
+ while low < high:
307
+ middle = (low + high + 1) // 2
308
+ if size(text[-middle:] if tail else text[:middle]) <= budget:
309
+ low = middle
310
+ else:
311
+ high = middle - 1
312
+ return (text[len(text) - low:] if tail else text[:low]), True
313
+
314
+
315
+ def check_intent(args):
316
+ """(intent or None, epoch or None) of a mutating request's optional keys -> ProtocolError args_invalid for an
317
+ intent that is not INTENT or an epoch that is not an integer >= 0. Neither is required in v1 (RESERVED_ERRORS)."""
318
+ intent, epoch = args.get('intent'), args.get('epoch')
319
+ if intent is not None and (not isinstance(intent, str) or not INTENT.match(intent)):
320
+ raise ProtocolError('args_invalid', 'intent is an id of at most 64 letters, digits and . _ : -')
321
+ if epoch is not None and (not isinstance(epoch, int) or isinstance(epoch, bool) or epoch < 0):
322
+ raise ProtocolError('args_invalid', 'epoch is an integer >= 0')
323
+ return intent, epoch
324
+
325
+
326
+ def tmux_literal(text):
327
+ """= lane_core.tmux_text: a trailing `;` written as `\\;` so tmux types it instead of ending the command there."""
328
+ return text[:-1] + '\\;' if text.endswith(';') else text
329
+
330
+
331
+ def check_exec(args):
332
+ """(template, container) of an exec request's args, else ProtocolError: template_unknown for an id not in
333
+ EXEC_TEMPLATES, argv_refused for any key but `template`, `args`, `intent` and `epoch` (check_intent), or args
334
+ holding any key but `container`
335
+ (an `argv`, a `command`, an environment: no free-form spawn reaches a guest), args_invalid for a container that
336
+ is not an identifier."""
337
+ if not isinstance(args, dict):
338
+ raise ProtocolError('args_invalid', 'exec args is an object {template, args}')
339
+ extra = sorted(set(args) - {'template', 'args', 'intent', 'epoch'})
340
+ if extra:
341
+ raise ProtocolError('argv_refused', f'exec runs a template id only; refused key(s) {", ".join(extra)}')
342
+ template, inner = args.get('template'), args.get('args', {})
343
+ if not isinstance(inner, dict):
344
+ raise ProtocolError('argv_refused', 'exec runs a template id only; its args is an object {container}')
345
+ extra = sorted(set(inner) - set(EXEC_ARGS))
346
+ if extra:
347
+ raise ProtocolError('argv_refused', f'exec runs a template id only; refused arg(s) {", ".join(extra)}')
348
+ if not isinstance(template, str) or template not in EXEC_TEMPLATES:
349
+ raise ProtocolError('template_unknown', f'exec templates: {", ".join(sorted(EXEC_TEMPLATES))}')
350
+ container = inner.get('container')
351
+ if not isinstance(container, str) or not IDENT.match(container):
352
+ raise ProtocolError('args_invalid', 'exec args.container is a container name')
353
+ return template, container
354
+
355
+
356
+ def secret_keys(value, path=''):
357
+ """The key paths in a decoded frame whose names look like a secret's (SECRET_KEY): none may cross the wire."""
358
+ found = []
359
+ if isinstance(value, dict):
360
+ for key, inner in value.items():
361
+ here = f'{path}.{key}' if path else str(key)
362
+ if SECRET_KEY.search(str(key)):
363
+ found.append(here)
364
+ found += secret_keys(inner, here)
365
+ elif isinstance(value, list):
366
+ for index, inner in enumerate(value):
367
+ found += secret_keys(inner, f'{path}[{index}]')
368
+ return found