pty-manager 1.9.7 → 1.10.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/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  PTY session manager with lifecycle management, pluggable adapters, and blocking prompt detection.
4
4
 
5
+ > Need crash-resilient sessions without native compilation? See [tmux-manager](../tmux-manager) — same adapter interface, backed by tmux instead of node-pty.
6
+
5
7
  ## Features
6
8
 
7
9
  - **Multi-session management** - Spawn and manage multiple PTY sessions concurrently
package/dist/index.d.mts CHANGED
@@ -1,69 +1,37 @@
1
1
  import { EventEmitter } from 'events';
2
+ import * as adapter_types from 'adapter-types';
3
+ import { SpawnConfig, CLIAdapter, AutoResponseRule, ToolRunningInfo, AdapterRegistry, LoginDetection, BlockingPromptDetection, ParsedOutput } from 'adapter-types';
4
+ export { AdapterFactoryConfig, AdapterRegistry, AutoResponseRule, BaseCLIAdapter, BlockingPromptDetection, BlockingPromptType, CLIAdapter, LoginDetection, MessageType, ParsedOutput, SpawnConfig, ToolRunningInfo, createAdapter } from 'adapter-types';
2
5
 
3
6
  /**
4
- * PTY Agent Manager Types
7
+ * Lazy runtime check for node-pty native addon.
5
8
  *
6
- * Standalone type definitions for PTY session and adapter management.
9
+ * Called once before the first PTY spawn. Ensures the native binary is
10
+ * loadable and spawn-helper permissions are correct.
11
+ *
12
+ * 1. Finds the binary — checks for prebuilt pty.node under
13
+ * prebuilds/<platform>-<arch>/ (node-pty >=1.0), then falls back to
14
+ * checking for a node-gyp compiled build/Release/pty.node
15
+ * 2. Fixes spawn-helper permissions — bun install can strip execute
16
+ * bits from the spawn-helper Mach-O binary, causing posix_spawnp
17
+ * failed at runtime. The script chmod 755s all spawn-helpers under
18
+ * prebuilds/
19
+ * 3. Rebuilds if missing — if no binary is found at all, runs
20
+ * node-gyp rebuild as a last resort (with a 2-minute timeout)
21
+ */
22
+ /**
23
+ * Ensure node-pty is usable. Called once before first spawn.
24
+ * Idempotent — subsequent calls are no-ops.
25
+ *
26
+ * @param log - logger function (defaults to console.log)
27
+ * @throws Error if no native binary can be found or built
7
28
  */
29
+ declare function ensurePty(log?: (msg: string) => void): void;
30
+
8
31
  /**
9
32
  * Session lifecycle states
10
33
  */
11
34
  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
- /** Per-session stall timeout in ms. Overrides PTYManagerConfig.stallTimeoutMs. */
39
- stallTimeoutMs?: number;
40
- /** Override adapter's readySettleMs for this session.
41
- * Ms of output silence after detectReady match before emitting session_ready. */
42
- readySettleMs?: number;
43
- /** Enable verbose task-completion trace logs.
44
- * Disabled by default; set true to enable. */
45
- traceTaskCompletion?: boolean;
46
- /** Override or disable specific adapter auto-response rules for this session.
47
- * Keys are regex source strings (from rule.pattern.source).
48
- * - null value disables that rule entirely
49
- * - Object value merges fields into the matching adapter rule */
50
- ruleOverrides?: Record<string, Partial<Omit<AutoResponseRule, 'pattern'>> | null>;
51
- /** When true, adapter detectBlockingPrompt() results with suggestedResponse
52
- * are emitted as autoResponded=false instead of being auto-responded.
53
- * Auto-response rules (ruleOverrides) are unaffected. */
54
- skipAdapterAutoResponse?: boolean;
55
- /**
56
- * Whether to inherit the parent process environment variables.
57
- * When `true` (default), `process.env` is spread as the base of the spawned
58
- * process environment. When `false`, only `adapter.getEnv()` output and
59
- * `config.env` are used — the caller is responsible for providing any
60
- * necessary system vars (PATH, HOME, etc.) via `config.env`.
61
- *
62
- * Set to `false` for security-sensitive contexts where the host process has
63
- * secrets that spawned agents should not access.
64
- */
65
- inheritProcessEnv?: boolean;
66
- }
67
35
  /**
68
36
  * Handle to a running session
69
37
  */
