@ebowwa/terminal 0.2.0

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.
package/dist/scp.js ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * SCP/SFTP file transfer operations
3
+ * Uses SSH connection pool and SFTP for efficient transfers
4
+ */
5
+ import { SSHError } from "./error.js";
6
+ import { SCPOptionsSchema } from '@ebowwa/codespaces-types/runtime/ssh';
7
+ import { getSSHPool } from './pool.js';
8
+ /**
9
+ * Upload a file to remote server via SFTP
10
+ * @param options - SCP options including source and destination
11
+ * @returns True if successful
12
+ */
13
+ export async function scpUpload(options) {
14
+ // Validate inputs with Zod
15
+ const validated = SCPOptionsSchema.safeParse(options);
16
+ if (!validated.success) {
17
+ throw new Error(`Invalid SCP options: ${validated.error.issues.map(i => i.message).join(', ')}`);
18
+ }
19
+ const { host, user = "root", timeout = 30, port = 22, keyPath, source, destination, recursive = false, preserve = false, } = validated.data;
20
+ try {
21
+ const pool = getSSHPool();
22
+ const ssh = await pool.getConnection({ host, user, port, keyPath, timeout });
23
+ // Use SFTP for file transfer
24
+ await ssh.putFile(source, destination, null, {
25
+ mode: recursive ? 'recursive' : undefined,
26
+ });
27
+ return true;
28
+ }
29
+ catch (error) {
30
+ throw new SSHError(`SFTP upload failed: ${source} -> ${destination}`, error);
31
+ }
32
+ }
33
+ /**
34
+ * Download a file from remote server via SFTP
35
+ * @param options - SCP options including source (remote) and destination (local)
36
+ * @returns True if successful
37
+ */
38
+ export async function scpDownload(options) {
39
+ // Validate inputs with Zod
40
+ const validated = SCPOptionsSchema.safeParse(options);
41
+ if (!validated.success) {
42
+ throw new Error(`Invalid SCP options: ${validated.error.issues.map(i => i.message).join(', ')}`);
43
+ }
44
+ const { host, user = "root", timeout = 30, port = 22, keyPath, source, destination, recursive = false, preserve = false, } = validated.data;
45
+ try {
46
+ const pool = getSSHPool();
47
+ const ssh = await pool.getConnection({ host, user, port, keyPath, timeout });
48
+ // Use SFTP for file transfer
49
+ await ssh.getFile(destination, source, null, {
50
+ mode: recursive ? 'recursive' : undefined,
51
+ });
52
+ return true;
53
+ }
54
+ catch (error) {
55
+ throw new SSHError(`SFTP download failed: ${source} -> ${destination}`, error);
56
+ }
57
+ }
58
+ /**
59
+ * Upload a directory to remote server via SFTP
60
+ * @param options - SCP options with source directory
61
+ * @returns True if successful
62
+ */
63
+ export async function scpUploadDirectory(options) {
64
+ return scpUpload({ ...options, recursive: true });
65
+ }
66
+ /**
67
+ * Download a directory from remote server via SFTP
68
+ * @param options - SCP options with source directory
69
+ * @returns True if successful
70
+ */
71
+ export async function scpDownloadDirectory(options) {
72
+ return scpDownload({ ...options, recursive: true });
73
+ }
74
+ //# sourceMappingURL=scp.js.map
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Terminal Session Management
3
+ * Handles SSH PTY session lifecycle, persistence, and querying
4
+ * Uses tmux for persistent sessions that survive disconnections
5
+ */
6
+ /**
7
+ * Terminal session interface
8
+ * Represents an active SSH PTY session
9
+ */
10
+ export interface TerminalSession {
11
+ sessionId: string;
12
+ proc: Subprocess<"pipe", "pipe", "pipe">;
13
+ stdin: import("bun").SubprocessSink;
14
+ stdout: ReadableStream<Uint8Array>;
15
+ stderr: ReadableStream<Uint8Array>;
16
+ host: string;
17
+ user: string;
18
+ ws: ServerWebSocket | null;
19
+ createdAt: number;
20
+ lastUsed: number;
21
+ reader: ReadableStreamDefaultReader<Uint8Array> | null;
22
+ stderrReader: ReadableStreamDefaultReader<Uint8Array> | null;
23
+ writer: WritableStreamDefaultWriter<Uint8Array> | null;
24
+ closed: boolean;
25
+ tmuxSessionName?: string;
26
+ bootstrapLogStreamer?: Subprocess;
27
+ }
28
+ /**
29
+ * Session info for API responses (safe to expose)
30
+ */
31
+ export interface SessionInfo {
32
+ sessionId: string;
33
+ host: string;
34
+ user: string;
35
+ createdAt: number;
36
+ lastUsed: number;
37
+ hasActiveWebSocket: boolean;
38
+ closed: boolean;
39
+ }
40
+ /**
41
+ * Clean up old sessions (older than specified milliseconds)
42
+ * Called automatically by interval timer
43
+ */
44
+ export declare function cleanupStaleSessions(maxAge?: number): void;
45
+ /**
46
+ * Close a specific session
47
+ */
48
+ export declare function closeSession(sessionId: string): Promise<boolean>;
49
+ /**
50
+ * Find or create a session for a host
51
+ * If sessionId is provided, try to reuse that specific session
52
+ * If sessionId is null/undefined, always create a new session (for multiple terminals)
53
+ * @param onProgress - Optional callback to send progress updates to WebSocket
54
+ * @param onBootstrapOutput - Optional callback to stream bootstrap log output to WebSocket
55
+ */
56
+ export declare function getOrCreateSession(host: string, user?: string, sessionId?: string | null, keyPath?: string, onProgress?: (message: string, status: "info" | "success" | "error") => void, environmentId?: string, onBootstrapOutput?: (data: string) => void): Promise<TerminalSession>;
57
+ /**
58
+ * Get a session by ID
59
+ */
60
+ export declare function getSession(sessionId: string): TerminalSession | undefined;
61
+ /**
62
+ * Get all active sessions
63
+ */
64
+ export declare function getAllSessions(): TerminalSession[];
65
+ /**
66
+ * Get session info for all sessions (safe for API responses)
67
+ */
68
+ export declare function getAllSessionInfo(): SessionInfo[];
69
+ /**
70
+ * Get session info for a specific session
71
+ */
72
+ export declare function getSessionInfo(sessionId: string): SessionInfo | undefined;
73
+ /**
74
+ * Get the total number of active sessions
75
+ */
76
+ export declare function getSessionCount(): number;
77
+ /**
78
+ * Find sessions by host
79
+ */
80
+ export declare function getSessionsByHost(host: string): TerminalSession[];
81
+ /**
82
+ * Attach a WebSocket to a session
83
+ * Sets up stdin/stdout/stderr streaming
84
+ */
85
+ export declare function attachWebSocket(session: TerminalSession, ws: ServerWebSocket, wasReused?: boolean): void;
86
+ /**
87
+ * Write data to a session's stdin
88
+ */
89
+ export declare function writeToSession(sessionId: string, data: string): Promise<boolean>;
90
+ /**
91
+ * Resize a session's PTY
92
+ */
93
+ export declare function resizeSession(sessionId: string, rows: number, cols: number): Promise<boolean>;
94
+ /**
95
+ * Detach WebSocket from session (without closing session)
96
+ */
97
+ export declare function detachWebSocket(sessionId: string, ws: ServerWebSocket): boolean;
98
+ //# sourceMappingURL=sessions.d.ts.map
@@ -0,0 +1,50 @@
1
+ /**
2
+ * SSH command execution via tmux
3
+ * Executes commands through persistent tmux sessions instead of creating new SSH connections
4
+ */
5
+ import type { SSHOptions } from "./types.js";
6
+ /**
7
+ * Execute a command via tmux session (simplified approach)
8
+ *
9
+ * DESIGN RATIONALE:
10
+ * ================
11
+ *
12
+ * Current approach: Each API call creates multiple SSH connections
13
+ * - /api/environments/:id/resources: 4 connections (9 commands distributed)
14
+ * - /api/environments/:id/node-agent: 1 connection
15
+ * - Total: 5 SSH connections per page load
16
+ *
17
+ * New approach: Use existing tmux session for all commands
18
+ * - One persistent tmux session per server (already used for terminal WebSocket)
19
+ * - Execute commands via tmux send-keys, capture output
20
+ * - Total: 1 SSH connection per server (for tmux session management)
21
+ *
22
+ * Implementation:
23
+ * - Use existing tmux session's main window
24
+ * - Send command via send-keys
25
+ * - Wait for completion
26
+ * - Capture output with capture-pane
27
+ *
28
+ * Note: This is a simplified implementation that reuses the main tmux window.
29
+ * For production, we should create dedicated windows per command.
30
+ *
31
+ * @param command - Shell command to execute
32
+ * @param options - SSH connection options
33
+ * @param timeout - Command timeout in seconds (default: 10)
34
+ * @returns Command stdout output
35
+ */
36
+ export declare function execViaTmux(command: string, options: SSHOptions, timeout?: number): Promise<string>;
37
+ /**
38
+ * Execute multiple commands in parallel via tmux
39
+ *
40
+ * Note: This creates multiple temporary windows in parallel,
41
+ * each executing one command. This is more efficient than
42
+ * sequential execution but uses more tmux windows temporarily.
43
+ *
44
+ * @param commands - Object mapping names to shell commands
45
+ * @param options - SSH connection options
46
+ * @param timeout - Per-command timeout in seconds (default: 10)
47
+ * @returns Object mapping names to command outputs
48
+ */
49
+ export declare function execViaTmuxParallel(commands: Record<string, string>, options: SSHOptions, timeout?: number): Promise<Record<string, string>>;
50
+ //# sourceMappingURL=tmux-exec.d.ts.map
package/dist/tmux.d.ts ADDED
@@ -0,0 +1,213 @@
1
+ /**
2
+ * tmux-based Terminal Sessions
3
+ * Provides persistent terminal sessions using tmux on remote servers
4
+ * Includes automatic tmux installation and session management
5
+ */
6
+ import type { SSHOptions } from "./types.js";
7
+ /**
8
+ * tmux session configuration
9
+ */
10
+ interface TmuxConfig {
11
+ /** Session name prefix for codespaces sessions */
12
+ sessionPrefix: string;
13
+ /** Default shell to use in tmux */
14
+ defaultShell: string;
15
+ /** Terminal type */
16
+ term: string;
17
+ /** Timeout for SSH commands (seconds) */
18
+ timeout: number;
19
+ /** Scrollback limit (lines) */
20
+ historyLimit: number;
21
+ /** Session age limit for cleanup (milliseconds) */
22
+ sessionAgeLimit: number;
23
+ }
24
+ /**
25
+ * Generate a tmux session name for a host
26
+ */
27
+ export declare function generateSessionName(host: string, user?: string): string;
28
+ /**
29
+ * Check if tmux is installed on the remote server
30
+ */
31
+ export declare function isTmuxInstalled(options: SSHOptions): Promise<boolean>;
32
+ /**
33
+ * Install tmux on the remote server
34
+ *
35
+ * FALLBACK MECHANISM: This should NOT be the primary installation method.
36
+ * tmux should be installed via cloud-init during initial node provisioning.
37
+ *
38
+ * This function exists for:
39
+ * - Legacy nodes provisioned before cloud-init included tmux
40
+ * - Manual node provisioning outside cheapspaces
41
+ * - Recovery scenarios where cloud-init failed
42
+ *
43
+ * @see workspace/docs/design/node-agent/TMUX-INSTALLATION.md
44
+ * @see workspace/src/lib/bootstrap/cloud-init.ts - where tmux should be added to packages
45
+ *
46
+ * Supports Debian/Ubuntu (apt) and CentOS/RHEL (yum/dnf)
47
+ */
48
+ export declare function installTmux(options: SSHOptions): Promise<{
49
+ success: boolean;
50
+ message: string;
51
+ }>;
52
+ /**
53
+ * Ensure tmux is available, installing if necessary
54
+ */
55
+ export declare function ensureTmux(options: SSHOptions): Promise<{
56
+ success: boolean;
57
+ message: string;
58
+ }>;
59
+ /**
60
+ * List existing tmux sessions on the remote server
61
+ */
62
+ export declare function listTmuxSessions(options: SSHOptions): Promise<string[]>;
63
+ /**
64
+ * Check if a specific tmux session exists
65
+ */
66
+ export declare function hasTmuxSession(sessionName: string, options: SSHOptions): Promise<boolean>;
67
+ /**
68
+ * Create or attach to a tmux session
69
+ * Returns the SSH command arguments to connect to the tmux session
70
+ */
71
+ export declare function createOrAttachTmuxSession(host: string, user?: string, keyPath?: string, config?: Partial<TmuxConfig>): Promise<{
72
+ sshArgs: string[];
73
+ sessionName: string;
74
+ newlyCreated: boolean;
75
+ }>;
76
+ /**
77
+ * Kill a tmux session on the remote server
78
+ */
79
+ export declare function killTmuxSession(sessionName: string, options: SSHOptions): Promise<boolean>;
80
+ /**
81
+ * Get tmux session information
82
+ */
83
+ export declare function getTmuxSessionInfo(sessionName: string, options: SSHOptions): Promise<{
84
+ exists: boolean;
85
+ windows?: number;
86
+ panes?: number;
87
+ } | null>;
88
+ /**
89
+ * Cleanup old tmux sessions on a remote server
90
+ * Kills sessions with matching prefix that are older than specified age limit
91
+ * @param options SSH connection options
92
+ * @param config Optional configuration (uses default age limit if not provided)
93
+ * @returns Object with cleaned count and errors
94
+ */
95
+ export declare function cleanupOldTmuxSessions(options: SSHOptions, config?: Partial<TmuxConfig>): Promise<{
96
+ cleaned: number;
97
+ errors: string[];
98
+ }>;
99
+ /**
100
+ * Get resource usage information for tmux sessions on a remote server
101
+ * @param options SSH connection options
102
+ * @returns Resource usage summary
103
+ */
104
+ export declare function getTmuxResourceUsage(options: SSHOptions): Promise<{
105
+ totalSessions: number;
106
+ codespacesSessions: number;
107
+ estimatedMemoryMB: number;
108
+ } | null>;
109
+ /**
110
+ * Send a command to a specific pane in a tmux session
111
+ * @param sessionName Target tmux session name
112
+ * @param paneIndex Pane index (default: 0 for first pane)
113
+ * @param command Command to execute (sent as keystrokes)
114
+ * @param options SSH connection options
115
+ */
116
+ export declare function sendCommandToPane(sessionName: string, command: string, paneIndex: string | undefined, options: SSHOptions): Promise<boolean>;
117
+ /**
118
+ * Split a pane horizontally or vertically in a tmux session
119
+ * @param sessionName Target tmux session name
120
+ * @param windowIndex Window index (default: 0)
121
+ * @param direction Split direction: "h" (horizontal) or "v" (vertical)
122
+ * @param command Optional command to run in the new pane
123
+ * @param options SSH connection options
124
+ * @returns The new pane index
125
+ */
126
+ export declare function splitPane(sessionName: string, direction: "h" | "v" | undefined, command: string | null | undefined, options: SSHOptions): Promise<string | null>;
127
+ /**
128
+ * List all windows in a tmux session
129
+ * @param sessionName Target tmux session name
130
+ * @param options SSH connection options
131
+ */
132
+ export declare function listSessionWindows(sessionName: string, options: SSHOptions): Promise<Array<{
133
+ index: string;
134
+ name: string;
135
+ active: boolean;
136
+ }>>;
137
+ /**
138
+ * List all panes in a tmux session window
139
+ * @param sessionName Target tmux session name
140
+ * @param windowIndex Window index (default: 0)
141
+ * @param options SSH connection options
142
+ */
143
+ export declare function listWindowPanes(sessionName: string, windowIndex: string | undefined, options: SSHOptions): Promise<Array<{
144
+ index: string;
145
+ currentPath: string;
146
+ pid: string;
147
+ active: boolean;
148
+ }>>;
149
+ /**
150
+ * Capture the current output of a pane
151
+ * @param sessionName Target tmux session name
152
+ * @param paneIndex Pane index (default: 0)
153
+ * @param options SSH connection options
154
+ */
155
+ export declare function capturePane(sessionName: string, paneIndex: string | undefined, options: SSHOptions): Promise<string | null>;
156
+ /**
157
+ * Get scrollback/history from a pane
158
+ * @param sessionName Target tmux session name
159
+ * @param paneIndex Pane index (default: 0)
160
+ * @param lines Number of lines to retrieve (default: all)
161
+ * @param options SSH connection options
162
+ */
163
+ export declare function getPaneHistory(sessionName: string, paneIndex: string | undefined, lines: number | undefined, options: SSHOptions): Promise<string | null>;
164
+ /**
165
+ * Switch to a specific window in a tmux session
166
+ * @param sessionName Target tmux session name
167
+ * @param windowIndex Target window index
168
+ * @param options SSH connection options
169
+ */
170
+ export declare function switchWindow(sessionName: string, windowIndex: string, options: SSHOptions): Promise<boolean>;
171
+ /**
172
+ * Switch to a specific pane in a tmux session window
173
+ * @param sessionName Target tmux session name
174
+ * @param paneIndex Target pane index (e.g., "0", "1", "0.1" for window.pane)
175
+ * @param options SSH connection options
176
+ */
177
+ export declare function switchPane(sessionName: string, paneIndex: string, options: SSHOptions): Promise<boolean>;
178
+ /**
179
+ * Rename a window in a tmux session
180
+ * @param sessionName Target tmux session name
181
+ * @param windowIndex Window index (default: 0)
182
+ * @param newName New window name
183
+ * @param options SSH connection options
184
+ */
185
+ export declare function renameWindow(sessionName: string, windowIndex: string, newName: string, options: SSHOptions): Promise<boolean>;
186
+ /**
187
+ * Kill a specific pane in a tmux session
188
+ * @param sessionName Target tmux session name
189
+ * @param paneIndex Pane index to kill
190
+ * @param options SSH connection options
191
+ */
192
+ export declare function killPane(sessionName: string, paneIndex: string, options: SSHOptions): Promise<boolean>;
193
+ /**
194
+ * Get detailed information about all panes in a session
195
+ * @param sessionName Target tmux session name
196
+ * @param options SSH connection options
197
+ */
198
+ export declare function getDetailedSessionInfo(sessionName: string, options: SSHOptions): Promise<{
199
+ exists: boolean;
200
+ windows: Array<{
201
+ index: string;
202
+ name: string;
203
+ active: boolean;
204
+ panes: Array<{
205
+ index: string;
206
+ currentPath: string;
207
+ pid: string;
208
+ active: boolean;
209
+ }>;
210
+ }>;
211
+ } | null>;
212
+ export {};
213
+ //# sourceMappingURL=tmux.d.ts.map