juart-cli 0.1.0__py3-none-any.whl

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.
juart/session.py ADDED
@@ -0,0 +1,822 @@
1
+ """Session/editor state and bounded, serialized byte transport orchestration."""
2
+
3
+ import asyncio
4
+ from collections import deque
5
+ from collections.abc import Callable
6
+ from contextlib import suppress
7
+ from dataclasses import dataclass
8
+ from math import isfinite
9
+
10
+ from .backends.base import Target, Transport, TransportError
11
+ from .commands import (
12
+ MAX_PAYLOAD,
13
+ CommandResult,
14
+ complete_command,
15
+ history_allowed,
16
+ parse_command,
17
+ parse_hex,
18
+ parse_log,
19
+ )
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class _Submission:
24
+ data: bytes
25
+ kind: str
26
+
27
+
28
+ class Session:
29
+ def __init__(
30
+ self,
31
+ transport: Transport,
32
+ target: Target = Target(),
33
+ *,
34
+ logger=None,
35
+ notify: Callable[[str], None] | None = None,
36
+ on_rx: Callable[[bytes], None] | None = None,
37
+ on_change: Callable[[], None] | None = None,
38
+ write_timeout: float = 2.0,
39
+ ):
40
+ if not isfinite(write_timeout) or write_timeout <= 0:
41
+ raise ValueError("write_timeout must be finite and positive")
42
+ self.transport = transport
43
+ self.target = target
44
+ self.logger = logger
45
+ self.notify = notify
46
+ self.on_rx = on_rx
47
+ self.on_change = on_change
48
+ self.write_timeout = write_timeout
49
+ self.state = "DISCONNECTED"
50
+ self.mode = "direct"
51
+ self.context = "TRANSMIT"
52
+ self.buffer = ""
53
+ self.cursor = 0
54
+ self.command = ""
55
+ self.command_cursor = 0
56
+ self.view = "text"
57
+ self.last_error = ""
58
+ self.history: list[str] = []
59
+ self.closed = False
60
+ self.shell: str | None = None
61
+ self.send_requested = 0
62
+ self.send_accepted = 0
63
+ self._lifecycle_lock = asyncio.Lock()
64
+ self._io_lock = asyncio.Lock()
65
+ self._send_task: asyncio.Task | None = None
66
+ self._rx_task: asyncio.Task | None = None
67
+ self._cleanup_task: asyncio.Task | None = None
68
+ self._shutdown_task: asyncio.Task | None = None
69
+ self._queue: deque[_Submission] = deque()
70
+ self._queued_bytes = 0
71
+ self._send_kind: str | None = None
72
+ self._stop_io = False
73
+ self._owns_transport = False
74
+ self._generation = 0
75
+ self._history_position = 0
76
+ self._history_draft = ""
77
+ self._history_draft_cursor = 0
78
+
79
+ @property
80
+ def sending(self) -> bool:
81
+ return self._send_task is not None and not self._send_task.done()
82
+
83
+ def _changed(self) -> None:
84
+ if self.on_change is not None:
85
+ self.on_change()
86
+
87
+ def _notice(self, message: str) -> None:
88
+ if self.notify is not None:
89
+ self.notify(message)
90
+ self._changed()
91
+
92
+ def _error(self, message: str) -> CommandResult:
93
+ self.last_error = message
94
+ self._notice(message)
95
+ return CommandResult(ok=False)
96
+
97
+ def _info(self) -> dict:
98
+ try:
99
+ return self.transport.info()
100
+ except Exception:
101
+ return {}
102
+
103
+ def _log(self, event: str, **fields) -> None:
104
+ if self.logger is None:
105
+ return
106
+ info = self._info()
107
+ self.logger.emit(
108
+ event,
109
+ driver=info.get("driver", "unavailable"),
110
+ target={
111
+ "cable": self.target.cable,
112
+ "device": self.target.device,
113
+ "instance": self.target.instance,
114
+ },
115
+ **fields,
116
+ )
117
+
118
+ def _state(self, state: str, code: str) -> None:
119
+ self.state = state
120
+ self._log("state", state=state, code=code)
121
+ self._changed()
122
+
123
+ async def connect(self) -> None:
124
+ async with self._lifecycle_lock:
125
+ if self.closed:
126
+ self._error("Session is closed.")
127
+ return
128
+ if self.state == "CONNECTED":
129
+ self._notice("Already connected.")
130
+ return
131
+ if self.state != "DISCONNECTED":
132
+ self._error("Release is not confirmed. Use :disconnect before connecting.")
133
+ return
134
+ self._state("CONNECTING", "connect_started")
135
+ self._owns_transport = True
136
+ try:
137
+ async with self._io_lock:
138
+ await asyncio.wait_for(
139
+ self.transport.connect(self.target), max(3.0, self.write_timeout)
140
+ )
141
+ info = self._info()
142
+ selected = info.get("target", info)
143
+ if isinstance(selected, Target):
144
+ self.target = selected
145
+ elif isinstance(selected, dict):
146
+ self.target = Target(
147
+ cable=selected.get("cable", self.target.cable),
148
+ device=selected.get("device", self.target.device),
149
+ instance=selected.get("instance", self.target.instance),
150
+ )
151
+ except asyncio.CancelledError:
152
+ await self._release()
153
+ raise
154
+ except Exception as error:
155
+ self._error(f"Connection failed: {error}")
156
+ code = error.code if isinstance(error, TransportError) else "connect_failed"
157
+ self._state("ERROR", code)
158
+ await self._release()
159
+ return
160
+ self._generation += 1
161
+ self._stop_io = False
162
+ self.last_error = ""
163
+ self._state("CONNECTED", "connected")
164
+ self._rx_task = asyncio.create_task(self._receive(self._generation))
165
+
166
+ async def _release(self) -> bool:
167
+ try:
168
+ async with self._io_lock:
169
+ await asyncio.wait_for(self.transport.close(), max(3.0, self.write_timeout))
170
+ except Exception as error:
171
+ self._owns_transport = True
172
+ self._error(f"Release failed; transport ownership is unconfirmed: {error}")
173
+ self._state("ERROR", "release_failed")
174
+ return False
175
+ self._owns_transport = False
176
+ self._state("DISCONNECTED", "released")
177
+ return True
178
+
179
+ def _cancel_queue(self) -> None:
180
+ direct_discarded = 0
181
+ while self._queue:
182
+ submission = self._queue.popleft()
183
+ if submission.kind == "direct":
184
+ direct_discarded += len(submission.data)
185
+ self._log(
186
+ "send_result", requested=len(submission.data), accepted=0, uncertain=False
187
+ )
188
+ else:
189
+ self._settle(
190
+ submission, 0, False, TransportError("Send cancelled.", code="cancelled")
191
+ )
192
+ self._queued_bytes = 0
193
+ if direct_discarded:
194
+ self._notice(f"Discarded {direct_discarded} queued direct byte(s).")
195
+
196
+ async def _stop_workers(self) -> None:
197
+ self._stop_io = True
198
+ self._cancel_queue()
199
+ if self._rx_task is not None:
200
+ self._rx_task.cancel()
201
+ with suppress(asyncio.CancelledError):
202
+ await self._rx_task
203
+ self._rx_task = None
204
+ if self._send_task is not None:
205
+ # Do not cancel an in-flight write: its bounded result determines delivery.
206
+ with suppress(asyncio.CancelledError):
207
+ await asyncio.shield(self._send_task)
208
+ self._send_task = None
209
+
210
+ async def disconnect(self) -> None:
211
+ operation = asyncio.create_task(self._disconnect())
212
+ try:
213
+ await asyncio.shield(operation)
214
+ except asyncio.CancelledError:
215
+ await asyncio.shield(operation)
216
+ raise
217
+
218
+ async def _disconnect(self) -> None:
219
+ async with self._lifecycle_lock:
220
+ if self.state == "DISCONNECTED" and not self._owns_transport:
221
+ self._notice("Already disconnected.")
222
+ return
223
+ self._state("DISCONNECTING", "disconnect_started")
224
+ await self._stop_workers()
225
+ await self._release()
226
+
227
+ async def shutdown(self) -> None:
228
+ # A cancelled UI handler must not strand a vendor operation or handle.
229
+ if self._shutdown_task is None:
230
+ self._shutdown_task = asyncio.create_task(self._shutdown())
231
+ try:
232
+ await asyncio.shield(self._shutdown_task)
233
+ except asyncio.CancelledError:
234
+ await asyncio.shield(self._shutdown_task)
235
+ raise
236
+
237
+ async def _shutdown(self) -> None:
238
+ self.closed = True
239
+ await self.disconnect()
240
+ discarded = len(self.buffer)
241
+ self.buffer = ""
242
+ self.cursor = 0
243
+ self.command = ""
244
+ self.command_cursor = 0
245
+ self.context = "TRANSMIT"
246
+ self._notice(f"Discarded {discarded} pending byte(s).")
247
+ if self.logger is not None:
248
+ try:
249
+ report = await self.logger.stop()
250
+ if report.get("unwritten") or report.get("error"):
251
+ self._notice(
252
+ f"Log stopped: last sequence {report.get('last_written', 0)}, "
253
+ f"unwritten {report.get('unwritten', 0)}."
254
+ )
255
+ except Exception as error:
256
+ self._error(f"Log shutdown failed: {error}")
257
+ self._changed()
258
+
259
+ def _transport_failure(self, error: Exception, generation: int) -> None:
260
+ if generation != self._generation or self._stop_io:
261
+ return
262
+ self._error(f"Transport failed: {error}")
263
+ code = error.code if isinstance(error, TransportError) else "io_failed"
264
+ self._state("ERROR", code)
265
+ self._stop_io = True
266
+ if self._cleanup_task is None or self._cleanup_task.done():
267
+ self._cleanup_task = asyncio.create_task(self._failed_cleanup(generation))
268
+
269
+ async def _failed_cleanup(self, generation: int) -> None:
270
+ async with self._lifecycle_lock:
271
+ if generation != self._generation or not self._owns_transport:
272
+ return
273
+ await self._stop_workers()
274
+ await self._release()
275
+
276
+ async def _receive(self, generation: int) -> None:
277
+ try:
278
+ while not self._stop_io and generation == self._generation:
279
+ async with self._io_lock:
280
+ if self._stop_io:
281
+ return
282
+ data = await asyncio.wait_for(self.transport.read(4096, 0.5), 0.75)
283
+ if data:
284
+ self._log("rx", data=data.hex())
285
+ if self.on_rx is not None:
286
+ self.on_rx(data)
287
+ self._changed()
288
+ else:
289
+ await asyncio.sleep(0.01)
290
+ except asyncio.CancelledError:
291
+ raise
292
+ except Exception as error:
293
+ self._transport_failure(error, generation)
294
+
295
+ def _submit(self, data: bytes, kind: str) -> CommandResult:
296
+ if self.closed:
297
+ return self._error("Session is closed.")
298
+ if self.state != "CONNECTED" or self._stop_io:
299
+ return self._error("Not connected. Use :connect; input was not transmitted.")
300
+ if self.sending and (kind != "direct" or self._send_kind != "direct"):
301
+ return self._error("Busy sending; payload editing and submissions are locked.")
302
+ if self._queued_bytes + len(data) > MAX_PAYLOAD + 1:
303
+ return self._error("Transmit queue is full; input was not transmitted.")
304
+ if (
305
+ kind == "direct"
306
+ and self._queue
307
+ and self._queue[-1].kind == "direct"
308
+ and len(self._queue[-1].data) + len(data) <= 256
309
+ ):
310
+ previous = self._queue.pop()
311
+ self._queue.append(_Submission(previous.data + data, kind))
312
+ else:
313
+ self._queue.append(_Submission(data, kind))
314
+ self._queued_bytes += len(data)
315
+ if not self.sending:
316
+ self._send_kind = kind
317
+ self.send_requested = len(data)
318
+ self.send_accepted = 0
319
+ self._send_task = asyncio.create_task(self._send())
320
+ self._changed()
321
+ return CommandResult()
322
+
323
+ async def _send(self) -> None:
324
+ generation = self._generation
325
+ try:
326
+ while self._queue and not self._stop_io:
327
+ submission = self._queue.popleft()
328
+ self._queued_bytes -= len(submission.data)
329
+ self._send_kind = submission.kind
330
+ self.send_requested = len(submission.data)
331
+ self.send_accepted = 0
332
+ accepted, uncertain, error = await self._deliver(submission.data)
333
+ self._settle(submission, accepted, uncertain, error)
334
+ if error is not None:
335
+ self._cancel_queue()
336
+ if not self._stop_io:
337
+ self._transport_failure(error, generation)
338
+ break
339
+ finally:
340
+ self._changed()
341
+ # Invalidate after the task becomes done as well, so the busy badge clears.
342
+ asyncio.get_running_loop().call_soon(self._changed)
343
+
344
+ async def _deliver(self, data: bytes) -> tuple[int, bool, Exception | None]:
345
+ accepted = 0
346
+ loop = asyncio.get_running_loop()
347
+ deadline = loop.time() + self.write_timeout
348
+ in_flight = False
349
+ try:
350
+ while accepted < len(data):
351
+ if self._stop_io:
352
+ return accepted, False, TransportError("Send cancelled.", code="cancelled")
353
+ remaining = deadline - loop.time()
354
+ if remaining <= 0:
355
+ return (
356
+ accepted,
357
+ False,
358
+ TransportError("Write made no progress.", code="stalled"),
359
+ )
360
+ chunk = data[accepted : accepted + 256]
361
+ async with self._io_lock:
362
+ if self._stop_io:
363
+ continue
364
+ remaining = deadline - loop.time()
365
+ if remaining <= 0:
366
+ return (
367
+ accepted,
368
+ False,
369
+ TransportError("Write made no progress.", code="stalled"),
370
+ )
371
+ in_flight = True
372
+ count = await asyncio.wait_for(
373
+ self.transport.write(chunk, remaining), remaining
374
+ )
375
+ in_flight = False
376
+ if (
377
+ not isinstance(count, int)
378
+ or isinstance(count, bool)
379
+ or not 0 <= count <= len(chunk)
380
+ ):
381
+ raise TransportError(
382
+ "Driver returned an invalid accepted count.",
383
+ code="invalid_count",
384
+ uncertain=True,
385
+ )
386
+ if count:
387
+ self._log("tx", data=chunk[:count].hex())
388
+ accepted += count
389
+ self.send_accepted = accepted
390
+ deadline = loop.time() + self.write_timeout
391
+ self._changed()
392
+ await asyncio.sleep(0 if count else min(0.01, self.write_timeout))
393
+ return accepted, False, None
394
+ except asyncio.CancelledError:
395
+ return (
396
+ accepted,
397
+ in_flight,
398
+ TransportError("Send cancelled.", code="cancelled", uncertain=in_flight),
399
+ )
400
+ except TimeoutError:
401
+ return (
402
+ accepted,
403
+ True,
404
+ TransportError(
405
+ "Write timed out; delivery is uncertain.", code="write_timeout", uncertain=True
406
+ ),
407
+ )
408
+ except Exception as error:
409
+ uncertain = error.uncertain if isinstance(error, TransportError) else True
410
+ if isinstance(error, TransportError) and in_flight:
411
+ count = error.accepted
412
+ if (
413
+ isinstance(count, int)
414
+ and not isinstance(count, bool)
415
+ and 0 <= count <= len(chunk)
416
+ ):
417
+ if count:
418
+ self._log("tx", data=chunk[:count].hex())
419
+ accepted += count
420
+ self.send_accepted = accepted
421
+ self._changed()
422
+ else:
423
+ error = TransportError(
424
+ "Driver returned an invalid failure accepted count.",
425
+ code="invalid_count",
426
+ uncertain=True,
427
+ )
428
+ uncertain = True
429
+ return accepted, uncertain, error
430
+
431
+ def _settle(
432
+ self, submission: _Submission, accepted: int, uncertain: bool, error: Exception | None
433
+ ) -> None:
434
+ requested = len(submission.data)
435
+ self._log("send_result", requested=requested, accepted=accepted, uncertain=uncertain)
436
+ if submission.kind == "buffer" and (error is None or accepted or uncertain):
437
+ self.buffer = ""
438
+ self.cursor = 0
439
+ if error is None:
440
+ self._changed()
441
+ return
442
+ self.last_error = (
443
+ f"Send stopped: accepted {accepted}/{requested}, uncertain={uncertain}: {error}"
444
+ )
445
+ if accepted or uncertain:
446
+ snapshot = (
447
+ submission.data.hex(" ")
448
+ if submission.kind == "hex"
449
+ else repr(submission.data.decode("ascii"))
450
+ )
451
+ self._notice(
452
+ f"Send stopped: accepted {accepted}/{requested}, uncertain={uncertain}. "
453
+ f"Snapshot: {snapshot}. Re-enter deliberately; no automatic replay."
454
+ )
455
+ elif submission.kind == "hex":
456
+ self._notice(
457
+ f"Send stopped: accepted 0/{requested}, uncertain=False. "
458
+ f"Retry explicitly: :hex {submission.data.hex(' ')}"
459
+ )
460
+ else:
461
+ self._notice(
462
+ f"Send stopped: accepted 0/{requested}, uncertain=False; "
463
+ + (
464
+ "buffer retained for explicit retry."
465
+ if submission.kind == "buffer"
466
+ else "queued direct input discarded."
467
+ )
468
+ )
469
+
470
+ async def wait_idle(self) -> None:
471
+ while True:
472
+ sender = self._send_task
473
+ cleanup = self._cleanup_task
474
+ if sender is not None and not sender.done():
475
+ await asyncio.shield(sender)
476
+ if cleanup is not None and not cleanup.done():
477
+ await asyncio.shield(cleanup)
478
+ if not self.sending and (self._cleanup_task is None or self._cleanup_task.done()):
479
+ return
480
+
481
+ def status(self) -> str:
482
+ logging = "on" if self.logger is not None and self.logger.active else "off"
483
+ progress = f"sending {self.send_accepted}/{self.send_requested}" if self.sending else "idle"
484
+ return (
485
+ f"[{self.state.lower()}] [{self.mode}] [{self.context.lower()}] "
486
+ f"pending={len(self.buffer)}/{MAX_PAYLOAD} [{progress}] "
487
+ f"view={self.view} log={logging} shell={self.shell or 'not selected'} "
488
+ f"last_error={self.last_error or 'none'}"
489
+ )
490
+
491
+ async def execute(self, line: str) -> CommandResult:
492
+ if self.closed:
493
+ return self._error("Session is closed.")
494
+ try:
495
+ parsed = parse_command(line)
496
+ except ValueError as error:
497
+ return self._error(str(error))
498
+ name = parsed.name
499
+ if not name:
500
+ return CommandResult()
501
+ result = CommandResult()
502
+ if name in {"direct", "buffer"}:
503
+ if self.sending:
504
+ return self._error("Busy sending; mode changes are locked.")
505
+ if name == "direct" and self.buffer:
506
+ return self._error("Buffer is not empty. Send with Enter or clear with Esc.")
507
+ self.mode = name
508
+ elif name == "connect":
509
+ await self.connect()
510
+ result = CommandResult(ok=self.state == "CONNECTED")
511
+ elif name == "disconnect":
512
+ await self.disconnect()
513
+ result = CommandResult(ok=self.state == "DISCONNECTED")
514
+ elif name == "reconnect":
515
+ await self.disconnect()
516
+ if self.state == "DISCONNECTED":
517
+ await self.connect()
518
+ result = CommandResult(ok=self.state == "CONNECTED")
519
+ elif name == "quit":
520
+ await self.shutdown()
521
+ result = CommandResult(ok=self.state == "DISCONNECTED", exit_requested=True)
522
+ elif name == "status":
523
+ self._notice(self.status())
524
+ elif name == "info":
525
+ info = self._info()
526
+ metadata = {
527
+ key: value
528
+ for key, value in info.items()
529
+ if key not in {"driver", "target", "cable", "device", "instance"}
530
+ }
531
+ fields = {
532
+ "driver": info.get("driver", "unavailable"),
533
+ "cable": self.target.cable,
534
+ "device": self.target.device,
535
+ "instance": self.target.instance,
536
+ "state": self.state,
537
+ "metadata": metadata or "unavailable",
538
+ }
539
+ self._notice(
540
+ " ".join(
541
+ f"{key}={value if value is not None else 'unavailable'}"
542
+ for key, value in fields.items()
543
+ )
544
+ )
545
+ elif name == "help":
546
+ self._notice(
547
+ "Commands\n"
548
+ " :direct Send each key immediately.\n"
549
+ " :buffer Edit bytes before sending with Enter.\n"
550
+ " :c / :connect Connect to the selected UART.\n"
551
+ " :d / :disconnect Release the UART; keep pending input.\n"
552
+ " :r / :reconnect Disconnect, then connect again.\n"
553
+ " :s / :status Show connection, mode and pending input.\n"
554
+ " :i / :info Show driver and target details.\n"
555
+ " :h / :help Show this help.\n"
556
+ " :q / :quit Release resources and exit.\n"
557
+ " :hex <pairs> Send exact bytes, e.g. :hex 61 62 63.\n"
558
+ " :view text|hex Select receive display format.\n"
559
+ " :log start <path> Create a new JSONL log; quote paths with spaces.\n"
560
+ " :log stop Flush and close the log.\n"
561
+ " :! [shell command] Run a command, or open an interactive shell.\n"
562
+ " :: Send/insert a literal colon.\n"
563
+ "\n"
564
+ "Input and editing\n"
565
+ " : opens command input in either transmission mode.\n"
566
+ " Direct: Enter sends CR (0D); Tab sends 09; Backspace sends 08.\n"
567
+ " Buffer: ASCII/Tab; arrows/Home/End move; Backspace/Delete edit.\n"
568
+ " Buffer Enter sends only edited bytes; empty Enter sends nothing.\n"
569
+ " Buffer Esc clears input. Use :hex 0d for an explicit CR.\n"
570
+ " Command: Enter executes; Tab completes; Up/Down browse history.\n"
571
+ " Command Esc cancels and restores pending transmission input.\n"
572
+ " Ctrl+D sends 04 in direct; ignored in buffer/command.\n"
573
+ " Ctrl+C quits outside the child shell.\n"
574
+ "\n"
575
+ "Status and shell\n"
576
+ " Indicators: connection, mode, pending bytes, sending progress, view/log.\n"
577
+ " Shell requires :d first; return from the shell to resume editing.\n"
578
+ f" Selected shell: {self.shell or 'not selected'}."
579
+ )
580
+ elif name == "!":
581
+ if self.state != "DISCONNECTED" or self._owns_transport:
582
+ return self._error(f"Shell requires DISCONNECTED (now {self.state}); use :d first.")
583
+ result = CommandResult(shell_requested=True, shell_command=parsed.argument or None)
584
+ elif name == "hex":
585
+ try:
586
+ payload = parse_hex(parsed.argument)
587
+ except ValueError as error:
588
+ return self._error(str(error))
589
+ if self.buffer:
590
+ return self._error("HEX requires an empty pending text buffer.")
591
+ result = self._submit(payload, "hex")
592
+ elif name == "view":
593
+ if parsed.argument not in {"text", "hex"}:
594
+ return self._error("Use :view text or :view hex.")
595
+ self.view = parsed.argument
596
+ elif name == "log":
597
+ try:
598
+ action, path = parse_log(parsed.argument)
599
+ if self.logger is None:
600
+ return self._error("Logging is unavailable.")
601
+ if action == "start":
602
+ await self.logger.start(path)
603
+ self._log("state", state=self.state, code="log_started")
604
+ else:
605
+ report = await self.logger.stop()
606
+ self._notice(
607
+ f"Log stopped: last sequence {report.get('last_written', 0)}, "
608
+ f"unwritten {report.get('unwritten', 0)}."
609
+ )
610
+ if report.get("error") or report.get("unwritten"):
611
+ result = CommandResult(ok=False)
612
+ except (OSError, ValueError) as error:
613
+ return self._error(f"Log command failed: {error}")
614
+ if result.ok and history_allowed(parsed):
615
+ self.history.append(line.strip().removeprefix(":").lstrip())
616
+ del self.history[:-100]
617
+ self._changed()
618
+ return result
619
+
620
+ def _open_command(self) -> None:
621
+ self.context = "COMMAND"
622
+ self.command = ""
623
+ self.command_cursor = 0
624
+ self._history_position = len(self.history)
625
+ self._history_draft = ""
626
+ self._history_draft_cursor = 0
627
+ self._changed()
628
+
629
+ def _insert_command(self, text: str) -> CommandResult:
630
+ self.command = (
631
+ self.command[: self.command_cursor] + text + self.command[self.command_cursor :]
632
+ )
633
+ self.command_cursor += len(text)
634
+ self._changed()
635
+ return CommandResult()
636
+
637
+ def _insert_buffer(self, text: str) -> CommandResult:
638
+ if self.sending:
639
+ return self._error("Busy sending; payload editing is locked.")
640
+ if len(self.buffer) + len(text) > MAX_PAYLOAD:
641
+ return self._error("Buffer exceeds 4096 bytes.")
642
+ self.buffer = self.buffer[: self.cursor] + text + self.buffer[self.cursor :]
643
+ self.cursor += len(text)
644
+ self._changed()
645
+ return CommandResult()
646
+
647
+ def _literal(self, text: str) -> CommandResult:
648
+ if self.mode == "buffer":
649
+ return self._insert_buffer(text)
650
+ return self._submit(text.encode("ascii"), "direct")
651
+
652
+ async def key(self, name: str) -> CommandResult:
653
+ if self.closed:
654
+ return self._error("Session is closed.")
655
+ if self.context == "SHELL":
656
+ return CommandResult()
657
+ if name == "ctrl-c":
658
+ await self.shutdown()
659
+ return CommandResult(exit_requested=True, ok=self.state == "DISCONNECTED")
660
+ if self.context == "COMMAND":
661
+ return await self._command_key(name)
662
+ if name == ":":
663
+ self._open_command()
664
+ return CommandResult()
665
+ if self.mode == "direct":
666
+ special = {"enter": "\r", "tab": "\t", "backspace": "\b", "ctrl-d": "\x04"}
667
+ if name in special:
668
+ return self._literal(special[name])
669
+ if len(name) == 1:
670
+ if not " " <= name <= "~":
671
+ return self._error("Only printable ASCII is accepted.")
672
+ return self._literal(name)
673
+ return CommandResult()
674
+ editing = {"enter", "escape", "backspace", "delete", "left", "right", "home", "end", "tab"}
675
+ if self.sending and (name in editing or len(name) == 1):
676
+ return self._error("Busy sending; payload editing is locked.")
677
+ if name == "enter":
678
+ if not self.buffer:
679
+ return CommandResult()
680
+ return self._submit(self.buffer.encode("ascii"), "buffer")
681
+ if name == "escape":
682
+ self.buffer = ""
683
+ self.cursor = 0
684
+ elif name == "backspace" and self.cursor:
685
+ self.buffer = self.buffer[: self.cursor - 1] + self.buffer[self.cursor :]
686
+ self.cursor -= 1
687
+ elif name == "delete":
688
+ self.buffer = self.buffer[: self.cursor] + self.buffer[self.cursor + 1 :]
689
+ elif name == "left":
690
+ self.cursor = max(0, self.cursor - 1)
691
+ elif name == "right":
692
+ self.cursor = min(len(self.buffer), self.cursor + 1)
693
+ elif name == "home":
694
+ self.cursor = 0
695
+ elif name == "end":
696
+ self.cursor = len(self.buffer)
697
+ elif name == "tab":
698
+ return self._insert_buffer("\t")
699
+ elif len(name) == 1:
700
+ if not " " <= name <= "~":
701
+ return self._error("Only printable ASCII and Tab are accepted.")
702
+ return self._insert_buffer(name)
703
+ self._changed()
704
+ return CommandResult()
705
+
706
+ async def _command_key(self, name: str) -> CommandResult:
707
+ if name == "enter":
708
+ line = self.command
709
+ self.context = "TRANSMIT"
710
+ self.command = ""
711
+ self.command_cursor = 0
712
+ result = await self.execute(line)
713
+ self._changed()
714
+ return result
715
+ if name == "escape":
716
+ self.context = "TRANSMIT"
717
+ self.command = ""
718
+ self.command_cursor = 0
719
+ elif name == ":" and not self.command:
720
+ self.context = "TRANSMIT"
721
+ return self._literal(":")
722
+ elif name == "backspace" and self.command_cursor:
723
+ self.command = (
724
+ self.command[: self.command_cursor - 1] + self.command[self.command_cursor :]
725
+ )
726
+ self.command_cursor -= 1
727
+ elif name == "delete":
728
+ self.command = (
729
+ self.command[: self.command_cursor] + self.command[self.command_cursor + 1 :]
730
+ )
731
+ elif name == "left":
732
+ self.command_cursor = max(0, self.command_cursor - 1)
733
+ elif name == "right":
734
+ self.command_cursor = min(len(self.command), self.command_cursor + 1)
735
+ elif name == "home":
736
+ self.command_cursor = 0
737
+ elif name == "end":
738
+ self.command_cursor = len(self.command)
739
+ elif name in {"up", "down"}:
740
+ if self._history_position == len(self.history):
741
+ self._history_draft = self.command
742
+ self._history_draft_cursor = self.command_cursor
743
+ self._history_position = max(
744
+ 0, min(len(self.history), self._history_position + (-1 if name == "up" else 1))
745
+ )
746
+ if self._history_position == len(self.history):
747
+ self.command = self._history_draft
748
+ self.command_cursor = self._history_draft_cursor
749
+ else:
750
+ self.command = self.history[self._history_position]
751
+ self.command_cursor = len(self.command)
752
+ elif name == "tab":
753
+ prefix = self.command[: self.command_cursor]
754
+ completed, candidates = complete_command(prefix)
755
+ if completed != prefix:
756
+ end = self.command_cursor
757
+ while end < len(self.command) and not self.command[end].isspace():
758
+ end += 1
759
+ suffix = self.command[end:]
760
+ cursor = len(completed)
761
+ if completed.endswith(" ") and suffix[:1].isspace():
762
+ completed = completed[:-1]
763
+ self.command = completed + suffix
764
+ self.command_cursor = cursor
765
+ if len(candidates) > 1:
766
+ self._notice("Completions: " + " ".join(candidates))
767
+ elif len(name) == 1:
768
+ if not " " <= name <= "~":
769
+ return self._error("Only printable ASCII is accepted in commands.")
770
+ return self._insert_command(name)
771
+ self._changed()
772
+ return CommandResult()
773
+
774
+ def _validate_paste(self, text: str) -> str | None:
775
+ if any(character != "\t" and not " " <= character <= "~" for character in text):
776
+ return "Paste rejected: use single-line printable ASCII/Tab without CR/LF."
777
+ # Simulate colon transitions before applying any portion of the paste.
778
+ context = self.context
779
+ command_length = len(self.command)
780
+ buffer_length = len(self.buffer)
781
+ direct_bytes = 0
782
+ for character in text:
783
+ if context == "COMMAND":
784
+ if character == ":" and command_length == 0:
785
+ context = "TRANSMIT"
786
+ else:
787
+ command_length += 1
788
+ continue
789
+ elif character == ":":
790
+ context = "COMMAND"
791
+ command_length = 0
792
+ continue
793
+ if self.mode == "buffer":
794
+ if self.sending:
795
+ return "Busy sending; paste was not applied."
796
+ buffer_length += 1
797
+ if buffer_length > MAX_PAYLOAD:
798
+ return "Paste rejected: buffer exceeds 4096 bytes."
799
+ else:
800
+ if self.sending and self._send_kind != "direct":
801
+ return "Busy sending; paste was not applied."
802
+ direct_bytes += 1
803
+ if direct_bytes + self._queued_bytes > MAX_PAYLOAD + 1:
804
+ return "Paste rejected: transmit queue capacity exceeded."
805
+ return None
806
+
807
+ async def paste(self, text: str) -> CommandResult:
808
+ if self.closed:
809
+ return self._error("Session is closed.")
810
+ if self.context == "SHELL":
811
+ return CommandResult()
812
+ error = self._validate_paste(text)
813
+ if error is not None:
814
+ return self._error(error)
815
+ ok = True
816
+ for character in text:
817
+ if character == "\t" and self.context == "COMMAND":
818
+ result = self._insert_command(character)
819
+ else:
820
+ result = await self.key("tab" if character == "\t" else character)
821
+ ok = result.ok and ok
822
+ return CommandResult(ok=ok)