@@ -85,7 +53,7 @@ interface SessionMessage {
85
53
  id: string;
86
54
  sessionId: string;
87
55
  direction: 'inbound' | 'outbound';
88
- type: MessageType;
56
+ type: adapter_types.MessageType;
89
57
  content: string;
90
58
  metadata?: Record<string, unknown>;
91
59
  timestamp: Date;
@@ -97,26 +65,6 @@ interface SessionFilter {
97
65
  status?: SessionStatus | SessionStatus[];
98
66
  type?: string | string[];
99
67
  }
100
- /**
101
- * Parsed output from a CLI
102
- */
103
- interface ParsedOutput {
104
- type: MessageType;
105
- content: string;
106
- isComplete: boolean;
107
- isQuestion: boolean;
108
- metadata?: Record<string, unknown>;
109
- }
110
- /**
111
- * Login/auth detection result
112
- */
113
- interface LoginDetection {
114
- required: boolean;
115
- type?: 'api_key' | 'oauth' | 'browser' | 'device_code' | 'cli_auth';
116
- url?: string;
117
- deviceCode?: string;
118
- instructions?: string;
119
- }
120
68
  /**
121
69
  * Normalized authentication methods for runtime event consumers.
122
70
  */
@@ -131,57 +79,11 @@ interface AuthRequiredInfo {
131
79
  instructions?: string;
132
80
  promptSnippet?: string;
133
81
  }
134
- /**
135
- * Types of blocking prompts that can occur
136
- */
137
- type BlockingPromptType = 'login' | 'update' | 'config' | 'tos' | 'model_select' | 'project_select' | 'permission' | 'tool_wait' | 'unknown';
138
- /**
139
- * Blocking prompt detection result
140
- */
141
- interface BlockingPromptDetection {
142
- /** Whether a blocking prompt was detected */
143
- detected: boolean;
144
- /** Type of blocking prompt */
145
- type?: BlockingPromptType;
146
- /** The prompt text shown to the user */
147
- prompt?: string;
148
- /** Available options/choices if detected */
149
- options?: string[];
150
- /** Suggested auto-response (if safe to auto-respond) */
151
- suggestedResponse?: string;
152
- /** Whether it's safe to auto-respond without user confirmation */
153
- canAutoRespond?: boolean;
154
- /** Instructions for the user if manual intervention needed */
155
- instructions?: string;
156
- /** URL to open if browser action needed */
157
- url?: string;
158
- }
159
- /**
160
- * Auto-response rule for handling known blocking prompts
161
- */
162
- interface AutoResponseRule {
163
- /** Pattern to match in output */
164
- pattern: RegExp;
165
- /** Type of prompt this handles */
166
- type: BlockingPromptType;
167
- /** Response to send automatically */
168
- response: string;
169
- /** How to deliver the response: 'text' writes raw text + CR, 'keys' sends key sequences (default: 'text') */
170
- responseType?: 'text' | 'keys';
171
- /** Key names to send when responseType is 'keys' (e.g. ['down', 'enter']) */
172
- keys?: string[];
173
- /** Human-readable description of what this does */
174
- description: string;
175
- /** Whether this is safe to auto-respond (default: true) */
176
- safe?: boolean;
177
- /** Fire this rule at most once per session (prevents thrashing on TUI re-renders) */
178
- once?: boolean;
179
- }
180
82
  /**
181
83
  * Blocking prompt info for events
182
84
  */
183
85
  interface BlockingPromptInfo {
184
- type: BlockingPromptType | string;
86
+ type: adapter_types.BlockingPromptType | string;
185
87
  prompt?: string;
186
88
  options?: string[];
187
89
  canAutoRespond: boolean;
@@ -199,17 +101,6 @@ interface StallClassification {
199
101
  /** Suggested response to send (for waiting_for_input with auto-respond) */
200
102
  suggestedResponse?: string;
201
103
  }
202
- /**
203
- * Information about an external tool/process running within a session.
204
- * Emitted when the adapter detects a tool is actively executing (e.g. browser,
205
- * bash command, Node process). Suppresses stall detection while active.
206
- */
207
- interface ToolRunningInfo {
208
- /** Name of the tool (e.g. "Chrome", "bash", "node", "python") */
209
- toolName: string;
210
- /** Optional description of what the tool is doing */
211
- description?: string;
212
- }
213
104
  /**
214
105
  * Logger interface (bring your own logger)
215
106
  */
@@ -271,201 +162,6 @@ interface PTYManagerConfig {
271
162
  */
272
163
  onStallClassify?: (sessionId: string, recentOutput: string, stallDurationMs: number) => Promise<StallClassification | null>;
273
164
  }
274
- /**
275
- * Configuration for creating an adapter via factory
276
- */
277
- interface AdapterFactoryConfig {
278
- /** Command to execute */
279
- command: string;
280
- /** Default arguments */
281
- args?: string[] | ((config: SpawnConfig) => string[]);
282
- /** Environment variables */
283
- env?: Record<string, string> | ((config: SpawnConfig) => Record<string, string>);
284
- /** Login detection configuration */
285
- loginDetection?: {
286
- patterns: RegExp[];
287
- extractUrl?: (output: string) => string | null;
288
- extractInstructions?: (output: string) => string | null;
289
- };
290
- /** Blocking prompt configuration */
291
- blockingPrompts?: Array<{
292
- pattern: RegExp;
293
- type: BlockingPromptType;
294
- autoResponse?: string;
295
- safe?: boolean;
296
- description?: string;
297
- }>;
298
- /** Ready state indicators */
299
- readyIndicators?: RegExp[];
300
- /** Exit indicators */
301
- exitIndicators?: Array<{
302
- pattern: RegExp;
303
- codeExtractor?: (match: RegExpMatchArray) => number;
304
- }>;
305
- /** Output parser */
306
- parseOutput?: (output: string) => ParsedOutput | null;
307
- /** Input formatter */
308
- formatInput?: (message: string) => string;
309
- /** Prompt pattern for detecting input readiness */
310
- promptPattern?: RegExp;
311
- }
312
-
313
- /**
314
- * CLI Adapter Interface
315
- *
316
- * Defines how to interact with different CLI tools via PTY.
317
- */
318
-
319
- /**
320
- * Interface that CLI adapters must implement
321
- */
322
- interface CLIAdapter {
323
- /** Adapter type identifier */
324
- readonly adapterType: string;
325
- /** Display name for the CLI */
326
- readonly displayName: string;
327
- /**
328
- * Auto-response rules for handling known blocking prompts.
329
- * These are applied automatically during startup and execution.
330
- */
331
- readonly autoResponseRules?: AutoResponseRule[];
332
- /**
333
- * Whether this CLI uses TUI menus that require arrow-key navigation.
334
- * When true, auto-response rules without an explicit responseType
335
- * default to sending Enter via sendKeys instead of writeRaw.
336
- */
337
- readonly usesTuiMenus?: boolean;
338
- /**
339
- * Get the CLI command to execute
340
- */
341
- getCommand(): string;
342
- /**
343
- * Get command arguments
344
- */
345
- getArgs(config: SpawnConfig): string[];
346
- /**
347
- * Get environment variables needed
348
- */
349
- getEnv(config: SpawnConfig): Record<string, string>;
350
- /**
351
- * Detect if output indicates login is required
352
- * @deprecated Use detectBlockingPrompt() instead for comprehensive detection
353
- */
354
- detectLogin(output: string): LoginDetection;
355
- /**
356
- * Detect any blocking prompt that requires user input or auto-response.
357
- */
358
- detectBlockingPrompt?(output: string): BlockingPromptDetection;
359
- /**
360
- * Detect if CLI is ready to receive input
361
- */
362
- detectReady(output: string): boolean;
363
- /**
364
- * Detect if CLI has exited or crashed
365
- */
366
- detectExit(output: string): {
367
- exited: boolean;
368
- code?: number;
369
- error?: string;
370
- };
371
- /**
372
- * Parse structured response from output buffer
373
- * Returns null if output is incomplete
374
- */
375
- parseOutput(output: string): ParsedOutput | null;
376
- /**
377
- * Format a message/task for this CLI
378
- */
379
- formatInput(message: string): string;
380
- /**
381
- * Get prompt pattern to detect when CLI is waiting for input
382
- */
383
- getPromptPattern(): RegExp;
384
- /**
385
- * Optional: Detect if the CLI has completed a task and returned to its idle prompt.
386
- * More specific than detectReady — matches high-confidence completion indicators
387
- * (e.g. duration summaries, explicit "done" messages) alongside the idle prompt.
388
- *
389
- * Used as a fast-path in stall detection to avoid expensive LLM classifier calls.
390
- * If not implemented, the stall classifier is used as the fallback.
391
- */
392
- detectTaskComplete?(output: string): boolean;
393
- /**
394
- * Optional: Validate that the CLI is installed and accessible
395
- */
396
- validateInstallation?(): Promise<{
397
- installed: boolean;
398
- version?: string;
399
- error?: string;
400
- }>;
401
- /** Ms of output silence after detectReady match before emitting session_ready (default: 100) */
402
- readonly readySettleMs?: number;
403
- /**
404
- * Optional: Detect if the CLI is actively loading/processing (thinking spinner,
405
- * file reading, model streaming, etc.). When true, stall detection is suppressed
406
- * because the agent is provably working — just not producing new visible text.
407
- *
408
- * Patterns should match active loading indicators like "esc to interrupt",
409
- * "Reading N files", "Waiting for LLM", etc.
410
- */
411
- detectLoading?(output: string): boolean;
412
- /**
413
- * Optional: Detect if an external tool/process is currently running within
414
- * the session (e.g. browser, bash command, Node server, Python script).
415
- *
416
- * When a tool is detected, stall detection is suppressed (the agent is
417
- * working, just through an external process) and a `tool_running` event
418
- * is emitted so the UI can display the active tool.
419
- *
420
- * Return null when no tool is detected.
421
- */
422
- detectToolRunning?(output: string): ToolRunningInfo | null;
423
- /**
424
- * Optional: Get health check command
425
- */
426
- getHealthCheckCommand?(): string;
427
- }
428
-
429
- /**
430
- * Adapter Registry
431
- *
432
- * Registry for managing CLI adapters.
433
- */
434
-
435
- /**
436
- * Registry of available CLI adapters
437
- */
438
- declare class AdapterRegistry {
439
- private adapters;
440
- /**
441
- * Register an adapter
442
- */
443
- register(adapter: CLIAdapter): void;
444
- /**
445
- * Get adapter for type
446
- */
447
- get(adapterType: string): CLIAdapter | undefined;
448
- /**
449
- * Check if adapter exists for type
450
- */
451
- has(adapterType: string): boolean;
452
- /**
453
- * Unregister an adapter
454
- */
455
- unregister(adapterType: string): boolean;
456
- /**
457
- * List all registered adapter types
458
- */
459
- list(): string[];
460
- /**
461
- * Get all adapters
462
- */
463
- all(): CLIAdapter[];
464
- /**
465
- * Clear all adapters
466
- */
467
- clear(): void;
468
- }
469
165
 
470
166
  /**
471
167
  * PTY Session
@@ -947,87 +643,6 @@ declare function extractTaskCompletionTraceRecords(entries: Array<string | Recor
947
643
  */
948
644
  declare function buildTaskCompletionTimeline(records: TaskCompletionTraceRecord[], options?: BuildTimelineOptions): TaskCompletionTimelineResult;
949
645
 
950
- /**
951
- * Base CLI Adapter
952
- *
953
- * Abstract base class with common functionality for CLI adapters.
954
- */
955
-
956
- /**
957
- * Abstract base class for CLI adapters with common functionality
958
- */
959
- declare abstract class BaseCLIAdapter implements CLIAdapter {
960
- abstract readonly adapterType: string;
961
- abstract readonly displayName: string;
962
- /**
963
- * Auto-response rules for handling known blocking prompts.
964
- * Subclasses should override this to add CLI-specific rules.
965
- */
966
- readonly autoResponseRules: AutoResponseRule[];
967
- /**
968
- * Whether this CLI uses TUI menus requiring arrow-key navigation.
969
- * Defaults to false; coding agent adapters override to true.
970
- */
971
- readonly usesTuiMenus: boolean;
972
- abstract getCommand(): string;
973
- abstract getArgs(config: SpawnConfig): string[];
974
- abstract getEnv(config: SpawnConfig): Record<string, string>;
975
- abstract detectLogin(output: string): LoginDetection;
976
- abstract detectReady(output: string): boolean;
977
- abstract parseOutput(output: string): ParsedOutput | null;
978
- abstract getPromptPattern(): RegExp;
979
- /**
980
- * Default exit detection - look for common exit patterns
981
- */
982
- detectExit(output: string): {
983
- exited: boolean;
984
- code?: number;
985
- error?: string;
986
- };
987
- /**
988
- * Default blocking prompt detection - looks for common prompt patterns.
989
- * Subclasses should override for CLI-specific detection.
990
- */
991
- detectBlockingPrompt(output: string): BlockingPromptDetection;
992
- /**
993
- * Default task completion detection — delegates to detectReady().
994
- * Subclasses should override to match high-confidence completion patterns
995
- * (e.g. duration summaries) that short-circuit the LLM stall classifier.
996
- */
997
- detectTaskComplete(output: string): boolean;
998
- /**
999
- * Default input formatting - just return as-is
1000
- */
1001
- formatInput(message: string): string;
1002
- /**
1003
- * Validate CLI installation by running --version or --help
1004
- */
1005
- validateInstallation(): Promise<{
1006
- installed: boolean;
1007
- version?: string;
1008
- error?: string;
1009
- }>;
1010
- /**
1011
- * Helper to check if output contains a question
1012
- */
1013
- protected containsQuestion(output: string): boolean;
1014
- /**
1015
- * Helper to strip ANSI escape codes from output
1016
- */
1017
- protected stripAnsi(str: string): string;
1018
- }
1019
-
1020
- /**
1021
- * Adapter Factory
1022
- *
1023
- * Factory function for creating CLI adapters from configuration.
1024
- */
1025
-
1026
- /**
1027
- * Creates a CLI adapter from configuration
1028
- */
1029
- declare function createAdapter(config: AdapterFactoryConfig): CLIAdapter;
1030
-
1031
646
  /**
1032
647
  * Shell Adapter
1033
648
  *
@@ -1251,4 +866,4 @@ declare function isBun(): boolean;
1251
866
  */
1252
867
  declare function createPTYManager(options?: BunPTYManagerOptions): BunCompatiblePTYManager;
1253
868
 
1254
- export { type AdapterFactoryConfig, AdapterRegistry, type AuthRequiredInfo, type AuthRequiredMethod, type AutoResponseRule, BaseCLIAdapter, type BlockingPromptDetection, type BlockingPromptInfo, type BlockingPromptType, type BuildTimelineOptions, BunCompatiblePTYManager, type BunPTYManagerOptions, type CLIAdapter, type LogOptions, type Logger, type LoginDetection, type MessageType, PTYManager, type PTYManagerConfig, type PTYManagerEvents, PTYSession, type PTYSessionEvents, type ParsedOutput, SPECIAL_KEYS, type SessionFilter, type SessionHandle, type SessionMessage, type SessionStatus, ShellAdapter, type ShellAdapterOptions, type SpawnConfig, type StallClassification, type StopOptions, type TaskCompletionTimelineResult, type TaskCompletionTimelineStep, type TaskCompletionTraceRecord, type TaskCompletionTurnTimeline, type TerminalAttachment, type ToolRunningInfo, type WorkerSessionHandle, buildTaskCompletionTimeline, createAdapter, createPTYManager, extractTaskCompletionTraceRecords, isBun };
869
+ export { type AuthRequiredInfo, type AuthRequiredMethod, type BlockingPromptInfo, type BuildTimelineOptions, BunCompatiblePTYManager, type BunPTYManagerOptions, type LogOptions, type Logger, PTYManager, type PTYManagerConfig, type PTYManagerEvents, PTYSession, type PTYSessionEvents, SPECIAL_KEYS, type SessionFilter, type SessionHandle, type SessionMessage, type SessionStatus, ShellAdapter, type ShellAdapterOptions, type StallClassification, type StopOptions, type TaskCompletionTimelineResult, type TaskCompletionTimelineStep, type TaskCompletionTraceRecord, type TaskCompletionTurnTimeline, type TerminalAttachment, type WorkerSessionHandle, buildTaskCompletionTimeline, createPTYManager, ensurePty, extractTaskCompletionTraceRecords, isBun };