zettcode-ssh 0.5.2__tar.gz

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.
@@ -0,0 +1,40 @@
1
+ **/.venv/
2
+ **/__pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ .smoke/
8
+ .coverage
9
+ **/.pytest_cache/
10
+ **/.ruff_cache/
11
+ .zett-tool-output/
12
+ .env
13
+ .DS_Store
14
+
15
+ # viztracer writes its trace here by default.
16
+ /result.json
17
+
18
+ # The docs site: dependencies, build output, and VitePress' cache.
19
+ node_modules
20
+ docs/.vitepress/dist/
21
+ docs/.vitepress/cache/
22
+ docs/.vitepress/.temp/
23
+
24
+ # The TypeScript client is built from its sources; only dist/ is published.
25
+ clients/typescript/dist/
26
+
27
+ # The gateway's page is built from clients/gateway into the package when a distribution is made (`make gateway-ui`);
28
+ # the build output is not kept in the repository. pyproject's `artifacts` puts it in the wheel all the same.
29
+ packages/zettcode-gateway/src/zettcode/gateway/static/
30
+
31
+ # The palette gallery is generated by `make palettes`: every widget painted in
32
+ # every palette, written by docs/scripts/palette_gallery.py. Regenerate it
33
+ # rather than committing a 2 MB copy that goes stale the moment a colour moves.
34
+ docs/internal/palettes.html
35
+
36
+ # The release order is generated from the pyproject.toml files (`make order`); it is not kept in git.
37
+ packages/order.txt
38
+
39
+ # electron-builder writes the desktop installers under release/.
40
+ clients/desktop/release/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chang-LeHung
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,17 @@
1
+ # The SSH plugin alone; shared tool configuration remains at the workspace root.
2
+ UV ?= uv
3
+
4
+ .PHONY: test lint typecheck build
5
+
6
+ test:
7
+ $(UV) run --no-sync pytest
8
+
9
+ lint:
10
+ $(UV) run --no-sync ruff format --check src tests
11
+ $(UV) run --no-sync ruff check src tests
12
+
13
+ typecheck:
14
+ @cd ../.. && $(UV) run --no-sync mypy packages/zettcode-ssh/src
15
+
16
+ build:
17
+ $(UV) build
@@ -0,0 +1,204 @@
1
+ Metadata-Version: 2.5
2
+ Name: zettcode-ssh
3
+ Version: 0.5.2
4
+ Summary: A ZettCode plugin: use the coding tools in a remote workspace over OpenSSH
5
+ Project-URL: Repository, https://github.com/Chang-LeHung/zettcode/tree/main/packages/zettcode-ssh
6
+ Project-URL: Issues, https://github.com/Chang-LeHung/zettcode/issues
7
+ Author: Chang-LeHung
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: plugin,ssh,zettcode
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: 3.15
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: pydantic<3,>=2
22
+ Requires-Dist: zett-agent<0.4,>=0.3.1
23
+ Requires-Dist: zettcode-plugin-api<0.6,>=0.5.2
24
+ Description-Content-Type: text/markdown
25
+
26
+ # zettcode-ssh
27
+
28
+ Use ZettCode's conventional coding tools in a remote workspace, without installing or downloading
29
+ ZettCode on that machine.
30
+
31
+ ```sh
32
+ pip install zettcode-ssh
33
+ ```
34
+
35
+ In the terminal, select `/permission full`, then enter `/ssh` **without arguments** to open the SSH panel. It has
36
+ the shape of the other plugin panels: the title with the channel's state at the right, one row per thing, the
37
+ sentence the marked row does, and the keys.
38
+
39
+ ```text
40
+ SSH ● connected · full
41
+
42
+ ▸ Host build-host-1 select or type a host
43
+ Workspace /srv/project remote working directory
44
+ User (from config) from ~/.ssh/config
45
+ Sign in ●───────── key/agent no password needed
46
+ Password (none needed) not needed
47
+ Connect ↵ enter check, then use it
48
+ Disconnect ↵ enter close the remote channel
49
+
50
+ Host: an alias from ~/.ssh/config, or user@hostname typed by hand
51
+ ↑ ↓ row · ← → switch · F2 hosts · enter connect · esc cancel
52
+ ```
53
+
54
+ When `~/.ssh/config` has literal Host aliases, the panel opens on them first (Up/Down and Enter, or a click).
55
+ Bounded `Include` files are supported; wildcard patterns are not offered as destinations, and `Enter a host
56
+ manually…` is always the last choice. F2 reopens that list. Typing and pasting edit the marked row, with a caret
57
+ where the next character goes; a password is painted as bullets.
58
+
59
+ **Both sign-ins are supported.** `Sign in: key/agent` is the no-password path: OpenSSH uses the key or the agent
60
+ from the reader's config, and nothing is asked; the knob sits on the left, and Right (or a click, or Space) slides
61
+ it to `password`. `Sign in: password` asks for the user's password; typing in the
62
+ password row selects it without a separate toggle. The password is handed to OpenSSH through a private `askpass`
63
+ helper (directory `0700`, file `0600`) and never appears in argv, environment values, logs, or a child's state;
64
+ it lives in memory for the session and is deleted when the channel closes. It is therefore not inherited by a
65
+ daemon: a target that needs one is retained but offers no remote tools, with a sentence explaining that a
66
+ headless daemon cannot enter a password. Reconnect in a terminal session or use key/agent authentication.
67
+
68
+ **Connect** checks the remote workspace before changing the target (with a 30-second limit, so an unreachable host
69
+ is reported rather than left turning); an invalid field, a wrong password, a failed
70
+ connection, and cancellation all leave the previous target unchanged. **Disconnect** closes the channel and
71
+ returns to local tools.
72
+
73
+ The `/ssh` command is terminal-only: it is not registered in VS Code or the HTTP client's plain command list.
74
+ Headless daemons can still restore an inherited target. A configuration can also select a target at startup,
75
+ connecting lazily on the first remote tool call:
76
+
77
+ ```toml
78
+ [plugins.ssh]
79
+ host = "my-build-host"
80
+ path = "/srv/project"
81
+ ```
82
+
83
+ Both keys are required together. Unknown keys, options masquerading as hosts, relative workspaces and malformed
84
+ inherited descriptors are refused. A daemon's inherited target takes precedence over the startup configuration.
85
+
86
+ ## Requirements and security
87
+
88
+ - Local system **OpenSSH `ssh`** with an already verified host in `known_hosts`. Use ordinary SSH manually to verify
89
+ an unknown host before using this plugin. Sign in with a key or the agent (no password), or with the account's
90
+ password; password sign-in needs OpenSSH 8.4+ for `SSH_ASKPASS_REQUIRE=force`.
91
+ - Remote POSIX host with **Python 3.10+** and, for `bash`, `/bin/bash`. Python uses only its standard library.
92
+ - OpenSSH always uses `StrictHostKeyChecking=yes`, a ten-second connect timeout and no pseudo-terminal. Key/agent
93
+ sign-in also uses `BatchMode=yes`; password sign-in uses `BatchMode=no`, one password prompt, and
94
+ `PreferredAuthentications=password,keyboard-interactive`. Every server prompt is answered with the password, so
95
+ a host that asks for a second factor (a one-time code) fails rather than waiting. The plugin never disables host
96
+ verification, copies keys, exports credentials, or downloads ZettCode. One persistent SSH channel runs a
97
+ standard-library Python worker through stdin/stdout; the worker never binds a network port or installs remote
98
+ packages.
99
+ - **Every remote tool, including reads, requires the current permission `full`.** `ask`, `deny`, and `safe` are
100
+ refused before starting SSH. The local safe sandbox does **not** constrain remote access. Per-command approval
101
+ is not implemented; approving an ordinary local bash request cannot authorize this plugin. This deliberately
102
+ conservative rule covers the remote Python interpreter as well as the command it executes.
103
+ - Remote paths have the user's remote filesystem access: absolute paths, `..`, and symlinks can leave the selected
104
+ workspace. This is not a remote filesystem sandbox. Use a restricted remote account when confinement is needed.
105
+ - Host, remote path, user and sign-in method are the only inherited state; a password is never part of it.
106
+ Request-scoped local daemon handoff variables are stripped from the
107
+ local SSH subprocess environment; no handoff is encoded in the remote command or JSON. The reader's own OpenSSH
108
+ `SendEnv` configuration remains theirs to audit for unrelated environment secrets. The askpass helper is removed
109
+ when the channel closes and at process exit; only a process killed with `SIGKILL` can leave it, its directory
110
+ `0700` and its file `0600`.
111
+
112
+ ## Tools and bounds
113
+
114
+ Selecting a target **adds** remote tools; it replaces nothing, and the set mirrors what the local tools offer the
115
+ same session. `read`, `read_file`, `write_file`, `edit`, `bash`, `glob` and `grep` keep working on this machine.
116
+ On the selected host:
117
+
118
+ - a coding session (the main agent and the `coding` child) gets `ssh__read`, `ssh__write_file`, `ssh__edit` and
119
+ `ssh__bash` — searching is the shell's job, exactly as it is locally, so there is no remote `glob`/`grep`;
120
+ - an `explore` child has no shell, so it gets `ssh__read`, `ssh__glob` and `ssh__grep`, and may not write or run;
121
+ - a `reasoning` child gets none of them;
122
+ - `ssh__read_file` replaces `ssh__read` for a model that cannot take a picture, and is never offered beside it.
123
+
124
+ All relative paths and `ssh__bash.work_dir` are remote; local tools never reach the host. Every remote action
125
+ requires the current permission `full`, and an SSH failure, missing Python, malformed response or permission
126
+ refusal is reported as it is, never retried as a local operation. The main agent receives a line saying which names
127
+ are remote; local workspace instructions still apply to local work, and the remote `AGENTS.md` is read explicitly
128
+ when it matters. An invalid SSH configuration does not stop the program: the plugin is reported as failed (on
129
+ `/plugins`) and the local tools simply stay as they are.
130
+
131
+ Those `ssh__` rows are drawn by the shell's own tool presenters: a presenter of this plugin only renames the row from
132
+ `ssh__read` to `read` before the chain draws it, so the colour, symbol, timer, fold and preview are the local tool's
133
+ and only the title keeps `ssh/` in the name. `ssh__` is reserved for this plugin: if an MCP server also produces one
134
+ of those names, adding the tools stops that request with a sentence naming the server to rename.
135
+
136
+ - UTF-8 text reads: at most 2,000 lines and 50 KiB per call, numbered lines and continuation hints. Files are
137
+ limited to 16 MiB; the maximum offset is 1,000,000. A single very long line returns a bounded prefix and a hint.
138
+ - `ssh__read` supports PNG/JPEG/GIF/WebP images up to 4 MiB. `ssh__read_file` is always text-only.
139
+ - Writes are atomic replacements in the target directory; existing file modes are preserved. Edits match exact
140
+ text (including original line endings), require one occurrence unless `replace_all=true`, and write nothing on
141
+ a missing or ambiguous match. Concurrent external edits are not locked; read immediately before editing.
142
+ - Glob and grep results are bounded to 50 KiB and at most 5,000 entries (default 200). Glob sorts the bounded
143
+ collected batch, not an unlimited tree. Grep accepts Python regular expressions, skips binary and oversized
144
+ files, and limits each match preview to 2,000 bytes.
145
+ - Requests: 4 MiB JSON maximum; responses: 6 MiB maximum (including base64 images); SSH stderr: the first 16 KiB are retained and the remainder continuously drained.
146
+ An interrupted request is not replayed; a later new request may reconnect. Closing or replacing the target
147
+ permanently invalidates its old channels.
148
+ - Remote Python operations have a 125-second remote deadline and a 135-second local SSH deadline. `bash` has a
149
+ configurable deadline greater than zero and at most 600 seconds (default 60); its remote alarm allows five
150
+ extra seconds (rounded up), and its local SSH deadline allows fifteen extra seconds. It continuously drains
151
+ output to a 50 KiB preview, reports the
152
+ remote exit code, and kills its process group on completion or timeout. Cancellation kills and reaps the local
153
+ SSH process. A lost SSH connection is not a guarantee of immediate remote termination; remote deadlines remain
154
+ the backstop. Processes deliberately escaping their process group are not a supported daemon mechanism.
155
+
156
+ ## Children and daemons
157
+
158
+ Each in-process child gets a fresh extension over a snapshot of the target and the **shared live permission
159
+ policy**, reusing the parent's channel. Requests on one channel are serialized and responses are matched by ID.
160
+ `explore` gets the remote read/search tools (`ssh__read`, `ssh__glob`, `ssh__grep`); `coding` gets the same set
161
+ its own local bundle has (`ssh__read`, `ssh__write_file`, `ssh__edit`, `ssh__bash`); `reasoning` gets none. A child
162
+ keeps its own local tools — nothing is replaced — and receives the line saying which names are remote.
163
+
164
+ The active **`Client.spawn_daemon` API** creates a *local* daemon with the selected SSH descriptor, restored before
165
+ plugin activation. The daemon needs this matching `zettcode-ssh` installed locally and uses its own permission
166
+ policy and establishes its own SSH channel. Only host, path, user and the sign-in method are serialized, never the
167
+ live connection and never a password.
168
+ Selecting local tools in the panel clears the target and closes the parent's owned channels.
169
+
170
+ Model `bash` is **remote**, so `zettcode daemon spawn` in that tool runs *on the remote host*, not locally. It would
171
+ require ZettCode and this matching plugin installed and configured there; no local daemon token, credentials or
172
+ inheritance handoff is sent remotely. Use the active client's spawn API for local inheriting daemons, not remote
173
+ bash. An independently started local CLI has no active client's runtime descriptor.
174
+
175
+ ## Development
176
+
177
+ From this uv workspace: `make -C packages/zettcode-ssh test lint typecheck`, `uv build --package zettcode-ssh`.
178
+ Tests use mocked SSH processes and a temporary fake `ssh` executable to execute the fixed Python payload locally;
179
+ no network, remote credentials or real SSH server is needed. These are unit/fake-process checks, **not real SSH
180
+ acceptance**. This suite is skipped on Windows because its fake executables, paths and process groups require
181
+ POSIX; it does not test Windows SSH support. Generic SDK and application alias tests remain enabled there.
182
+ Before release, run the checklist below against a disposable POSIX sshd and record OS, OpenSSH and
183
+ remote Python versions plus pass/fail evidence. Do not use production credentials or workspaces.
184
+
185
+ ### Manual acceptance checklist (not yet executed by the unit suite)
186
+
187
+ - [ ] Verified `known_hosts`: connect with a configured key, then with ssh-agent only; read/write/edit a temporary
188
+ remote project and verify local files are unchanged. Confirm one channel is reused across requests.
189
+ - [ ] Password: connect from the terminal panel with a correct password; reject an incorrect password and unsupported
190
+ multi-factor prompt promptly, preserving the previous target. Verify password masking and helper cleanup.
191
+ - [ ] Host-key rejection: unknown and changed host keys must refuse, never auto-accept. Establish trust separately
192
+ with ordinary SSH, then retry explicitly. Never disable verification to make this test pass.
193
+ - [ ] Real terminal PTY: open `/ssh`, choose Host with Enter/F2, type/paste fields, switch sign-in, connect/disconnect,
194
+ resize/scroll, cancel a pending check with Escape/Ctrl-C, and confirm the prior target survives cancellation.
195
+ SSH itself must remain non-PTY (`-T`).
196
+ - [ ] Permissions: full offers and runs remote tools; switching to safe/ask/deny removes them on the next request
197
+ and refuses a previously offered handler. Restored password daemons retain the descriptor but offer no remote
198
+ tools and explain that nobody can enter a password there; key/agent daemons work without terminal input.
199
+ - [ ] Large log: a >16 MiB text file supports a small late line range; a very long line has one bounded prefix and
200
+ `line truncated` advice. Inspect transcript highlighting, line count, fold and resumed tool identity.
201
+ - [ ] Deadline/disconnect/no replay: run a long command with a short deadline and verify bounded output and group
202
+ termination; interrupt a mutating request or sever its connection and check the unknown outcome warning.
203
+ Confirm it is never replayed automatically; a later, explicitly new request may reconnect. Observe the remote
204
+ deadline backstop after disconnect (disconnect alone does not guarantee immediate remote termination).
@@ -0,0 +1,179 @@
1
+ # zettcode-ssh
2
+
3
+ Use ZettCode's conventional coding tools in a remote workspace, without installing or downloading
4
+ ZettCode on that machine.
5
+
6
+ ```sh
7
+ pip install zettcode-ssh
8
+ ```
9
+
10
+ In the terminal, select `/permission full`, then enter `/ssh` **without arguments** to open the SSH panel. It has
11
+ the shape of the other plugin panels: the title with the channel's state at the right, one row per thing, the
12
+ sentence the marked row does, and the keys.
13
+
14
+ ```text
15
+ SSH ● connected · full
16
+
17
+ ▸ Host build-host-1 select or type a host
18
+ Workspace /srv/project remote working directory
19
+ User (from config) from ~/.ssh/config
20
+ Sign in ●───────── key/agent no password needed
21
+ Password (none needed) not needed
22
+ Connect ↵ enter check, then use it
23
+ Disconnect ↵ enter close the remote channel
24
+
25
+ Host: an alias from ~/.ssh/config, or user@hostname typed by hand
26
+ ↑ ↓ row · ← → switch · F2 hosts · enter connect · esc cancel
27
+ ```
28
+
29
+ When `~/.ssh/config` has literal Host aliases, the panel opens on them first (Up/Down and Enter, or a click).
30
+ Bounded `Include` files are supported; wildcard patterns are not offered as destinations, and `Enter a host
31
+ manually…` is always the last choice. F2 reopens that list. Typing and pasting edit the marked row, with a caret
32
+ where the next character goes; a password is painted as bullets.
33
+
34
+ **Both sign-ins are supported.** `Sign in: key/agent` is the no-password path: OpenSSH uses the key or the agent
35
+ from the reader's config, and nothing is asked; the knob sits on the left, and Right (or a click, or Space) slides
36
+ it to `password`. `Sign in: password` asks for the user's password; typing in the
37
+ password row selects it without a separate toggle. The password is handed to OpenSSH through a private `askpass`
38
+ helper (directory `0700`, file `0600`) and never appears in argv, environment values, logs, or a child's state;
39
+ it lives in memory for the session and is deleted when the channel closes. It is therefore not inherited by a
40
+ daemon: a target that needs one is retained but offers no remote tools, with a sentence explaining that a
41
+ headless daemon cannot enter a password. Reconnect in a terminal session or use key/agent authentication.
42
+
43
+ **Connect** checks the remote workspace before changing the target (with a 30-second limit, so an unreachable host
44
+ is reported rather than left turning); an invalid field, a wrong password, a failed
45
+ connection, and cancellation all leave the previous target unchanged. **Disconnect** closes the channel and
46
+ returns to local tools.
47
+
48
+ The `/ssh` command is terminal-only: it is not registered in VS Code or the HTTP client's plain command list.
49
+ Headless daemons can still restore an inherited target. A configuration can also select a target at startup,
50
+ connecting lazily on the first remote tool call:
51
+
52
+ ```toml
53
+ [plugins.ssh]
54
+ host = "my-build-host"
55
+ path = "/srv/project"
56
+ ```
57
+
58
+ Both keys are required together. Unknown keys, options masquerading as hosts, relative workspaces and malformed
59
+ inherited descriptors are refused. A daemon's inherited target takes precedence over the startup configuration.
60
+
61
+ ## Requirements and security
62
+
63
+ - Local system **OpenSSH `ssh`** with an already verified host in `known_hosts`. Use ordinary SSH manually to verify
64
+ an unknown host before using this plugin. Sign in with a key or the agent (no password), or with the account's
65
+ password; password sign-in needs OpenSSH 8.4+ for `SSH_ASKPASS_REQUIRE=force`.
66
+ - Remote POSIX host with **Python 3.10+** and, for `bash`, `/bin/bash`. Python uses only its standard library.
67
+ - OpenSSH always uses `StrictHostKeyChecking=yes`, a ten-second connect timeout and no pseudo-terminal. Key/agent
68
+ sign-in also uses `BatchMode=yes`; password sign-in uses `BatchMode=no`, one password prompt, and
69
+ `PreferredAuthentications=password,keyboard-interactive`. Every server prompt is answered with the password, so
70
+ a host that asks for a second factor (a one-time code) fails rather than waiting. The plugin never disables host
71
+ verification, copies keys, exports credentials, or downloads ZettCode. One persistent SSH channel runs a
72
+ standard-library Python worker through stdin/stdout; the worker never binds a network port or installs remote
73
+ packages.
74
+ - **Every remote tool, including reads, requires the current permission `full`.** `ask`, `deny`, and `safe` are
75
+ refused before starting SSH. The local safe sandbox does **not** constrain remote access. Per-command approval
76
+ is not implemented; approving an ordinary local bash request cannot authorize this plugin. This deliberately
77
+ conservative rule covers the remote Python interpreter as well as the command it executes.
78
+ - Remote paths have the user's remote filesystem access: absolute paths, `..`, and symlinks can leave the selected
79
+ workspace. This is not a remote filesystem sandbox. Use a restricted remote account when confinement is needed.
80
+ - Host, remote path, user and sign-in method are the only inherited state; a password is never part of it.
81
+ Request-scoped local daemon handoff variables are stripped from the
82
+ local SSH subprocess environment; no handoff is encoded in the remote command or JSON. The reader's own OpenSSH
83
+ `SendEnv` configuration remains theirs to audit for unrelated environment secrets. The askpass helper is removed
84
+ when the channel closes and at process exit; only a process killed with `SIGKILL` can leave it, its directory
85
+ `0700` and its file `0600`.
86
+
87
+ ## Tools and bounds
88
+
89
+ Selecting a target **adds** remote tools; it replaces nothing, and the set mirrors what the local tools offer the
90
+ same session. `read`, `read_file`, `write_file`, `edit`, `bash`, `glob` and `grep` keep working on this machine.
91
+ On the selected host:
92
+
93
+ - a coding session (the main agent and the `coding` child) gets `ssh__read`, `ssh__write_file`, `ssh__edit` and
94
+ `ssh__bash` — searching is the shell's job, exactly as it is locally, so there is no remote `glob`/`grep`;
95
+ - an `explore` child has no shell, so it gets `ssh__read`, `ssh__glob` and `ssh__grep`, and may not write or run;
96
+ - a `reasoning` child gets none of them;
97
+ - `ssh__read_file` replaces `ssh__read` for a model that cannot take a picture, and is never offered beside it.
98
+
99
+ All relative paths and `ssh__bash.work_dir` are remote; local tools never reach the host. Every remote action
100
+ requires the current permission `full`, and an SSH failure, missing Python, malformed response or permission
101
+ refusal is reported as it is, never retried as a local operation. The main agent receives a line saying which names
102
+ are remote; local workspace instructions still apply to local work, and the remote `AGENTS.md` is read explicitly
103
+ when it matters. An invalid SSH configuration does not stop the program: the plugin is reported as failed (on
104
+ `/plugins`) and the local tools simply stay as they are.
105
+
106
+ Those `ssh__` rows are drawn by the shell's own tool presenters: a presenter of this plugin only renames the row from
107
+ `ssh__read` to `read` before the chain draws it, so the colour, symbol, timer, fold and preview are the local tool's
108
+ and only the title keeps `ssh/` in the name. `ssh__` is reserved for this plugin: if an MCP server also produces one
109
+ of those names, adding the tools stops that request with a sentence naming the server to rename.
110
+
111
+ - UTF-8 text reads: at most 2,000 lines and 50 KiB per call, numbered lines and continuation hints. Files are
112
+ limited to 16 MiB; the maximum offset is 1,000,000. A single very long line returns a bounded prefix and a hint.
113
+ - `ssh__read` supports PNG/JPEG/GIF/WebP images up to 4 MiB. `ssh__read_file` is always text-only.
114
+ - Writes are atomic replacements in the target directory; existing file modes are preserved. Edits match exact
115
+ text (including original line endings), require one occurrence unless `replace_all=true`, and write nothing on
116
+ a missing or ambiguous match. Concurrent external edits are not locked; read immediately before editing.
117
+ - Glob and grep results are bounded to 50 KiB and at most 5,000 entries (default 200). Glob sorts the bounded
118
+ collected batch, not an unlimited tree. Grep accepts Python regular expressions, skips binary and oversized
119
+ files, and limits each match preview to 2,000 bytes.
120
+ - Requests: 4 MiB JSON maximum; responses: 6 MiB maximum (including base64 images); SSH stderr: the first 16 KiB are retained and the remainder continuously drained.
121
+ An interrupted request is not replayed; a later new request may reconnect. Closing or replacing the target
122
+ permanently invalidates its old channels.
123
+ - Remote Python operations have a 125-second remote deadline and a 135-second local SSH deadline. `bash` has a
124
+ configurable deadline greater than zero and at most 600 seconds (default 60); its remote alarm allows five
125
+ extra seconds (rounded up), and its local SSH deadline allows fifteen extra seconds. It continuously drains
126
+ output to a 50 KiB preview, reports the
127
+ remote exit code, and kills its process group on completion or timeout. Cancellation kills and reaps the local
128
+ SSH process. A lost SSH connection is not a guarantee of immediate remote termination; remote deadlines remain
129
+ the backstop. Processes deliberately escaping their process group are not a supported daemon mechanism.
130
+
131
+ ## Children and daemons
132
+
133
+ Each in-process child gets a fresh extension over a snapshot of the target and the **shared live permission
134
+ policy**, reusing the parent's channel. Requests on one channel are serialized and responses are matched by ID.
135
+ `explore` gets the remote read/search tools (`ssh__read`, `ssh__glob`, `ssh__grep`); `coding` gets the same set
136
+ its own local bundle has (`ssh__read`, `ssh__write_file`, `ssh__edit`, `ssh__bash`); `reasoning` gets none. A child
137
+ keeps its own local tools — nothing is replaced — and receives the line saying which names are remote.
138
+
139
+ The active **`Client.spawn_daemon` API** creates a *local* daemon with the selected SSH descriptor, restored before
140
+ plugin activation. The daemon needs this matching `zettcode-ssh` installed locally and uses its own permission
141
+ policy and establishes its own SSH channel. Only host, path, user and the sign-in method are serialized, never the
142
+ live connection and never a password.
143
+ Selecting local tools in the panel clears the target and closes the parent's owned channels.
144
+
145
+ Model `bash` is **remote**, so `zettcode daemon spawn` in that tool runs *on the remote host*, not locally. It would
146
+ require ZettCode and this matching plugin installed and configured there; no local daemon token, credentials or
147
+ inheritance handoff is sent remotely. Use the active client's spawn API for local inheriting daemons, not remote
148
+ bash. An independently started local CLI has no active client's runtime descriptor.
149
+
150
+ ## Development
151
+
152
+ From this uv workspace: `make -C packages/zettcode-ssh test lint typecheck`, `uv build --package zettcode-ssh`.
153
+ Tests use mocked SSH processes and a temporary fake `ssh` executable to execute the fixed Python payload locally;
154
+ no network, remote credentials or real SSH server is needed. These are unit/fake-process checks, **not real SSH
155
+ acceptance**. This suite is skipped on Windows because its fake executables, paths and process groups require
156
+ POSIX; it does not test Windows SSH support. Generic SDK and application alias tests remain enabled there.
157
+ Before release, run the checklist below against a disposable POSIX sshd and record OS, OpenSSH and
158
+ remote Python versions plus pass/fail evidence. Do not use production credentials or workspaces.
159
+
160
+ ### Manual acceptance checklist (not yet executed by the unit suite)
161
+
162
+ - [ ] Verified `known_hosts`: connect with a configured key, then with ssh-agent only; read/write/edit a temporary
163
+ remote project and verify local files are unchanged. Confirm one channel is reused across requests.
164
+ - [ ] Password: connect from the terminal panel with a correct password; reject an incorrect password and unsupported
165
+ multi-factor prompt promptly, preserving the previous target. Verify password masking and helper cleanup.
166
+ - [ ] Host-key rejection: unknown and changed host keys must refuse, never auto-accept. Establish trust separately
167
+ with ordinary SSH, then retry explicitly. Never disable verification to make this test pass.
168
+ - [ ] Real terminal PTY: open `/ssh`, choose Host with Enter/F2, type/paste fields, switch sign-in, connect/disconnect,
169
+ resize/scroll, cancel a pending check with Escape/Ctrl-C, and confirm the prior target survives cancellation.
170
+ SSH itself must remain non-PTY (`-T`).
171
+ - [ ] Permissions: full offers and runs remote tools; switching to safe/ask/deny removes them on the next request
172
+ and refuses a previously offered handler. Restored password daemons retain the descriptor but offer no remote
173
+ tools and explain that nobody can enter a password there; key/agent daemons work without terminal input.
174
+ - [ ] Large log: a >16 MiB text file supports a small late line range; a very long line has one bounded prefix and
175
+ `line truncated` advice. Inspect transcript highlighting, line count, fold and resumed tool identity.
176
+ - [ ] Deadline/disconnect/no replay: run a long command with a short deadline and verify bounded output and group
177
+ termination; interrupt a mutating request or sever its connection and check the unknown outcome warning.
178
+ Confirm it is never replayed automatically; a later, explicitly new request may reconnect. Observe the remote
179
+ deadline backstop after disconnect (disconnect alone does not guarantee immediate remote termination).
@@ -0,0 +1,52 @@
1
+ [project]
2
+ name = "zettcode-ssh"
3
+ description = "A ZettCode plugin: use the coding tools in a remote workspace over OpenSSH"
4
+ readme = "README.md"
5
+ requires-python = ">=3.10"
6
+ dynamic = ["version"]
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{name = "Chang-LeHung"}]
10
+ keywords = ["zettcode", "plugin", "ssh"]
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Environment :: Console",
14
+ "Programming Language :: Python :: 3.10",
15
+ "Programming Language :: Python :: 3.11",
16
+ "Programming Language :: Python :: 3.12",
17
+ "Programming Language :: Python :: 3.13",
18
+ "Programming Language :: Python :: 3.14",
19
+ "Programming Language :: Python :: 3.15",
20
+ "Typing :: Typed",
21
+ ]
22
+ dependencies = ["zettcode-plugin-api>=0.5.2,<0.6", "zett-agent>=0.3.1,<0.4", "pydantic>=2,<3"]
23
+
24
+ [project.urls]
25
+ Repository = "https://github.com/Chang-LeHung/zettcode/tree/main/packages/zettcode-ssh"
26
+ Issues = "https://github.com/Chang-LeHung/zettcode/issues"
27
+
28
+ [project.entry-points."zettcode.plugin"]
29
+ ssh = "zettcode.ssh:SSHPlugin"
30
+
31
+ [tool.zettcode]
32
+ plugin = true
33
+
34
+ [build-system]
35
+ requires = ["hatchling"]
36
+ build-backend = "hatchling.build"
37
+
38
+ [tool.hatch.version]
39
+ path = "src/zettcode/ssh/__init__.py"
40
+
41
+ [tool.hatch.build.targets.wheel]
42
+ packages = ["src/zettcode"]
43
+
44
+ [tool.hatch.build.targets.sdist]
45
+ include = ["/src", "/tests", "/README.md", "/LICENSE", "/Makefile", "/pyproject.toml"]
46
+
47
+ [dependency-groups]
48
+ dev = ["pytest>=8,<9", "pytest-asyncio>=0.26,<2"]
49
+
50
+ [tool.pytest.ini_options]
51
+ testpaths = ["tests"]
52
+ asyncio_mode = "auto"
@@ -0,0 +1,6 @@
1
+ """Remote coding tools over system OpenSSH."""
2
+
3
+ from .plugin import SSHPlugin
4
+
5
+ __version__ = "0.5.2"
6
+ __all__ = ["SSHPlugin"]
@@ -0,0 +1,74 @@
1
+ """Discover selectable literal aliases without executing SSH configuration directives."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import glob
6
+ import shlex
7
+ from pathlib import Path
8
+
9
+ from .transport import HOST
10
+
11
+ MAX_FILES = 64
12
+ MAX_BYTES = 256 * 1024
13
+ MAX_ALIASES = 200
14
+
15
+
16
+ def host_aliases(config: Path | None = None) -> tuple[str, ...]:
17
+ """Read literal Host aliases and bounded Includes; ignore wildcard/negated patterns and Match sections.
18
+
19
+ Authentication and connection settings remain OpenSSH's responsibility. Match exec is never executed.
20
+ """
21
+ root = config if config is not None else Path.home() / ".ssh" / "config"
22
+ aliases: dict[str, None] = {}
23
+ visited: set[Path] = set()
24
+ remaining = MAX_BYTES
25
+
26
+ def read(path: Path, matching: bool = False) -> bool:
27
+ nonlocal remaining
28
+ try:
29
+ path = path.expanduser().resolve()
30
+ if path in visited or len(visited) >= MAX_FILES or remaining <= 0:
31
+ return matching
32
+ visited.add(path)
33
+ with path.open("rb") as handle:
34
+ data = handle.read(remaining + 1)
35
+ if len(data) > remaining:
36
+ remaining = 0
37
+ return matching
38
+ remaining -= len(data)
39
+ lines = data.decode("utf-8").splitlines()
40
+ except (OSError, UnicodeError, RuntimeError):
41
+ return matching
42
+ for line in lines:
43
+ try:
44
+ words = shlex.split(line, comments=True)
45
+ except ValueError:
46
+ continue
47
+ if not words:
48
+ continue
49
+ key, _, inline = words[0].partition("=")
50
+ args = ([inline] if inline else []) + words[1:]
51
+ if args and args[0] == "=":
52
+ args = args[1:]
53
+ key = key.lower()
54
+ if key == "match":
55
+ matching = True
56
+ elif key == "host":
57
+ matching = False
58
+ for alias in args:
59
+ if len(aliases) < MAX_ALIASES and len(alias) <= 255 and HOST.fullmatch(alias):
60
+ aliases.setdefault(alias, None)
61
+ elif key == "include" and not matching:
62
+ for expression in args:
63
+ candidate = Path(expression).expanduser()
64
+ if not candidate.is_absolute():
65
+ candidate = root.expanduser().parent / candidate
66
+ # Limit expansion as well as reads; never traverse an unbounded Include tree.
67
+ for index, included in enumerate(glob.iglob(str(candidate))):
68
+ if index >= MAX_FILES:
69
+ break
70
+ matching = read(Path(included), matching)
71
+ return matching
72
+
73
+ read(root)
74
+ return tuple(aliases)