pty-manager 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Jakob Grant
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.
package/README.md ADDED
@@ -0,0 +1,267 @@
1
+ # pty-manager
2
+
3
+ PTY session manager with lifecycle management, pluggable adapters, and blocking prompt detection.
4
+
5
+ ## Features
6
+
7
+ - **Multi-session management** - Spawn and manage multiple PTY sessions concurrently
8
+ - **Pluggable adapters** - Built-in shell adapter, easy to create custom adapters for Docker, SSH, or any CLI tool
9
+ - **Blocking prompt detection** - Detect login prompts, confirmations, and interactive prompts
10
+ - **Auto-response rules** - Automatically respond to known prompts
11
+ - **Terminal attachment** - Attach to sessions for raw I/O streaming
12
+ - **Event-driven** - Rich event system for session lifecycle
13
+ - **TypeScript-first** - Full type definitions included
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install pty-manager
19
+ ```
20
+
21
+ **Note:** This package requires `node-pty` which has native dependencies. On some systems you may need build tools:
22
+
23
+ ```bash
24
+ # macOS
25
+ xcode-select --install
26
+
27
+ # Ubuntu/Debian
28
+ sudo apt-get install build-essential
29
+
30
+ # Windows
31
+ npm install --global windows-build-tools
32
+ ```
33
+
34
+ ## Quick Start
35
+
36
+ ```typescript
37
+ import { PTYManager, ShellAdapter, createAdapter } from 'pty-manager';
38
+
39
+ // Create manager
40
+ const manager = new PTYManager();
41
+
42
+ // Register adapters
43
+ manager.registerAdapter(new ShellAdapter());
44
+
45
+ // Spawn a session
46
+ const handle = await manager.spawn({
47
+ name: 'my-shell',
48
+ type: 'shell',
49
+ workdir: '/path/to/project',
50
+ });
51
+
52
+ // Listen for events
53
+ manager.on('session_ready', ({ id }) => {
54
+ console.log(`Session ${id} is ready`);
55
+ });
56
+
57
+ // Send commands
58
+ manager.send(handle.id, 'echo "Hello, World!"');
59
+
60
+ // Attach terminal for raw I/O
61
+ const terminal = manager.attachTerminal(handle.id);
62
+ terminal.onData((data) => process.stdout.write(data));
63
+ terminal.write('ls -la\n');
64
+
65
+ // Stop session
66
+ await manager.stop(handle.id);
67
+ ```
68
+
69
+ ## Creating Custom Adapters
70
+
71
+ ### Using the Factory
72
+
73
+ ```typescript
74
+ import { createAdapter } from 'pty-manager';
75
+
76
+ const myCliAdapter = createAdapter({
77
+ command: 'my-cli',
78
+ args: ['--interactive'],
79
+
80
+ loginDetection: {
81
+ patterns: [/please log in/i, /auth required/i],
82
+ extractUrl: (output) => output.match(/https:\/\/[^\s]+/)?.[0] || null,
83
+ },
84
+
85
+ blockingPrompts: [
86
+ { pattern: /\[Y\/n\]/i, type: 'config', autoResponse: 'Y' },
87
+ { pattern: /continue\?/i, type: 'config', autoResponse: 'yes' },
88
+ ],
89
+
90
+ readyIndicators: [/\$ $/, /ready>/i],
91
+ });
92
+
93
+ manager.registerAdapter(myCliAdapter);
94
+ ```
95
+
96
+ ### Extending BaseCLIAdapter
97
+
98
+ ```typescript
99
+ import { BaseCLIAdapter } from 'pty-manager';
100
+
101
+ class MyCLIAdapter extends BaseCLIAdapter {
102
+ readonly adapterType = 'my-cli';
103
+ readonly displayName = 'My CLI Tool';
104
+
105
+ getCommand() {
106
+ return 'my-cli';
107
+ }
108
+
109
+ getArgs(config) {
110
+ return ['--mode', 'interactive'];
111
+ }
112
+
113
+ getEnv(config) {
114
+ return { MY_CLI_CONFIG: config.name };
115
+ }
116
+
117
+ detectLogin(output) {
118
+ if (/login required/i.test(output)) {
119
+ return { required: true, type: 'browser' };
120
+ }
121
+ return { required: false };
122
+ }
123
+
124
+ detectReady(output) {
125
+ return /ready>/.test(output);
126
+ }
127
+
128
+ parseOutput(output) {
129
+ return {
130
+ type: 'response',
131
+ content: output.trim(),
132
+ isComplete: true,
133
+ isQuestion: output.includes('?'),
134
+ };
135
+ }
136
+
137
+ getPromptPattern() {
138
+ return /my-cli>/;
139
+ }
140
+ }
141
+ ```
142
+
143
+ ## API Reference
144
+
145
+ ### PTYManager
146
+
147
+ ```typescript
148
+ class PTYManager extends EventEmitter {
149
+ // Adapter management
150
+ registerAdapter(adapter: CLIAdapter): void;
151
+ readonly adapters: AdapterRegistry;
152
+
153
+ // Session lifecycle
154
+ spawn(config: SpawnConfig): Promise<SessionHandle>;
155
+ stop(id: string, options?: StopOptions): Promise<void>;
156
+ stopAll(options?: StopOptions): Promise<void>;
157
+ shutdown(): Promise<void>;
158
+
159
+ // Session operations
160
+ get(id: string): SessionHandle | null;
161
+ list(filter?: SessionFilter): SessionHandle[];
162
+ send(id: string, message: string): SessionMessage;
163
+ logs(id: string, options?: LogOptions): AsyncIterable<string>;
164
+ metrics(id: string): { uptime?: number } | null;
165
+
166
+ // Terminal access
167
+ attachTerminal(id: string): TerminalAttachment | null;
168
+
169
+ // Utilities
170
+ has(id: string): boolean;
171
+ getStatusCounts(): Record<SessionStatus, number>;
172
+ }
173
+ ```
174
+
175
+ ### Events
176
+
177
+ | Event | Payload | Description |
178
+ |-------|---------|-------------|
179
+ | `session_started` | `SessionHandle` | Session spawn initiated |
180
+ | `session_ready` | `SessionHandle` | Session ready for input |
181
+ | `session_stopped` | `SessionHandle, reason` | Session terminated |
182
+ | `session_error` | `SessionHandle, error` | Error occurred |
183
+ | `login_required` | `SessionHandle, instructions?, url?` | Auth required |
184
+ | `blocking_prompt` | `SessionHandle, promptInfo, autoResponded` | Prompt detected |
185
+ | `message` | `SessionMessage` | Parsed message received |
186
+ | `question` | `SessionHandle, question` | Question detected |
187
+
188
+ ### SpawnConfig
189
+
190
+ ```typescript
191
+ interface SpawnConfig {
192
+ id?: string; // Auto-generated if not provided
193
+ name: string; // Human-readable name
194
+ type: string; // Adapter type
195
+ workdir?: string; // Working directory
196
+ env?: Record<string, string>; // Environment variables
197
+ cols?: number; // Terminal columns (default: 120)
198
+ rows?: number; // Terminal rows (default: 40)
199
+ timeout?: number; // Session timeout in ms
200
+ }
201
+ ```
202
+
203
+ ### SessionHandle
204
+
205
+ ```typescript
206
+ interface SessionHandle {
207
+ id: string;
208
+ name: string;
209
+ type: string;
210
+ status: SessionStatus;
211
+ pid?: number;
212
+ startedAt?: Date;
213
+ lastActivityAt?: Date;
214
+ }
215
+
216
+ type SessionStatus =
217
+ | 'pending'
218
+ | 'starting'
219
+ | 'authenticating'
220
+ | 'ready'
221
+ | 'busy'
222
+ | 'stopping'
223
+ | 'stopped'
224
+ | 'error';
225
+ ```
226
+
227
+ ### TerminalAttachment
228
+
229
+ ```typescript
230
+ interface TerminalAttachment {
231
+ onData: (callback: (data: string) => void) => () => void;
232
+ write: (data: string) => void;
233
+ resize: (cols: number, rows: number) => void;
234
+ }
235
+ ```
236
+
237
+ ## Built-in Adapters
238
+
239
+ ### ShellAdapter
240
+
241
+ Basic shell adapter for bash/zsh sessions.
242
+
243
+ ```typescript
244
+ import { ShellAdapter } from 'pty-manager';
245
+
246
+ const adapter = new ShellAdapter({
247
+ shell: '/bin/zsh', // default: $SHELL or /bin/bash
248
+ prompt: 'pty> ', // default: 'pty> '
249
+ });
250
+ ```
251
+
252
+ ## Blocking Prompt Types
253
+
254
+ The library recognizes these blocking prompt types:
255
+
256
+ - `login` - Authentication required
257
+ - `update` - Update/upgrade available
258
+ - `config` - Configuration choice needed
259
+ - `tos` - Terms of service acceptance
260
+ - `model_select` - Model/version selection
261
+ - `project_select` - Project/workspace selection
262
+ - `permission` - Permission request
263
+ - `unknown` - Unrecognized prompt
264
+
265
+ ## License
266
+
267
+ MIT