loopzero-sdk-pty 0.0.0-stage → 0.1.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,256 @@
1
+ import { InteractiveBackend, InteractiveUnavailableError, StartInteractiveOptions, StartInteractiveResult, WriteStdinOptions, WriteStdinResult } from 'loopzero-sdk/interactive';
2
+ import { SandboxMode } from 'loopzero-sdk/sandbox';
3
+
4
+ /**
5
+ * Options for {@link createConfinedPtyBackend}.
6
+ *
7
+ * @public
8
+ */
9
+ interface ConfinedPtyBackendOptions {
10
+ /** Every session starts here; a cwd passed to startInteractive is ignored. */
11
+ root: string;
12
+ /** Sandbox mode handed to interactiveWrapCommand from loopzero-sdk/sandbox. */
13
+ mode: SandboxMode;
14
+ /** Variable names kept from `sourceEnv`. Default: PATH, USER, LOGNAME, LANG, LC_ALL, LC_CTYPE, TERM, TZ. HOME is always set to `root`. */
15
+ envAllowlist?: readonly string[];
16
+ /** Default `process.env`. */
17
+ sourceEnv?: Readonly<Record<string, string | undefined>>;
18
+ /** Default 4. */
19
+ maxSessions?: number;
20
+ /**
21
+ * Test seam: builds the backend that actually spawns. Receives the sandbox wrap and the session
22
+ * ceiling. Defaults to a `PtyInteractiveBackend`.
23
+ */
24
+ createInner?: (inner: {
25
+ wrapCommand: (command: string, cwd: string) => string | null;
26
+ maxSessions: number;
27
+ }) => InteractiveBackend;
28
+ }
29
+ /**
30
+ * An {@link InteractiveBackend} whose every session starts in `root`, runs under
31
+ * `interactiveWrapCommand({ mode })` and sees only the allowlisted environment (plus `HOME=root`).
32
+ * Gate its use on {@link probeConfinement}: a sandbox that is unavailable wraps nothing.
33
+ */
34
+ declare function createConfinedPtyBackend(options: ConfinedPtyBackendOptions): InteractiveBackend;
35
+ /**
36
+ * Outcome of {@link probeConfinement}: confined, or the reason it could not be proven.
37
+ *
38
+ * @public
39
+ */
40
+ type ConfinementProbeResult = {
41
+ confined: true;
42
+ } | {
43
+ confined: false;
44
+ reason: "cannot_write_inside" | "wrote_outside" | "start_failed";
45
+ detail?: string;
46
+ };
47
+ /**
48
+ * Starts a real session that touches `paths.inside` (inside the root) and `paths.outside` (beside
49
+ * it), and reports whether the confinement held. Both paths must be caller-owned, distinct and
50
+ * disposable: they are removed afterwards. The session is always killed.
51
+ *
52
+ * `start_failed` means `startInteractive` rejected (no `node-pty`, no sandbox, spawn error) and
53
+ * carries the message in `detail`. A spawn that succeeds but whose command then fails to run shows
54
+ * up as `cannot_write_inside`.
55
+ */
56
+ declare function probeConfinement(backend: InteractiveBackend, paths: {
57
+ inside: string;
58
+ outside: string;
59
+ }, options?: {
60
+ timeoutMs?: number;
61
+ }): Promise<ConfinementProbeResult>;
62
+
63
+ /**
64
+ * Floor for `StartInteractiveOptions.yieldMs` — how long a call waits for the process to produce
65
+ * output before returning what it has.
66
+ *
67
+ * A shorter wait does not make the call faster, it makes it return an empty or truncated buffer that
68
+ * the model then reasons about as if the program had said nothing. Anything below this is clamped
69
+ * up, silently and on purpose: the alternative is an agent concluding a command produced no output
70
+ * when it simply had not flushed yet.
71
+ */
72
+ declare const YIELD_MIN_MS = 250;
73
+ /**
74
+ * Ceiling for `StartInteractiveOptions.yieldMs`, clamped down.
75
+ *
76
+ * A pty session is interactive; a caller asking to block for longer than this wants a batch command,
77
+ * which `shell` already does without holding a session open. The cap is what keeps a mistyped
78
+ * `yieldMs` from parking an agent turn indefinitely.
79
+ */
80
+ declare const YIELD_MAX_MS = 30000;
81
+ /** Bound the yield window to [{@link YIELD_MIN_MS}, {@link YIELD_MAX_MS}]. */
82
+ declare function clampYield(ms: number | undefined): number;
83
+ /**
84
+ * Constructor options for {@link PtyInteractiveBackend}. Both are optional; `new
85
+ * PtyInteractiveBackend()` gives unconfined commands and an unlimited number of sessions.
86
+ *
87
+ * @public
88
+ */
89
+ interface PtyInteractiveBackendOptions {
90
+ /**
91
+ * Transforms the command immediately before the spawn. It receives the ALREADY-RESOLVED `cwd` — the PTY spawns
92
+ * in it, so a wrap targeting another directory would produce confinement that confines nothing.
93
+ *
94
+ * Returning `null` means **do not wrap** — an explicit decision, distinct from "I wrapped and it made no
95
+ * difference". It is the case of the unconfined mode.
96
+ */
97
+ readonly wrapCommand?: (command: string, cwd: string) => string | null;
98
+ /**
99
+ * M77 — ceiling on simultaneously LIVE sessions. Absent => no ceiling (the long-standing behavior).
100
+ *
101
+ * Each session is a real process with a 5-minute TTL. A model that does not notice it already has a
102
+ * shell open opens another, and the TTL only collects later — too late when the limit is the machine's
103
+ * PID count. On overflow, {@link MaxSessionsError} lists the live sessions, because the correct
104
+ * action is to **reuse** one of them, and an error that does not say so only teaches the model to retry.
105
+ */
106
+ readonly maxSessions?: number;
107
+ }
108
+ /**
109
+ * M77 — the {@link PtyInteractiveBackendOptions.maxSessions} ceiling was reached.
110
+ *
111
+ * Carries `liveSessionIds` by design: `rules/error-handling.md § 2` asks for a message with enough
112
+ * context to act, and here the action is reusing an existing session. An error merely stating
113
+ * "limit reached" would leave the model with no way out — it would retry, and fail again.
114
+ *
115
+ * It EXTENDS {@link InteractiveUnavailableError} and inherits its
116
+ * `code === "interactive_unavailable"`, so a caller catching the parent — or branching on `code` —
117
+ * cannot tell "no pty on this machine" from "you already have N open". Use `instanceof
118
+ * MaxSessionsError` when the two need different handling; only this one is retryable after a
119
+ * `kill()`.
120
+ *
121
+ * @public
122
+ */
123
+ declare class MaxSessionsError extends InteractiveUnavailableError {
124
+ readonly max: number;
125
+ readonly liveSessionIds: readonly string[];
126
+ constructor(max: number, liveSessionIds: readonly string[]);
127
+ }
128
+ /**
129
+ * `InteractiveBackend` backed by a real pty, for programs that only behave correctly on a terminal.
130
+ *
131
+ * Use it when the target REQUIRES a tty — a REPL that prints a prompt, an installer that asks a
132
+ * question, `ssh` asking for a passphrase, anything that checks `isatty` and changes behaviour. For
133
+ * a command that reads stdin and exits, the plain `shell` tool is simpler and does not leave a
134
+ * session to reap.
135
+ *
136
+ * `node-pty` is an OPTIONAL dependency (`optionalDependencies`, not a peer), imported lazily on
137
+ * first use: an install that cannot build the native module still succeeds, and a caller that never
138
+ * starts a session never needs one. When it is absent,
139
+ * starting a session raises `InteractiveUnavailableError` rather than failing at import time — so an
140
+ * agent that merely has the backend registered still runs.
141
+ *
142
+ * Sessions are stateful and idle-reaped (5 minutes by default). A session id that has been reaped
143
+ * raises `NoSuchSessionError`, which is a different fact from "the command failed" and should be
144
+ * handled as "start again", not as an error from the program.
145
+ */
146
+ declare class PtyInteractiveBackend extends InteractiveBackend {
147
+ private readonly sessions;
148
+ private readonly wrapCommand;
149
+ /** M77 — live-session ceiling; `undefined` means unlimited (the historical behaviour). */
150
+ private readonly maxSessions;
151
+ constructor(options?: PtyInteractiveBackendOptions);
152
+ private ptyModule;
153
+ private exitReaperArmed;
154
+ /** Lazy, cached node-pty load — a failed native build must degrade, not crash at import time. */
155
+ private loadPty;
156
+ /**
157
+ * Whether `node-pty` loaded — i.e. whether `startInteractive` can work at all here.
158
+ *
159
+ * Extra to the `InteractiveBackend` contract; a caller writing against the base class must catch
160
+ * {@link InteractiveUnavailableError} instead. `require`s the native module on the first call and
161
+ * CACHES the answer for the life of this instance, so it is cheap to poll and will not notice a
162
+ * module installed afterwards.
163
+ *
164
+ * `true` does not promise a session: the spawn can still fail, and a missing `cwd` is rejected —
165
+ * both surface as {@link InteractiveUnavailableError} from `startInteractive`.
166
+ */
167
+ available(): boolean;
168
+ /** Reap orphaned PTYs when the host process exits. ONLY the `exit` event — installing SIGINT/SIGTERM
169
+ * handlers would remove Node's default terminate-on-signal behavior. Armed once, lazily. */
170
+ private armExitReaper;
171
+ private collect;
172
+ private armTtl;
173
+ /** Allocate a PTY for `command` or throw a typed {@link InteractiveUnavailableError}. Validates the
174
+ * cwd at the boundary (node-pty does NOT throw on a non-existent cwd — it spawns a broken session). */
175
+ private spawnPty;
176
+ /**
177
+ * Spawn `command` on a real pty and return its id plus whatever it printed during the yield
178
+ * window.
179
+ *
180
+ * ```ts
181
+ * const { sessionId, output } = await backend.startInteractive("python3 -i");
182
+ * await backend.writeStdin(sessionId, "print(1+1)\n");
183
+ * backend.kill(sessionId);
184
+ * ```
185
+ *
186
+ * The command runs as `$SHELL -c <command>`, falling back to `/bin/bash` when `SHELL` is unset —
187
+ * so shell syntax works, and so does the user's rc-file behaviour. The child inherits
188
+ * `process.env` WHOLE; there is no allowlist, so every secret in the parent's environment is
189
+ * visible to it.
190
+ *
191
+ * Defaults applied here: `yieldMs` 500 (clamped into [{@link YIELD_MIN_MS},
192
+ * {@link YIELD_MAX_MS}]), `ttlMs` 300000 (5 min idle, then reaped), `maxBytes` 100000, `cols` 80,
193
+ * `rows` 24, `cwd` `process.cwd()`.
194
+ *
195
+ * IT ALWAYS RESOLVES AFTER THE YIELD WINDOW, never when the program is ready. `output` is
196
+ * whatever arrived by then, TAIL-capped to `maxBytes` with a `…(truncated)` marker — so a slow
197
+ * starter returns an empty string that reads exactly like "the program said nothing". Poll with
198
+ * `writeStdin(id, "")` rather than raising `yieldMs`.
199
+ *
200
+ * Throws {@link InteractiveUnavailableError} when `node-pty` is absent, when `cwd` does not exist
201
+ * (checked here because node-pty spawns a broken session instead of failing), or when the spawn
202
+ * itself fails. Throws {@link MaxSessionsError} — a SUBCLASS of it, so a `catch` on the parent
203
+ * swallows the distinction — when `maxSessions` is set and reached.
204
+ *
205
+ * The session outlives this call and must be reclaimed: `kill()` it, or let the idle TTL do it.
206
+ */
207
+ startInteractive(command: string, opts?: StartInteractiveOptions): Promise<StartInteractiveResult>;
208
+ /**
209
+ * Write `chars` to a live session's stdin and return the output produced during the yield window,
210
+ * plus whether the process is still alive.
211
+ *
212
+ * YOU SUPPLY THE NEWLINE. `"print(1+1)"` leaves a REPL waiting; `"print(1+1)\n"` runs it. An
213
+ * EMPTY `chars` writes nothing and just waits — the supported way to poll a program that is still
214
+ * producing output.
215
+ *
216
+ * Every call resets the idle TTL, so a polled session never gets reaped mid-work. Defaults match
217
+ * `startInteractive`: `yieldMs` 500 (clamped), `ttlMs` 300000, `maxBytes` 100000 tail-capped.
218
+ *
219
+ * Concurrent calls on the same session are SERIALIZED, each reading only its own output window —
220
+ * two writes in flight cannot steal each other's output. They are not, however, interleaved with
221
+ * anything the program prints unprompted, which is drained by whichever call is waiting.
222
+ *
223
+ * Throws {@link NoSuchSessionError} when the id is unknown, already killed, or was reaped for
224
+ * idleness. That is a different fact from a failing command: the correct response is to start a
225
+ * new session, not to report an error from the program.
226
+ */
227
+ writeStdin(sessionId: string, chars: string, opts?: WriteStdinOptions): Promise<WriteStdinResult>;
228
+ /**
229
+ * End a session and free its `maxSessions` slot. Idempotent — an unknown or already-killed id is a
230
+ * silent no-op, never a throw.
231
+ *
232
+ * SIGKILLs the whole process GROUP, so a detached grandchild dies with it; there is no graceful
233
+ * shutdown and no chance for the program to flush or save. Falls back to killing just the pty
234
+ * process if the group kill fails. Any output buffered but not yet collected is discarded.
235
+ */
236
+ kill(sessionId: string): void;
237
+ /**
238
+ * `kill()` every live session of THIS backend instance. Extra to the `InteractiveBackend`
239
+ * contract.
240
+ *
241
+ * Also runs automatically on the host process's `exit` event, armed lazily on the first
242
+ * `startInteractive`. Only `exit` — installing SIGINT/SIGTERM handlers would suppress Node's
243
+ * default terminate-on-signal, so a `kill -9` of the host still orphans the ptys.
244
+ */
245
+ killAll(): void;
246
+ /**
247
+ * How many sessions this instance currently holds — the number `maxSessions` is compared against.
248
+ * Extra to the `InteractiveBackend` contract.
249
+ *
250
+ * Drops on its own when a process exits or a TTL fires, so it is a live gauge rather than a
251
+ * counter, and it never counts sessions belonging to another backend instance.
252
+ */
253
+ activeSessionCount(): number;
254
+ }
255
+
256
+ export { type ConfinedPtyBackendOptions, type ConfinementProbeResult, MaxSessionsError, PtyInteractiveBackend, type PtyInteractiveBackendOptions, YIELD_MAX_MS, YIELD_MIN_MS, clampYield, createConfinedPtyBackend, probeConfinement };
@@ -0,0 +1,256 @@
1
+ import { InteractiveBackend, InteractiveUnavailableError, StartInteractiveOptions, StartInteractiveResult, WriteStdinOptions, WriteStdinResult } from 'loopzero-sdk/interactive';
2
+ import { SandboxMode } from 'loopzero-sdk/sandbox';
3
+
4
+ /**
5
+ * Options for {@link createConfinedPtyBackend}.
6
+ *
7
+ * @public
8
+ */
9
+ interface ConfinedPtyBackendOptions {
10
+ /** Every session starts here; a cwd passed to startInteractive is ignored. */
11
+ root: string;
12
+ /** Sandbox mode handed to interactiveWrapCommand from loopzero-sdk/sandbox. */
13
+ mode: SandboxMode;
14
+ /** Variable names kept from `sourceEnv`. Default: PATH, USER, LOGNAME, LANG, LC_ALL, LC_CTYPE, TERM, TZ. HOME is always set to `root`. */
15
+ envAllowlist?: readonly string[];
16
+ /** Default `process.env`. */
17
+ sourceEnv?: Readonly<Record<string, string | undefined>>;
18
+ /** Default 4. */
19
+ maxSessions?: number;
20
+ /**
21
+ * Test seam: builds the backend that actually spawns. Receives the sandbox wrap and the session
22
+ * ceiling. Defaults to a `PtyInteractiveBackend`.
23
+ */
24
+ createInner?: (inner: {
25
+ wrapCommand: (command: string, cwd: string) => string | null;
26
+ maxSessions: number;
27
+ }) => InteractiveBackend;
28
+ }
29
+ /**
30
+ * An {@link InteractiveBackend} whose every session starts in `root`, runs under
31
+ * `interactiveWrapCommand({ mode })` and sees only the allowlisted environment (plus `HOME=root`).
32
+ * Gate its use on {@link probeConfinement}: a sandbox that is unavailable wraps nothing.
33
+ */
34
+ declare function createConfinedPtyBackend(options: ConfinedPtyBackendOptions): InteractiveBackend;
35
+ /**
36
+ * Outcome of {@link probeConfinement}: confined, or the reason it could not be proven.
37
+ *
38
+ * @public
39
+ */
40
+ type ConfinementProbeResult = {
41
+ confined: true;
42
+ } | {
43
+ confined: false;
44
+ reason: "cannot_write_inside" | "wrote_outside" | "start_failed";
45
+ detail?: string;
46
+ };
47
+ /**
48
+ * Starts a real session that touches `paths.inside` (inside the root) and `paths.outside` (beside
49
+ * it), and reports whether the confinement held. Both paths must be caller-owned, distinct and
50
+ * disposable: they are removed afterwards. The session is always killed.
51
+ *
52
+ * `start_failed` means `startInteractive` rejected (no `node-pty`, no sandbox, spawn error) and
53
+ * carries the message in `detail`. A spawn that succeeds but whose command then fails to run shows
54
+ * up as `cannot_write_inside`.
55
+ */
56
+ declare function probeConfinement(backend: InteractiveBackend, paths: {
57
+ inside: string;
58
+ outside: string;
59
+ }, options?: {
60
+ timeoutMs?: number;
61
+ }): Promise<ConfinementProbeResult>;
62
+
63
+ /**
64
+ * Floor for `StartInteractiveOptions.yieldMs` — how long a call waits for the process to produce
65
+ * output before returning what it has.
66
+ *
67
+ * A shorter wait does not make the call faster, it makes it return an empty or truncated buffer that
68
+ * the model then reasons about as if the program had said nothing. Anything below this is clamped
69
+ * up, silently and on purpose: the alternative is an agent concluding a command produced no output
70
+ * when it simply had not flushed yet.
71
+ */
72
+ declare const YIELD_MIN_MS = 250;
73
+ /**
74
+ * Ceiling for `StartInteractiveOptions.yieldMs`, clamped down.
75
+ *
76
+ * A pty session is interactive; a caller asking to block for longer than this wants a batch command,
77
+ * which `shell` already does without holding a session open. The cap is what keeps a mistyped
78
+ * `yieldMs` from parking an agent turn indefinitely.
79
+ */
80
+ declare const YIELD_MAX_MS = 30000;
81
+ /** Bound the yield window to [{@link YIELD_MIN_MS}, {@link YIELD_MAX_MS}]. */
82
+ declare function clampYield(ms: number | undefined): number;
83
+ /**
84
+ * Constructor options for {@link PtyInteractiveBackend}. Both are optional; `new
85
+ * PtyInteractiveBackend()` gives unconfined commands and an unlimited number of sessions.
86
+ *
87
+ * @public
88
+ */
89
+ interface PtyInteractiveBackendOptions {
90
+ /**
91
+ * Transforms the command immediately before the spawn. It receives the ALREADY-RESOLVED `cwd` — the PTY spawns
92
+ * in it, so a wrap targeting another directory would produce confinement that confines nothing.
93
+ *
94
+ * Returning `null` means **do not wrap** — an explicit decision, distinct from "I wrapped and it made no
95
+ * difference". It is the case of the unconfined mode.
96
+ */
97
+ readonly wrapCommand?: (command: string, cwd: string) => string | null;
98
+ /**
99
+ * M77 — ceiling on simultaneously LIVE sessions. Absent => no ceiling (the long-standing behavior).
100
+ *
101
+ * Each session is a real process with a 5-minute TTL. A model that does not notice it already has a
102
+ * shell open opens another, and the TTL only collects later — too late when the limit is the machine's
103
+ * PID count. On overflow, {@link MaxSessionsError} lists the live sessions, because the correct
104
+ * action is to **reuse** one of them, and an error that does not say so only teaches the model to retry.
105
+ */
106
+ readonly maxSessions?: number;
107
+ }
108
+ /**
109
+ * M77 — the {@link PtyInteractiveBackendOptions.maxSessions} ceiling was reached.
110
+ *
111
+ * Carries `liveSessionIds` by design: `rules/error-handling.md § 2` asks for a message with enough
112
+ * context to act, and here the action is reusing an existing session. An error merely stating
113
+ * "limit reached" would leave the model with no way out — it would retry, and fail again.
114
+ *
115
+ * It EXTENDS {@link InteractiveUnavailableError} and inherits its
116
+ * `code === "interactive_unavailable"`, so a caller catching the parent — or branching on `code` —
117
+ * cannot tell "no pty on this machine" from "you already have N open". Use `instanceof
118
+ * MaxSessionsError` when the two need different handling; only this one is retryable after a
119
+ * `kill()`.
120
+ *
121
+ * @public
122
+ */
123
+ declare class MaxSessionsError extends InteractiveUnavailableError {
124
+ readonly max: number;
125
+ readonly liveSessionIds: readonly string[];
126
+ constructor(max: number, liveSessionIds: readonly string[]);
127
+ }
128
+ /**
129
+ * `InteractiveBackend` backed by a real pty, for programs that only behave correctly on a terminal.
130
+ *
131
+ * Use it when the target REQUIRES a tty — a REPL that prints a prompt, an installer that asks a
132
+ * question, `ssh` asking for a passphrase, anything that checks `isatty` and changes behaviour. For
133
+ * a command that reads stdin and exits, the plain `shell` tool is simpler and does not leave a
134
+ * session to reap.
135
+ *
136
+ * `node-pty` is an OPTIONAL dependency (`optionalDependencies`, not a peer), imported lazily on
137
+ * first use: an install that cannot build the native module still succeeds, and a caller that never
138
+ * starts a session never needs one. When it is absent,
139
+ * starting a session raises `InteractiveUnavailableError` rather than failing at import time — so an
140
+ * agent that merely has the backend registered still runs.
141
+ *
142
+ * Sessions are stateful and idle-reaped (5 minutes by default). A session id that has been reaped
143
+ * raises `NoSuchSessionError`, which is a different fact from "the command failed" and should be
144
+ * handled as "start again", not as an error from the program.
145
+ */
146
+ declare class PtyInteractiveBackend extends InteractiveBackend {
147
+ private readonly sessions;
148
+ private readonly wrapCommand;
149
+ /** M77 — live-session ceiling; `undefined` means unlimited (the historical behaviour). */
150
+ private readonly maxSessions;
151
+ constructor(options?: PtyInteractiveBackendOptions);
152
+ private ptyModule;
153
+ private exitReaperArmed;
154
+ /** Lazy, cached node-pty load — a failed native build must degrade, not crash at import time. */
155
+ private loadPty;
156
+ /**
157
+ * Whether `node-pty` loaded — i.e. whether `startInteractive` can work at all here.
158
+ *
159
+ * Extra to the `InteractiveBackend` contract; a caller writing against the base class must catch
160
+ * {@link InteractiveUnavailableError} instead. `require`s the native module on the first call and
161
+ * CACHES the answer for the life of this instance, so it is cheap to poll and will not notice a
162
+ * module installed afterwards.
163
+ *
164
+ * `true` does not promise a session: the spawn can still fail, and a missing `cwd` is rejected —
165
+ * both surface as {@link InteractiveUnavailableError} from `startInteractive`.
166
+ */
167
+ available(): boolean;
168
+ /** Reap orphaned PTYs when the host process exits. ONLY the `exit` event — installing SIGINT/SIGTERM
169
+ * handlers would remove Node's default terminate-on-signal behavior. Armed once, lazily. */
170
+ private armExitReaper;
171
+ private collect;
172
+ private armTtl;
173
+ /** Allocate a PTY for `command` or throw a typed {@link InteractiveUnavailableError}. Validates the
174
+ * cwd at the boundary (node-pty does NOT throw on a non-existent cwd — it spawns a broken session). */
175
+ private spawnPty;
176
+ /**
177
+ * Spawn `command` on a real pty and return its id plus whatever it printed during the yield
178
+ * window.
179
+ *
180
+ * ```ts
181
+ * const { sessionId, output } = await backend.startInteractive("python3 -i");
182
+ * await backend.writeStdin(sessionId, "print(1+1)\n");
183
+ * backend.kill(sessionId);
184
+ * ```
185
+ *
186
+ * The command runs as `$SHELL -c <command>`, falling back to `/bin/bash` when `SHELL` is unset —
187
+ * so shell syntax works, and so does the user's rc-file behaviour. The child inherits
188
+ * `process.env` WHOLE; there is no allowlist, so every secret in the parent's environment is
189
+ * visible to it.
190
+ *
191
+ * Defaults applied here: `yieldMs` 500 (clamped into [{@link YIELD_MIN_MS},
192
+ * {@link YIELD_MAX_MS}]), `ttlMs` 300000 (5 min idle, then reaped), `maxBytes` 100000, `cols` 80,
193
+ * `rows` 24, `cwd` `process.cwd()`.
194
+ *
195
+ * IT ALWAYS RESOLVES AFTER THE YIELD WINDOW, never when the program is ready. `output` is
196
+ * whatever arrived by then, TAIL-capped to `maxBytes` with a `…(truncated)` marker — so a slow
197
+ * starter returns an empty string that reads exactly like "the program said nothing". Poll with
198
+ * `writeStdin(id, "")` rather than raising `yieldMs`.
199
+ *
200
+ * Throws {@link InteractiveUnavailableError} when `node-pty` is absent, when `cwd` does not exist
201
+ * (checked here because node-pty spawns a broken session instead of failing), or when the spawn
202
+ * itself fails. Throws {@link MaxSessionsError} — a SUBCLASS of it, so a `catch` on the parent
203
+ * swallows the distinction — when `maxSessions` is set and reached.
204
+ *
205
+ * The session outlives this call and must be reclaimed: `kill()` it, or let the idle TTL do it.
206
+ */
207
+ startInteractive(command: string, opts?: StartInteractiveOptions): Promise<StartInteractiveResult>;
208
+ /**
209
+ * Write `chars` to a live session's stdin and return the output produced during the yield window,
210
+ * plus whether the process is still alive.
211
+ *
212
+ * YOU SUPPLY THE NEWLINE. `"print(1+1)"` leaves a REPL waiting; `"print(1+1)\n"` runs it. An
213
+ * EMPTY `chars` writes nothing and just waits — the supported way to poll a program that is still
214
+ * producing output.
215
+ *
216
+ * Every call resets the idle TTL, so a polled session never gets reaped mid-work. Defaults match
217
+ * `startInteractive`: `yieldMs` 500 (clamped), `ttlMs` 300000, `maxBytes` 100000 tail-capped.
218
+ *
219
+ * Concurrent calls on the same session are SERIALIZED, each reading only its own output window —
220
+ * two writes in flight cannot steal each other's output. They are not, however, interleaved with
221
+ * anything the program prints unprompted, which is drained by whichever call is waiting.
222
+ *
223
+ * Throws {@link NoSuchSessionError} when the id is unknown, already killed, or was reaped for
224
+ * idleness. That is a different fact from a failing command: the correct response is to start a
225
+ * new session, not to report an error from the program.
226
+ */
227
+ writeStdin(sessionId: string, chars: string, opts?: WriteStdinOptions): Promise<WriteStdinResult>;
228
+ /**
229
+ * End a session and free its `maxSessions` slot. Idempotent — an unknown or already-killed id is a
230
+ * silent no-op, never a throw.
231
+ *
232
+ * SIGKILLs the whole process GROUP, so a detached grandchild dies with it; there is no graceful
233
+ * shutdown and no chance for the program to flush or save. Falls back to killing just the pty
234
+ * process if the group kill fails. Any output buffered but not yet collected is discarded.
235
+ */
236
+ kill(sessionId: string): void;
237
+ /**
238
+ * `kill()` every live session of THIS backend instance. Extra to the `InteractiveBackend`
239
+ * contract.
240
+ *
241
+ * Also runs automatically on the host process's `exit` event, armed lazily on the first
242
+ * `startInteractive`. Only `exit` — installing SIGINT/SIGTERM handlers would suppress Node's
243
+ * default terminate-on-signal, so a `kill -9` of the host still orphans the ptys.
244
+ */
245
+ killAll(): void;
246
+ /**
247
+ * How many sessions this instance currently holds — the number `maxSessions` is compared against.
248
+ * Extra to the `InteractiveBackend` contract.
249
+ *
250
+ * Drops on its own when a process exits or a TTL fires, so it is a live gauge rather than a
251
+ * counter, and it never counts sessions belonging to another backend instance.
252
+ */
253
+ activeSessionCount(): number;
254
+ }
255
+
256
+ export { type ConfinedPtyBackendOptions, type ConfinementProbeResult, MaxSessionsError, PtyInteractiveBackend, type PtyInteractiveBackendOptions, YIELD_MAX_MS, YIELD_MIN_MS, clampYield, createConfinedPtyBackend, probeConfinement };