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,600 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import hashlib
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import posixpath
|
|
6
|
+
import sys
|
|
7
|
+
import tempfile
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Any, Optional
|
|
12
|
+
|
|
13
|
+
from replx_agent.rpc.protocol import AgentProtocol
|
|
14
|
+
from replx_agent.utils.constants import MAX_PAYLOAD_SIZE
|
|
15
|
+
from ..command_dispatcher import CommandContext
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
_MAX_TRANSFER_SIZE = 512 * 1024 * 1024
|
|
20
|
+
_TRANSFER_PROGRESS_INTERVAL = 0.1
|
|
21
|
+
_FILE_CHUNK_SIZE = 64 * 1024
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class _IncomingTransfer:
|
|
26
|
+
context: CommandContext
|
|
27
|
+
purpose: str
|
|
28
|
+
file_name: str
|
|
29
|
+
expected_size: int
|
|
30
|
+
temp_path: str
|
|
31
|
+
file_handle: Any
|
|
32
|
+
remote_path: Optional[str] = None
|
|
33
|
+
options: dict[str, Any] = field(default_factory=dict)
|
|
34
|
+
received_size: int = 0
|
|
35
|
+
digest: Any = field(default_factory=hashlib.sha256)
|
|
36
|
+
last_progress_time: float = field(default_factory=time.monotonic)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class _FirmwareStage:
|
|
41
|
+
file_name: str
|
|
42
|
+
size: int
|
|
43
|
+
digest: str
|
|
44
|
+
path: str
|
|
45
|
+
created_at: float = field(default_factory=time.monotonic)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class TransferCommandsMixin:
|
|
49
|
+
def _init_transfer_state(self) -> None:
|
|
50
|
+
self._incoming_transfers: dict[tuple[Any, int], _IncomingTransfer] = {}
|
|
51
|
+
self._incoming_transfers_lock = threading.Lock()
|
|
52
|
+
self._firmware_stages: dict[str, _FirmwareStage] = {}
|
|
53
|
+
self._firmware_stages_lock = threading.Lock()
|
|
54
|
+
|
|
55
|
+
def _send_stream_completion(self, response: dict, client_addr: Any) -> None:
|
|
56
|
+
encoded = AgentProtocol.encode_message(response)
|
|
57
|
+
seq = response.get("seq", 0)
|
|
58
|
+
self._cache_response(client_addr, seq, encoded)
|
|
59
|
+
if not self.send_completion(encoded, client_addr, seq):
|
|
60
|
+
logger.warning("Could not send streaming response %s to %s", seq, client_addr)
|
|
61
|
+
|
|
62
|
+
def _cmd_get_file(self, ctx: CommandContext, remote_path: str) -> dict:
|
|
63
|
+
conn = ctx.connection
|
|
64
|
+
if not conn or not conn.file_system:
|
|
65
|
+
if conn:
|
|
66
|
+
conn.release()
|
|
67
|
+
raise RuntimeError("Not connected")
|
|
68
|
+
|
|
69
|
+
try:
|
|
70
|
+
real_path = self._to_real_path(remote_path, conn)
|
|
71
|
+
content = conn.file_system.get(real_path)
|
|
72
|
+
max_content_size = ((MAX_PAYLOAD_SIZE - 1024) * 3) // 4
|
|
73
|
+
if len(content) > max_content_size:
|
|
74
|
+
raise RuntimeError(
|
|
75
|
+
f"File is too large for an inline response: {len(content)} bytes"
|
|
76
|
+
)
|
|
77
|
+
return {
|
|
78
|
+
"content": base64.b64encode(content).decode("ascii"),
|
|
79
|
+
"encoding": "base64",
|
|
80
|
+
"path": remote_path,
|
|
81
|
+
}
|
|
82
|
+
except Exception as exc:
|
|
83
|
+
raise RuntimeError(f"get_file failed: {exc}") from exc
|
|
84
|
+
|
|
85
|
+
def _cmd_put_file(self, ctx: CommandContext, remote_path: str, content: str) -> dict:
|
|
86
|
+
conn = ctx.connection
|
|
87
|
+
if not conn or not conn.file_system:
|
|
88
|
+
raise RuntimeError("Not connected")
|
|
89
|
+
|
|
90
|
+
temp_path = None
|
|
91
|
+
try:
|
|
92
|
+
real_path = self._to_real_path(remote_path, conn)
|
|
93
|
+
content_bytes = base64.b64decode(content, validate=True)
|
|
94
|
+
with tempfile.NamedTemporaryFile(
|
|
95
|
+
mode="wb", delete=False, suffix=".tmp", prefix="replx-agent-"
|
|
96
|
+
) as file:
|
|
97
|
+
file.write(content_bytes)
|
|
98
|
+
temp_path = file.name
|
|
99
|
+
conn.file_system.put(temp_path, real_path)
|
|
100
|
+
return {"uploaded": remote_path, "bytes": len(content_bytes)}
|
|
101
|
+
except Exception as exc:
|
|
102
|
+
raise RuntimeError(f"put_file failed: {exc}") from exc
|
|
103
|
+
finally:
|
|
104
|
+
if temp_path:
|
|
105
|
+
try:
|
|
106
|
+
os.unlink(temp_path)
|
|
107
|
+
except FileNotFoundError:
|
|
108
|
+
pass
|
|
109
|
+
|
|
110
|
+
def _cmd_put_file_batch(self, ctx: CommandContext, file_specs: list) -> dict:
|
|
111
|
+
conn = ctx.connection
|
|
112
|
+
if not conn or not conn.file_system:
|
|
113
|
+
raise RuntimeError("Not connected")
|
|
114
|
+
|
|
115
|
+
results = []
|
|
116
|
+
for spec in file_specs:
|
|
117
|
+
remote_path = spec.get("remote_path")
|
|
118
|
+
content_b64 = spec.get("content")
|
|
119
|
+
if "local_path" in spec:
|
|
120
|
+
results.append({
|
|
121
|
+
"path": remote_path,
|
|
122
|
+
"success": False,
|
|
123
|
+
"error": "Agent RPC does not accept CLI-local paths",
|
|
124
|
+
})
|
|
125
|
+
continue
|
|
126
|
+
if not remote_path or not content_b64:
|
|
127
|
+
results.append({
|
|
128
|
+
"path": remote_path,
|
|
129
|
+
"success": False,
|
|
130
|
+
"error": "Remote path and content are required",
|
|
131
|
+
})
|
|
132
|
+
continue
|
|
133
|
+
|
|
134
|
+
temp_path = None
|
|
135
|
+
try:
|
|
136
|
+
content = base64.b64decode(content_b64, validate=True)
|
|
137
|
+
real_path = self._to_real_path(remote_path, conn)
|
|
138
|
+
with tempfile.NamedTemporaryFile(
|
|
139
|
+
mode="wb", delete=False, suffix=".tmp", prefix="replx-agent-"
|
|
140
|
+
) as file:
|
|
141
|
+
file.write(content)
|
|
142
|
+
temp_path = file.name
|
|
143
|
+
conn.file_system.put(temp_path, real_path)
|
|
144
|
+
results.append({"path": remote_path, "success": True})
|
|
145
|
+
except Exception as exc:
|
|
146
|
+
results.append({
|
|
147
|
+
"path": remote_path,
|
|
148
|
+
"success": False,
|
|
149
|
+
"error": str(exc),
|
|
150
|
+
})
|
|
151
|
+
finally:
|
|
152
|
+
if temp_path:
|
|
153
|
+
try:
|
|
154
|
+
os.unlink(temp_path)
|
|
155
|
+
except FileNotFoundError:
|
|
156
|
+
pass
|
|
157
|
+
|
|
158
|
+
return {
|
|
159
|
+
"results": results,
|
|
160
|
+
"success_count": sum(1 for result in results if result["success"]),
|
|
161
|
+
"total": len(file_specs),
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
def _cmd_get_file_batch(self, ctx: CommandContext, remote_paths: list) -> dict:
|
|
165
|
+
conn = ctx.connection
|
|
166
|
+
if not conn or not conn.file_system:
|
|
167
|
+
raise RuntimeError("Not connected")
|
|
168
|
+
|
|
169
|
+
results = []
|
|
170
|
+
for remote_path in remote_paths:
|
|
171
|
+
try:
|
|
172
|
+
real_path = self._to_real_path(remote_path, conn)
|
|
173
|
+
content = conn.file_system.get(real_path)
|
|
174
|
+
if isinstance(content, str):
|
|
175
|
+
content = content.encode("utf-8")
|
|
176
|
+
results.append({
|
|
177
|
+
"path": remote_path,
|
|
178
|
+
"content": base64.b64encode(content).decode("ascii"),
|
|
179
|
+
"success": True,
|
|
180
|
+
})
|
|
181
|
+
except Exception as exc:
|
|
182
|
+
results.append({
|
|
183
|
+
"path": remote_path,
|
|
184
|
+
"success": False,
|
|
185
|
+
"error": str(exc),
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
return {
|
|
189
|
+
"results": results,
|
|
190
|
+
"success_count": sum(1 for result in results if result["success"]),
|
|
191
|
+
"total": len(remote_paths),
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
def _start_incoming_transfer(
|
|
195
|
+
self,
|
|
196
|
+
ctx: CommandContext,
|
|
197
|
+
*,
|
|
198
|
+
purpose: str,
|
|
199
|
+
file_name: str,
|
|
200
|
+
size: int,
|
|
201
|
+
remote_path: str = None,
|
|
202
|
+
options: Optional[dict] = None,
|
|
203
|
+
) -> None:
|
|
204
|
+
if isinstance(size, bool) or not isinstance(size, int) or not 0 <= size <= _MAX_TRANSFER_SIZE:
|
|
205
|
+
raise ValueError(f"Invalid transfer size: {size!r}")
|
|
206
|
+
if purpose not in {"put", "script_run", "script_interactive", "firmware"}:
|
|
207
|
+
raise ValueError(f"Unsupported transfer purpose: {purpose}")
|
|
208
|
+
if purpose == "put" and not remote_path:
|
|
209
|
+
raise ValueError("Remote file path is required")
|
|
210
|
+
if purpose in {"put", "script_run", "script_interactive"}:
|
|
211
|
+
if not ctx.connection or not ctx.connection.file_system:
|
|
212
|
+
raise RuntimeError("Not connected")
|
|
213
|
+
if purpose == "put":
|
|
214
|
+
self._to_real_path(remote_path, ctx.connection)
|
|
215
|
+
|
|
216
|
+
file = tempfile.NamedTemporaryFile(
|
|
217
|
+
mode="wb", delete=False, suffix=".tmp", prefix="replx-agent-"
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
key = (ctx.client_addr, ctx.seq)
|
|
221
|
+
state = _IncomingTransfer(
|
|
222
|
+
context=ctx,
|
|
223
|
+
purpose=purpose,
|
|
224
|
+
file_name=os.path.basename(file_name or "transfer"),
|
|
225
|
+
expected_size=size,
|
|
226
|
+
temp_path=file.name,
|
|
227
|
+
file_handle=file,
|
|
228
|
+
remote_path=remote_path,
|
|
229
|
+
options=options or {},
|
|
230
|
+
)
|
|
231
|
+
with self._incoming_transfers_lock:
|
|
232
|
+
if key in self._incoming_transfers:
|
|
233
|
+
file.close()
|
|
234
|
+
os.unlink(file.name)
|
|
235
|
+
raise RuntimeError("Transfer ID is already active")
|
|
236
|
+
self._incoming_transfers[key] = state
|
|
237
|
+
|
|
238
|
+
def _cmd_transfer_start(
|
|
239
|
+
self,
|
|
240
|
+
ctx: CommandContext,
|
|
241
|
+
purpose: str,
|
|
242
|
+
file_name: str,
|
|
243
|
+
size: int,
|
|
244
|
+
remote_path: str = None,
|
|
245
|
+
echo: bool = False,
|
|
246
|
+
reset: bool = True,
|
|
247
|
+
detach: bool = False,
|
|
248
|
+
) -> None:
|
|
249
|
+
try:
|
|
250
|
+
self._start_incoming_transfer(
|
|
251
|
+
ctx,
|
|
252
|
+
purpose=purpose,
|
|
253
|
+
file_name=file_name,
|
|
254
|
+
size=size,
|
|
255
|
+
remote_path=remote_path,
|
|
256
|
+
options={"echo": echo, "reset": reset, "detach": detach},
|
|
257
|
+
)
|
|
258
|
+
except Exception:
|
|
259
|
+
key = (ctx.client_addr, ctx.seq)
|
|
260
|
+
with self._incoming_transfers_lock:
|
|
261
|
+
transfer_exists = key in self._incoming_transfers
|
|
262
|
+
if ctx.connection and not transfer_exists:
|
|
263
|
+
ctx.connection.release()
|
|
264
|
+
raise
|
|
265
|
+
|
|
266
|
+
def _cmd_firmware_stage(
|
|
267
|
+
self, ctx: CommandContext, file_name: str, size: int
|
|
268
|
+
) -> None:
|
|
269
|
+
self._start_incoming_transfer(
|
|
270
|
+
ctx,
|
|
271
|
+
purpose="firmware",
|
|
272
|
+
file_name=file_name,
|
|
273
|
+
size=size,
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
def _handle_binary_frame(self, client_addr: Any, seq: int, data: bytes) -> None:
|
|
277
|
+
key = (client_addr, seq)
|
|
278
|
+
with self._incoming_transfers_lock:
|
|
279
|
+
state = self._incoming_transfers.get(key)
|
|
280
|
+
|
|
281
|
+
if state is None:
|
|
282
|
+
self._safe_send(
|
|
283
|
+
AgentProtocol.encode_message(AgentProtocol.create_response(
|
|
284
|
+
seq, error="No active transfer for binary frame"
|
|
285
|
+
)),
|
|
286
|
+
client_addr,
|
|
287
|
+
)
|
|
288
|
+
return
|
|
289
|
+
|
|
290
|
+
try:
|
|
291
|
+
if state.received_size + len(data) > state.expected_size:
|
|
292
|
+
raise ValueError("Transfer contains more data than declared")
|
|
293
|
+
state.file_handle.write(data)
|
|
294
|
+
state.digest.update(data)
|
|
295
|
+
state.received_size += len(data)
|
|
296
|
+
|
|
297
|
+
now = time.monotonic()
|
|
298
|
+
if now - state.last_progress_time >= _TRANSFER_PROGRESS_INTERVAL:
|
|
299
|
+
state.last_progress_time = now
|
|
300
|
+
progress = AgentProtocol.create_progress_stream(seq, {
|
|
301
|
+
"current": state.received_size,
|
|
302
|
+
"total": state.expected_size,
|
|
303
|
+
"file": state.file_name,
|
|
304
|
+
"status": "receiving",
|
|
305
|
+
})
|
|
306
|
+
self._safe_send(AgentProtocol.encode_message(progress), client_addr)
|
|
307
|
+
except Exception as exc:
|
|
308
|
+
self._abort_incoming_transfer(client_addr, seq, str(exc), notify=True)
|
|
309
|
+
|
|
310
|
+
def _handle_transfer_end(self, client_addr: Any, msg: dict) -> None:
|
|
311
|
+
seq = msg.get("seq", 0)
|
|
312
|
+
key = (client_addr, seq)
|
|
313
|
+
with self._incoming_transfers_lock:
|
|
314
|
+
state = self._incoming_transfers.get(key)
|
|
315
|
+
|
|
316
|
+
if state is None:
|
|
317
|
+
self._send_stream_completion(
|
|
318
|
+
AgentProtocol.create_response(seq, error="No active transfer to finish"),
|
|
319
|
+
client_addr,
|
|
320
|
+
)
|
|
321
|
+
return
|
|
322
|
+
|
|
323
|
+
try:
|
|
324
|
+
state.file_handle.flush()
|
|
325
|
+
state.file_handle.close()
|
|
326
|
+
state.file_handle = None
|
|
327
|
+
except OSError as exc:
|
|
328
|
+
self._abort_incoming_transfer(
|
|
329
|
+
client_addr, seq, f"Could not stage transfer: {exc}", notify=True
|
|
330
|
+
)
|
|
331
|
+
return
|
|
332
|
+
|
|
333
|
+
expected_digest = str(msg.get("sha256") or "").lower()
|
|
334
|
+
if (
|
|
335
|
+
msg.get("size") != state.expected_size
|
|
336
|
+
or state.received_size != state.expected_size
|
|
337
|
+
or expected_digest != state.digest.hexdigest()
|
|
338
|
+
):
|
|
339
|
+
self._abort_incoming_transfer(
|
|
340
|
+
client_addr, seq, "Transfer size or SHA-256 verification failed", notify=True
|
|
341
|
+
)
|
|
342
|
+
return
|
|
343
|
+
|
|
344
|
+
with self._incoming_transfers_lock:
|
|
345
|
+
self._incoming_transfers.pop(key, None)
|
|
346
|
+
|
|
347
|
+
if state.purpose == "firmware":
|
|
348
|
+
stage_id = os.urandom(16).hex()
|
|
349
|
+
stage = _FirmwareStage(
|
|
350
|
+
file_name=state.file_name,
|
|
351
|
+
size=state.expected_size,
|
|
352
|
+
digest=state.digest.hexdigest(),
|
|
353
|
+
path=state.temp_path,
|
|
354
|
+
)
|
|
355
|
+
with self._firmware_stages_lock:
|
|
356
|
+
self._firmware_stages[stage_id] = stage
|
|
357
|
+
self._send_stream_completion(
|
|
358
|
+
AgentProtocol.create_response(seq, result={
|
|
359
|
+
"stage_id": stage_id,
|
|
360
|
+
"file_name": stage.file_name,
|
|
361
|
+
"size": stage.size,
|
|
362
|
+
"sha256": stage.digest,
|
|
363
|
+
}),
|
|
364
|
+
client_addr,
|
|
365
|
+
)
|
|
366
|
+
return
|
|
367
|
+
|
|
368
|
+
threading.Thread(
|
|
369
|
+
target=self._complete_incoming_transfer,
|
|
370
|
+
args=(state,),
|
|
371
|
+
daemon=True,
|
|
372
|
+
name=f"replx-transfer-{seq}",
|
|
373
|
+
).start()
|
|
374
|
+
|
|
375
|
+
def _complete_incoming_transfer(self, state: _IncomingTransfer) -> None:
|
|
376
|
+
ctx = state.context
|
|
377
|
+
seq = ctx.seq
|
|
378
|
+
client_addr = ctx.client_addr
|
|
379
|
+
conn = ctx.connection
|
|
380
|
+
keep_connection = False
|
|
381
|
+
|
|
382
|
+
try:
|
|
383
|
+
if state.purpose == "put":
|
|
384
|
+
real_path = self._to_real_path(state.remote_path, conn)
|
|
385
|
+
with conn.file_system.repl.session():
|
|
386
|
+
conn.file_system.put(state.temp_path, real_path)
|
|
387
|
+
result = {
|
|
388
|
+
"uploaded": state.remote_path,
|
|
389
|
+
"bytes": state.received_size,
|
|
390
|
+
"sha256": state.digest.hexdigest(),
|
|
391
|
+
"success": True,
|
|
392
|
+
}
|
|
393
|
+
elif state.purpose == "script_run":
|
|
394
|
+
result = self._cmd_run(
|
|
395
|
+
ctx,
|
|
396
|
+
script_path=state.temp_path,
|
|
397
|
+
detach=bool(state.options.get("detach")),
|
|
398
|
+
)
|
|
399
|
+
result["script"] = state.file_name
|
|
400
|
+
elif state.purpose == "script_interactive":
|
|
401
|
+
self._cmd_run_interactive(
|
|
402
|
+
ctx,
|
|
403
|
+
script_path=state.temp_path,
|
|
404
|
+
echo=bool(state.options.get("echo")),
|
|
405
|
+
reset=bool(state.options.get("reset", True)),
|
|
406
|
+
)
|
|
407
|
+
keep_connection = bool(conn and conn.interactive.active)
|
|
408
|
+
result = {"run": True, "started": True}
|
|
409
|
+
else:
|
|
410
|
+
raise ValueError(f"Unsupported transfer purpose: {state.purpose}")
|
|
411
|
+
|
|
412
|
+
response = AgentProtocol.create_response(seq, result=result)
|
|
413
|
+
except Exception as exc:
|
|
414
|
+
response = AgentProtocol.create_response(seq, error=str(exc))
|
|
415
|
+
finally:
|
|
416
|
+
if conn and not keep_connection:
|
|
417
|
+
conn.release()
|
|
418
|
+
try:
|
|
419
|
+
os.unlink(state.temp_path)
|
|
420
|
+
except FileNotFoundError:
|
|
421
|
+
pass
|
|
422
|
+
|
|
423
|
+
self._send_stream_completion(response, client_addr)
|
|
424
|
+
|
|
425
|
+
def _abort_incoming_transfer(
|
|
426
|
+
self, client_addr: Any, seq: int, reason: str, *, notify: bool
|
|
427
|
+
) -> None:
|
|
428
|
+
key = (client_addr, seq)
|
|
429
|
+
with self._incoming_transfers_lock:
|
|
430
|
+
state = self._incoming_transfers.pop(key, None)
|
|
431
|
+
if state is None:
|
|
432
|
+
return
|
|
433
|
+
if state.context.connection:
|
|
434
|
+
state.context.connection.release()
|
|
435
|
+
if state.file_handle:
|
|
436
|
+
state.file_handle.close()
|
|
437
|
+
try:
|
|
438
|
+
os.unlink(state.temp_path)
|
|
439
|
+
except FileNotFoundError:
|
|
440
|
+
pass
|
|
441
|
+
if notify:
|
|
442
|
+
self._send_stream_completion(
|
|
443
|
+
AgentProtocol.create_response(seq, error=reason), client_addr
|
|
444
|
+
)
|
|
445
|
+
|
|
446
|
+
def _handle_transfer_abort(self, client_addr: Any, msg: dict) -> None:
|
|
447
|
+
self._abort_incoming_transfer(
|
|
448
|
+
client_addr,
|
|
449
|
+
msg.get("seq", 0),
|
|
450
|
+
str(msg.get("error") or "Transfer was cancelled"),
|
|
451
|
+
notify=False,
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
def _cmd_get_file_streaming(
|
|
455
|
+
self, ctx: CommandContext, remote_path: str
|
|
456
|
+
) -> None:
|
|
457
|
+
conn = ctx.connection
|
|
458
|
+
if not conn or not conn.file_system:
|
|
459
|
+
if conn:
|
|
460
|
+
conn.release()
|
|
461
|
+
raise RuntimeError("Not connected")
|
|
462
|
+
|
|
463
|
+
seq = ctx.seq
|
|
464
|
+
client_addr = ctx.client_addr
|
|
465
|
+
try:
|
|
466
|
+
real_path = self._to_real_path(remote_path, conn)
|
|
467
|
+
except Exception:
|
|
468
|
+
conn.release()
|
|
469
|
+
raise
|
|
470
|
+
|
|
471
|
+
def download() -> None:
|
|
472
|
+
temp_path = None
|
|
473
|
+
try:
|
|
474
|
+
with tempfile.NamedTemporaryFile(
|
|
475
|
+
mode="wb", delete=False, suffix=".tmp", prefix="replx-agent-"
|
|
476
|
+
) as file:
|
|
477
|
+
temp_path = file.name
|
|
478
|
+
with conn.file_system.repl.session():
|
|
479
|
+
conn.file_system.get(real_path, temp_path)
|
|
480
|
+
|
|
481
|
+
size = os.path.getsize(temp_path)
|
|
482
|
+
digest = hashlib.sha256()
|
|
483
|
+
sent = 0
|
|
484
|
+
last_progress_time = time.monotonic()
|
|
485
|
+
if not self._safe_send(AgentProtocol.encode_message(
|
|
486
|
+
AgentProtocol.create_progress_stream(seq, {
|
|
487
|
+
"current": 0,
|
|
488
|
+
"total": size,
|
|
489
|
+
"file": posixpath.basename(remote_path),
|
|
490
|
+
"status": "starting",
|
|
491
|
+
})
|
|
492
|
+
), client_addr):
|
|
493
|
+
raise ConnectionError("Client disconnected during file download")
|
|
494
|
+
|
|
495
|
+
with open(temp_path, "rb") as file:
|
|
496
|
+
while chunk := file.read(_FILE_CHUNK_SIZE):
|
|
497
|
+
digest.update(chunk)
|
|
498
|
+
if not self._safe_send(
|
|
499
|
+
AgentProtocol.encode_binary(seq, chunk), client_addr
|
|
500
|
+
):
|
|
501
|
+
raise ConnectionError("Client disconnected during file download")
|
|
502
|
+
sent += len(chunk)
|
|
503
|
+
now = time.monotonic()
|
|
504
|
+
if (
|
|
505
|
+
now - last_progress_time >= _TRANSFER_PROGRESS_INTERVAL
|
|
506
|
+
or sent == size
|
|
507
|
+
):
|
|
508
|
+
last_progress_time = now
|
|
509
|
+
self._safe_send(AgentProtocol.encode_message(
|
|
510
|
+
AgentProtocol.create_progress_stream(seq, {
|
|
511
|
+
"current": sent,
|
|
512
|
+
"total": size,
|
|
513
|
+
"file": posixpath.basename(remote_path),
|
|
514
|
+
"status": "downloading",
|
|
515
|
+
})
|
|
516
|
+
), client_addr)
|
|
517
|
+
|
|
518
|
+
response = AgentProtocol.create_response(seq, result={
|
|
519
|
+
"downloaded": remote_path,
|
|
520
|
+
"size": sent,
|
|
521
|
+
"sha256": digest.hexdigest(),
|
|
522
|
+
"success": True,
|
|
523
|
+
})
|
|
524
|
+
except Exception as exc:
|
|
525
|
+
response = AgentProtocol.create_response(
|
|
526
|
+
seq, error=f"get_file failed: {exc}"
|
|
527
|
+
)
|
|
528
|
+
finally:
|
|
529
|
+
conn.release()
|
|
530
|
+
if temp_path:
|
|
531
|
+
try:
|
|
532
|
+
os.unlink(temp_path)
|
|
533
|
+
except FileNotFoundError:
|
|
534
|
+
pass
|
|
535
|
+
self._send_stream_completion(response, client_addr)
|
|
536
|
+
|
|
537
|
+
threading.Thread(
|
|
538
|
+
target=download,
|
|
539
|
+
daemon=True,
|
|
540
|
+
name=f"replx-download-{seq}",
|
|
541
|
+
).start()
|
|
542
|
+
|
|
543
|
+
def _cleanup_transfer_state(self) -> None:
|
|
544
|
+
with self._incoming_transfers_lock:
|
|
545
|
+
incoming = list(self._incoming_transfers.values())
|
|
546
|
+
self._incoming_transfers.clear()
|
|
547
|
+
for state in incoming:
|
|
548
|
+
if state.context.connection:
|
|
549
|
+
state.context.connection.release()
|
|
550
|
+
if state.file_handle:
|
|
551
|
+
state.file_handle.close()
|
|
552
|
+
try:
|
|
553
|
+
os.unlink(state.temp_path)
|
|
554
|
+
except FileNotFoundError:
|
|
555
|
+
pass
|
|
556
|
+
|
|
557
|
+
with self._firmware_stages_lock:
|
|
558
|
+
stages = list(self._firmware_stages.values())
|
|
559
|
+
self._firmware_stages.clear()
|
|
560
|
+
for stage in stages:
|
|
561
|
+
try:
|
|
562
|
+
os.unlink(stage.path)
|
|
563
|
+
except FileNotFoundError:
|
|
564
|
+
pass
|
|
565
|
+
|
|
566
|
+
def _handle_peer_disconnect(self, client_addr: Any) -> None:
|
|
567
|
+
with self._incoming_transfers_lock:
|
|
568
|
+
keys = [
|
|
569
|
+
key for key in self._incoming_transfers
|
|
570
|
+
if key[0] is client_addr
|
|
571
|
+
]
|
|
572
|
+
transfers = [
|
|
573
|
+
self._incoming_transfers.pop(key)
|
|
574
|
+
for key in keys
|
|
575
|
+
]
|
|
576
|
+
for state in transfers:
|
|
577
|
+
if state.file_handle:
|
|
578
|
+
try:
|
|
579
|
+
state.file_handle.close()
|
|
580
|
+
except OSError as exc:
|
|
581
|
+
logger.warning("Could not close interrupted transfer %s: %s", state.temp_path, exc)
|
|
582
|
+
if state.context.connection:
|
|
583
|
+
state.context.connection.release()
|
|
584
|
+
try:
|
|
585
|
+
os.unlink(state.temp_path)
|
|
586
|
+
except FileNotFoundError:
|
|
587
|
+
pass
|
|
588
|
+
except OSError as exc:
|
|
589
|
+
logger.warning("Could not remove interrupted transfer %s: %s", state.temp_path, exc)
|
|
590
|
+
|
|
591
|
+
for conn in self.connection_manager.get_all_connections().values():
|
|
592
|
+
if conn.interactive.active and conn.interactive.client_addr is client_addr:
|
|
593
|
+
with conn.interactive.lock:
|
|
594
|
+
conn.interactive.stop_requested = True
|
|
595
|
+
if conn.repl_protocol:
|
|
596
|
+
try:
|
|
597
|
+
conn.repl_protocol.interrupt()
|
|
598
|
+
except Exception as exc:
|
|
599
|
+
logger.warning("Could not interrupt disconnected interactive session on %s: %s", conn.port, exc)
|
|
600
|
+
self._forget_peer(client_addr)
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from ..command_dispatcher import CommandContext
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class UartCommandsMixin:
|
|
5
|
+
def _uart_resolve_port(self, ctx: CommandContext) -> str:
|
|
6
|
+
port = self._resolve_connection_for_session(ctx.ppid, ctx.explicit_port)
|
|
7
|
+
if not port:
|
|
8
|
+
raise ValueError("No active connection. Connect to a board first.")
|
|
9
|
+
return port
|
|
10
|
+
|
|
11
|
+
def _cmd_uart_bus_set(self, ctx: CommandContext,
|
|
12
|
+
tx, rx, ch: int,
|
|
13
|
+
baud: int, bits: int, parity: str,
|
|
14
|
+
stop: int, timeout_ms: int,
|
|
15
|
+
family: str = 'other', id_mode: str = '') -> dict:
|
|
16
|
+
port = self._uart_resolve_port(ctx)
|
|
17
|
+
self._uart_bus[port] = {
|
|
18
|
+
'tx': tx, 'rx': rx, 'ch': ch,
|
|
19
|
+
'baud': baud, 'bits': bits, 'parity': parity,
|
|
20
|
+
'stop': stop, 'timeout_ms': timeout_ms,
|
|
21
|
+
'family': family, 'id_mode': id_mode,
|
|
22
|
+
}
|
|
23
|
+
return self._uart_bus[port]
|
|
24
|
+
|
|
25
|
+
def _cmd_uart_bus_get(self, ctx: CommandContext) -> dict:
|
|
26
|
+
port = self._uart_resolve_port(ctx)
|
|
27
|
+
return self._uart_bus.get(port) or {}
|
|
28
|
+
|
|
29
|
+
def _cmd_uart_bus_clear(self, ctx: CommandContext) -> dict:
|
|
30
|
+
port = self._uart_resolve_port(ctx)
|
|
31
|
+
self._uart_bus.pop(port, None)
|
|
32
|
+
return {}
|