replx-agent 2.0.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.
Potentially problematic release.
This version of replx-agent might be problematic. Click here for more details.
- replx_agent/__init__.py +3 -0
- replx_agent/__main__.py +5 -0
- replx_agent/commands.py +131 -0
- replx_agent/helpers/__init__.py +3 -0
- replx_agent/helpers/scanner.py +308 -0
- replx_agent/pkg/__init__.py +11 -0
- replx_agent/pkg/compiler.py +153 -0
- replx_agent/pkg/registry.py +387 -0
- replx_agent/pkg/service.py +690 -0
- replx_agent/pkg/store.py +83 -0
- replx_agent/protocol/__init__.py +11 -0
- replx_agent/protocol/repl.py +1029 -0
- replx_agent/protocol/storage.py +1018 -0
- replx_agent/rpc/__init__.py +3 -0
- replx_agent/rpc/protocol.py +220 -0
- replx_agent/server/__init__.py +3 -0
- replx_agent/server/__main__.py +4 -0
- replx_agent/server/command_dispatcher.py +49 -0
- replx_agent/server/connection_manager.py +654 -0
- replx_agent/server/core.py +1221 -0
- replx_agent/server/handlers/__init__.py +24 -0
- replx_agent/server/handlers/exec.py +553 -0
- replx_agent/server/handlers/filesystem.py +383 -0
- replx_agent/server/handlers/firmware.py +118 -0
- replx_agent/server/handlers/i2c.py +23 -0
- replx_agent/server/handlers/package.py +182 -0
- replx_agent/server/handlers/repl.py +188 -0
- replx_agent/server/handlers/session.py +205 -0
- replx_agent/server/handlers/spi.py +23 -0
- replx_agent/server/handlers/transfer.py +600 -0
- replx_agent/server/handlers/uart.py +32 -0
- replx_agent/server/session_manager.py +391 -0
- replx_agent/server/tcp.py +207 -0
- replx_agent/terminal.py +566 -0
- replx_agent/transport/__init__.py +32 -0
- replx_agent/transport/serial.py +220 -0
- replx_agent/utils/__init__.py +95 -0
- replx_agent/utils/constants.py +78 -0
- replx_agent/utils/device_info.py +183 -0
- replx_agent/utils/exceptions.py +31 -0
- replx_agent-2.0.0.dist-info/METADATA +74 -0
- replx_agent-2.0.0.dist-info/RECORD +46 -0
- replx_agent-2.0.0.dist-info/WHEEL +5 -0
- replx_agent-2.0.0.dist-info/entry_points.txt +2 -0
- replx_agent-2.0.0.dist-info/licenses/LICENSE +21 -0
- replx_agent-2.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from .session import SessionCommandsMixin
|
|
2
|
+
from .exec import ExecCommandsMixin
|
|
3
|
+
from .filesystem import FilesystemCommandsMixin, DisconnectedError
|
|
4
|
+
from .transfer import TransferCommandsMixin
|
|
5
|
+
from .firmware import FirmwareCommandsMixin
|
|
6
|
+
from .package import PackageCommandsMixin
|
|
7
|
+
from .repl import ReplCommandsMixin
|
|
8
|
+
from .i2c import I2cCommandsMixin
|
|
9
|
+
from .uart import UartCommandsMixin
|
|
10
|
+
from .spi import SpiCommandsMixin
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
'SessionCommandsMixin',
|
|
14
|
+
'ExecCommandsMixin',
|
|
15
|
+
'FilesystemCommandsMixin',
|
|
16
|
+
'TransferCommandsMixin',
|
|
17
|
+
'FirmwareCommandsMixin',
|
|
18
|
+
'PackageCommandsMixin',
|
|
19
|
+
'ReplCommandsMixin',
|
|
20
|
+
'I2cCommandsMixin',
|
|
21
|
+
'UartCommandsMixin',
|
|
22
|
+
'SpiCommandsMixin',
|
|
23
|
+
'DisconnectedError',
|
|
24
|
+
]
|
|
@@ -0,0 +1,553 @@
|
|
|
1
|
+
import codecs
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
import time
|
|
5
|
+
import threading
|
|
6
|
+
import sys
|
|
7
|
+
from typing import NoReturn, Optional
|
|
8
|
+
|
|
9
|
+
from replx_agent.utils import canon_port
|
|
10
|
+
from replx_agent.utils.constants import CTRL_C, CTRL_D, EOF_MARKER, MAX_PAYLOAD_SIZE
|
|
11
|
+
from replx_agent.utils.exceptions import ProtocolError, TransportError
|
|
12
|
+
from replx_agent.rpc.protocol import AgentProtocol
|
|
13
|
+
from ..command_dispatcher import CommandContext
|
|
14
|
+
from ..connection_manager import BoardConnection
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _find_connection_by_port(connection_manager, port: str) -> Optional[BoardConnection]:
|
|
20
|
+
if not port:
|
|
21
|
+
return None
|
|
22
|
+
|
|
23
|
+
conn = connection_manager.get_connection(port)
|
|
24
|
+
if conn:
|
|
25
|
+
return conn
|
|
26
|
+
|
|
27
|
+
if sys.platform.startswith("win"):
|
|
28
|
+
normalized = canon_port(port)
|
|
29
|
+
conn = connection_manager.get_connection(normalized)
|
|
30
|
+
if conn:
|
|
31
|
+
return conn
|
|
32
|
+
|
|
33
|
+
port_lower = port.lower()
|
|
34
|
+
for key, candidate in connection_manager.get_all_connections().items():
|
|
35
|
+
if isinstance(key, str) and key.lower() == port_lower:
|
|
36
|
+
return candidate
|
|
37
|
+
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ExecCommandsMixin:
|
|
42
|
+
def _cmd_exec(self, ctx: CommandContext, code: str, interactive: bool = False) -> dict:
|
|
43
|
+
conn = ctx.connection
|
|
44
|
+
if not conn or not conn.repl_protocol:
|
|
45
|
+
raise RuntimeError("Not connected")
|
|
46
|
+
|
|
47
|
+
result = conn.repl_protocol.exec(code)
|
|
48
|
+
result_str = result.decode('utf-8', errors='replace') if isinstance(result, bytes) else result
|
|
49
|
+
|
|
50
|
+
if len(result_str) > MAX_PAYLOAD_SIZE - 1000:
|
|
51
|
+
result_str = result_str[:MAX_PAYLOAD_SIZE - 1100] + "\n... [output truncated]"
|
|
52
|
+
|
|
53
|
+
return {"output": result_str}
|
|
54
|
+
|
|
55
|
+
def _cmd_status(self, ctx: CommandContext) -> dict:
|
|
56
|
+
conn = None
|
|
57
|
+
if ctx.explicit_port:
|
|
58
|
+
conn = _find_connection_by_port(self.connection_manager, ctx.explicit_port)
|
|
59
|
+
elif ctx.ppid:
|
|
60
|
+
conn = self._get_active_connection(ctx.ppid)
|
|
61
|
+
|
|
62
|
+
all_connections = self.connection_manager.get_all_connections()
|
|
63
|
+
any_detached = any(c.is_detached() for c in all_connections.values())
|
|
64
|
+
|
|
65
|
+
if conn and conn.repl_protocol:
|
|
66
|
+
busy, busy_command, _busy_session, _busy_client, is_this_detached = conn.busy_snapshot()
|
|
67
|
+
return {
|
|
68
|
+
"running": True,
|
|
69
|
+
"connected": True,
|
|
70
|
+
"port": conn.port,
|
|
71
|
+
"device": conn.device,
|
|
72
|
+
"core": conn.core,
|
|
73
|
+
"manufacturer": conn.manufacturer,
|
|
74
|
+
"version": conn.version,
|
|
75
|
+
"device_root_fs": conn.device_root_fs,
|
|
76
|
+
"in_raw_repl": conn.repl_protocol._in_raw_repl if conn.repl_protocol else False,
|
|
77
|
+
"pid": os.getpid(),
|
|
78
|
+
"busy": busy or is_this_detached,
|
|
79
|
+
"busy_command": busy_command or ("detached_script" if is_this_detached else None),
|
|
80
|
+
"detached_running": any_detached,
|
|
81
|
+
"board_id": conn.board_id
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if ctx.explicit_port:
|
|
85
|
+
return {
|
|
86
|
+
"running": True,
|
|
87
|
+
"connected": False,
|
|
88
|
+
"port": ctx.explicit_port,
|
|
89
|
+
"device": "",
|
|
90
|
+
"core": "",
|
|
91
|
+
"manufacturer": "",
|
|
92
|
+
"version": "",
|
|
93
|
+
"in_raw_repl": False,
|
|
94
|
+
"pid": os.getpid(),
|
|
95
|
+
"busy": False,
|
|
96
|
+
"busy_command": None,
|
|
97
|
+
"detached_running": any_detached
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if all_connections:
|
|
101
|
+
default_port = getattr(self, '_default_port', None)
|
|
102
|
+
if default_port and default_port in all_connections:
|
|
103
|
+
first_port, first_conn = default_port, all_connections[default_port]
|
|
104
|
+
else:
|
|
105
|
+
first_port, first_conn = next(iter(all_connections.items()))
|
|
106
|
+
busy, busy_command, _busy_session, _busy_client, is_this_detached = first_conn.busy_snapshot()
|
|
107
|
+
return {
|
|
108
|
+
"running": True,
|
|
109
|
+
"connected": True,
|
|
110
|
+
"port": first_conn.port,
|
|
111
|
+
"device": first_conn.device,
|
|
112
|
+
"core": first_conn.core,
|
|
113
|
+
"manufacturer": first_conn.manufacturer,
|
|
114
|
+
"version": first_conn.version,
|
|
115
|
+
"device_root_fs": first_conn.device_root_fs,
|
|
116
|
+
"in_raw_repl": first_conn.repl_protocol._in_raw_repl if first_conn.repl_protocol else False,
|
|
117
|
+
"pid": os.getpid(),
|
|
118
|
+
"busy": busy or is_this_detached,
|
|
119
|
+
"busy_command": busy_command or ("detached_script" if is_this_detached else None),
|
|
120
|
+
"detached_running": any_detached,
|
|
121
|
+
"board_id": first_conn.board_id
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
"running": True,
|
|
126
|
+
"connected": False,
|
|
127
|
+
"port": "",
|
|
128
|
+
"device": "",
|
|
129
|
+
"core": "",
|
|
130
|
+
"manufacturer": "",
|
|
131
|
+
"version": "",
|
|
132
|
+
"in_raw_repl": False,
|
|
133
|
+
"pid": os.getpid(),
|
|
134
|
+
"busy": False,
|
|
135
|
+
"busy_command": None,
|
|
136
|
+
"detached_running": False
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
def _cmd_shutdown(self, ctx: CommandContext = None) -> dict:
|
|
140
|
+
self.running = False
|
|
141
|
+
self.connection_manager.disconnect_all()
|
|
142
|
+
self.session_manager.clear_all_sessions()
|
|
143
|
+
|
|
144
|
+
# Defer cleanup so the shutdown response is sent before the TCP listener closes.
|
|
145
|
+
def _deferred_cleanup():
|
|
146
|
+
time.sleep(0.2)
|
|
147
|
+
self.cleanup()
|
|
148
|
+
|
|
149
|
+
threading.Thread(target=_deferred_cleanup, daemon=True).start()
|
|
150
|
+
|
|
151
|
+
return {"shutdown": True}
|
|
152
|
+
|
|
153
|
+
def _cmd_reset(self, ctx: CommandContext) -> dict:
|
|
154
|
+
conn = ctx.connection
|
|
155
|
+
if not conn or not conn.repl_protocol:
|
|
156
|
+
raise RuntimeError("Not connected")
|
|
157
|
+
|
|
158
|
+
if conn.is_detached():
|
|
159
|
+
self._stop_detached_script(conn)
|
|
160
|
+
|
|
161
|
+
conn.repl_protocol.reset()
|
|
162
|
+
return {"reset": True}
|
|
163
|
+
|
|
164
|
+
def _handle_input(self, msg: dict, client_addr: tuple, ppid: int = None, port: str = None):
|
|
165
|
+
conn = None
|
|
166
|
+
if port:
|
|
167
|
+
conn = self.connection_manager.get_connection(port)
|
|
168
|
+
else:
|
|
169
|
+
for c in self.connection_manager.get_all_connections().values():
|
|
170
|
+
if c.interactive.active and c.interactive.client_addr == client_addr:
|
|
171
|
+
conn = c
|
|
172
|
+
break
|
|
173
|
+
if not conn and self._default_port:
|
|
174
|
+
conn = self.connection_manager.get_connection(self._default_port)
|
|
175
|
+
|
|
176
|
+
if not conn:
|
|
177
|
+
return
|
|
178
|
+
|
|
179
|
+
with conn.interactive.lock:
|
|
180
|
+
if not conn.interactive.active:
|
|
181
|
+
return
|
|
182
|
+
|
|
183
|
+
if conn.interactive.client_addr != client_addr:
|
|
184
|
+
return
|
|
185
|
+
|
|
186
|
+
input_data = AgentProtocol.decode_stream_data(msg)
|
|
187
|
+
if input_data:
|
|
188
|
+
conn.interactive.input_queue.append(input_data)
|
|
189
|
+
|
|
190
|
+
def _cmd_run_interactive(self, ctx: CommandContext, script_path: str = None,
|
|
191
|
+
script_content: str = None, echo: bool = False,
|
|
192
|
+
reset: bool = True):
|
|
193
|
+
conn = ctx.connection
|
|
194
|
+
seq = ctx.seq
|
|
195
|
+
client_addr = ctx.client_addr
|
|
196
|
+
|
|
197
|
+
def send_error(msg: str) -> NoReturn:
|
|
198
|
+
if conn:
|
|
199
|
+
conn.release()
|
|
200
|
+
raise RuntimeError(msg)
|
|
201
|
+
|
|
202
|
+
if not conn or not conn.repl_protocol:
|
|
203
|
+
send_error("Not connected")
|
|
204
|
+
|
|
205
|
+
with conn.interactive.lock:
|
|
206
|
+
if conn.interactive.active:
|
|
207
|
+
thread = conn.interactive.thread
|
|
208
|
+
if thread is not None and thread.is_alive():
|
|
209
|
+
conn.interactive.stop_requested = True
|
|
210
|
+
try:
|
|
211
|
+
conn.repl_protocol.interrupt()
|
|
212
|
+
except Exception:
|
|
213
|
+
pass
|
|
214
|
+
else:
|
|
215
|
+
conn.interactive.active = False
|
|
216
|
+
conn.interactive.thread = None
|
|
217
|
+
|
|
218
|
+
for _ in range(20):
|
|
219
|
+
with conn.interactive.lock:
|
|
220
|
+
if not conn.interactive.active:
|
|
221
|
+
break
|
|
222
|
+
time.sleep(0.05)
|
|
223
|
+
|
|
224
|
+
with conn.interactive.lock:
|
|
225
|
+
if conn.interactive.active:
|
|
226
|
+
thread = conn.interactive.thread
|
|
227
|
+
if thread is None or not thread.is_alive():
|
|
228
|
+
conn.interactive.active = False
|
|
229
|
+
conn.interactive.thread = None
|
|
230
|
+
else:
|
|
231
|
+
send_error("Interactive session already active on this connection")
|
|
232
|
+
|
|
233
|
+
repl = conn.repl_protocol
|
|
234
|
+
if conn.is_detached():
|
|
235
|
+
self._stop_detached_script(conn)
|
|
236
|
+
|
|
237
|
+
if script_path:
|
|
238
|
+
if not os.path.exists(script_path):
|
|
239
|
+
send_error(f"Script not found: {script_path}")
|
|
240
|
+
with open(script_path, 'rb') as f:
|
|
241
|
+
script_data = f.read()
|
|
242
|
+
elif script_content is not None:
|
|
243
|
+
script_data = script_content.encode('utf-8') if isinstance(script_content, str) else script_content
|
|
244
|
+
else:
|
|
245
|
+
send_error("Either script_path or script_content required")
|
|
246
|
+
|
|
247
|
+
conn.interactive.start(ctx.ppid, seq, client_addr, echo)
|
|
248
|
+
|
|
249
|
+
thread = threading.Thread(
|
|
250
|
+
target=self._run_interactive_thread,
|
|
251
|
+
args=(conn, script_data, reset),
|
|
252
|
+
daemon=True,
|
|
253
|
+
name=f'Interactive-{conn.port}'
|
|
254
|
+
)
|
|
255
|
+
conn.interactive.thread = thread
|
|
256
|
+
thread.start()
|
|
257
|
+
|
|
258
|
+
def _safe_reset_repl(self, repl):
|
|
259
|
+
repl._in_raw_repl = False
|
|
260
|
+
repl.interrupt()
|
|
261
|
+
time.sleep(0.05)
|
|
262
|
+
repl.interrupt()
|
|
263
|
+
repl._rx_pushback.clear()
|
|
264
|
+
if not repl._resync_repl():
|
|
265
|
+
raise ProtocolError("REPL recovery failed")
|
|
266
|
+
repl._interrupt_requested = False
|
|
267
|
+
repl._in_raw_repl = True
|
|
268
|
+
|
|
269
|
+
def _run_interactive_thread(self, conn: BoardConnection, script_data: bytes,
|
|
270
|
+
reset: bool = True):
|
|
271
|
+
client_addr = conn.interactive.client_addr
|
|
272
|
+
seq = conn.interactive.seq
|
|
273
|
+
|
|
274
|
+
if client_addr is None:
|
|
275
|
+
return
|
|
276
|
+
|
|
277
|
+
output_buffer = bytearray()
|
|
278
|
+
output_decoder = codecs.getincrementaldecoder('utf-8')(errors='replace')
|
|
279
|
+
output_finalized = False
|
|
280
|
+
buffer_lock = threading.Lock()
|
|
281
|
+
last_flush_time = [time.time()]
|
|
282
|
+
last_stream_send_time = [time.time()]
|
|
283
|
+
flush_timer_running = [True]
|
|
284
|
+
BUFFER_FLUSH_SIZE = 4096
|
|
285
|
+
FLUSH_INTERVAL = 0.05
|
|
286
|
+
KEEPALIVE_INTERVAL = 1.0
|
|
287
|
+
|
|
288
|
+
def send_stream(output: str = '', completed: bool = False, error: str = None):
|
|
289
|
+
try:
|
|
290
|
+
msg = {'type': 'stream', 'seq': seq, 'output': output}
|
|
291
|
+
if completed:
|
|
292
|
+
msg['completed'] = True
|
|
293
|
+
msg['error'] = error
|
|
294
|
+
encoded = AgentProtocol.encode_message(msg)
|
|
295
|
+
self.send_completion(encoded, client_addr, seq)
|
|
296
|
+
else:
|
|
297
|
+
self._safe_send(AgentProtocol.encode_message(msg), client_addr)
|
|
298
|
+
last_stream_send_time[0] = time.time()
|
|
299
|
+
except Exception:
|
|
300
|
+
pass
|
|
301
|
+
|
|
302
|
+
def flush_buffer(final: bool = False):
|
|
303
|
+
nonlocal output_finalized
|
|
304
|
+
with buffer_lock:
|
|
305
|
+
if output_finalized or (not output_buffer and not final):
|
|
306
|
+
return
|
|
307
|
+
data_to_send = bytes(output_buffer)
|
|
308
|
+
output_buffer.clear()
|
|
309
|
+
last_flush_time[0] = time.time()
|
|
310
|
+
# Timer and producer flushes must decode and send in byte order.
|
|
311
|
+
output = output_decoder.decode(data_to_send, final=final)
|
|
312
|
+
output_finalized = final
|
|
313
|
+
if output:
|
|
314
|
+
send_stream(output)
|
|
315
|
+
|
|
316
|
+
first_chunk = [True]
|
|
317
|
+
|
|
318
|
+
def data_consumer(chunk: bytes):
|
|
319
|
+
if not chunk:
|
|
320
|
+
return
|
|
321
|
+
filtered = chunk.replace(EOF_MARKER, b'').replace(b'\r', b'')
|
|
322
|
+
if first_chunk[0] and filtered.startswith(b'>'):
|
|
323
|
+
filtered = filtered[1:]
|
|
324
|
+
first_chunk[0] = False
|
|
325
|
+
elif first_chunk[0]:
|
|
326
|
+
first_chunk[0] = False
|
|
327
|
+
|
|
328
|
+
if filtered.endswith(b'>'):
|
|
329
|
+
filtered = filtered[:-1]
|
|
330
|
+
if not filtered:
|
|
331
|
+
return
|
|
332
|
+
with buffer_lock:
|
|
333
|
+
output_buffer.extend(filtered)
|
|
334
|
+
should_flush = len(output_buffer) >= BUFFER_FLUSH_SIZE or \
|
|
335
|
+
time.time() - last_flush_time[0] >= FLUSH_INTERVAL
|
|
336
|
+
if should_flush:
|
|
337
|
+
flush_buffer()
|
|
338
|
+
|
|
339
|
+
def flush_timer():
|
|
340
|
+
while flush_timer_running[0]:
|
|
341
|
+
time.sleep(FLUSH_INTERVAL)
|
|
342
|
+
flush_buffer()
|
|
343
|
+
# Keep interactive session alive for client-side timeout logic,
|
|
344
|
+
# even when the script is running silently with no output.
|
|
345
|
+
if time.time() - last_stream_send_time[0] >= KEEPALIVE_INTERVAL:
|
|
346
|
+
send_stream('')
|
|
347
|
+
|
|
348
|
+
flush_thread = threading.Thread(target=flush_timer, daemon=True)
|
|
349
|
+
flush_thread.start()
|
|
350
|
+
input_thread = None
|
|
351
|
+
input_thread_running = [False]
|
|
352
|
+
needs_recovery = False
|
|
353
|
+
|
|
354
|
+
try:
|
|
355
|
+
if not conn or not conn.repl_protocol:
|
|
356
|
+
raise RuntimeError("Connection lost")
|
|
357
|
+
repl = conn.repl_protocol
|
|
358
|
+
|
|
359
|
+
input_thread_running = [True]
|
|
360
|
+
|
|
361
|
+
def input_handler():
|
|
362
|
+
while input_thread_running[0] and not conn.interactive.stop_requested:
|
|
363
|
+
input_data = None
|
|
364
|
+
with conn.interactive.lock:
|
|
365
|
+
if conn.interactive.input_queue:
|
|
366
|
+
input_data = conn.interactive.input_queue.popleft()
|
|
367
|
+
|
|
368
|
+
if input_data:
|
|
369
|
+
try:
|
|
370
|
+
if input_data == CTRL_C:
|
|
371
|
+
repl.interrupt()
|
|
372
|
+
repl._interrupt_requested = True
|
|
373
|
+
elif input_data == CTRL_D:
|
|
374
|
+
repl.send_eof()
|
|
375
|
+
elif input_data in (b'\n', b'\r'):
|
|
376
|
+
repl.send_raw(b'\r')
|
|
377
|
+
else:
|
|
378
|
+
repl.send_raw(input_data)
|
|
379
|
+
except Exception:
|
|
380
|
+
pass
|
|
381
|
+
time.sleep(0.01)
|
|
382
|
+
|
|
383
|
+
input_thread = threading.Thread(target=input_handler, daemon=True)
|
|
384
|
+
input_thread.start()
|
|
385
|
+
|
|
386
|
+
try:
|
|
387
|
+
if reset:
|
|
388
|
+
repl.reset()
|
|
389
|
+
elif not repl._in_raw_repl:
|
|
390
|
+
repl._enter_repl()
|
|
391
|
+
repl._exec(script_data, interactive=False, echo=False, detach=False,
|
|
392
|
+
data_consumer=data_consumer)
|
|
393
|
+
except ProtocolError as e:
|
|
394
|
+
conn.interactive.error = str(e)
|
|
395
|
+
needs_recovery = True
|
|
396
|
+
finally:
|
|
397
|
+
input_thread_running[0] = False
|
|
398
|
+
flush_timer_running[0] = False
|
|
399
|
+
flush_buffer(final=True)
|
|
400
|
+
|
|
401
|
+
except Exception as e:
|
|
402
|
+
input_thread_running[0] = False
|
|
403
|
+
flush_timer_running[0] = False
|
|
404
|
+
conn.interactive.error = str(e)
|
|
405
|
+
needs_recovery = True
|
|
406
|
+
flush_buffer(final=True)
|
|
407
|
+
finally:
|
|
408
|
+
input_thread_running[0] = False
|
|
409
|
+
flush_timer_running[0] = False
|
|
410
|
+
if input_thread is not None and input_thread.is_alive():
|
|
411
|
+
input_thread.join(timeout=0.5)
|
|
412
|
+
flush_thread.join(timeout=0.5)
|
|
413
|
+
if needs_recovery and conn.repl_protocol and not conn.repl_protocol._stop_event.is_set():
|
|
414
|
+
try:
|
|
415
|
+
self._safe_reset_repl(conn.repl_protocol)
|
|
416
|
+
except (ProtocolError, TransportError, OSError, ConnectionError) as exc:
|
|
417
|
+
if not self.connection_manager.check_health(conn.port):
|
|
418
|
+
conn.interactive.error = f"{conn.interactive.error}; REPL recovery failed: {exc}. Connection removed."
|
|
419
|
+
self._handle_port_disconnect(conn.port, conn)
|
|
420
|
+
error = conn.interactive.error
|
|
421
|
+
conn.interactive.stop()
|
|
422
|
+
conn.release()
|
|
423
|
+
self._last_command_time = time.time()
|
|
424
|
+
send_stream(completed=True, error=error)
|
|
425
|
+
|
|
426
|
+
def _cmd_run_stop(self, ctx: CommandContext) -> dict:
|
|
427
|
+
conn = ctx.connection
|
|
428
|
+
|
|
429
|
+
# RUN_STOP is in NON_REPL_COMMANDS so ctx.connection is always None.
|
|
430
|
+
# Resolve the connection directly via explicit_port or active interactive session.
|
|
431
|
+
if conn is None:
|
|
432
|
+
if ctx.explicit_port:
|
|
433
|
+
conn = _find_connection_by_port(self.connection_manager, ctx.explicit_port)
|
|
434
|
+
if conn is None:
|
|
435
|
+
# Find any connection that has an active interactive session owned by this ppid
|
|
436
|
+
for c in self.connection_manager.get_all_connections().values():
|
|
437
|
+
if c.interactive.active and c.interactive.is_owner(ctx.ppid):
|
|
438
|
+
conn = c
|
|
439
|
+
break
|
|
440
|
+
|
|
441
|
+
if not conn:
|
|
442
|
+
return {"stopped": False, "reason": "Not connected"}
|
|
443
|
+
|
|
444
|
+
with conn.interactive.lock:
|
|
445
|
+
if not conn.interactive.active:
|
|
446
|
+
return {"stopped": False, "reason": "No active session on this connection"}
|
|
447
|
+
|
|
448
|
+
if ctx.ppid is None or (
|
|
449
|
+
conn.interactive.ppid is not None and conn.interactive.ppid != ctx.ppid
|
|
450
|
+
):
|
|
451
|
+
return {"stopped": False, "reason": "Not the session owner"}
|
|
452
|
+
|
|
453
|
+
conn.interactive.stop_requested = True
|
|
454
|
+
|
|
455
|
+
if conn.repl_protocol:
|
|
456
|
+
try:
|
|
457
|
+
conn.repl_protocol._interrupt_requested = True
|
|
458
|
+
conn.repl_protocol._stop_event.set()
|
|
459
|
+
conn.repl_protocol.interrupt()
|
|
460
|
+
time.sleep(0.05)
|
|
461
|
+
except Exception as exc:
|
|
462
|
+
logger.warning("Failed to interrupt interactive session on %s: %s", conn.port, exc)
|
|
463
|
+
try:
|
|
464
|
+
conn.repl_protocol.interrupt()
|
|
465
|
+
except Exception as exc:
|
|
466
|
+
logger.warning("Failed to retry interrupt for interactive session on %s: %s", conn.port, exc)
|
|
467
|
+
|
|
468
|
+
for _ in range(40):
|
|
469
|
+
time.sleep(0.05)
|
|
470
|
+
with conn.interactive.lock:
|
|
471
|
+
if not conn.interactive.active:
|
|
472
|
+
return {"stopped": True}
|
|
473
|
+
|
|
474
|
+
conn.interactive.stop()
|
|
475
|
+
conn.release()
|
|
476
|
+
if not self.connection_manager.check_health(conn.port):
|
|
477
|
+
self._handle_port_disconnect(conn.port, conn)
|
|
478
|
+
return {"stopped": True, "disconnected": True,
|
|
479
|
+
"reason": "Device disconnected during stop"}
|
|
480
|
+
return {"stopped": True}
|
|
481
|
+
|
|
482
|
+
def _cmd_run(self, ctx: CommandContext, script_path: str = None, script_content: str = None, detach: bool = False) -> dict:
|
|
483
|
+
conn = ctx.connection
|
|
484
|
+
if not conn or not conn.repl_protocol:
|
|
485
|
+
raise RuntimeError("Not connected")
|
|
486
|
+
|
|
487
|
+
repl = conn.repl_protocol
|
|
488
|
+
|
|
489
|
+
if conn.is_detached():
|
|
490
|
+
self._stop_detached_script(conn)
|
|
491
|
+
|
|
492
|
+
repl.reset()
|
|
493
|
+
|
|
494
|
+
time.sleep(0.1)
|
|
495
|
+
|
|
496
|
+
if script_path:
|
|
497
|
+
if not os.path.exists(script_path):
|
|
498
|
+
raise RuntimeError(f"Script not found: {script_path}")
|
|
499
|
+
with open(script_path, 'rb') as f:
|
|
500
|
+
script_data = f.read()
|
|
501
|
+
display_name = script_path
|
|
502
|
+
elif script_content is not None:
|
|
503
|
+
script_data = script_content.encode('utf-8') if isinstance(script_content, str) else script_content
|
|
504
|
+
display_name = "<inline>"
|
|
505
|
+
else:
|
|
506
|
+
raise RuntimeError("Either script_path or script_content required")
|
|
507
|
+
|
|
508
|
+
if detach:
|
|
509
|
+
conn.set_busy_state(True, command='detached_script', session=ctx.ppid, client_addr=ctx.client_addr)
|
|
510
|
+
|
|
511
|
+
try:
|
|
512
|
+
try:
|
|
513
|
+
repl._leave_repl()
|
|
514
|
+
except Exception:
|
|
515
|
+
pass
|
|
516
|
+
repl._in_raw_repl = False
|
|
517
|
+
|
|
518
|
+
repl.interrupt()
|
|
519
|
+
time.sleep(0.05)
|
|
520
|
+
repl.interrupt()
|
|
521
|
+
time.sleep(0.05)
|
|
522
|
+
repl.exit_paste_mode()
|
|
523
|
+
time.sleep(0.1)
|
|
524
|
+
repl.drain()
|
|
525
|
+
|
|
526
|
+
repl.enter_paste_mode()
|
|
527
|
+
time.sleep(0.2)
|
|
528
|
+
repl.drain()
|
|
529
|
+
|
|
530
|
+
script_str = script_data.decode('utf-8', errors='replace')
|
|
531
|
+
for line in script_str.split('\n'):
|
|
532
|
+
repl.send_raw(line.encode('utf-8') + b'\r')
|
|
533
|
+
time.sleep(0.01)
|
|
534
|
+
|
|
535
|
+
time.sleep(0.1)
|
|
536
|
+
repl.send_eof()
|
|
537
|
+
|
|
538
|
+
self._start_drain_thread(conn)
|
|
539
|
+
return {"run": True, "script": display_name, "detached": True}
|
|
540
|
+
|
|
541
|
+
except Exception as e:
|
|
542
|
+
conn.set_detached(False)
|
|
543
|
+
conn.release()
|
|
544
|
+
raise RuntimeError(f"Script send failed: {e}")
|
|
545
|
+
else:
|
|
546
|
+
try:
|
|
547
|
+
script_code = script_data.decode('utf-8', errors='replace')
|
|
548
|
+
output = repl.exec(script_code)
|
|
549
|
+
if isinstance(output, bytes):
|
|
550
|
+
output = output.decode('utf-8', errors='replace')
|
|
551
|
+
return {"run": True, "script": display_name, "output": output}
|
|
552
|
+
except Exception as e:
|
|
553
|
+
raise RuntimeError(f"Script execution failed: {e}")
|