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/plugin.py ADDED
@@ -0,0 +1,362 @@
1
+ """Add remote coding tools beside the local ones for the SSH host ``/ssh`` selected.
2
+
3
+ Nothing local is replaced: ``read``, ``read_file``, ``write_file``, ``edit``, ``bash``, ``glob`` and ``grep`` keep
4
+ working on this machine, and the remote operations arrive as their own tools named ``ssh__read`` and so on. A
5
+ subagent gets the same addition, bounded by its profile: explore may read and search remotely, coding may also
6
+ write and run, reasoning gets none. Every remote action requires the current permission ``full``, because the local
7
+ sandbox cannot constrain a remote interpreter.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import json
14
+ from typing import Any
15
+
16
+ from zett_agent.agent import AgentRunContext
17
+ from zett_agent.extensions.base import AgentExtension
18
+ from zett_agent.messages import SystemMessage
19
+ from zett_agent.tools.base import AgentTool, ToolResult
20
+
21
+ from zettcode.plugin_api import (
22
+ MODELS,
23
+ POLICY,
24
+ ChildSession,
25
+ CommandContext,
26
+ CommandResult,
27
+ Plugin,
28
+ PluginContext,
29
+ ShellPolicy,
30
+ )
31
+
32
+ from .tools import ALL, READING, descriptor, tool_name
33
+ from .transport import Target, Transport
34
+
35
+ #: How long the panel's check may wait for the remote interpreter before it gives up and says why.
36
+ CONNECT_SECONDS = 30.0
37
+
38
+ #: How long reading ``~/.ssh/config`` may take before the panel opens for manual entry alone.
39
+ ALIASES_SECONDS = 2.0
40
+
41
+
42
+ class RemoteTools(AgentExtension):
43
+ """The remote tools one session or child may use: a snapshot of the target, its own transport, live policy."""
44
+
45
+ name = "SSHRemoteTools"
46
+
47
+ def __init__(
48
+ self,
49
+ target: Target,
50
+ policy: ShellPolicy,
51
+ profile: str,
52
+ transport: Transport | None = None,
53
+ *,
54
+ models: dict[Any, Any] | None = None,
55
+ ) -> None:
56
+ self.transport = transport
57
+ self.target = target
58
+ self.policy = policy
59
+ self.profile = profile
60
+ self.allowed = READING if profile == "explore" else ALL if profile == "coding" else frozenset()
61
+ self.models = models if models is not None else {}
62
+ self._tools: dict[str, AgentTool] = {}
63
+
64
+ @property
65
+ def transport_now(self) -> Transport:
66
+ if self.transport is None:
67
+ self.transport = Transport(self.target)
68
+ return self.transport
69
+
70
+ async def invoke(self, operation: str, arguments: dict[str, Any]) -> ToolResult:
71
+ # ``read_file`` is the text-only stand-in for ``read``, never a tool of its own beside it.
72
+ permitted = set(self.allowed) | ({"read_file"} if "read" in self.allowed else set())
73
+ if operation not in permitted:
74
+ raise PermissionError(f"The {self.profile} child cannot use {tool_name(operation)}")
75
+ # Read the shared policy at execution, including when it changes during a running request.
76
+ if self.policy.level != "full":
77
+ raise PermissionError(
78
+ f"Remote SSH actions require permission full (current: {self.policy.level}). "
79
+ "The local safe sandbox cannot protect a remote host; ask/deny/safe are refused, even for reads. "
80
+ "Ask the user to change permission explicitly."
81
+ )
82
+ return await self.transport_now.run(operation, arguments)
83
+
84
+ def tool(self, operation: str) -> AgentTool:
85
+ if operation not in self._tools:
86
+
87
+ async def handler(**arguments: Any) -> ToolResult:
88
+ return await self.invoke(operation, arguments)
89
+
90
+ self._tools[operation] = descriptor(operation, handler)
91
+ return self._tools[operation]
92
+
93
+ def _offered(self, context: AgentRunContext) -> set[str]:
94
+ """Return the operations this request may use.
95
+
96
+ The set mirrors the local tools for the same session: a coding session reads without pictures and searches
97
+ with its shell, so it is offered ``read`` or, for a text-only model, ``read_file`` in its place — never both,
98
+ and no ``glob``/``grep``. An explore child has no shell, so it keeps ``glob``/``grep`` and the same single
99
+ reader.
100
+ """
101
+ if self.policy.level != "full" or self.transport_now.needs_password:
102
+ return set()
103
+ offered = set(self.allowed)
104
+ model = next((entry for entry, built in self.models.items() if built is getattr(context, "model", None)), None)
105
+ if model is not None and not model.multimodal and "read" in offered:
106
+ offered.discard("read")
107
+ offered.add("read_file")
108
+ return offered
109
+
110
+ async def on_tool(self, context: AgentRunContext) -> None:
111
+ missing = sorted(
112
+ name for name in (tool_name(operation) for operation in self._offered(context)) if name in context.tools
113
+ )
114
+ if missing:
115
+ raise RuntimeError(
116
+ "Another tool already uses the name "
117
+ + ", ".join(missing)
118
+ + ". `ssh__` belongs to this plugin: rename that MCP server in ~/.zettcode/mcp.json "
119
+ "(a server called `ssh` produces `ssh__read` too) and try again."
120
+ )
121
+ for operation in sorted(self._offered(context)):
122
+ context.register_tool(self.tool(operation))
123
+
124
+ async def on_state(self, context: AgentRunContext) -> None:
125
+ # The offered set is what the request actually carries: a text-only model has no ssh__read to be told about.
126
+ unavailable: list[str] = []
127
+ if self.policy.level != "full":
128
+ unavailable.append(f"Remote SSH tools require permission full (current: {self.policy.level}).")
129
+ if self.transport_now.needs_password:
130
+ unavailable.append(
131
+ "This inherited password target has no password: passwords are never saved or inherited. "
132
+ "A daemon cannot enter one; reconnect in a terminal session or use key/agent authentication."
133
+ )
134
+ content = (
135
+ f"SSH target {json.dumps(self.target.host)} is retained, but no remote tools are available. "
136
+ + " ".join(unavailable)
137
+ + " Do not substitute local tools for remote actions. Ask the user to resolve this before proceeding."
138
+ if unavailable
139
+ else self.instructions(self._offered(context))
140
+ )
141
+ context.add_message(SystemMessage(content=content))
142
+
143
+ def instructions(self, offered: set[str] | None = None) -> str:
144
+ names = (
145
+ ", ".join(tool_name(operation) for operation in sorted(self.allowed if offered is None else offered))
146
+ or "none"
147
+ )
148
+ return (
149
+ "# SSH remote tools (added beside the local ones)\n"
150
+ f"Host: {json.dumps(self.target.host)}. Remote working directory: "
151
+ f"{json.dumps(self.target.path, ensure_ascii=False)}.\n"
152
+ f"The tools named {names} work on that SSH host and nowhere else: their paths and work_dir are remote. "
153
+ "The ordinary read, read_file, write_file, edit, bash, glob and grep still work on this machine; use "
154
+ "them for local files, tests and this repository, and the ssh__ tools for the remote project. "
155
+ "A remote failure is reported as it is, never retried through a local tool in its place. "
156
+ "Read the remote project's AGENTS.md explicitly when it matters; it is guidance, never permission. "
157
+ "All remote actions require the current permission full. No local sandbox protects the remote machine. "
158
+ "ssh__bash runs on the remote host; it cannot start a local daemon, and no credentials are sent there. "
159
+ f"Child/tool profile: {self.profile}; remote tools available: {names}."
160
+ )
161
+
162
+
163
+ class SSHPlugin(Plugin[PluginContext]):
164
+ name = "ssh"
165
+ description = "Adds remote coding tools over system OpenSSH beside the local ones"
166
+ #: Not fail-closed: nothing local is replaced, so a plugin that cannot start leaves the local tools in place and
167
+ #: is reported by the loader (and in `/plugins`) rather than stopping the program the reader was opening.
168
+
169
+ def __init__(self) -> None:
170
+ self.target: Target | None = None
171
+ self.policy: ShellPolicy | None = None
172
+ self._restored = False
173
+ self._transports: dict[Target, Transport] = {}
174
+ self.models: dict[Any, Any] = {}
175
+
176
+ async def aclose(self) -> None:
177
+ transports = tuple(self._transports.values())
178
+ self._transports.clear()
179
+ await self._retire(transports)
180
+
181
+ async def _retire(self, transports: tuple[Transport, ...]) -> None:
182
+ """Close the channels of a replaced target; shielded, so an interrupted switch still frees them."""
183
+ task = asyncio.create_task(self._close_all(transports))
184
+ cancelled = False
185
+ while not task.done():
186
+ try:
187
+ await asyncio.shield(task)
188
+ except asyncio.CancelledError:
189
+ cancelled = True
190
+ task.result()
191
+ if cancelled:
192
+ raise asyncio.CancelledError
193
+
194
+ @staticmethod
195
+ async def _close_all(transports: tuple[Transport, ...]) -> None:
196
+ for transport in transports:
197
+ await transport.aclose()
198
+
199
+ def restore_child(self, state: dict[str, Any]) -> None:
200
+ self.target = Target.restore(state)
201
+ self._restored = True
202
+
203
+ def export_child(self, child: ChildSession) -> dict[str, Any] | None:
204
+ return None if self.target is None else self.target.export()
205
+
206
+ def activate(self, ctx: PluginContext) -> None:
207
+ # Host/path can be configured without connecting. Unknown keys are rejected rather than ignored.
208
+ settings = ctx.settings.declare(host="", path="")
209
+ if set(ctx.config.plugin_settings.get(ctx.settings.plugin, {})) - set(settings):
210
+ raise ValueError("[plugins.ssh] accepts only host and path")
211
+ host, path = settings["host"], settings["path"]
212
+ if not isinstance(host, str) or not isinstance(path, str):
213
+ raise ValueError("[plugins.ssh] host and path must be text")
214
+ if bool(host) != bool(path):
215
+ raise ValueError("[plugins.ssh] host and path must be supplied together")
216
+ configured = Target(host, path) if host and path else None
217
+ # Optional, not required: a front end that hands no policy cannot be made safe for a remote interpreter,
218
+ # and the plugin says so on every action instead of refusing to start the whole program.
219
+ self.policy = ctx.find(POLICY, ShellPolicy)
220
+ # The runtime's own map, kept by identity: it is empty when the plugins activate and `_provider()` fills
221
+ # that same dict later, so replacing it with `or {}` would hide every model for the life of the process.
222
+ known = ctx.find(MODELS, dict)
223
+ self.models = known if known is not None else {}
224
+ if not self._restored:
225
+ self.target = configured
226
+ if self.target is not None and self.policy is None:
227
+ # A *target*, though, is a decision to run tools somewhere else: refuse the start rather than fail every
228
+ # broadcast hook with a runtime error once the session begins.
229
+ raise ValueError(
230
+ "SSH has a target but this front end provides no shell policy; a remote interpreter cannot be "
231
+ "constrained, so the plugin will not start with one"
232
+ )
233
+ if ctx.tui is not None:
234
+ from .presenter import SSHToolNames
235
+
236
+ # A row is the shell's own tool row with the local tool's name; only the title keeps `ssh/`.
237
+ ctx.tui.register_presenter(SSHToolNames())
238
+ ctx.tui.register_command("ssh", "Open the SSH workspace panel", self.open_panel, when_busy="refuse")
239
+
240
+ async def open_panel(self, ctx: CommandContext) -> CommandResult:
241
+ import asyncio
242
+
243
+ from zettcode.plugin_api import bottom_panel
244
+
245
+ from .config import host_aliases
246
+ from .panel import ROWS, SSHPage
247
+
248
+ if ctx.argument:
249
+ raise ValueError("Use /ssh without arguments to open the SSH panel")
250
+ host = ctx.require_host()
251
+
252
+ async def apply(target: Target | None, password: str) -> None:
253
+ if host.client.busy:
254
+ raise ValueError("Wait for the current request to finish before changing SSH targets")
255
+ candidate = Transport(target, password=password) if target is not None else None
256
+ if candidate is not None:
257
+ if self.policy is None or self.policy.level != "full":
258
+ raise ValueError("Select permission full before connecting to a remote workspace")
259
+ try:
260
+ # The check runs a remote interpreter; a host that cannot reach it must not hold the panel.
261
+ await asyncio.wait_for(candidate.run("ping", {}), CONNECT_SECONDS)
262
+ if host.client.busy:
263
+ raise ValueError("A request started while connecting; the previous target is unchanged")
264
+ except asyncio.TimeoutError as error:
265
+ await candidate.aclose()
266
+ raise ValueError(
267
+ f"The host did not answer within {CONNECT_SECONDS:g} seconds. Check the host, your key or "
268
+ "agent, and that the remote host runs Python 3.10+. The previous target is unchanged."
269
+ ) from error
270
+ except OSError as error:
271
+ await candidate.aclose()
272
+ raise ValueError(f"ssh could not be started: {error}") from error
273
+ except BaseException:
274
+ await candidate.aclose()
275
+ raise
276
+ # Swap first, then retire the old channels: the switch is committed at the assignment, so a cancellation
277
+ # during the clean-up must not report "nothing changed" — the channels are freed either way.
278
+ retired = tuple(self._transports.values())
279
+ self._transports.clear()
280
+ self.target = target
281
+ if candidate is not None and target is not None:
282
+ self._transports[target] = candidate
283
+ try:
284
+ await self._retire(retired)
285
+ except asyncio.CancelledError:
286
+ pass
287
+ ctx.ui.notify(self.status())
288
+
289
+ # A config on a hung mount must not keep the panel from opening: a timeout offers manual entry instead.
290
+ try:
291
+ aliases = await asyncio.wait_for(asyncio.to_thread(host_aliases), ALIASES_SECONDS)
292
+ except (asyncio.TimeoutError, OSError):
293
+ aliases = ()
294
+ return CommandResult(
295
+ widget=bottom_panel(
296
+ SSHPage(
297
+ target=self.target,
298
+ status=self.state,
299
+ on_apply=apply,
300
+ on_close=host.close_page,
301
+ aliases=aliases,
302
+ ),
303
+ rows=ROWS,
304
+ )
305
+ )
306
+
307
+ def state(self) -> str:
308
+ """Return the short state the panel's title carries: the channel and the shell level."""
309
+ if self.target is None:
310
+ return "off"
311
+ level = self.policy.level if self.policy is not None else "?"
312
+ transport = self._transports.get(self.target)
313
+ if self.target.auth == "password" and (transport is None or transport.needs_password):
314
+ return f"\u25cb password needed \u00b7 {level}"
315
+ if transport is not None and transport.status == "connected":
316
+ return f"\u25cf connected \u00b7 {level}"
317
+ return f"\u25cb not connected \u00b7 {level}"
318
+
319
+ def status(self) -> str:
320
+ if self.target is None:
321
+ return "SSH is off. Only the local coding tools are offered."
322
+ level = self.policy.level if self.policy is not None else "unavailable"
323
+ transport = self._transports.get(self.target)
324
+ state = transport.status if transport is not None else "not connected"
325
+ if self.target.auth == "password" and (transport is None or transport.needs_password):
326
+ sign_in = "a password, which is never saved or inherited: enter it again in /ssh"
327
+ elif self.target.auth == "password":
328
+ sign_in = "password, this session only"
329
+ else:
330
+ sign_in = "key or agent, no password"
331
+ return (
332
+ f"SSH target: {json.dumps(self.target.host)} {json.dumps(self.target.path, ensure_ascii=False)}"
333
+ f"{f' as {json.dumps(self.target.user)}' if self.target.user else ''}. "
334
+ f"{state}; signing in with {sign_in}. ssh__ tools require permission full (current: {level})."
335
+ )
336
+
337
+ def backend(self, profile: str = "coding") -> RemoteTools:
338
+ if self.target is None or self.policy is None:
339
+ raise RuntimeError("SSH backend is not active")
340
+ transport = self._transports.get(self.target)
341
+ if transport is None:
342
+ transport = self._transports[self.target] = Transport(self.target)
343
+ return RemoteTools(self.target, self.policy, profile, transport, models=self.models)
344
+
345
+ def child_extensions(self, child: ChildSession) -> tuple[AgentExtension, ...]:
346
+ if self.target is None:
347
+ return ()
348
+ if child.kind != "subagent" or child.profile not in {"explore", "coding", "reasoning"}:
349
+ raise ValueError("SSH child extensions require a known subagent profile")
350
+ if child.profile == "reasoning":
351
+ return ()
352
+ return (self.backend(child.profile),)
353
+
354
+ async def on_tool(self, context: AgentRunContext) -> None:
355
+ """Offer the remote tools beside the local ones the session already has."""
356
+ if self.target is not None:
357
+ await self.backend().on_tool(context)
358
+
359
+ async def on_state(self, context: AgentRunContext) -> None:
360
+ """Say where the ssh__ tools work; the local environment note is left alone."""
361
+ if self.target is not None:
362
+ await self.backend().on_state(context)
@@ -0,0 +1,34 @@
1
+ """Opt SSH tools into the local rendering families without changing their identity."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from zettcode.plugin_api import Entry, NextPresenter, Presenter, TextLine
8
+ from zettcode.plugin_api.presenters import ToolRenderingAlias
9
+
10
+ PREFIX = "ssh__"
11
+ _TOOL_NAMES = frozenset({"read", "read_file", "write_file", "edit", "bash", "glob", "grep"})
12
+
13
+
14
+ class SSHToolNames(Presenter[Any]):
15
+ """Supply explicit rendering aliases; the shell's own presenters draw the rows."""
16
+
17
+ priority = 10
18
+
19
+ def tool_rendering_alias(self, name: str) -> ToolRenderingAlias | None:
20
+ """Only the plugin's known tools share local rendering, never arbitrary MCP suffixes."""
21
+ if name.startswith(PREFIX) and name[len(PREFIX) :] in _TOOL_NAMES:
22
+ return ToolRenderingAlias(name[len(PREFIX) :], "ssh/")
23
+ return None
24
+
25
+ def handle(self, entry: Entry, next: NextPresenter) -> Presenter[Any]:
26
+ """Pass every entry on unchanged."""
27
+ return next(entry)
28
+
29
+ def lines(self, entry: Any, width: int, theme: Any, frame: int) -> list[TextLine]:
30
+ """Never called: this presenter only supplies aliases."""
31
+ raise AssertionError("SSHToolNames only supplies rendering aliases")
32
+
33
+
34
+ __all__ = ["PREFIX", "SSHToolNames"]
zettcode/ssh/py.typed ADDED
File without changes