jusi-shell 0.2.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.
- jusi_shell/__init__.py +5 -0
- jusi_shell/application.py +354 -0
- jusi_shell/catalog.py +23 -0
- jusi_shell/completion.py +55 -0
- jusi_shell/control.py +22 -0
- jusi_shell/kernel.py +73 -0
- jusi_shell/worker.py +130 -0
- jusi_shell-0.2.0.dist-info/METADATA +53 -0
- jusi_shell-0.2.0.dist-info/RECORD +12 -0
- jusi_shell-0.2.0.dist-info/WHEEL +4 -0
- jusi_shell-0.2.0.dist-info/entry_points.txt +2 -0
- jusi_shell-0.2.0.dist-info/licenses/LICENSE +21 -0
jusi_shell/__init__.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import fcntl
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import pty
|
|
9
|
+
import selectors
|
|
10
|
+
import shlex
|
|
11
|
+
import shutil
|
|
12
|
+
import signal
|
|
13
|
+
import socket
|
|
14
|
+
import struct
|
|
15
|
+
import sys
|
|
16
|
+
import tempfile
|
|
17
|
+
import termios
|
|
18
|
+
import threading
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
_INTERACTIVE_SHELLS = {"bash", "dash", "fish", "ksh", "sh", "zsh"}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _winsize(fd: int) -> bytes | None:
|
|
26
|
+
try:
|
|
27
|
+
return fcntl.ioctl(fd, termios.TIOCGWINSZ, struct.pack("HHHH", 0, 0, 0, 0))
|
|
28
|
+
except OSError:
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _set_winsize(fd: int, value: bytes | None) -> None:
|
|
33
|
+
if value is not None:
|
|
34
|
+
fcntl.ioctl(fd, termios.TIOCSWINSZ, value)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ShellApplication:
|
|
38
|
+
def __init__(self, launch: dict[str, Any], socket_path: str) -> None:
|
|
39
|
+
self.body = str(launch.get("body", ""))
|
|
40
|
+
self.requested_shell = str(launch.get("shell", "")).strip()
|
|
41
|
+
self.socket_path = socket_path
|
|
42
|
+
self.current_cwd = os.getcwd()
|
|
43
|
+
self.master_fd = -1
|
|
44
|
+
self.child_pid = 0
|
|
45
|
+
self.returncode: int | None = None
|
|
46
|
+
self.stop_event = threading.Event()
|
|
47
|
+
self.terminate_requested = threading.Event()
|
|
48
|
+
self.write_lock = threading.Lock()
|
|
49
|
+
self.state_lock = threading.Lock()
|
|
50
|
+
self.server: socket.socket | None = None
|
|
51
|
+
self.server_thread: threading.Thread | None = None
|
|
52
|
+
self.state_directory = tempfile.TemporaryDirectory(prefix="jusi-shell-app-")
|
|
53
|
+
self.saved_terminal: list[Any] | None = None
|
|
54
|
+
|
|
55
|
+
def run(self) -> int:
|
|
56
|
+
self._start_control_server()
|
|
57
|
+
shell_path, argv, env = self._shell_command()
|
|
58
|
+
pid, master_fd = pty.fork()
|
|
59
|
+
if pid == 0:
|
|
60
|
+
for signum in (signal.SIGINT, signal.SIGQUIT, signal.SIGTERM):
|
|
61
|
+
signal.signal(signum, signal.SIG_DFL)
|
|
62
|
+
try:
|
|
63
|
+
os.execvpe(shell_path, argv, env)
|
|
64
|
+
except BaseException as exc:
|
|
65
|
+
os.write(2, f"jusi-shell: {exc}\n".encode("utf-8", "replace"))
|
|
66
|
+
os._exit(127)
|
|
67
|
+
|
|
68
|
+
self.child_pid, self.master_fd = pid, master_fd
|
|
69
|
+
_set_winsize(master_fd, _winsize(sys.stdin.fileno()))
|
|
70
|
+
self._install_signal_handlers()
|
|
71
|
+
self._set_raw_terminal()
|
|
72
|
+
if self.body.strip():
|
|
73
|
+
self._send(self.body)
|
|
74
|
+
try:
|
|
75
|
+
return self._pump_terminal()
|
|
76
|
+
finally:
|
|
77
|
+
self.close()
|
|
78
|
+
|
|
79
|
+
def _shell_command(self) -> tuple[str, list[str], dict[str, str]]:
|
|
80
|
+
requested = self.requested_shell or os.environ.get("SHELL", "").strip() or "/bin/sh"
|
|
81
|
+
shell_path = shutil.which(requested) if not os.path.isabs(requested) else requested
|
|
82
|
+
if not shell_path:
|
|
83
|
+
raise RuntimeError(f"requested shell is not available: {requested}")
|
|
84
|
+
name = os.path.basename(shell_path)
|
|
85
|
+
env = os.environ.copy()
|
|
86
|
+
argv = [shell_path]
|
|
87
|
+
if name == "bash":
|
|
88
|
+
argv += ["--rcfile", self._write_bashrc(), "-i"]
|
|
89
|
+
elif name == "zsh":
|
|
90
|
+
env["ZDOTDIR"] = self.state_directory.name
|
|
91
|
+
self._write_zshrc()
|
|
92
|
+
argv.append("-i")
|
|
93
|
+
elif name == "fish":
|
|
94
|
+
argv += ["-i", "-C", self._fish_init()]
|
|
95
|
+
elif name in _INTERACTIVE_SHELLS:
|
|
96
|
+
argv.append("-i")
|
|
97
|
+
return shell_path, argv, env
|
|
98
|
+
|
|
99
|
+
def _client_command(self) -> str:
|
|
100
|
+
code = (
|
|
101
|
+
"import json,os,socket;"
|
|
102
|
+
f"s=socket.socket(socket.AF_UNIX);s.connect({self.socket_path!r});"
|
|
103
|
+
"s.sendall((json.dumps({'type':'cwd','cwd':os.getcwd()})+'\\n').encode());s.close()"
|
|
104
|
+
)
|
|
105
|
+
return f"{shlex.quote(sys.executable)} -c {shlex.quote(code)} >/dev/null 2>&1"
|
|
106
|
+
|
|
107
|
+
@staticmethod
|
|
108
|
+
def _open_command() -> str:
|
|
109
|
+
return f"{shlex.quote(sys.executable)} -m jusi.editor_client"
|
|
110
|
+
|
|
111
|
+
def _write_bashrc(self) -> str:
|
|
112
|
+
path = Path(self.state_directory.name) / "bashrc"
|
|
113
|
+
path.write_text(
|
|
114
|
+
"\n".join(
|
|
115
|
+
[
|
|
116
|
+
'if [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc"; fi',
|
|
117
|
+
'jusi-open() { case "${1-}" in -t|--tab) shift;; esac; [ "$#" -ge 1 ] || return 2; '
|
|
118
|
+
+ self._open_command()
|
|
119
|
+
+ ' "$1"; }',
|
|
120
|
+
"__jusi_emit_cwd() { " + self._client_command() + "; }",
|
|
121
|
+
"case \"${PROMPT_COMMAND-}\" in *__jusi_emit_cwd*) ;; *) PROMPT_COMMAND=\"__jusi_emit_cwd${PROMPT_COMMAND:+;$PROMPT_COMMAND}\";; esac",
|
|
122
|
+
"__jusi_emit_cwd",
|
|
123
|
+
]
|
|
124
|
+
)
|
|
125
|
+
+ "\n",
|
|
126
|
+
encoding="utf-8",
|
|
127
|
+
)
|
|
128
|
+
return str(path)
|
|
129
|
+
|
|
130
|
+
def _write_zshrc(self) -> None:
|
|
131
|
+
path = Path(self.state_directory.name) / ".zshrc"
|
|
132
|
+
path.write_text(
|
|
133
|
+
"\n".join(
|
|
134
|
+
[
|
|
135
|
+
'if [ -f "$HOME/.zshrc" ]; then . "$HOME/.zshrc"; fi',
|
|
136
|
+
'jusi-open() { case "${1-}" in -t|--tab) shift;; esac; [ "$#" -ge 1 ] || return 2; '
|
|
137
|
+
+ self._open_command()
|
|
138
|
+
+ ' "$1"; }',
|
|
139
|
+
"autoload -Uz add-zsh-hook",
|
|
140
|
+
"__jusi_emit_cwd() { " + self._client_command() + "; }",
|
|
141
|
+
"add-zsh-hook precmd __jusi_emit_cwd",
|
|
142
|
+
"__jusi_emit_cwd",
|
|
143
|
+
]
|
|
144
|
+
)
|
|
145
|
+
+ "\n",
|
|
146
|
+
encoding="utf-8",
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
def _fish_init(self) -> str:
|
|
150
|
+
return (
|
|
151
|
+
"function jusi-open; "
|
|
152
|
+
"if test (count $argv) -gt 0; and contains -- $argv[1] -t --tab; set -e argv[1]; end; "
|
|
153
|
+
"test (count $argv) -ge 1; or return 2; "
|
|
154
|
+
+ self._open_command()
|
|
155
|
+
+ " $argv[1]; end; "
|
|
156
|
+
"function __jusi_emit_cwd --on-event fish_prompt; "
|
|
157
|
+
+ self._client_command()
|
|
158
|
+
+ "; end; __jusi_emit_cwd"
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
def _start_control_server(self) -> None:
|
|
162
|
+
try:
|
|
163
|
+
os.unlink(self.socket_path)
|
|
164
|
+
except FileNotFoundError:
|
|
165
|
+
pass
|
|
166
|
+
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
167
|
+
server.bind(self.socket_path)
|
|
168
|
+
server.listen()
|
|
169
|
+
server.settimeout(0.2)
|
|
170
|
+
self.server = server
|
|
171
|
+
|
|
172
|
+
def serve() -> None:
|
|
173
|
+
while not self.stop_event.is_set():
|
|
174
|
+
try:
|
|
175
|
+
connection, _ = server.accept()
|
|
176
|
+
except socket.timeout:
|
|
177
|
+
continue
|
|
178
|
+
except OSError:
|
|
179
|
+
return
|
|
180
|
+
with connection:
|
|
181
|
+
try:
|
|
182
|
+
raw = connection.makefile("rb").readline()
|
|
183
|
+
request = json.loads(raw)
|
|
184
|
+
response = self._handle_request(request)
|
|
185
|
+
connection.sendall(json.dumps(response).encode("utf-8") + b"\n")
|
|
186
|
+
except (OSError, ValueError, TypeError, json.JSONDecodeError):
|
|
187
|
+
continue
|
|
188
|
+
|
|
189
|
+
self.server_thread = threading.Thread(target=serve, name="jusi-shell-control", daemon=True)
|
|
190
|
+
self.server_thread.start()
|
|
191
|
+
|
|
192
|
+
def _handle_request(self, request: object) -> dict[str, Any]:
|
|
193
|
+
if not isinstance(request, dict):
|
|
194
|
+
return {"ok": False, "error": "invalid request"}
|
|
195
|
+
kind = request.get("type")
|
|
196
|
+
if kind == "cwd":
|
|
197
|
+
value = str(request.get("cwd", "")).strip()
|
|
198
|
+
if value:
|
|
199
|
+
with self.state_lock:
|
|
200
|
+
self.current_cwd = value
|
|
201
|
+
return {"ok": True}
|
|
202
|
+
if kind == "status":
|
|
203
|
+
with self.state_lock:
|
|
204
|
+
cwd = self.current_cwd
|
|
205
|
+
return {"ok": True, "cwd": cwd}
|
|
206
|
+
if kind == "followup":
|
|
207
|
+
if self.returncode is not None:
|
|
208
|
+
return {"ok": False, "error": "shell has exited"}
|
|
209
|
+
self._send(str(request.get("body", "")))
|
|
210
|
+
return {"ok": True}
|
|
211
|
+
return {"ok": False, "error": f"unsupported request: {kind}"}
|
|
212
|
+
|
|
213
|
+
def _send(self, text: str) -> None:
|
|
214
|
+
data = text.encode("utf-8")
|
|
215
|
+
if not data.endswith(b"\n"):
|
|
216
|
+
data += b"\n"
|
|
217
|
+
with self.write_lock:
|
|
218
|
+
if self.master_fd < 0:
|
|
219
|
+
raise OSError("shell terminal is unavailable")
|
|
220
|
+
os.write(self.master_fd, data)
|
|
221
|
+
|
|
222
|
+
def _install_signal_handlers(self) -> None:
|
|
223
|
+
def resize(*_: object) -> None:
|
|
224
|
+
try:
|
|
225
|
+
_set_winsize(self.master_fd, _winsize(sys.stdin.fileno()))
|
|
226
|
+
except OSError:
|
|
227
|
+
pass
|
|
228
|
+
|
|
229
|
+
def forward(signum: int, _frame: object) -> None:
|
|
230
|
+
try:
|
|
231
|
+
os.killpg(self.child_pid, signum)
|
|
232
|
+
except ProcessLookupError:
|
|
233
|
+
pass
|
|
234
|
+
|
|
235
|
+
def terminate(_signum: int, _frame: object) -> None:
|
|
236
|
+
self.terminate_requested.set()
|
|
237
|
+
self.stop_event.set()
|
|
238
|
+
try:
|
|
239
|
+
os.killpg(self.child_pid, signal.SIGTERM)
|
|
240
|
+
except ProcessLookupError:
|
|
241
|
+
pass
|
|
242
|
+
|
|
243
|
+
signal.signal(signal.SIGWINCH, resize)
|
|
244
|
+
for signum in (signal.SIGINT, signal.SIGQUIT):
|
|
245
|
+
signal.signal(signum, forward)
|
|
246
|
+
signal.signal(signal.SIGTERM, terminate)
|
|
247
|
+
|
|
248
|
+
def _set_raw_terminal(self) -> None:
|
|
249
|
+
try:
|
|
250
|
+
self.saved_terminal = termios.tcgetattr(sys.stdin.fileno())
|
|
251
|
+
attrs = termios.tcgetattr(sys.stdin.fileno())
|
|
252
|
+
attrs[0] &= ~(termios.BRKINT | termios.ICRNL | termios.INPCK | termios.ISTRIP | termios.IXON)
|
|
253
|
+
attrs[1] &= ~termios.OPOST
|
|
254
|
+
attrs[2] |= termios.CS8
|
|
255
|
+
attrs[3] &= ~(termios.ECHO | termios.ICANON | termios.IEXTEN | termios.ISIG)
|
|
256
|
+
attrs[6][termios.VMIN] = 1
|
|
257
|
+
attrs[6][termios.VTIME] = 0
|
|
258
|
+
termios.tcsetattr(sys.stdin.fileno(), termios.TCSANOW, attrs)
|
|
259
|
+
except termios.error:
|
|
260
|
+
self.saved_terminal = None
|
|
261
|
+
|
|
262
|
+
def _pump_terminal(self) -> int:
|
|
263
|
+
selector = selectors.DefaultSelector()
|
|
264
|
+
selector.register(self.master_fd, selectors.EVENT_READ, "shell")
|
|
265
|
+
selector.register(sys.stdin.fileno(), selectors.EVENT_READ, "input")
|
|
266
|
+
try:
|
|
267
|
+
while not self.terminate_requested.is_set() and self._poll_child() is None:
|
|
268
|
+
for key, _ in selector.select(timeout=0.1):
|
|
269
|
+
try:
|
|
270
|
+
data = os.read(key.fd, 65536)
|
|
271
|
+
except OSError:
|
|
272
|
+
data = b""
|
|
273
|
+
if not data:
|
|
274
|
+
if key.data == "input":
|
|
275
|
+
selector.unregister(key.fd)
|
|
276
|
+
continue
|
|
277
|
+
if key.data == "input":
|
|
278
|
+
with self.write_lock:
|
|
279
|
+
os.write(self.master_fd, data)
|
|
280
|
+
else:
|
|
281
|
+
os.write(sys.stdout.fileno(), data)
|
|
282
|
+
if not self.terminate_requested.is_set():
|
|
283
|
+
while select_ready := selector.select(timeout=0.02):
|
|
284
|
+
shell_keys = [key for key, _ in select_ready if key.data == "shell"]
|
|
285
|
+
if not shell_keys:
|
|
286
|
+
break
|
|
287
|
+
try:
|
|
288
|
+
data = os.read(self.master_fd, 65536)
|
|
289
|
+
except OSError:
|
|
290
|
+
break
|
|
291
|
+
if not data:
|
|
292
|
+
break
|
|
293
|
+
os.write(sys.stdout.fileno(), data)
|
|
294
|
+
finally:
|
|
295
|
+
selector.close()
|
|
296
|
+
return int(self.returncode or 0)
|
|
297
|
+
|
|
298
|
+
def _poll_child(self) -> int | None:
|
|
299
|
+
if self.child_pid <= 0 or self.returncode is not None:
|
|
300
|
+
return self.returncode
|
|
301
|
+
try:
|
|
302
|
+
pid, status = os.waitpid(self.child_pid, os.WNOHANG)
|
|
303
|
+
except ChildProcessError:
|
|
304
|
+
self.returncode = 0
|
|
305
|
+
return self.returncode
|
|
306
|
+
if pid == 0:
|
|
307
|
+
return None
|
|
308
|
+
self.returncode = os.waitstatus_to_exitcode(status)
|
|
309
|
+
return self.returncode
|
|
310
|
+
|
|
311
|
+
def close(self) -> None:
|
|
312
|
+
self.stop_event.set()
|
|
313
|
+
if self.server is not None:
|
|
314
|
+
self.server.close()
|
|
315
|
+
child_running = self.child_pid > 0 and self._poll_child() is None
|
|
316
|
+
if child_running:
|
|
317
|
+
try:
|
|
318
|
+
os.killpg(self.child_pid, signal.SIGHUP)
|
|
319
|
+
except ProcessLookupError:
|
|
320
|
+
pass
|
|
321
|
+
if self.master_fd >= 0:
|
|
322
|
+
try:
|
|
323
|
+
os.close(self.master_fd)
|
|
324
|
+
except OSError:
|
|
325
|
+
pass
|
|
326
|
+
self.master_fd = -1
|
|
327
|
+
if self.saved_terminal is not None:
|
|
328
|
+
try:
|
|
329
|
+
termios.tcsetattr(sys.stdin.fileno(), termios.TCSANOW, self.saved_terminal)
|
|
330
|
+
except termios.error:
|
|
331
|
+
pass
|
|
332
|
+
self.state_directory.cleanup()
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _read_launch(path: Path) -> dict[str, Any]:
|
|
336
|
+
try:
|
|
337
|
+
value = json.loads(path.read_text(encoding="utf-8"))
|
|
338
|
+
finally:
|
|
339
|
+
path.unlink(missing_ok=True)
|
|
340
|
+
if not isinstance(value, dict):
|
|
341
|
+
raise ValueError("invalid shell launch payload")
|
|
342
|
+
return value
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def main(argv: list[str] | None = None) -> int:
|
|
346
|
+
parser = argparse.ArgumentParser(prog="python -m jusi_shell.application")
|
|
347
|
+
parser.add_argument("launch_path", type=Path)
|
|
348
|
+
parser.add_argument("socket_path")
|
|
349
|
+
args = parser.parse_args(argv)
|
|
350
|
+
return ShellApplication(_read_launch(args.launch_path), args.socket_path).run()
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
if __name__ == "__main__":
|
|
354
|
+
raise SystemExit(main())
|
jusi_shell/catalog.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Discovery-only catalog entry; runtime modules are deliberately not imported."""
|
|
2
|
+
|
|
3
|
+
from . import __version__
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def catalog_entry() -> dict[str, object]:
|
|
7
|
+
return {
|
|
8
|
+
"plugin_id": "jusi_shell",
|
|
9
|
+
"plugin_version": __version__,
|
|
10
|
+
"distribution": "jusi-shell",
|
|
11
|
+
"families": [
|
|
12
|
+
{
|
|
13
|
+
"family_id": "shell",
|
|
14
|
+
"magic_name": "shell",
|
|
15
|
+
"capabilities": ["execute", "followup", "complete", "editor_actions"],
|
|
16
|
+
"presentation": {"syntax": "sh", "indent": "sh"},
|
|
17
|
+
}
|
|
18
|
+
],
|
|
19
|
+
"kernel_extensions": ["jusi_shell.kernel"],
|
|
20
|
+
"worker_entry_point": "jusi_shell.worker:create_worker",
|
|
21
|
+
"media_types": ["text/x-ansi"],
|
|
22
|
+
"interaction": "terminal_interactive",
|
|
23
|
+
}
|
jusi_shell/completion.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _active_word(prefix: str) -> tuple[str, int]:
|
|
9
|
+
line_start = prefix.rfind("\n") + 1
|
|
10
|
+
line = prefix[line_start:]
|
|
11
|
+
index = len(line)
|
|
12
|
+
while index > 0 and not line[index - 1].isspace():
|
|
13
|
+
index -= 1
|
|
14
|
+
return line[index:], line_start + index
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def complete_paths(payload: dict[str, Any], cwd: str) -> dict[str, list[dict[str, Any]]]:
|
|
18
|
+
prefix = str(payload.get("prefix", ""))
|
|
19
|
+
cursor_pos = payload.get("cursor_pos")
|
|
20
|
+
if not isinstance(cursor_pos, int) or cursor_pos != len(prefix):
|
|
21
|
+
return {"items": []}
|
|
22
|
+
|
|
23
|
+
word, start = _active_word(prefix)
|
|
24
|
+
line_before_word = prefix[prefix.rfind("\n", 0, start) + 1:start]
|
|
25
|
+
if not word or ("/" not in word and not line_before_word.strip()):
|
|
26
|
+
return {"items": []}
|
|
27
|
+
|
|
28
|
+
slash = word.rfind("/")
|
|
29
|
+
typed_parent = word[: slash + 1] if slash >= 0 else ""
|
|
30
|
+
name_prefix = word[slash + 1:]
|
|
31
|
+
expanded_parent = Path(os.path.expanduser(typed_parent or "."))
|
|
32
|
+
search_parent = expanded_parent if expanded_parent.is_absolute() else Path(cwd) / expanded_parent
|
|
33
|
+
|
|
34
|
+
items: list[dict[str, Any]] = []
|
|
35
|
+
try:
|
|
36
|
+
entries = sorted(search_parent.iterdir(), key=lambda item: item.name.casefold())
|
|
37
|
+
except OSError:
|
|
38
|
+
return {"items": []}
|
|
39
|
+
for entry in entries:
|
|
40
|
+
if not entry.name.startswith(name_prefix):
|
|
41
|
+
continue
|
|
42
|
+
text = typed_parent + entry.name
|
|
43
|
+
if entry.is_dir():
|
|
44
|
+
text += "/"
|
|
45
|
+
items.append(
|
|
46
|
+
{
|
|
47
|
+
"text": text,
|
|
48
|
+
"label": entry.name,
|
|
49
|
+
"kind": "dir" if entry.is_dir() else "file",
|
|
50
|
+
"detail": str(entry),
|
|
51
|
+
"start": start,
|
|
52
|
+
"end": cursor_pos,
|
|
53
|
+
}
|
|
54
|
+
)
|
|
55
|
+
return {"items": items}
|
jusi_shell/control.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import socket
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def exchange(socket_path: str, request: dict[str, Any], *, timeout: float = 3.0) -> dict[str, Any]:
|
|
9
|
+
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
|
|
10
|
+
connection.settimeout(timeout)
|
|
11
|
+
connection.connect(socket_path)
|
|
12
|
+
stream = connection.makefile("rwb")
|
|
13
|
+
with stream:
|
|
14
|
+
stream.write(json.dumps(request).encode("utf-8") + b"\n")
|
|
15
|
+
stream.flush()
|
|
16
|
+
raw = stream.readline()
|
|
17
|
+
if not raw:
|
|
18
|
+
raise ConnectionError("shell application closed the control connection")
|
|
19
|
+
result = json.loads(raw)
|
|
20
|
+
if not isinstance(result, dict):
|
|
21
|
+
raise ValueError("invalid shell application response")
|
|
22
|
+
return result
|
jusi_shell/kernel.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
import shlex
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from IPython.core.error import UsageError
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
HANDOFF_MIME = "application/vnd.jusi.handoff.v1+json"
|
|
14
|
+
_runtime_configuration: dict[str, Any] = {}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class _ArgumentParser(argparse.ArgumentParser):
|
|
18
|
+
def error(self, message: str) -> None: # type: ignore[override]
|
|
19
|
+
raise UsageError(message)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _parser() -> argparse.ArgumentParser:
|
|
23
|
+
parser = _ArgumentParser(prog="%%shell", add_help=False)
|
|
24
|
+
parser.add_argument("-C", "--cwd", default="")
|
|
25
|
+
parser.add_argument("shell_name", nargs="?", default="")
|
|
26
|
+
return parser
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def jusi_kernel_adapter_v1() -> dict[str, object]:
|
|
30
|
+
return {
|
|
31
|
+
"plugin_id": "jusi_shell",
|
|
32
|
+
"plugin_version": __version__,
|
|
33
|
+
"families": [{"family_id": "shell", "magic_name": "shell"}],
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def configure_jusi_runtime_v1(configuration: dict[str, Any]) -> None:
|
|
38
|
+
global _runtime_configuration
|
|
39
|
+
_runtime_configuration = dict(configuration)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _default_shell() -> str:
|
|
43
|
+
shell = _runtime_configuration.get("shell")
|
|
44
|
+
if not isinstance(shell, dict):
|
|
45
|
+
return ""
|
|
46
|
+
return str(shell.get("default", shell.get("default_shell", ""))).strip()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def load_ipython_extension(ipython: Any) -> None:
|
|
50
|
+
cell_magics = getattr(getattr(ipython, "magics_manager", None), "magics", {}).get("cell", {})
|
|
51
|
+
if "shell" in cell_magics:
|
|
52
|
+
return
|
|
53
|
+
|
|
54
|
+
def _jusi_shell_magic(line: str, cell: str) -> None:
|
|
55
|
+
from IPython.display import display
|
|
56
|
+
|
|
57
|
+
args = _parser().parse_args(shlex.split(line))
|
|
58
|
+
shell_name = str(args.shell_name or "").strip() or _default_shell()
|
|
59
|
+
cwd = str(args.cwd or "").strip()
|
|
60
|
+
if cwd:
|
|
61
|
+
cwd = os.path.abspath(os.path.expanduser(cwd))
|
|
62
|
+
payload = {
|
|
63
|
+
"protocol_version": 1,
|
|
64
|
+
"kind": "plugin.handoff",
|
|
65
|
+
"plugin_id": "jusi_shell",
|
|
66
|
+
"plugin_version": __version__,
|
|
67
|
+
"family_id": "shell",
|
|
68
|
+
"magic_name": "shell",
|
|
69
|
+
"payload": {"shell": shell_name, "cwd": cwd, "body": str(cell or "")},
|
|
70
|
+
}
|
|
71
|
+
display({HANDOFF_MIME: payload}, raw=True)
|
|
72
|
+
|
|
73
|
+
ipython.register_magic_function(_jusi_shell_magic, magic_kind="cell", magic_name="shell")
|
jusi_shell/worker.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import shutil
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
import time
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from jusi.plugin_api import OperationRejected, WorkerResult, copy_text, open_text, show_diff, terminal_surface
|
|
13
|
+
|
|
14
|
+
from .completion import complete_paths
|
|
15
|
+
from .control import exchange
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _followup_body(body: str) -> str:
|
|
19
|
+
"""Remove this plugin's cell-magic header from a frontend followup."""
|
|
20
|
+
first_line, separator, remainder = body.partition("\n")
|
|
21
|
+
header = first_line.strip()
|
|
22
|
+
if header == "%%shell" or header.startswith(("%%shell ", "%%shell\t")):
|
|
23
|
+
return remainder if separator else ""
|
|
24
|
+
return body
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ShellWorker:
|
|
28
|
+
def __init__(self, context: object) -> None:
|
|
29
|
+
self.context = context
|
|
30
|
+
self.runtime_directory: Path | None = None
|
|
31
|
+
self.socket_path = ""
|
|
32
|
+
self.cwd = ""
|
|
33
|
+
|
|
34
|
+
def handle(self, operation: str, payload: dict[str, Any]) -> WorkerResult:
|
|
35
|
+
if operation == "execute":
|
|
36
|
+
return self._execute(payload)
|
|
37
|
+
if operation == "followup":
|
|
38
|
+
self._request({"type": "followup", "body": _followup_body(str(payload.get("body", "")))})
|
|
39
|
+
return WorkerResult({"accepted": True})
|
|
40
|
+
if operation == "complete":
|
|
41
|
+
status = self._request({"type": "status"})
|
|
42
|
+
cwd = str(status.get("cwd", "")).strip() or self.cwd
|
|
43
|
+
return WorkerResult(complete_paths(payload, cwd))
|
|
44
|
+
if operation == "editor_action":
|
|
45
|
+
return self._editor_action(payload)
|
|
46
|
+
raise OperationRejected(f"Unsupported shell operation: {operation}", reason="unsupported")
|
|
47
|
+
|
|
48
|
+
def _execute(self, payload: dict[str, Any]) -> WorkerResult:
|
|
49
|
+
if self.runtime_directory is not None:
|
|
50
|
+
raise OperationRejected("Shell client is already initialized", reason="conflict")
|
|
51
|
+
cwd = str(payload.get("cwd", "")).strip() or os.getcwd()
|
|
52
|
+
cwd = os.path.abspath(os.path.expanduser(cwd))
|
|
53
|
+
if not os.path.isdir(cwd):
|
|
54
|
+
raise OperationRejected(f"Shell working directory does not exist: {cwd}", reason="invalid_request")
|
|
55
|
+
|
|
56
|
+
shell_name = str(payload.get("shell", "")).strip()
|
|
57
|
+
if shell_name and shutil.which(shell_name) is None:
|
|
58
|
+
raise OperationRejected(f"Requested shell is not available: {shell_name}", reason="invalid_request")
|
|
59
|
+
|
|
60
|
+
self.runtime_directory = Path(tempfile.mkdtemp(prefix="jusi-shell-"))
|
|
61
|
+
self.runtime_directory.chmod(0o700)
|
|
62
|
+
self.socket_path = str(self.runtime_directory / "control.sock")
|
|
63
|
+
self.cwd = cwd
|
|
64
|
+
payload_path = self.runtime_directory / "launch.json"
|
|
65
|
+
fd = os.open(payload_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
66
|
+
try:
|
|
67
|
+
with os.fdopen(fd, "w", encoding="utf-8") as stream:
|
|
68
|
+
json.dump({"body": str(payload.get("body", "")), "shell": shell_name}, stream)
|
|
69
|
+
except BaseException:
|
|
70
|
+
self.close()
|
|
71
|
+
raise
|
|
72
|
+
|
|
73
|
+
return WorkerResult(
|
|
74
|
+
{"accepted": True, "cwd": cwd},
|
|
75
|
+
(
|
|
76
|
+
terminal_surface(
|
|
77
|
+
"shell_terminal",
|
|
78
|
+
(sys.executable, "-m", "jusi_shell.application", str(payload_path), self.socket_path),
|
|
79
|
+
cwd=cwd,
|
|
80
|
+
environment_overrides={"TERM": os.environ.get("JUSI_SHELL_TERM", "").strip() or "xterm-256color"},
|
|
81
|
+
signal=True,
|
|
82
|
+
),
|
|
83
|
+
),
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
def _request(self, request: dict[str, Any]) -> dict[str, Any]:
|
|
87
|
+
if self.runtime_directory is None:
|
|
88
|
+
raise OperationRejected("Shell client is not initialized", reason="conflict")
|
|
89
|
+
deadline = time.monotonic() + 3.0
|
|
90
|
+
while True:
|
|
91
|
+
try:
|
|
92
|
+
result = exchange(self.socket_path, request)
|
|
93
|
+
break
|
|
94
|
+
except (ConnectionError, FileNotFoundError, OSError, ValueError) as exc:
|
|
95
|
+
if time.monotonic() >= deadline:
|
|
96
|
+
raise OperationRejected("Shell application is not available", reason="conflict") from exc
|
|
97
|
+
time.sleep(0.02)
|
|
98
|
+
if not result.get("ok"):
|
|
99
|
+
raise OperationRejected(str(result.get("error", "Shell request failed")))
|
|
100
|
+
return result
|
|
101
|
+
|
|
102
|
+
@staticmethod
|
|
103
|
+
def _editor_action(payload: dict[str, Any]) -> WorkerResult:
|
|
104
|
+
selection = payload.get("selection")
|
|
105
|
+
if not isinstance(selection, dict):
|
|
106
|
+
raise OperationRejected("Shell selection is missing", reason="invalid_request")
|
|
107
|
+
action = str(payload.get("action", ""))
|
|
108
|
+
if action == "show_diff":
|
|
109
|
+
before, after = selection.get("before"), selection.get("after")
|
|
110
|
+
if not isinstance(before, str) or not isinstance(after, str):
|
|
111
|
+
raise OperationRejected("Shell diff selection requires before and after text", reason="invalid_request")
|
|
112
|
+
return show_diff(before, after, filetype="sh")
|
|
113
|
+
text = selection.get("text")
|
|
114
|
+
if not isinstance(text, str):
|
|
115
|
+
raise OperationRejected("Shell selection requires text", reason="invalid_request")
|
|
116
|
+
if action == "copy":
|
|
117
|
+
return copy_text(text, linewise=bool(selection.get("linewise", False)))
|
|
118
|
+
if action == "open":
|
|
119
|
+
return open_text(text, name="shell-selection.sh", filetype="sh")
|
|
120
|
+
raise OperationRejected(f"Unsupported editor action: {action}", reason="unsupported")
|
|
121
|
+
|
|
122
|
+
def close(self) -> None:
|
|
123
|
+
if self.runtime_directory is not None:
|
|
124
|
+
shutil.rmtree(self.runtime_directory, ignore_errors=True)
|
|
125
|
+
self.runtime_directory = None
|
|
126
|
+
self.socket_path = ""
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def create_worker(context: object) -> ShellWorker:
|
|
130
|
+
return ShellWorker(context)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: jusi-shell
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Shell plugin for Jusi
|
|
5
|
+
Author: Jusi contributors
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2025 notawhaleble
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
License-File: LICENSE
|
|
28
|
+
Requires-Python: >=3.9
|
|
29
|
+
Requires-Dist: jusi<2,>=1.0
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# jusi-shell
|
|
33
|
+
|
|
34
|
+
An interactive shell plugin for Jusi 1.0.
|
|
35
|
+
|
|
36
|
+
- `%%shell` starts the configured/default shell.
|
|
37
|
+
- `%%shell bash` selects a shell executable.
|
|
38
|
+
- `%%shell --cwd PATH` (or `-C PATH`) starts in an optional working directory.
|
|
39
|
+
- Follow-up cells are sent literally to the same live shell.
|
|
40
|
+
- Path completion follows the shell's current directory and uses explicit Jusi
|
|
41
|
+
1.0 replacement ranges. Absolute input produces absolute completion text;
|
|
42
|
+
relative input stays relative.
|
|
43
|
+
- `jusi-open PATH` sends the target-side file contents to the owning editor.
|
|
44
|
+
The legacy `-t`/`--tab` spelling remains accepted, but Jusi 1.0 owns the
|
|
45
|
+
destination window rather than exposing split/tab placement to plugins.
|
|
46
|
+
|
|
47
|
+
Configuration may select a default executable:
|
|
48
|
+
|
|
49
|
+
```json
|
|
50
|
+
{"shell": {"default": "zsh"}}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The plugin is discovered through the `jusi.plugins.v1` entry-point group.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
jusi_shell/__init__.py,sha256=jn9B9S6_N0EQShdcc5THiGAWx5am8BXeTPoLmF1hvYQ,91
|
|
2
|
+
jusi_shell/application.py,sha256=8UTPJ-JQcssK0b6xaqQBtL0kqEfS6XHQU-UqDTWPJrE,13181
|
|
3
|
+
jusi_shell/catalog.py,sha256=kJNug3NU7m1WFl0nrV1y9MsQ_O-QR61caw7kVryj2OE,780
|
|
4
|
+
jusi_shell/completion.py,sha256=cdPgGU1aN4okqcJEgW1iObMl_1PzAuFieHRzsVmtSgU,1833
|
|
5
|
+
jusi_shell/control.py,sha256=qtPhantixObrltQg883qUKt65pGD7PrmRwX72Ls_JrE,782
|
|
6
|
+
jusi_shell/kernel.py,sha256=OG-4a6bEZYpWLWXWryjc6RZ0mARqCc3VILpLUBmFZ5E,2266
|
|
7
|
+
jusi_shell/worker.py,sha256=hFoCURoQp72Z4MyEHO-mMV_RTTKUl4EARXxenWGGoVs,5689
|
|
8
|
+
jusi_shell-0.2.0.dist-info/METADATA,sha256=Mo-DNnWRVxzD7Kkkcrv4KR_u1BUFbugOYd6NeC5Tyhg,2334
|
|
9
|
+
jusi_shell-0.2.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
10
|
+
jusi_shell-0.2.0.dist-info/entry_points.txt,sha256=0DhVTa2D7C67Tac7XeJxV6lASxakTmBXq91zKozXY8M,64
|
|
11
|
+
jusi_shell-0.2.0.dist-info/licenses/LICENSE,sha256=lwMfAmf9Ge2qppMaQqO-kqV6ahJeVyRQT077xjdWM10,1069
|
|
12
|
+
jusi_shell-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 notawhaleble
|
|
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.
|