zettcode-ssh 0.5.2__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.
- zettcode/ssh/__init__.py +6 -0
- zettcode/ssh/config.py +74 -0
- zettcode/ssh/panel.py +682 -0
- zettcode/ssh/plugin.py +362 -0
- zettcode/ssh/presenter.py +34 -0
- zettcode/ssh/py.typed +0 -0
- zettcode/ssh/remote.py +421 -0
- zettcode/ssh/tools.py +144 -0
- zettcode/ssh/transport.py +500 -0
- zettcode_ssh-0.5.2.dist-info/METADATA +204 -0
- zettcode_ssh-0.5.2.dist-info/RECORD +14 -0
- zettcode_ssh-0.5.2.dist-info/WHEEL +4 -0
- zettcode_ssh-0.5.2.dist-info/entry_points.txt +2 -0
- zettcode_ssh-0.5.2.dist-info/licenses/LICENSE +21 -0
zettcode/ssh/remote.py
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
"""Fixed, standalone Python payload sent by OpenSSH; only the standard library is used remotely."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import signal
|
|
11
|
+
import stat
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import tempfile
|
|
15
|
+
from collections.abc import Callable, Iterator
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
MAX_FILE = 16 * 1024 * 1024
|
|
20
|
+
MAX_OUTPUT = 50 * 1024
|
|
21
|
+
MAX_TIMEOUT = 600
|
|
22
|
+
ALARM_MARGIN = 5
|
|
23
|
+
DEFAULT_ALARM = 125
|
|
24
|
+
MAX_IMAGE = 4 * 1024 * 1024
|
|
25
|
+
MAX_REQUEST = 4 * 1024 * 1024
|
|
26
|
+
TRUNCATED = "\n... [truncated; narrow the request]"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def text(value: object, name: str, *, empty: bool = False, nul: bool = False) -> str:
|
|
30
|
+
if not isinstance(value, str) or (not nul and "\x00" in value) or (not empty and not value):
|
|
31
|
+
raise ValueError(f"{name} must be {'text' if empty else 'nonempty text'}" + ("" if nul else " without NUL"))
|
|
32
|
+
return value
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def integer(value: object, name: str, minimum: int, maximum: int) -> int:
|
|
36
|
+
if type(value) is not int or not minimum <= value <= maximum:
|
|
37
|
+
raise ValueError(f"{name} must be an integer from {minimum} to {maximum}")
|
|
38
|
+
return value
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def boolean(value: object, name: str) -> bool:
|
|
42
|
+
if type(value) is not bool:
|
|
43
|
+
raise ValueError(f"{name} must be true or false")
|
|
44
|
+
return value
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def duration(value: object) -> float:
|
|
48
|
+
if (
|
|
49
|
+
isinstance(value, bool)
|
|
50
|
+
or not isinstance(value, (int, float))
|
|
51
|
+
or not 0 < value <= MAX_TIMEOUT
|
|
52
|
+
or not math.isfinite(value)
|
|
53
|
+
):
|
|
54
|
+
raise ValueError(f"timeout_seconds must be a finite number greater than 0 and at most {MAX_TIMEOUT}")
|
|
55
|
+
return float(value)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def alarm_for(request: dict[str, Any]) -> int:
|
|
59
|
+
"""Leave bash time to kill and report its process group before the remote backstop fires."""
|
|
60
|
+
if request.get("operation") == "bash":
|
|
61
|
+
arguments = request.get("arguments")
|
|
62
|
+
if isinstance(arguments, dict):
|
|
63
|
+
try:
|
|
64
|
+
return math.ceil(duration(arguments.get("timeout_seconds", 60))) + ALARM_MARGIN
|
|
65
|
+
except ValueError:
|
|
66
|
+
pass
|
|
67
|
+
return DEFAULT_ALARM
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def prefix(value: str, size: int = MAX_OUTPUT) -> str:
|
|
71
|
+
return value.encode("utf-8")[:size].decode("utf-8", errors="ignore")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def located(file_path: str) -> Path:
|
|
75
|
+
return Path(text(file_path, "file_path")).expanduser().resolve()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def regular(path: Path) -> None:
|
|
79
|
+
if not stat.S_ISREG(path.stat().st_mode):
|
|
80
|
+
raise ValueError(f"Not a regular file: {path}")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def contents(path: Path, maximum: int = MAX_FILE) -> bytes:
|
|
84
|
+
regular(path)
|
|
85
|
+
with path.open("rb") as source:
|
|
86
|
+
data = source.read(maximum + 1)
|
|
87
|
+
if len(data) > maximum:
|
|
88
|
+
raise ValueError(f"File exceeds {maximum} bytes: {path}")
|
|
89
|
+
return data
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def read_file(file_path: str, offset: int = 1, limit: int = 2000) -> str:
|
|
93
|
+
integer(offset, "offset", 1, 1_000_000)
|
|
94
|
+
integer(limit, "limit", 1, 2000)
|
|
95
|
+
path = located(file_path)
|
|
96
|
+
regular(path)
|
|
97
|
+
rendered: list[str] = []
|
|
98
|
+
used = 0
|
|
99
|
+
# Universal newlines retain vertical tabs/Unicode separators as content. Bound even
|
|
100
|
+
# skipped lines: an enormous unterminated log line must not be materialized in memory.
|
|
101
|
+
with path.open("r", encoding="utf-8", newline=None) as source:
|
|
102
|
+
for _ in range(offset - 1):
|
|
103
|
+
while True:
|
|
104
|
+
chunk = source.readline(MAX_OUTPUT + 1)
|
|
105
|
+
if not chunk:
|
|
106
|
+
return ""
|
|
107
|
+
if chunk.endswith("\n"):
|
|
108
|
+
break
|
|
109
|
+
for number in range(offset, offset + limit):
|
|
110
|
+
line = source.readline(MAX_OUTPUT + 1)
|
|
111
|
+
if not line:
|
|
112
|
+
break
|
|
113
|
+
row = f"{number}\t{line}"
|
|
114
|
+
size = len(row.encode("utf-8"))
|
|
115
|
+
if used + size > MAX_OUTPUT:
|
|
116
|
+
if not rendered:
|
|
117
|
+
return prefix(row) + (
|
|
118
|
+
"\n... [line truncated; use ssh__bash for a bounded slice of this remote line]"
|
|
119
|
+
)
|
|
120
|
+
return "".join(rendered) + f"\n... [more lines; continue with offset={number}]"
|
|
121
|
+
rendered.append(row)
|
|
122
|
+
used += size
|
|
123
|
+
if source.read(1):
|
|
124
|
+
rendered.append(f"\n... [more lines; continue with offset={offset + len(rendered)}]")
|
|
125
|
+
return "".join(rendered)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def read(file_path: str, offset: int = 1, limit: int = 2000) -> Any:
|
|
129
|
+
integer(offset, "offset", 1, 1_000_000)
|
|
130
|
+
integer(limit, "limit", 1, 2000)
|
|
131
|
+
path = located(file_path)
|
|
132
|
+
regular(path)
|
|
133
|
+
with path.open("rb") as source:
|
|
134
|
+
signature = source.read(16)
|
|
135
|
+
media = None
|
|
136
|
+
if signature.startswith(b"\x89PNG\r\n\x1a\n"):
|
|
137
|
+
media = "image/png"
|
|
138
|
+
elif signature.startswith(b"\xff\xd8\xff"):
|
|
139
|
+
media = "image/jpeg"
|
|
140
|
+
elif signature.startswith((b"GIF87a", b"GIF89a")):
|
|
141
|
+
media = "image/gif"
|
|
142
|
+
elif signature.startswith(b"RIFF") and signature[8:12] == b"WEBP":
|
|
143
|
+
media = "image/webp"
|
|
144
|
+
if media is None:
|
|
145
|
+
return read_file(file_path, offset, limit)
|
|
146
|
+
if path.stat().st_size > MAX_IMAGE:
|
|
147
|
+
raise ValueError(f"Image exceeds {MAX_IMAGE} bytes")
|
|
148
|
+
return {
|
|
149
|
+
"image": base64.b64encode(contents(path, MAX_IMAGE)).decode("ascii"),
|
|
150
|
+
"media_type": media,
|
|
151
|
+
"name": path.name,
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def atomic(path: Path, content: str) -> None:
|
|
156
|
+
text(content, "content", empty=True, nul=True)
|
|
157
|
+
if len(content.encode("utf-8")) > MAX_FILE:
|
|
158
|
+
raise ValueError(f"Content exceeds {MAX_FILE} bytes")
|
|
159
|
+
if path.exists() and not path.is_file():
|
|
160
|
+
raise ValueError(f"Not a regular file: {path}")
|
|
161
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
162
|
+
fd, temporary = tempfile.mkstemp(prefix=".zettcode-ssh-", dir=path.parent)
|
|
163
|
+
try:
|
|
164
|
+
with os.fdopen(fd, "w", encoding="utf-8", newline="") as target:
|
|
165
|
+
target.write(content)
|
|
166
|
+
target.flush()
|
|
167
|
+
os.fsync(target.fileno())
|
|
168
|
+
if path.exists():
|
|
169
|
+
os.chmod(temporary, stat.S_IMODE(path.stat().st_mode))
|
|
170
|
+
os.replace(temporary, path)
|
|
171
|
+
finally:
|
|
172
|
+
if os.path.exists(temporary):
|
|
173
|
+
os.unlink(temporary)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def write_file(file_path: str, content: str) -> str:
|
|
177
|
+
path = located(file_path)
|
|
178
|
+
exists = path.exists()
|
|
179
|
+
atomic(path, content)
|
|
180
|
+
return f"{'Wrote' if exists else 'Created'} {path}"
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def edit(file_path: str, old_string: str, new_string: str, replace_all: bool = False) -> str:
|
|
184
|
+
text(old_string, "old_string", nul=True)
|
|
185
|
+
text(new_string, "new_string", empty=True, nul=True)
|
|
186
|
+
boolean(replace_all, "replace_all")
|
|
187
|
+
path = located(file_path)
|
|
188
|
+
original = contents(path).decode("utf-8")
|
|
189
|
+
count = original.count(old_string)
|
|
190
|
+
if count == 0:
|
|
191
|
+
raise ValueError(
|
|
192
|
+
"old_string not found. Read the file again and copy the exact whitespace and line endings; "
|
|
193
|
+
"omit the numbered-line prefixes from old_string."
|
|
194
|
+
)
|
|
195
|
+
if count != 1 and not replace_all:
|
|
196
|
+
raise ValueError(f"Exact edit requires a unique match (found {count}); use replace_all only intentionally")
|
|
197
|
+
atomic(path, original.replace(old_string, new_string))
|
|
198
|
+
return f"Replaced {count} occurrence{'s' if count != 1 else ''} in {path}"
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def matches(pattern: str) -> Iterator[tuple[Path, str]]:
|
|
202
|
+
"""Path.glob semantics on Python 3.10: hidden entries included, ** does not follow directory links."""
|
|
203
|
+
candidate = Path(pattern).expanduser()
|
|
204
|
+
absolute = candidate.is_absolute()
|
|
205
|
+
root = Path(candidate.anchor) if absolute else Path.cwd()
|
|
206
|
+
expression = candidate.relative_to(root).as_posix() if absolute else candidate.as_posix()
|
|
207
|
+
for match in root.glob(expression):
|
|
208
|
+
shown = match.as_posix() if absolute else Path(os.path.relpath(match, root)).as_posix()
|
|
209
|
+
yield match, shown
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def glob(pattern: str, max_results: int = 200) -> str:
|
|
213
|
+
text(pattern, "pattern")
|
|
214
|
+
integer(max_results, "max_results", 1, 5000)
|
|
215
|
+
results: list[str] = []
|
|
216
|
+
used = 0
|
|
217
|
+
# Stop gathering before sorting: recursive patterns must not materialize an unbounded tree.
|
|
218
|
+
for _, match in matches(pattern):
|
|
219
|
+
size = len(match.encode("utf-8")) + 1
|
|
220
|
+
if len(results) >= max_results or used + size > MAX_OUTPUT:
|
|
221
|
+
return "\n".join(sorted(results)) + TRUNCATED
|
|
222
|
+
results.append(match)
|
|
223
|
+
used += size
|
|
224
|
+
return "\n".join(sorted(results))
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def grep(pattern: str, file_pattern: str = "**/*", case_sensitive: bool = True, max_results: int = 200) -> str:
|
|
228
|
+
text(pattern, "pattern")
|
|
229
|
+
text(file_pattern, "file_pattern")
|
|
230
|
+
boolean(case_sensitive, "case_sensitive")
|
|
231
|
+
integer(max_results, "max_results", 1, 5000)
|
|
232
|
+
expression = re.compile(pattern, 0 if case_sensitive else re.IGNORECASE)
|
|
233
|
+
results: list[str] = []
|
|
234
|
+
used = 0
|
|
235
|
+
for path, match in matches(file_pattern):
|
|
236
|
+
if not path.is_file() or path.stat().st_size > MAX_FILE:
|
|
237
|
+
continue
|
|
238
|
+
try:
|
|
239
|
+
lines = contents(path).decode("utf-8").splitlines()
|
|
240
|
+
except UnicodeDecodeError:
|
|
241
|
+
continue
|
|
242
|
+
for number, line in enumerate(lines, 1):
|
|
243
|
+
found = expression.search(line)
|
|
244
|
+
if found is None:
|
|
245
|
+
continue
|
|
246
|
+
row = f"{match}:{number}: {prefix(line[max(0, found.start() - 100) :], 2000)}"
|
|
247
|
+
size = len(row.encode("utf-8")) + 1
|
|
248
|
+
if len(results) >= max_results or used + size > MAX_OUTPUT:
|
|
249
|
+
return "\n".join(results) + TRUNCATED
|
|
250
|
+
results.append(row)
|
|
251
|
+
used += size
|
|
252
|
+
return "\n".join(results)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
class CommandFailed(RuntimeError):
|
|
256
|
+
"""A failed remote shell command, with its bounded combined stdout/stderr."""
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def bash(command: str, timeout_seconds: float = 60, work_dir: str | None = None) -> str:
|
|
260
|
+
text(command, "command")
|
|
261
|
+
if not command.strip():
|
|
262
|
+
raise ValueError("Shell command cannot be blank")
|
|
263
|
+
timeout = duration(timeout_seconds)
|
|
264
|
+
directory = Path.cwd() if work_dir is None else located(work_dir)
|
|
265
|
+
# Output is drained continuously with a bounded buffer, not communicate() over arbitrary remote output.
|
|
266
|
+
import selectors
|
|
267
|
+
import time
|
|
268
|
+
|
|
269
|
+
process = subprocess.Popen(
|
|
270
|
+
["/bin/bash", "-c", command],
|
|
271
|
+
cwd=directory,
|
|
272
|
+
stdin=subprocess.DEVNULL,
|
|
273
|
+
stdout=subprocess.PIPE,
|
|
274
|
+
stderr=subprocess.PIPE,
|
|
275
|
+
start_new_session=True,
|
|
276
|
+
)
|
|
277
|
+
assert process.stdout is not None and process.stderr is not None
|
|
278
|
+
output = bytearray()
|
|
279
|
+
errors = bytearray()
|
|
280
|
+
truncated = False
|
|
281
|
+
deadline = time.monotonic() + timeout
|
|
282
|
+
selector = selectors.DefaultSelector()
|
|
283
|
+
timed_out = False
|
|
284
|
+
try:
|
|
285
|
+
selector.register(process.stdout, selectors.EVENT_READ, output)
|
|
286
|
+
selector.register(process.stderr, selectors.EVENT_READ, errors)
|
|
287
|
+
while selector.get_map():
|
|
288
|
+
remaining = deadline - time.monotonic()
|
|
289
|
+
if remaining <= 0:
|
|
290
|
+
timed_out = True
|
|
291
|
+
break
|
|
292
|
+
for key, _ in selector.select(min(remaining, 0.1)):
|
|
293
|
+
chunk = os.read(key.fd, 8192)
|
|
294
|
+
if not chunk:
|
|
295
|
+
selector.unregister(key.fileobj)
|
|
296
|
+
continue
|
|
297
|
+
room = MAX_OUTPUT - len(output) - len(errors)
|
|
298
|
+
key.data.extend(chunk[:room])
|
|
299
|
+
truncated = truncated or len(chunk) > room
|
|
300
|
+
if not timed_out:
|
|
301
|
+
try:
|
|
302
|
+
process.wait(timeout=max(0.001, deadline - time.monotonic()))
|
|
303
|
+
except subprocess.TimeoutExpired:
|
|
304
|
+
timed_out = True
|
|
305
|
+
finally:
|
|
306
|
+
# Bound descendants even if the shell exits before them. Pipes retained by background
|
|
307
|
+
# children must not extend either the operation deadline or cleanup indefinitely.
|
|
308
|
+
try:
|
|
309
|
+
os.killpg(process.pid, signal.SIGKILL)
|
|
310
|
+
except ProcessLookupError:
|
|
311
|
+
pass
|
|
312
|
+
try:
|
|
313
|
+
process.wait(timeout=1)
|
|
314
|
+
except subprocess.TimeoutExpired:
|
|
315
|
+
pass
|
|
316
|
+
finally:
|
|
317
|
+
process.stdout.close()
|
|
318
|
+
process.stderr.close()
|
|
319
|
+
selector.close()
|
|
320
|
+
sections = []
|
|
321
|
+
if output:
|
|
322
|
+
sections.append(output.decode("utf-8", errors="replace"))
|
|
323
|
+
if errors:
|
|
324
|
+
sections.append("[stderr]\n" + errors.decode("utf-8", errors="replace"))
|
|
325
|
+
result = "\n".join(sections) + (TRUNCATED if truncated else "")
|
|
326
|
+
details = f"[remote exit code: {process.returncode}]\n{result}"
|
|
327
|
+
if timed_out:
|
|
328
|
+
raise CommandFailed(f"Remote bash timed out after {timeout:g} seconds\n{details}")
|
|
329
|
+
if process.returncode != 0:
|
|
330
|
+
raise CommandFailed(f"Command exited with code {process.returncode}\n{details}")
|
|
331
|
+
return result
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def ping() -> str:
|
|
335
|
+
return str(Path.cwd())
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
OPERATIONS: dict[str, Callable[..., Any]] = {
|
|
339
|
+
"ping": ping,
|
|
340
|
+
"read": read,
|
|
341
|
+
"read_file": read_file,
|
|
342
|
+
"write_file": write_file,
|
|
343
|
+
"edit": edit,
|
|
344
|
+
"bash": bash,
|
|
345
|
+
"glob": glob,
|
|
346
|
+
"grep": grep,
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def dispatch(request: dict[str, Any]) -> Any:
|
|
351
|
+
operation = request["operation"]
|
|
352
|
+
if operation not in OPERATIONS:
|
|
353
|
+
raise ValueError("Unknown remote operation")
|
|
354
|
+
workspace = text(request["workspace"], "workspace")
|
|
355
|
+
if not workspace.startswith("/"):
|
|
356
|
+
raise ValueError("Remote workspace must be absolute")
|
|
357
|
+
os.chdir(workspace)
|
|
358
|
+
arguments = request["arguments"]
|
|
359
|
+
if not isinstance(arguments, dict):
|
|
360
|
+
raise ValueError("Tool arguments must be an object")
|
|
361
|
+
return OPERATIONS[operation](**arguments)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def serve() -> None:
|
|
365
|
+
"""Process bounded newline-framed requests until the owning SSH channel closes."""
|
|
366
|
+
|
|
367
|
+
def expired(signum: int, frame: Any) -> None:
|
|
368
|
+
raise TimeoutError("Remote operation exceeded its deadline")
|
|
369
|
+
|
|
370
|
+
signal.signal(signal.SIGALRM, expired)
|
|
371
|
+
output = sys.stdout.buffer
|
|
372
|
+
while True:
|
|
373
|
+
raw = sys.stdin.buffer.readline(MAX_REQUEST + 2)
|
|
374
|
+
if not raw:
|
|
375
|
+
return
|
|
376
|
+
if len(raw) > MAX_REQUEST + 1 or not raw.endswith(b"\n"):
|
|
377
|
+
return # A corrupt/oversized frame cannot be safely resynchronized.
|
|
378
|
+
signal.alarm(DEFAULT_ALARM)
|
|
379
|
+
request: dict[str, Any] = {}
|
|
380
|
+
try:
|
|
381
|
+
request = json.loads(raw)
|
|
382
|
+
signal.alarm(alarm_for(request))
|
|
383
|
+
result = dispatch(request)
|
|
384
|
+
response = {"ok": True, "result": result, "id": request["id"]}
|
|
385
|
+
except Exception as error:
|
|
386
|
+
size = MAX_OUTPUT + 1000 if isinstance(error, CommandFailed) else 4000
|
|
387
|
+
response = {"ok": False, "error": prefix(f"{type(error).__name__}: {error}", size), "id": request.get("id")}
|
|
388
|
+
finally:
|
|
389
|
+
signal.alarm(0)
|
|
390
|
+
output.write(json.dumps(response, ensure_ascii=False).encode("utf-8") + b"\n")
|
|
391
|
+
output.flush()
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def main() -> None:
|
|
395
|
+
# The transport timeout is the outer bound. The remote alarm also bounds regexes and filesystem traversal
|
|
396
|
+
# if the SSH connection is lost; bash has its own, shorter deadline and kills its process group.
|
|
397
|
+
def expired(signum: int, frame: Any) -> None:
|
|
398
|
+
raise TimeoutError("Remote operation exceeded its deadline")
|
|
399
|
+
|
|
400
|
+
signal.signal(signal.SIGALRM, expired)
|
|
401
|
+
signal.alarm(DEFAULT_ALARM)
|
|
402
|
+
try:
|
|
403
|
+
raw = sys.stdin.buffer.read(MAX_REQUEST + 1)
|
|
404
|
+
if len(raw) > MAX_REQUEST:
|
|
405
|
+
raise ValueError("Remote request exceeds 4 MiB")
|
|
406
|
+
request = json.loads(raw)
|
|
407
|
+
signal.alarm(alarm_for(request))
|
|
408
|
+
result = dispatch(request)
|
|
409
|
+
response = {"ok": True, "result": result}
|
|
410
|
+
except Exception as error:
|
|
411
|
+
# Shell failures carry the same bounded output as successes, not just an exception summary.
|
|
412
|
+
size = MAX_OUTPUT + 1000 if isinstance(error, CommandFailed) else 4000
|
|
413
|
+
response = {"ok": False, "error": prefix(f"{type(error).__name__}: {error}", size)}
|
|
414
|
+
finally:
|
|
415
|
+
signal.alarm(0)
|
|
416
|
+
sys.stdout.buffer.write(json.dumps(response, ensure_ascii=False).encode("utf-8"))
|
|
417
|
+
sys.stdout.buffer.flush()
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
if __name__ == "__main__":
|
|
421
|
+
serve() if "--worker" in sys.argv else main()
|
zettcode/ssh/tools.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Remote tools built through zett-agent's typed decorator, named apart from the local ones.
|
|
2
|
+
|
|
3
|
+
The local coding tools keep their names and keep working; these add the same operations on the SSH host that
|
|
4
|
+
``/ssh`` selected. The ``ssh__`` prefix is the runtime's own namespacing for a tool that belongs to a server, so a
|
|
5
|
+
row reads "ssh/read" in the transcript and the model can never mistake one for the other.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Awaitable, Callable
|
|
11
|
+
from typing import Annotated, Any
|
|
12
|
+
|
|
13
|
+
from pydantic import Field
|
|
14
|
+
from zett_agent.tools.base import AgentTool, ToolExecutionMode, tool
|
|
15
|
+
|
|
16
|
+
#: The same boundaries the local tools use. The main agent reads, writes and runs a shell — searching is the shell's
|
|
17
|
+
#: job, so there is no remote glob/grep there either; an explore subagent has no shell and gets read/glob/grep.
|
|
18
|
+
#: ``read_file`` is not a tool of its own: it replaces ``read`` for a model that cannot take a picture.
|
|
19
|
+
READING = frozenset({"read", "glob", "grep"})
|
|
20
|
+
ALL = frozenset({"read", "write_file", "edit", "bash"})
|
|
21
|
+
PREFIX = "ssh__"
|
|
22
|
+
FilePath = Annotated[str, Field(min_length=1)]
|
|
23
|
+
Offset = Annotated[int, Field(ge=1)]
|
|
24
|
+
Limit = Annotated[int, Field(ge=1, le=2000)]
|
|
25
|
+
MaxResults = Annotated[int, Field(ge=1, le=5000)]
|
|
26
|
+
Timeout = Annotated[float, Field(gt=0, le=600)]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def tool_name(operation: str) -> str:
|
|
30
|
+
"""Return the model-facing name of a remote operation: ``read`` is ``ssh__read``."""
|
|
31
|
+
return f"{PREFIX}{operation}"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def descriptor(operation: str, handler: Callable[..., Awaitable[Any]]) -> AgentTool:
|
|
35
|
+
"""Build one remote tool with framework-generated validation and schema.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
operation: ``read``, ``read_file``, ``glob``, ``grep``, ``write_file``, ``edit`` or ``bash``.
|
|
39
|
+
handler: Called with the validated keyword arguments; raises whatever the transport raised.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def selected(**options: Any) -> Any:
|
|
43
|
+
# Only the requested function needs framework validation/schema generation.
|
|
44
|
+
# Unselected functions are plain definitions, never registered or called.
|
|
45
|
+
if options["name"] == tool_name(operation):
|
|
46
|
+
return tool(**options)
|
|
47
|
+
return lambda function: function
|
|
48
|
+
|
|
49
|
+
@selected(
|
|
50
|
+
name=tool_name("read"),
|
|
51
|
+
guidelines=("Paths are on the SSH host, not this machine. The local read tool is still there for local files."),
|
|
52
|
+
)
|
|
53
|
+
async def read(file_path: FilePath, offset: Offset = 1, limit: Limit = 2000) -> Any:
|
|
54
|
+
"""Read numbered text or a PNG/JPEG/GIF/WebP image on the SSH host.
|
|
55
|
+
|
|
56
|
+
Guidelines:
|
|
57
|
+
- Paths are on the SSH host, not this machine; the local read tool still reads local files.
|
|
58
|
+
- Remote operations require full permission.
|
|
59
|
+
"""
|
|
60
|
+
return await handler(file_path=file_path, offset=offset, limit=limit)
|
|
61
|
+
|
|
62
|
+
@selected(
|
|
63
|
+
name=tool_name("read_file"),
|
|
64
|
+
guidelines="Text only, on the SSH host. Use offset and limit for the next range.",
|
|
65
|
+
)
|
|
66
|
+
async def read_file(file_path: FilePath, offset: Offset = 1, limit: Limit = 2000) -> Any:
|
|
67
|
+
"""Read numbered UTF-8 text on the SSH host, bounded to 2000 lines and 50 KiB.
|
|
68
|
+
|
|
69
|
+
Guidelines:
|
|
70
|
+
- Paths are on the SSH host; the local read_file tool is unchanged.
|
|
71
|
+
"""
|
|
72
|
+
return await handler(file_path=file_path, offset=offset, limit=limit)
|
|
73
|
+
|
|
74
|
+
@selected(name=tool_name("glob"), guidelines="Patterns match the SSH host's filesystem, not this machine.")
|
|
75
|
+
async def glob(pattern: FilePath, max_results: MaxResults = 200) -> Any:
|
|
76
|
+
"""Find paths matching a glob on the SSH host.
|
|
77
|
+
|
|
78
|
+
Guidelines:
|
|
79
|
+
- Narrow the pattern when results are truncated.
|
|
80
|
+
"""
|
|
81
|
+
return await handler(pattern=pattern, max_results=max_results)
|
|
82
|
+
|
|
83
|
+
@selected(name=tool_name("grep"), guidelines="Searches the SSH host; narrow file_pattern when truncated.")
|
|
84
|
+
async def grep(
|
|
85
|
+
pattern: FilePath, file_pattern: str = "**/*", case_sensitive: bool = True, max_results: MaxResults = 200
|
|
86
|
+
) -> Any:
|
|
87
|
+
"""Search UTF-8 files on the SSH host with a Python regular expression.
|
|
88
|
+
|
|
89
|
+
Guidelines:
|
|
90
|
+
- Narrow file_pattern when results are truncated.
|
|
91
|
+
"""
|
|
92
|
+
return await handler(
|
|
93
|
+
pattern=pattern, file_pattern=file_pattern, case_sensitive=case_sensitive, max_results=max_results
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
@selected(
|
|
97
|
+
name=tool_name("write_file"),
|
|
98
|
+
execution_mode=ToolExecutionMode.SERIAL,
|
|
99
|
+
guidelines="Writes on the SSH host. Read an existing remote file before replacing it.",
|
|
100
|
+
)
|
|
101
|
+
async def write_file(file_path: FilePath, content: str) -> Any:
|
|
102
|
+
"""Atomically write a complete UTF-8 file on the SSH host.
|
|
103
|
+
|
|
104
|
+
Guidelines:
|
|
105
|
+
- Paths are on the SSH host; the local write_file tool is unchanged.
|
|
106
|
+
"""
|
|
107
|
+
return await handler(file_path=file_path, content=content)
|
|
108
|
+
|
|
109
|
+
@selected(
|
|
110
|
+
name=tool_name("edit"),
|
|
111
|
+
execution_mode=ToolExecutionMode.SERIAL,
|
|
112
|
+
guidelines="Exact remote replacement; read first and omit numbered-line prefixes.",
|
|
113
|
+
)
|
|
114
|
+
async def edit(file_path: FilePath, old_string: FilePath, new_string: str, replace_all: bool = False) -> Any:
|
|
115
|
+
"""Replace exact text in a file on the SSH host, requiring a unique match by default.
|
|
116
|
+
|
|
117
|
+
Guidelines:
|
|
118
|
+
- Paths are on the SSH host. Read first; omit numbered-line prefixes from replacements.
|
|
119
|
+
"""
|
|
120
|
+
return await handler(file_path=file_path, old_string=old_string, new_string=new_string, replace_all=replace_all)
|
|
121
|
+
|
|
122
|
+
@selected(
|
|
123
|
+
name=tool_name("bash"),
|
|
124
|
+
execution_mode=ToolExecutionMode.SERIAL,
|
|
125
|
+
guidelines="Runs on the SSH host; nonzero exits and timeouts fail with captured output.",
|
|
126
|
+
)
|
|
127
|
+
async def bash(command: FilePath, timeout_seconds: Timeout = 60, work_dir: str | None = None) -> Any:
|
|
128
|
+
"""Run a command with the SSH host's /bin/bash.
|
|
129
|
+
|
|
130
|
+
Guidelines:
|
|
131
|
+
- This runs on the SSH host, not this machine; the local bash tool is unchanged.
|
|
132
|
+
- Remote operations require full permission; no local sandbox protects the remote host.
|
|
133
|
+
"""
|
|
134
|
+
return await handler(command=command, timeout_seconds=timeout_seconds, work_dir=work_dir)
|
|
135
|
+
|
|
136
|
+
return {
|
|
137
|
+
"read": read,
|
|
138
|
+
"read_file": read_file,
|
|
139
|
+
"glob": glob,
|
|
140
|
+
"grep": grep,
|
|
141
|
+
"write_file": write_file,
|
|
142
|
+
"edit": edit,
|
|
143
|
+
"bash": bash,
|
|
144
|
+
}[operation]
|