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.
@@ -0,0 +1,641 @@
1
+ import { EventEmitter } from 'events';
2
+
3
+ /**
4
+ * PTY Agent Manager Types
5
+ *
6
+ * Standalone type definitions for PTY session and adapter management.
7
+ */
8
+ /**
9
+ * Session lifecycle states
10
+ */
11
+ type SessionStatus = 'pending' | 'starting' | 'authenticating' | 'ready' | 'busy' | 'stopping' | 'stopped' | 'error';
12
+ /**
13
+ * Message types for session communication
14
+ */
15
+ type MessageType = 'task' | 'response' | 'question' | 'answer' | 'status' | 'error';
16
+ /**
17
+ * Configuration for spawning a PTY session
18
+ */
19
+ interface SpawnConfig {
20
+ /** Optional unique ID (auto-generated if not provided) */
21
+ id?: string;
22
+ /** Human-readable name */
23
+ name: string;
24
+ /** Adapter type to use */
25
+ type: string;
26
+ /** Working directory */
27
+ workdir?: string;
28
+ /** Environment variables */
29
+ env?: Record<string, string>;
30
+ /** Initial terminal columns (default: 120) */
31
+ cols?: number;
32
+ /** Initial terminal rows (default: 40) */
33
+ rows?: number;
34
+ /** Session timeout in ms */
35
+ timeout?: number;
36
+ /** Custom adapter configuration */
37
+ adapterConfig?: Record<string, unknown>;
38
+ }
39
+ /**
40
+ * Handle to a running session
41
+ */
42
+ interface SessionHandle {
43
+ id: string;
44
+ name: string;
45
+ type: string;
46
+ status: SessionStatus;
47
+ pid?: number;
48
+ startedAt?: Date;
49
+ lastActivityAt?: Date;
50
+ error?: string;
51
+ exitCode?: number;
52
+ }
53
+ /**
54
+ * Message to/from a session
55
+ */
56
+ interface SessionMessage {
57
+ id: string;
58
+ sessionId: string;
59
+ direction: 'inbound' | 'outbound';
60
+ type: MessageType;
61
+ content: string;
62
+ metadata?: Record<string, unknown>;
63
+ timestamp: Date;
64
+ }
65
+ /**
66
+ * Filter for listing sessions
67
+ */
68
+ interface SessionFilter {
69
+ status?: SessionStatus | SessionStatus[];
70
+ type?: string | string[];
71
+ }
72
+ /**
73
+ * Parsed output from a CLI
74
+ */
75
+ interface ParsedOutput {
76
+ type: MessageType;
77
+ content: string;
78
+ isComplete: boolean;
79
+ isQuestion: boolean;
80
+ metadata?: Record<string, unknown>;
81
+ }
82
+ /**
83
+ * Login/auth detection result
84
+ */
85
+ interface LoginDetection {
86
+ required: boolean;
87
+ type?: 'api_key' | 'oauth' | 'browser' | 'device_code';
88
+ url?: string;
89
+ instructions?: string;
90
+ }
91
+ /**
92
+ * Types of blocking prompts that can occur
93
+ */
94
+ type BlockingPromptType = 'login' | 'update' | 'config' | 'tos' | 'model_select' | 'project_select' | 'permission' | 'unknown';
95
+ /**
96
+ * Blocking prompt detection result
97
+ */
98
+ interface BlockingPromptDetection {
99
+ /** Whether a blocking prompt was detected */
100
+ detected: boolean;
101
+ /** Type of blocking prompt */
102
+ type?: BlockingPromptType;
103
+ /** The prompt text shown to the user */
104
+ prompt?: string;
105
+ /** Available options/choices if detected */
106
+ options?: string[];
107
+ /** Suggested auto-response (if safe to auto-respond) */
108
+ suggestedResponse?: string;
109
+ /** Whether it's safe to auto-respond without user confirmation */
110
+ canAutoRespond?: boolean;
111
+ /** Instructions for the user if manual intervention needed */
112
+ instructions?: string;
113
+ /** URL to open if browser action needed */
114
+ url?: string;
115
+ }
116
+ /**
117
+ * Auto-response rule for handling known blocking prompts
118
+ */
119
+ interface AutoResponseRule {
120
+ /** Pattern to match in output */
121
+ pattern: RegExp;
122
+ /** Type of prompt this handles */
123
+ type: BlockingPromptType;
124
+ /** Response to send automatically */
125
+ response: string;
126
+ /** Human-readable description of what this does */
127
+ description: string;
128
+ /** Whether this is safe to auto-respond (default: true) */
129
+ safe?: boolean;
130
+ }
131
+ /**
132
+ * Blocking prompt info for events
133
+ */
134
+ interface BlockingPromptInfo {
135
+ type: BlockingPromptType | string;
136
+ prompt?: string;
137
+ options?: string[];
138
+ canAutoRespond: boolean;
139
+ instructions?: string;
140
+ url?: string;
141
+ }
142
+ /**
143
+ * Logger interface (bring your own logger)
144
+ */
145
+ interface Logger {
146
+ debug(message: string, context?: Record<string, unknown>): void;
147
+ debug(context: Record<string, unknown>, message: string): void;
148
+ info(message: string, context?: Record<string, unknown>): void;
149
+ info(context: Record<string, unknown>, message: string): void;
150
+ warn(message: string, context?: Record<string, unknown>): void;
151
+ warn(context: Record<string, unknown>, message: string): void;
152
+ error(message: string, context?: Record<string, unknown>): void;
153
+ error(context: Record<string, unknown>, message: string): void;
154
+ }
155
+ /**
156
+ * Options for stopping a session
157
+ */
158
+ interface StopOptions {
159
+ /** Force kill without graceful shutdown */
160
+ force?: boolean;
161
+ /** Timeout in ms before force kill (default: 5000) */
162
+ timeout?: number;
163
+ }
164
+ /**
165
+ * Options for reading logs
166
+ */
167
+ interface LogOptions {
168
+ /** Number of lines from the end */
169
+ tail?: number;
170
+ }
171
+ /**
172
+ * Terminal attachment for raw I/O streaming
173
+ */
174
+ interface TerminalAttachment {
175
+ /** Subscribe to raw terminal output (returns unsubscribe function) */
176
+ onData: (callback: (data: string) => void) => () => void;
177
+ /** Write raw data to terminal */
178
+ write: (data: string) => void;
179
+ /** Resize the terminal */
180
+ resize: (cols: number, rows: number) => void;
181
+ }
182
+ /**
183
+ * PTYManager configuration
184
+ */
185
+ interface PTYManagerConfig {
186
+ /** Logger instance (optional - uses console if not provided) */
187
+ logger?: Logger;
188
+ /** Maximum output log lines per session (default: 1000) */
189
+ maxLogLines?: number;
190
+ }
191
+ /**
192
+ * Configuration for creating an adapter via factory
193
+ */
194
+ interface AdapterFactoryConfig {
195
+ /** Command to execute */
196
+ command: string;
197
+ /** Default arguments */
198
+ args?: string[] | ((config: SpawnConfig) => string[]);
199
+ /** Environment variables */
200
+ env?: Record<string, string> | ((config: SpawnConfig) => Record<string, string>);
201
+ /** Login detection configuration */
202
+ loginDetection?: {
203
+ patterns: RegExp[];
204
+ extractUrl?: (output: string) => string | null;
205
+ extractInstructions?: (output: string) => string | null;
206
+ };
207
+ /** Blocking prompt configuration */
208
+ blockingPrompts?: Array<{
209
+ pattern: RegExp;
210
+ type: BlockingPromptType;
211
+ autoResponse?: string;
212
+ safe?: boolean;
213
+ description?: string;
214
+ }>;
215
+ /** Ready state indicators */
216
+ readyIndicators?: RegExp[];
217
+ /** Exit indicators */
218
+ exitIndicators?: Array<{
219
+ pattern: RegExp;
220
+ codeExtractor?: (match: RegExpMatchArray) => number;
221
+ }>;
222
+ /** Output parser */
223
+ parseOutput?: (output: string) => ParsedOutput | null;
224
+ /** Input formatter */
225
+ formatInput?: (message: string) => string;
226
+ /** Prompt pattern for detecting input readiness */
227
+ promptPattern?: RegExp;
228
+ }
229
+
230
+ /**
231
+ * CLI Adapter Interface
232
+ *
233
+ * Defines how to interact with different CLI tools via PTY.
234
+ */
235
+
236
+ /**
237
+ * Interface that CLI adapters must implement
238
+ */
239
+ interface CLIAdapter {
240
+ /** Adapter type identifier */
241
+ readonly adapterType: string;
242
+ /** Display name for the CLI */
243
+ readonly displayName: string;
244
+ /**
245
+ * Auto-response rules for handling known blocking prompts.
246
+ * These are applied automatically during startup and execution.
247
+ */
248
+ readonly autoResponseRules?: AutoResponseRule[];
249
+ /**
250
+ * Get the CLI command to execute
251
+ */
252
+ getCommand(): string;
253
+ /**
254
+ * Get command arguments
255
+ */
256
+ getArgs(config: SpawnConfig): string[];
257
+ /**
258
+ * Get environment variables needed
259
+ */
260
+ getEnv(config: SpawnConfig): Record<string, string>;
261
+ /**
262
+ * Detect if output indicates login is required
263
+ * @deprecated Use detectBlockingPrompt() instead for comprehensive detection
264
+ */
265
+ detectLogin(output: string): LoginDetection;
266
+ /**
267
+ * Detect any blocking prompt that requires user input or auto-response.
268
+ */
269
+ detectBlockingPrompt?(output: string): BlockingPromptDetection;
270
+ /**
271
+ * Detect if CLI is ready to receive input
272
+ */
273
+ detectReady(output: string): boolean;
274
+ /**
275
+ * Detect if CLI has exited or crashed
276
+ */
277
+ detectExit(output: string): {
278
+ exited: boolean;
279
+ code?: number;
280
+ error?: string;
281
+ };
282
+ /**
283
+ * Parse structured response from output buffer
284
+ * Returns null if output is incomplete
285
+ */
286
+ parseOutput(output: string): ParsedOutput | null;
287
+ /**
288
+ * Format a message/task for this CLI
289
+ */
290
+ formatInput(message: string): string;
291
+ /**
292
+ * Get prompt pattern to detect when CLI is waiting for input
293
+ */
294
+ getPromptPattern(): RegExp;
295
+ /**
296
+ * Optional: Validate that the CLI is installed and accessible
297
+ */
298
+ validateInstallation?(): Promise<{
299
+ installed: boolean;
300
+ version?: string;
301
+ error?: string;
302
+ }>;
303
+ /**
304
+ * Optional: Get health check command
305
+ */
306
+ getHealthCheckCommand?(): string;
307
+ }
308
+
309
+ /**
310
+ * Adapter Registry
311
+ *
312
+ * Registry for managing CLI adapters.
313
+ */
314
+
315
+ /**
316
+ * Registry of available CLI adapters
317
+ */
318
+ declare class AdapterRegistry {
319
+ private adapters;
320
+ /**
321
+ * Register an adapter
322
+ */
323
+ register(adapter: CLIAdapter): void;
324
+ /**
325
+ * Get adapter for type
326
+ */
327
+ get(adapterType: string): CLIAdapter | undefined;
328
+ /**
329
+ * Check if adapter exists for type
330
+ */
331
+ has(adapterType: string): boolean;
332
+ /**
333
+ * Unregister an adapter
334
+ */
335
+ unregister(adapterType: string): boolean;
336
+ /**
337
+ * List all registered adapter types
338
+ */
339
+ list(): string[];
340
+ /**
341
+ * Get all adapters
342
+ */
343
+ all(): CLIAdapter[];
344
+ /**
345
+ * Clear all adapters
346
+ */
347
+ clear(): void;
348
+ }
349
+
350
+ /**
351
+ * PTY Session
352
+ *
353
+ * Manages a single pseudo-terminal session for a CLI tool.
354
+ */
355
+
356
+ interface PTYSessionEvents {
357
+ output: (data: string) => void;
358
+ ready: () => void;
359
+ login_required: (instructions?: string, url?: string) => void;
360
+ blocking_prompt: (prompt: BlockingPromptInfo, autoResponded: boolean) => void;
361
+ message: (message: SessionMessage) => void;
362
+ question: (question: string) => void;
363
+ exit: (code: number) => void;
364
+ error: (error: Error) => void;
365
+ }
366
+ declare class PTYSession extends EventEmitter {
367
+ private adapter;
368
+ private ptyProcess;
369
+ private outputBuffer;
370
+ private _status;
371
+ private _startedAt;
372
+ private _lastActivityAt;
373
+ private messageCounter;
374
+ private logger;
375
+ readonly id: string;
376
+ readonly config: SpawnConfig;
377
+ constructor(adapter: CLIAdapter, config: SpawnConfig, logger?: Logger);
378
+ get status(): SessionStatus;
379
+ get pid(): number | undefined;
380
+ get startedAt(): Date | undefined;
381
+ get lastActivityAt(): Date | undefined;
382
+ /**
383
+ * Start the PTY session
384
+ */
385
+ start(): Promise<void>;
386
+ /**
387
+ * Set up event handlers for the PTY
388
+ */
389
+ private setupEventHandlers;
390
+ /**
391
+ * Detect blocking prompts and handle them with auto-responses or user notification
392
+ */
393
+ private detectAndHandleBlockingPrompt;
394
+ /**
395
+ * Try to match and apply auto-response rules
396
+ */
397
+ private tryAutoResponse;
398
+ /**
399
+ * Try to parse the output buffer into structured messages
400
+ */
401
+ private tryParseOutput;
402
+ /**
403
+ * Write data to the PTY (formatted by adapter)
404
+ */
405
+ write(data: string): void;
406
+ /**
407
+ * Write raw data directly to the PTY (no formatting)
408
+ */
409
+ writeRaw(data: string): void;
410
+ /**
411
+ * Send a task/message to the session
412
+ */
413
+ send(message: string): SessionMessage;
414
+ /**
415
+ * Resize the PTY terminal
416
+ */
417
+ resize(cols: number, rows: number): void;
418
+ /**
419
+ * Kill the PTY process
420
+ */
421
+ kill(signal?: string): void;
422
+ /**
423
+ * Get current output buffer
424
+ */
425
+ getOutputBuffer(): string;
426
+ /**
427
+ * Clear output buffer
428
+ */
429
+ clearOutputBuffer(): void;
430
+ /**
431
+ * Convert to SessionHandle
432
+ */
433
+ toHandle(): SessionHandle;
434
+ }
435
+
436
+ /**
437
+ * PTY Manager
438
+ *
439
+ * Manages multiple PTY sessions for CLI tools.
440
+ */
441
+
442
+ interface PTYManagerEvents {
443
+ session_started: (session: SessionHandle) => void;
444
+ session_ready: (session: SessionHandle) => void;
445
+ session_stopped: (session: SessionHandle, reason: string) => void;
446
+ session_error: (session: SessionHandle, error: string) => void;
447
+ login_required: (session: SessionHandle, instructions?: string, url?: string) => void;
448
+ blocking_prompt: (session: SessionHandle, promptInfo: BlockingPromptInfo, autoResponded: boolean) => void;
449
+ message: (message: SessionMessage) => void;
450
+ question: (session: SessionHandle, question: string) => void;
451
+ }
452
+ declare class PTYManager extends EventEmitter {
453
+ private sessions;
454
+ private outputLogs;
455
+ private maxLogLines;
456
+ private logger;
457
+ readonly adapters: AdapterRegistry;
458
+ constructor(config?: PTYManagerConfig);
459
+ /**
460
+ * Register a CLI adapter
461
+ */
462
+ registerAdapter(adapter: CLIAdapter): void;
463
+ /**
464
+ * Spawn a new PTY session
465
+ */
466
+ spawn(config: SpawnConfig): Promise<SessionHandle>;
467
+ /**
468
+ * Set up event handlers for a session
469
+ */
470
+ private setupSessionEvents;
471
+ /**
472
+ * Stop a session
473
+ */
474
+ stop(sessionId: string, options?: StopOptions): Promise<void>;
475
+ /**
476
+ * Stop all sessions
477
+ */
478
+ stopAll(options?: StopOptions): Promise<void>;
479
+ /**
480
+ * Get a session by ID
481
+ */
482
+ get(sessionId: string): SessionHandle | null;
483
+ /**
484
+ * List all sessions
485
+ */
486
+ list(filter?: SessionFilter): SessionHandle[];
487
+ /**
488
+ * Send a message to a session
489
+ */
490
+ send(sessionId: string, message: string): SessionMessage;
491
+ /**
492
+ * Get logs for a session
493
+ */
494
+ logs(sessionId: string, options?: LogOptions): AsyncIterable<string>;
495
+ /**
496
+ * Get metrics for a session
497
+ */
498
+ metrics(sessionId: string): {
499
+ uptime?: number;
500
+ messageCount?: number;
501
+ } | null;
502
+ /**
503
+ * Shutdown manager and stop all sessions
504
+ */
505
+ shutdown(): Promise<void>;
506
+ /**
507
+ * Get count of sessions by status
508
+ */
509
+ getStatusCounts(): Record<SessionStatus, number>;
510
+ /**
511
+ * Attach to a session's terminal for raw I/O streaming
512
+ */
513
+ attachTerminal(sessionId: string): TerminalAttachment | null;
514
+ /**
515
+ * Check if a session exists
516
+ */
517
+ has(sessionId: string): boolean;
518
+ /**
519
+ * Get the underlying PTYSession (for advanced use)
520
+ */
521
+ getSession(sessionId: string): PTYSession | undefined;
522
+ }
523
+
524
+ /**
525
+ * Base CLI Adapter
526
+ *
527
+ * Abstract base class with common functionality for CLI adapters.
528
+ */
529
+
530
+ /**
531
+ * Abstract base class for CLI adapters with common functionality
532
+ */
533
+ declare abstract class BaseCLIAdapter implements CLIAdapter {
534
+ abstract readonly adapterType: string;
535
+ abstract readonly displayName: string;
536
+ /**
537
+ * Auto-response rules for handling known blocking prompts.
538
+ * Subclasses should override this to add CLI-specific rules.
539
+ */
540
+ readonly autoResponseRules: AutoResponseRule[];
541
+ abstract getCommand(): string;
542
+ abstract getArgs(config: SpawnConfig): string[];
543
+ abstract getEnv(config: SpawnConfig): Record<string, string>;
544
+ abstract detectLogin(output: string): LoginDetection;
545
+ abstract detectReady(output: string): boolean;
546
+ abstract parseOutput(output: string): ParsedOutput | null;
547
+ abstract getPromptPattern(): RegExp;
548
+ /**
549
+ * Default exit detection - look for common exit patterns
550
+ */
551
+ detectExit(output: string): {
552
+ exited: boolean;
553
+ code?: number;
554
+ error?: string;
555
+ };
556
+ /**
557
+ * Default blocking prompt detection - looks for common prompt patterns.
558
+ * Subclasses should override for CLI-specific detection.
559
+ */
560
+ detectBlockingPrompt(output: string): BlockingPromptDetection;
561
+ /**
562
+ * Default input formatting - just return as-is
563
+ */
564
+ formatInput(message: string): string;
565
+ /**
566
+ * Validate CLI installation by running --version or --help
567
+ */
568
+ validateInstallation(): Promise<{
569
+ installed: boolean;
570
+ version?: string;
571
+ error?: string;
572
+ }>;
573
+ /**
574
+ * Helper to check if output contains a question
575
+ */
576
+ protected containsQuestion(output: string): boolean;
577
+ /**
578
+ * Helper to strip ANSI escape codes from output
579
+ */
580
+ protected stripAnsi(str: string): string;
581
+ }
582
+
583
+ /**
584
+ * Adapter Factory
585
+ *
586
+ * Factory function for creating CLI adapters from configuration.
587
+ */
588
+
589
+ /**
590
+ * Creates a CLI adapter from configuration
591
+ */
592
+ declare function createAdapter(config: AdapterFactoryConfig): CLIAdapter;
593
+
594
+ /**
595
+ * Shell Adapter
596
+ *
597
+ * Built-in adapter for bash/zsh shell sessions.
598
+ */
599
+
600
+ /**
601
+ * Options for the shell adapter
602
+ */
603
+ interface ShellAdapterOptions {
604
+ /** Shell to use (default: $SHELL or /bin/bash) */
605
+ shell?: string;
606
+ /** Custom prompt string (default: 'pty> ') */
607
+ prompt?: string;
608
+ }
609
+ /**
610
+ * Built-in adapter for shell sessions (bash/zsh)
611
+ */
612
+ declare class ShellAdapter implements CLIAdapter {
613
+ readonly adapterType = "shell";
614
+ readonly displayName = "Shell";
615
+ readonly autoResponseRules: AutoResponseRule[];
616
+ private shell;
617
+ private promptStr;
618
+ constructor(options?: ShellAdapterOptions);
619
+ getCommand(): string;
620
+ getArgs(_config: SpawnConfig): string[];
621
+ getEnv(_config: SpawnConfig): Record<string, string>;
622
+ detectLogin(_output: string): LoginDetection;
623
+ detectBlockingPrompt(_output: string): BlockingPromptDetection;
624
+ detectReady(output: string): boolean;
625
+ detectExit(output: string): {
626
+ exited: boolean;
627
+ code?: number;
628
+ error?: string;
629
+ };
630
+ parseOutput(output: string): ParsedOutput | null;
631
+ formatInput(message: string): string;
632
+ getPromptPattern(): RegExp;
633
+ validateInstallation(): Promise<{
634
+ installed: boolean;
635
+ version?: string;
636
+ error?: string;
637
+ }>;
638
+ private stripAnsi;
639
+ }
640
+
641
+ export { type AdapterFactoryConfig, AdapterRegistry, type AutoResponseRule, BaseCLIAdapter, type BlockingPromptDetection, type BlockingPromptInfo, type BlockingPromptType, type CLIAdapter, type LogOptions, type Logger, type LoginDetection, type MessageType, PTYManager, type PTYManagerConfig, type PTYManagerEvents, PTYSession, type PTYSessionEvents, type ParsedOutput, type SessionFilter, type SessionHandle, type SessionMessage, type SessionStatus, ShellAdapter, type ShellAdapterOptions, type SpawnConfig, type StopOptions, type TerminalAttachment, createAdapter };