ptn 0.1.4__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.
Files changed (73) hide show
  1. porterminal/__init__.py +288 -0
  2. porterminal/__main__.py +8 -0
  3. porterminal/app.py +381 -0
  4. porterminal/application/__init__.py +1 -0
  5. porterminal/application/ports/__init__.py +7 -0
  6. porterminal/application/ports/connection_port.py +34 -0
  7. porterminal/application/services/__init__.py +13 -0
  8. porterminal/application/services/management_service.py +279 -0
  9. porterminal/application/services/session_service.py +249 -0
  10. porterminal/application/services/tab_service.py +286 -0
  11. porterminal/application/services/terminal_service.py +426 -0
  12. porterminal/asgi.py +38 -0
  13. porterminal/cli/__init__.py +19 -0
  14. porterminal/cli/args.py +91 -0
  15. porterminal/cli/display.py +157 -0
  16. porterminal/composition.py +208 -0
  17. porterminal/config.py +195 -0
  18. porterminal/container.py +65 -0
  19. porterminal/domain/__init__.py +91 -0
  20. porterminal/domain/entities/__init__.py +16 -0
  21. porterminal/domain/entities/output_buffer.py +73 -0
  22. porterminal/domain/entities/session.py +86 -0
  23. porterminal/domain/entities/tab.py +71 -0
  24. porterminal/domain/ports/__init__.py +12 -0
  25. porterminal/domain/ports/pty_port.py +80 -0
  26. porterminal/domain/ports/session_repository.py +58 -0
  27. porterminal/domain/ports/tab_repository.py +75 -0
  28. porterminal/domain/services/__init__.py +18 -0
  29. porterminal/domain/services/environment_sanitizer.py +61 -0
  30. porterminal/domain/services/rate_limiter.py +63 -0
  31. porterminal/domain/services/session_limits.py +104 -0
  32. porterminal/domain/services/tab_limits.py +54 -0
  33. porterminal/domain/values/__init__.py +25 -0
  34. porterminal/domain/values/environment_rules.py +156 -0
  35. porterminal/domain/values/rate_limit_config.py +21 -0
  36. porterminal/domain/values/session_id.py +20 -0
  37. porterminal/domain/values/shell_command.py +37 -0
  38. porterminal/domain/values/tab_id.py +24 -0
  39. porterminal/domain/values/terminal_dimensions.py +45 -0
  40. porterminal/domain/values/user_id.py +25 -0
  41. porterminal/infrastructure/__init__.py +20 -0
  42. porterminal/infrastructure/cloudflared.py +295 -0
  43. porterminal/infrastructure/config/__init__.py +9 -0
  44. porterminal/infrastructure/config/shell_detector.py +84 -0
  45. porterminal/infrastructure/config/yaml_loader.py +34 -0
  46. porterminal/infrastructure/network.py +43 -0
  47. porterminal/infrastructure/registry/__init__.py +5 -0
  48. porterminal/infrastructure/registry/user_connection_registry.py +104 -0
  49. porterminal/infrastructure/repositories/__init__.py +9 -0
  50. porterminal/infrastructure/repositories/in_memory_session.py +70 -0
  51. porterminal/infrastructure/repositories/in_memory_tab.py +124 -0
  52. porterminal/infrastructure/server.py +161 -0
  53. porterminal/infrastructure/web/__init__.py +7 -0
  54. porterminal/infrastructure/web/websocket_adapter.py +78 -0
  55. porterminal/logging_setup.py +48 -0
  56. porterminal/pty/__init__.py +46 -0
  57. porterminal/pty/env.py +97 -0
  58. porterminal/pty/manager.py +163 -0
  59. porterminal/pty/protocol.py +84 -0
  60. porterminal/pty/unix.py +162 -0
  61. porterminal/pty/windows.py +131 -0
  62. porterminal/static/assets/app-BQiuUo6Q.css +32 -0
  63. porterminal/static/assets/app-YNN_jEhv.js +71 -0
  64. porterminal/static/icon.svg +34 -0
  65. porterminal/static/index.html +139 -0
  66. porterminal/static/manifest.json +31 -0
  67. porterminal/static/sw.js +66 -0
  68. porterminal/updater.py +257 -0
  69. ptn-0.1.4.dist-info/METADATA +191 -0
  70. ptn-0.1.4.dist-info/RECORD +73 -0
  71. ptn-0.1.4.dist-info/WHEEL +4 -0
  72. ptn-0.1.4.dist-info/entry_points.txt +2 -0
  73. ptn-0.1.4.dist-info/licenses/LICENSE +661 -0
porterminal/pty/env.py ADDED
@@ -0,0 +1,97 @@
1
+ """Environment variable sanitization for PTY processes."""
2
+
3
+ import os
4
+
5
+ # Environment variables to allowlist (safe to pass to shell)
6
+ SAFE_ENV_VARS: frozenset[str] = frozenset(
7
+ {
8
+ # System paths
9
+ "PATH",
10
+ "PATHEXT",
11
+ "SYSTEMROOT",
12
+ "WINDIR",
13
+ "TEMP",
14
+ "TMP",
15
+ "COMSPEC",
16
+ # User directories
17
+ "HOME",
18
+ "USERPROFILE",
19
+ "HOMEDRIVE",
20
+ "HOMEPATH",
21
+ "LOCALAPPDATA",
22
+ "APPDATA",
23
+ "PROGRAMFILES",
24
+ "PROGRAMFILES(X86)",
25
+ "COMMONPROGRAMFILES",
26
+ # System info
27
+ "COMPUTERNAME",
28
+ "USERNAME",
29
+ "USERDOMAIN",
30
+ "OS",
31
+ "PROCESSOR_ARCHITECTURE",
32
+ "NUMBER_OF_PROCESSORS",
33
+ # Terminal
34
+ "TERM",
35
+ # Locale settings for proper text rendering
36
+ "LANG",
37
+ "LC_ALL",
38
+ "LC_CTYPE",
39
+ }
40
+ )
41
+
42
+ # Environment variables to explicitly block (secrets)
43
+ BLOCKED_ENV_VARS: frozenset[str] = frozenset(
44
+ {
45
+ # AWS
46
+ "AWS_ACCESS_KEY_ID",
47
+ "AWS_SECRET_ACCESS_KEY",
48
+ "AWS_SESSION_TOKEN",
49
+ # Azure
50
+ "AZURE_CLIENT_SECRET",
51
+ "AZURE_CLIENT_ID",
52
+ # Git/GitHub/GitLab
53
+ "GH_TOKEN",
54
+ "GITHUB_TOKEN",
55
+ "GITLAB_TOKEN",
56
+ # Package managers
57
+ "NPM_TOKEN",
58
+ # AI APIs
59
+ "ANTHROPIC_API_KEY",
60
+ "OPENAI_API_KEY",
61
+ "GOOGLE_API_KEY",
62
+ # Payment
63
+ "STRIPE_SECRET_KEY",
64
+ # Database
65
+ "DATABASE_URL",
66
+ "DB_PASSWORD",
67
+ # Generic secrets
68
+ "SECRET_KEY",
69
+ "API_KEY",
70
+ "API_SECRET",
71
+ "PRIVATE_KEY",
72
+ }
73
+ )
74
+
75
+
76
+ def build_safe_environment() -> dict[str, str]:
77
+ """Build a sanitized environment for the PTY.
78
+
79
+ Returns:
80
+ Dictionary of safe environment variables.
81
+ """
82
+ safe_env: dict[str, str] = {}
83
+
84
+ # Copy only allowed variables
85
+ for var in SAFE_ENV_VARS:
86
+ if var in os.environ:
87
+ safe_env[var] = os.environ[var]
88
+
89
+ # Ensure blocked vars are not included (defense in depth)
90
+ for var in BLOCKED_ENV_VARS:
91
+ safe_env.pop(var, None)
92
+
93
+ # Set custom variables for audit trail
94
+ safe_env["TERM"] = "xterm-256color"
95
+ safe_env["TERM_SESSION_TYPE"] = "remote-web"
96
+
97
+ return safe_env
@@ -0,0 +1,163 @@
1
+ """Secure PTY manager with security controls."""
2
+
3
+ import logging
4
+ import shutil
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING
7
+
8
+ from .env import build_safe_environment
9
+ from .protocol import PTYBackend
10
+
11
+ if TYPE_CHECKING:
12
+ from ..config import ShellConfig
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class SecurePTYManager:
18
+ """PTY manager with security controls - delegates to platform backend.
19
+
20
+ This class provides:
21
+ - Environment variable sanitization
22
+ - Shell path validation
23
+ - Bounds checking for terminal dimensions
24
+ - Unified interface across platforms
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ backend: PTYBackend,
30
+ shell_config: "ShellConfig",
31
+ cols: int = 120,
32
+ rows: int = 30,
33
+ cwd: str | None = None,
34
+ ) -> None:
35
+ """Initialize the PTY manager.
36
+
37
+ Args:
38
+ backend: Platform-specific PTY backend.
39
+ shell_config: Shell configuration (command, args).
40
+ cols: Initial terminal columns (clamped to 40-500).
41
+ rows: Initial terminal rows (clamped to 10-200).
42
+ cwd: Working directory, or None for default.
43
+ """
44
+ self._backend = backend
45
+ self.shell_config = shell_config
46
+ self.cols = max(40, min(cols, 500))
47
+ self.rows = max(10, min(rows, 200))
48
+ self.cwd = cwd
49
+ self._closed = False
50
+
51
+ def _build_command(self) -> list[str]:
52
+ """Build the shell command with arguments."""
53
+ cmd = [self.shell_config.command]
54
+ cmd.extend(self.shell_config.args)
55
+ return cmd
56
+
57
+ def spawn(self) -> "SecurePTYManager":
58
+ """Spawn the PTY process.
59
+
60
+ Returns:
61
+ Self for method chaining.
62
+
63
+ Raises:
64
+ FileNotFoundError: If shell command is not found.
65
+ """
66
+ # Verify shell exists
67
+ shell_cmd = self.shell_config.command
68
+ if not shutil.which(shell_cmd) and not Path(shell_cmd).exists():
69
+ raise FileNotFoundError(f"Shell not found: {shell_cmd}")
70
+
71
+ # Build command and environment
72
+ cmd = self._build_command()
73
+ env = build_safe_environment()
74
+
75
+ # Validate working directory
76
+ cwd = self.cwd
77
+ if cwd:
78
+ cwd_path = Path(cwd)
79
+ if not cwd_path.exists() or not cwd_path.is_dir():
80
+ logger.warning("Invalid cwd %s, using default", cwd)
81
+ cwd = None
82
+
83
+ logger.info(
84
+ "Spawning PTY cmd=%s rows=%d cols=%d cwd=%s",
85
+ cmd,
86
+ self.rows,
87
+ self.cols,
88
+ cwd,
89
+ )
90
+
91
+ self._backend.spawn(cmd, env, cwd, self.rows, self.cols)
92
+ return self
93
+
94
+ def read(self, size: int = 4096) -> bytes:
95
+ """Read from the PTY (non-blocking).
96
+
97
+ Args:
98
+ size: Maximum bytes to read.
99
+
100
+ Returns:
101
+ Bytes read, or empty bytes if nothing available or closed.
102
+ """
103
+ if self._closed:
104
+ return b""
105
+
106
+ try:
107
+ return self._backend.read(size)
108
+ except OSError as e:
109
+ logger.error("PTY read error: %s", e)
110
+ return b""
111
+
112
+ def write(self, data: bytes) -> None:
113
+ """Write to the PTY.
114
+
115
+ Args:
116
+ data: Bytes to write.
117
+ """
118
+ if self._closed:
119
+ return
120
+
121
+ try:
122
+ self._backend.write(data)
123
+ except OSError as e:
124
+ logger.error("PTY write error: %s", e)
125
+
126
+ def resize(self, cols: int, rows: int) -> None:
127
+ """Resize the PTY with bounds checking.
128
+
129
+ Args:
130
+ cols: New number of columns (clamped to 40-500).
131
+ rows: New number of rows (clamped to 10-200).
132
+ """
133
+ if self._closed:
134
+ return
135
+
136
+ cols = max(40, min(cols, 500))
137
+ rows = max(10, min(rows, 200))
138
+
139
+ try:
140
+ self._backend.resize(rows, cols)
141
+ self.cols = cols
142
+ self.rows = rows
143
+ except OSError as e:
144
+ logger.error("PTY resize error: %s", e)
145
+
146
+ def is_alive(self) -> bool:
147
+ """Check if the PTY process is still alive.
148
+
149
+ Returns:
150
+ True if process is running and not closed, False otherwise.
151
+ """
152
+ if self._closed:
153
+ return False
154
+ return self._backend.is_alive()
155
+
156
+ def close(self) -> None:
157
+ """Close the PTY and clean up resources."""
158
+ if self._closed:
159
+ return
160
+
161
+ self._closed = True
162
+ self._backend.close()
163
+ logger.info("PTY closed")
@@ -0,0 +1,84 @@
1
+ """Protocol definition for PTY backends."""
2
+
3
+ from typing import Protocol, runtime_checkable
4
+
5
+
6
+ @runtime_checkable
7
+ class PTYBackend(Protocol):
8
+ """Protocol for platform-specific PTY implementations.
9
+
10
+ This defines the interface that all PTY backends must implement.
11
+ Using a Protocol allows for structural subtyping (duck typing with type hints).
12
+ """
13
+
14
+ @property
15
+ def rows(self) -> int:
16
+ """Current number of rows."""
17
+ ...
18
+
19
+ @property
20
+ def cols(self) -> int:
21
+ """Current number of columns."""
22
+ ...
23
+
24
+ def spawn(
25
+ self,
26
+ cmd: list[str],
27
+ env: dict[str, str],
28
+ cwd: str | None,
29
+ rows: int,
30
+ cols: int,
31
+ ) -> None:
32
+ """Spawn the PTY process.
33
+
34
+ Args:
35
+ cmd: Command and arguments to execute.
36
+ env: Environment variables for the process.
37
+ cwd: Working directory, or None for default.
38
+ rows: Initial terminal rows.
39
+ cols: Initial terminal columns.
40
+
41
+ Raises:
42
+ RuntimeError: If PTY is already spawned.
43
+ """
44
+ ...
45
+
46
+ def read(self, size: int = 4096) -> bytes:
47
+ """Read from the PTY (non-blocking).
48
+
49
+ Args:
50
+ size: Maximum bytes to read.
51
+
52
+ Returns:
53
+ Bytes read, or empty bytes if nothing available.
54
+ """
55
+ ...
56
+
57
+ def write(self, data: bytes) -> None:
58
+ """Write to the PTY.
59
+
60
+ Args:
61
+ data: Bytes to write.
62
+ """
63
+ ...
64
+
65
+ def resize(self, rows: int, cols: int) -> None:
66
+ """Resize the PTY window.
67
+
68
+ Args:
69
+ rows: New number of rows.
70
+ cols: New number of columns.
71
+ """
72
+ ...
73
+
74
+ def is_alive(self) -> bool:
75
+ """Check if the PTY process is still alive.
76
+
77
+ Returns:
78
+ True if process is running, False otherwise.
79
+ """
80
+ ...
81
+
82
+ def close(self) -> None:
83
+ """Close the PTY and clean up resources."""
84
+ ...
@@ -0,0 +1,162 @@
1
+ """Unix PTY backend using the pty module."""
2
+
3
+ import logging
4
+ import os
5
+ import select
6
+ import sys
7
+ import time
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ # Unix-only imports
12
+ if sys.platform != "win32":
13
+ import fcntl
14
+ import pty
15
+ import signal
16
+ import struct
17
+ import termios
18
+
19
+
20
+ class UnixPTYBackend:
21
+ """Unix PTY implementation using the pty module."""
22
+
23
+ def __init__(self) -> None:
24
+ if sys.platform == "win32":
25
+ raise RuntimeError("UnixPTYBackend is not supported on Windows")
26
+ self._master_fd: int | None = None
27
+ self._pid: int | None = None
28
+ self._rows: int = 30
29
+ self._cols: int = 120
30
+
31
+ @property
32
+ def rows(self) -> int:
33
+ """Current number of rows."""
34
+ return self._rows
35
+
36
+ @property
37
+ def cols(self) -> int:
38
+ """Current number of columns."""
39
+ return self._cols
40
+
41
+ def spawn(
42
+ self,
43
+ cmd: list[str],
44
+ env: dict[str, str],
45
+ cwd: str | None,
46
+ rows: int,
47
+ cols: int,
48
+ ) -> None:
49
+ """Spawn PTY on Unix using pty module."""
50
+ if self._master_fd is not None:
51
+ raise RuntimeError("PTY already spawned")
52
+
53
+ self._rows = rows
54
+ self._cols = cols
55
+
56
+ self._pid, self._master_fd = pty.fork()
57
+
58
+ if self._pid == 0:
59
+ # Child process
60
+ if cwd:
61
+ os.chdir(cwd)
62
+ os.execvpe(cmd[0], cmd, env)
63
+ else:
64
+ # Parent process - set non-blocking
65
+ flags = fcntl.fcntl(self._master_fd, fcntl.F_GETFL)
66
+ fcntl.fcntl(self._master_fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
67
+ # Set initial size
68
+ self._set_winsize(rows, cols)
69
+ logger.debug("Unix PTY spawned pid=%d cmd=%s", self._pid, cmd)
70
+
71
+ def _set_winsize(self, rows: int, cols: int) -> None:
72
+ """Set window size on Unix PTY."""
73
+ if self._master_fd is None:
74
+ return
75
+ winsize = struct.pack("HHHH", rows, cols, 0, 0)
76
+ fcntl.ioctl(self._master_fd, termios.TIOCSWINSZ, winsize)
77
+
78
+ def read(self, size: int = 4096) -> bytes:
79
+ """Read from Unix PTY (non-blocking)."""
80
+ if self._master_fd is None:
81
+ return b""
82
+
83
+ readable, _, _ = select.select([self._master_fd], [], [], 0)
84
+ if not readable:
85
+ return b""
86
+
87
+ try:
88
+ data = os.read(self._master_fd, size)
89
+ if data:
90
+ logger.debug("PTY read bytes=%d", len(data))
91
+ return data
92
+ except OSError:
93
+ return b""
94
+
95
+ def write(self, data: bytes) -> None:
96
+ """Write to Unix PTY."""
97
+ if self._master_fd is None:
98
+ return
99
+ logger.debug("PTY write bytes=%d", len(data))
100
+ os.write(self._master_fd, data)
101
+
102
+ def resize(self, rows: int, cols: int) -> None:
103
+ """Resize the PTY window."""
104
+ self._set_winsize(rows, cols)
105
+ self._rows = rows
106
+ self._cols = cols
107
+ logger.debug("PTY resize rows=%d cols=%d", rows, cols)
108
+
109
+ def is_alive(self) -> bool:
110
+ """Check if the PTY process is still alive."""
111
+ if self._pid is None:
112
+ return False
113
+ try:
114
+ pid, _ = os.waitpid(self._pid, os.WNOHANG)
115
+ return pid == 0
116
+ except ChildProcessError:
117
+ return False
118
+
119
+ def close(self) -> None:
120
+ """Close the PTY and clean up resources."""
121
+ try:
122
+ if self._master_fd is not None:
123
+ os.close(self._master_fd)
124
+ self._master_fd = None
125
+
126
+ if self._pid is not None:
127
+ try:
128
+ # Send SIGTERM for graceful termination
129
+ os.kill(self._pid, signal.SIGTERM)
130
+
131
+ # Poll with WNOHANG for up to 3 seconds
132
+ grace_period_ms = 3000
133
+ poll_interval_ms = 100
134
+ elapsed = 0
135
+
136
+ while elapsed < grace_period_ms:
137
+ pid, _ = os.waitpid(self._pid, os.WNOHANG)
138
+ if pid != 0:
139
+ # Process exited gracefully
140
+ logger.debug("PTY process exited gracefully after SIGTERM")
141
+ self._pid = None
142
+ return
143
+ time.sleep(poll_interval_ms / 1000)
144
+ elapsed += poll_interval_ms
145
+
146
+ # Process didn't respond to SIGTERM, escalate to SIGKILL
147
+ logger.warning(
148
+ "PTY process %d did not respond to SIGTERM, sending SIGKILL",
149
+ self._pid,
150
+ )
151
+ os.kill(self._pid, signal.SIGKILL)
152
+ os.waitpid(self._pid, 0) # SIGKILL cannot be ignored
153
+
154
+ except (ProcessLookupError, ChildProcessError):
155
+ # Process already dead
156
+ pass
157
+ finally:
158
+ self._pid = None
159
+ except OSError as e:
160
+ logger.error("PTY close error: %s", e)
161
+ finally:
162
+ logger.info("Unix PTY closed")
@@ -0,0 +1,131 @@
1
+ """Windows PTY backend using pywinpty."""
2
+
3
+ import logging
4
+ import select
5
+ import time
6
+ from typing import Any
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ # Import pywinpty - only available on Windows
11
+ try:
12
+ from winpty import PtyProcess as WinPtyProcess
13
+
14
+ HAS_WINPTY = True
15
+ except ImportError:
16
+ WinPtyProcess = None # type: ignore[misc, assignment]
17
+ HAS_WINPTY = False
18
+
19
+
20
+ class WindowsPTYBackend:
21
+ """Windows PTY implementation using pywinpty."""
22
+
23
+ def __init__(self) -> None:
24
+ if not HAS_WINPTY:
25
+ raise RuntimeError("pywinpty is not installed")
26
+ self._pty: Any | None = None
27
+ self._rows: int = 30
28
+ self._cols: int = 120
29
+
30
+ @property
31
+ def rows(self) -> int:
32
+ """Current number of rows."""
33
+ return self._rows
34
+
35
+ @property
36
+ def cols(self) -> int:
37
+ """Current number of columns."""
38
+ return self._cols
39
+
40
+ def spawn(
41
+ self,
42
+ cmd: list[str],
43
+ env: dict[str, str],
44
+ cwd: str | None,
45
+ rows: int,
46
+ cols: int,
47
+ ) -> None:
48
+ """Spawn PTY on Windows using pywinpty."""
49
+ if self._pty is not None:
50
+ raise RuntimeError("PTY already spawned")
51
+
52
+ self._rows = rows
53
+ self._cols = cols
54
+
55
+ self._pty = WinPtyProcess.spawn(
56
+ cmd,
57
+ dimensions=(rows, cols),
58
+ env=env,
59
+ cwd=cwd,
60
+ )
61
+ logger.debug("Windows PTY spawned cmd=%s", cmd)
62
+
63
+ def read(self, size: int = 4096) -> bytes:
64
+ """Read from Windows PTY (non-blocking)."""
65
+ if self._pty is None:
66
+ return b""
67
+
68
+ # Try socket-based read first (faster)
69
+ sock = getattr(self._pty, "fileobj", None)
70
+ if sock is not None:
71
+ readable, _, _ = select.select([sock], [], [], 0)
72
+ if not readable:
73
+ return b""
74
+ data = sock.recv(size)
75
+ # Filter out pywinpty noise
76
+ if not data or data == b"0011Ignore":
77
+ return b""
78
+ logger.debug("PTY read bytes=%d", len(data))
79
+ return data
80
+
81
+ # Fallback to blocking read
82
+ data = self._pty.read(size)
83
+ data_bytes = data.encode("utf-8") if isinstance(data, str) else data
84
+ if data_bytes:
85
+ logger.debug("PTY read bytes=%d", len(data_bytes))
86
+ return data_bytes
87
+
88
+ def write(self, data: bytes) -> None:
89
+ """Write to Windows PTY."""
90
+ if self._pty is None:
91
+ return
92
+ text = data.decode("utf-8", errors="replace")
93
+ logger.debug("PTY write bytes=%d", len(data))
94
+ self._pty.write(text)
95
+
96
+ def resize(self, rows: int, cols: int) -> None:
97
+ """Resize the PTY window."""
98
+ if self._pty is None:
99
+ return
100
+ self._pty.setwinsize(rows, cols)
101
+ self._rows = rows
102
+ self._cols = cols
103
+ logger.debug("PTY resize rows=%d cols=%d", rows, cols)
104
+
105
+ def is_alive(self) -> bool:
106
+ """Check if the PTY process is still alive."""
107
+ return self._pty is not None and self._pty.isalive()
108
+
109
+ def close(self) -> None:
110
+ """Close the PTY with grace period before force kill."""
111
+ if self._pty is None:
112
+ return
113
+
114
+ try:
115
+ if self._pty.isalive():
116
+ # Try graceful termination first
117
+ self._pty.terminate(force=False)
118
+ # Wait up to 3 seconds for process to exit
119
+ for _ in range(30):
120
+ if not self._pty.isalive():
121
+ break
122
+ time.sleep(0.1)
123
+ # Force kill if still alive
124
+ if self._pty.isalive():
125
+ logger.debug("PTY did not exit gracefully, force killing")
126
+ self._pty.terminate(force=True)
127
+ except OSError as e:
128
+ logger.error("PTY close error: %s", e)
129
+ finally:
130
+ self._pty = None
131
+ logger.info("Windows PTY closed")
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.
3
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
4
+ * https://github.com/chjj/term.js
5
+ * @license MIT
6
+ *
7
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ * of this software and associated documentation files (the "Software"), to deal
9
+ * in the Software without restriction, including without limitation the rights
10
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ * copies of the Software, and to permit persons to whom the Software is
12
+ * furnished to do so, subject to the following conditions:
13
+ *
14
+ * The above copyright notice and this permission notice shall be included in
15
+ * all copies or substantial portions of the Software.
16
+ *
17
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+ * THE SOFTWARE.
24
+ *
25
+ * Originally forked from (with the author's permission):
26
+ * Fabrice Bellard's javascript vt100 for jslinux:
27
+ * http://bellard.org/jslinux/
28
+ * Copyright (c) 2011 Fabrice Bellard
29
+ * The original design remains. The terminal itself
30
+ * has been extended to include xterm CSI codes, among
31
+ * other features.
32
+ */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm .xterm-scroll-area{visibility:hidden}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{-webkit-user-select:text;user-select:text;white-space:pre}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}:root{--bg-primary: #1e1e1e;--bg-elevated: #252525;--bg-surface: #2d2d2d;--bg-gradient-top: #232323;--bg-gradient-bottom: #1a1a1a;--text-primary: #cccccc;--text-high: rgba(255, 255, 255, .9);--text-secondary: rgba(255, 255, 255, .7);--text-muted: rgba(255, 255, 255, .5);--text-disabled: rgba(255, 255, 255, .4);--border-subtle: rgba(255, 255, 255, .05);--border-light: rgba(255, 255, 255, .1);--border-medium: rgba(255, 255, 255, .15);--color-success: rgba(100, 220, 100, .8);--color-success-text: rgba(130, 230, 150, 1);--color-success-bg: rgba(100, 200, 120, .15);--color-danger: rgba(255, 100, 100, .8);--color-danger-muted: rgba(255, 120, 120, .7);--color-danger-text: rgba(255, 150, 150, 1);--color-danger-bg: rgba(255, 80, 80, .15);--color-accent: rgba(80, 160, 255, .8);--color-accent-text: rgba(150, 200, 255, 1);--color-accent-bg: rgba(80, 160, 255, .3);--color-accent-strong: rgba(80, 160, 255, .5);--hover-overlay: rgba(255, 255, 255, .05);--active-overlay: rgba(255, 255, 255, .08);--scrollbar-thumb: rgba(255, 255, 255, .15);--scrollbar-hover: rgba(255, 255, 255, .25);--cursor-color: #aeafad;--selection-bg: rgba(38, 79, 120, .5);--shadow-elevated: 0 4px 16px rgba(0, 0, 0, .5);--glow-success: 0 0 6px rgba(100, 220, 100, .4);--glow-danger: 0 0 6px rgba(255, 100, 100, .4);--glow-accent: 0 0 8px rgba(80, 160, 255, .4);--overlay-bg: rgba(0, 0, 0, .9)}.tool-btn,.tab-btn{-webkit-touch-callout:none}html,body{margin:0;padding:0;height:100%;overflow:hidden;background:var(--bg-primary);color:var(--text-primary);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;font-size:13px;position:fixed;width:100%;touch-action:none;overscroll-behavior:none}#app{display:flex;flex-direction:column;height:100%;height:100dvh;height:100svh;padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px);overflow:hidden;overscroll-behavior:none}#tab-bar{display:flex;align-items:center;height:30px;min-height:30px;background:linear-gradient(to bottom,var(--bg-gradient-top),var(--bg-gradient-bottom));border-bottom:1px solid var(--border-subtle);overflow-x:auto;overflow-y:hidden;scrollbar-width:none;-ms-overflow-style:none}#tab-bar::-webkit-scrollbar{display:none}.tab-btn{display:flex;align-items:center;gap:2px;height:30px;padding:0 2px 0 8px;background:transparent;border:none;border-right:1px solid var(--border-subtle);color:var(--text-muted);font-size:12px;cursor:pointer;white-space:nowrap;flex-shrink:0;transition:all .15s ease}.tab-btn:active{background:var(--hover-overlay)}.tab-btn.active{background:var(--active-overlay);color:var(--text-high)}.tab-btn.tab-add{color:var(--text-disabled);font-size:18px;padding:0 10px;border-right:none}.tab-btn.tab-add:active{color:#fffc}.tab-label{max-width:100px;overflow:hidden;text-overflow:ellipsis}.tab-close{display:flex;align-items:center;justify-content:center;width:16px;height:16px;margin-left:2px;border-radius:4px;font-size:14px;color:var(--text-disabled);transition:all .15s ease;position:relative;overflow:hidden}.tab-close:before{content:"";position:absolute;top:0;left:0;width:100%;height:100%;background:var(--color-danger-bg);transform:scaleX(0);transform-origin:left;transition:transform .4s ease-out;z-index:-1}.tab-close.holding:before{transform:scaleX(1)}.tab-close.holding{color:var(--color-danger-text)}.tab-close.ready{background:var(--color-danger-bg);color:var(--color-danger-text);animation:pulseReady .3s ease}@keyframes pulseReady{0%,to{transform:scale(1)}50%{transform:scale(1.1)}}#shell-selector{margin-left:auto;display:flex;align-items:center;padding:0 12px;height:30px;border-left:1px solid var(--border-subtle)}#shell-select{background:transparent;border:none;color:#fff9;font-size:11px;padding:4px 8px;cursor:pointer;-webkit-appearance:none;-moz-appearance:none;appearance:none}#connection-dot{width:6px;height:6px;border-radius:50%;background:var(--color-danger);margin-left:12px;margin-right:8px;box-shadow:var(--glow-danger);flex-shrink:0}#connection-dot.connected{background:var(--color-success);box-shadow:var(--glow-success)}#btn-info,#btn-textview,#btn-shutdown{background:transparent;border:none;color:var(--text-disabled);font-size:14px;padding:4px;margin-left:4px;cursor:pointer;transition:color .15s ease}#btn-info:active,#btn-textview:active{color:var(--color-accent)}#btn-shutdown{color:var(--color-danger-muted)}#btn-shutdown:active{color:var(--color-danger-text)}#terminal-container{flex:1;overflow:hidden;background:var(--bg-primary);-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;touch-action:none;overscroll-behavior:contain;contain:strict;isolation:isolate}#terminal{height:100%!important;width:100%!important;contain:layout paint}.terminal-instance{height:100%;width:100%;contain:layout paint}.xterm-screen canvas,.xterm canvas{transform:translateZ(0);backface-visibility:hidden}#terminal .xterm-viewport{background:var(--bg-primary)!important;touch-action:none;overscroll-behavior:contain;contain:paint}#terminal .xterm-viewport::-webkit-scrollbar{width:8px}#terminal .xterm-viewport::-webkit-scrollbar-track{background:transparent}#terminal .xterm-viewport::-webkit-scrollbar-thumb{background:var(--scrollbar-thumb);border-radius:4px}#terminal .xterm-viewport::-webkit-scrollbar-thumb:hover{background:var(--scrollbar-hover)}#terminal .xterm-screen{-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}#terminal .xterm-helper-textarea,.xterm-helper-textarea{-webkit-text-security:none!important;font-size:16px!important;-webkit-user-select:text;user-select:text}.xterm-helper-textarea::-webkit-contacts-auto-fill-button,.xterm-helper-textarea::-webkit-credentials-auto-fill-button{visibility:hidden;display:none!important;pointer-events:none;position:absolute;right:0;width:0;height:0}#toolbar{display:flex;flex-direction:column;background:linear-gradient(to bottom,var(--bg-gradient-top),var(--bg-gradient-bottom));border-top:1px solid var(--border-subtle);padding-bottom:env(safe-area-inset-bottom,0px)}.toolbar-row{display:flex;align-items:center;justify-content:center;height:30px;min-height:30px;gap:0;overflow-x:auto;overflow-y:hidden;scrollbar-width:none;-ms-overflow-style:none}.toolbar-row:first-child{border-bottom:1px solid var(--border-subtle)}.toolbar-row::-webkit-scrollbar{display:none}.tool-btn{display:flex;align-items:center;justify-content:center;height:30px;padding:0 10px;background:transparent;border:none;border-right:1px solid var(--border-subtle);border-radius:0;color:var(--text-muted);font-size:12px;cursor:pointer;transition:all .15s ease;-webkit-touch-callout:none;flex-shrink:0}.tool-btn:active{background:var(--hover-overlay);color:var(--text-high)}.tool-btn.arrow{padding:0 10px}.tool-btn.danger{color:var(--color-danger-muted)}.tool-btn.danger:active{background:var(--color-danger-bg);color:var(--color-danger-text)}.tool-btn.modifier{padding:0 10px}.tool-btn.icon{font-size:18px}.tool-btn.enter{color:#64c878cc}.tool-btn.enter:active{background:var(--color-success-bg);color:var(--color-success-text)}.tool-btn.sticky{background:var(--color-accent-bg);color:var(--color-accent-text)}.tool-btn.locked{background:var(--color-accent-strong);color:#fff;box-shadow:var(--glow-accent)}#disconnect-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background:var(--overlay-bg);z-index:1000;display:flex;align-items:center;justify-content:center}#disconnect-content{text-align:center}#disconnect-icon{font-size:48px;color:var(--color-danger);margin-bottom:16px}#disconnect-text{color:var(--text-secondary);font-size:18px;margin-bottom:24px}#disconnect-retry{padding:12px 32px;background:var(--border-light);border:1px solid var(--border-medium);border-radius:8px;color:#fffc;font-size:14px;cursor:pointer;transition:all .15s ease}#disconnect-retry:active{background:#fff3;color:#fff}#copy-button{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);padding:8px 20px;background:linear-gradient(to bottom,var(--bg-surface),var(--bg-elevated));border:1px solid var(--border-light);border-radius:6px;color:var(--text-high);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;font-size:13px;font-weight:500;cursor:pointer;z-index:10000;box-shadow:var(--shadow-elevated);display:none;-webkit-tap-highlight-color:transparent;-webkit-touch-callout:none;touch-action:manipulation;transition:all .15s ease}#copy-button:active{background:linear-gradient(to bottom,#3a3a3a,var(--bg-surface));transform:translate(-50%,-50%) scale(.97)}#copy-button.visible{display:block;animation:copyButtonAppear .1s ease-out}#copy-button.success{background:linear-gradient(to bottom,#2a3a2a,#1f2f1f);border-color:#64c8784d;color:var(--color-success-text)}#copy-button.error{background:linear-gradient(to bottom,#3a2a2a,#2f1f1f);border-color:#ff78784d;color:var(--color-danger-text)}@keyframes copyButtonAppear{0%{opacity:0;transform:translate(-50%,-50%) scale(.9)}to{opacity:1;transform:translate(-50%,-50%) scale(1)}}#help-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background:var(--overlay-bg);z-index:1000;display:flex;align-items:center;justify-content:center;padding:20px}#help-content{background:var(--bg-elevated);border:1px solid var(--border-light);border-radius:12px;max-width:320px;width:100%;box-shadow:var(--shadow-elevated);animation:helpAppear .15s ease-out}@keyframes helpAppear{0%{opacity:0;transform:scale(.95)}to{opacity:1;transform:scale(1)}}#help-header{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid var(--border-subtle);color:var(--text-high);font-size:14px;font-weight:500}#help-close{background:transparent;border:none;color:var(--text-muted);font-size:20px;cursor:pointer;padding:4px 8px;line-height:1}#help-close:active{color:var(--text-high)}#help-body{padding:12px 16px}.help-section{margin-bottom:12px}.help-section:last-child{margin-bottom:0}.help-title{color:var(--text-muted);font-size:10px;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px}.help-item{display:flex;align-items:center;gap:10px;padding:4px 0;color:var(--text-secondary);font-size:12px}.help-key{display:inline-block;min-width:80px;padding:2px 6px;background:var(--bg-surface);border:1px solid var(--border-subtle);border-radius:4px;color:var(--text-high);font-size:11px;text-align:center}#textview-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background:var(--bg-primary);z-index:1000;display:flex;flex-direction:column;padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px)}#textview-content{display:flex;flex-direction:column;width:100%;height:100%;background:var(--bg-primary)}#textview-header{display:flex;align-items:center;height:30px;min-height:30px;background:linear-gradient(to bottom,var(--bg-gradient-top),var(--bg-gradient-bottom));border-bottom:1px solid var(--border-subtle);flex-shrink:0}#textview-title{padding:0 12px;color:var(--text-muted);font-size:12px;border-right:1px solid var(--border-subtle)}.textview-zoom-btn{display:flex;align-items:center;justify-content:center;height:30px;padding:0 12px;background:transparent;border:none;border-right:1px solid var(--border-subtle);color:var(--text-muted);font-size:14px;cursor:pointer;transition:all .15s ease}.textview-zoom-btn:active{background:var(--hover-overlay);color:var(--text-high)}#textview-close{margin-left:auto;display:flex;align-items:center;justify-content:center;height:30px;padding:0 12px;background:transparent;border:none;border-left:1px solid var(--border-subtle);color:var(--text-muted);font-size:16px;cursor:pointer;transition:all .15s ease}#textview-close:active{background:var(--hover-overlay);color:var(--text-high)}#textview-body{flex:1;min-height:0;margin:0;padding:8px 12px;background:var(--bg-primary);border:none;color:var(--text-primary);font-family:Menlo,Monaco,Consolas,monospace;font-size:10px;line-height:1.3;overflow-y:auto;white-space:pre-wrap;word-wrap:break-word;user-select:text;-webkit-user-select:text}.hidden{display:none!important}@media(prefers-reduced-motion:reduce){*,*:before,*:after{animation-duration:.01ms!important;transition-duration:.01ms!important}}