@mastra/core
Version:
200 lines • 8.54 kB
TypeScript
/**
* Process Handle (Base Class)
*
* Abstract base class for process handles.
* Manages stdout/stderr callback dispatch and provides lazy
* reader/writer stream getters — subclasses only implement
* the platform-specific primitives.
*/
import { Readable, Writable } from 'node:stream';
import type { CommandResult } from '../types.js';
import type { SpawnProcessOptions } from './types.js';
export declare const DEFAULT_MAX_RETAINED_PROCESS_OUTPUT_BYTES: number;
/**
* Most output one stream can retain, even with `maxRetainedBytes: Infinity`.
* Retained chunks are joined into one string, and V8 throws `RangeError: Invalid string length`
* past ~512 Mi UTF-16 code units. A string never has more code units than UTF-8 bytes, so
* 256 MiB keeps the join well inside that limit.
*/
export declare const MAX_RETAINED_PROCESS_OUTPUT_BYTES: number;
/**
* A process asked to keep all of its output (`maxRetainedBytes` above
* {@link MAX_RETAINED_PROCESS_OUTPUT_BYTES}, e.g. Infinity) produced more than can be held.
* The process is killed and `wait()` rejects with this error rather than returning partial output.
*/
export declare class ProcessOutputLimitError extends Error {
readonly stream: 'stdout' | 'stderr';
readonly limitBytes: number;
readonly name = "ProcessOutputLimitError";
constructor(stream: 'stdout' | 'stderr', limitBytes: number);
}
/** @internal */
export declare function validateMaxRetainedProcessOutputBytes(maxRetainedBytes: number): number;
export declare class RetainedOutputBuffer {
private readonly maxBytes;
readonly hardLimitBytes: number;
private chunks;
private bytes;
private droppedBytes;
private cachedValue;
private overflowedLimit;
/**
* @param maxBytes keep the newest `maxBytes`; above `hardLimitBytes` (e.g. Infinity) means keep everything
* @param hardLimitBytes overridable only so tests can reach the limit without allocating 256 MiB
*/
constructor(maxBytes: number, hardLimitBytes?: number);
/**
* True once a keep-everything buffer received more than `hardLimitBytes`.
* It then stops retaining: what it holds is incomplete and further data is only counted as dropped.
*/
get overflowed(): boolean;
append(data: string): void;
toString(): string;
get truncated(): boolean;
get dropped(): number;
private trim;
private compactIfNeeded;
}
/**
* Thrown by {@link ProcessHandle.closeStdin} when the sandbox provider has no
* way to close a running process's stdin.
*
* `handle.writer.end()` treats this error as a successful finish, so piping to
* a process stays safe on providers without stdin close support.
*/
export declare class UnsupportedStdinCloseError extends Error {
readonly name = "UnsupportedStdinCloseError";
}
/**
* Handle to a spawned process.
*
* Subclasses implement the platform-specific primitives (kill, sendStdin,
* wait). The base class handles bounded stdout/stderr accumulation, callback
* dispatch via `emitStdout`/`emitStderr`, lazy `reader`/`writer` stream
* getters, and optional streaming callbacks on `wait()`.
*
* **For consumers:**
* - `handle.stdout` — poll retained output
* - `handle.wait()` — wait for exit, optionally with streaming callbacks
* - `handle.reader` / `handle.writer` — Node.js stream interop (LSP, JSON-RPC, pipes)
* - `onStdout`/`onStderr` callbacks in {@link SpawnProcessOptions} — stream at spawn time
*
* **For implementors:** Call `emitStdout(data)` / `emitStderr(data)` from
* your transport callback (ChildProcess events, WebSocket messages, etc.)
* to dispatch data. Pass `options` through to `super(options)` to wire
* user callbacks automatically.
*
* @example
* ```typescript
* // Poll model
* const handle = await sandbox.processes.spawn('node server.js');
* console.log(handle.stdout);
*
* // Stream model — callbacks at spawn time
* const handle = await sandbox.processes.spawn('npm run dev', {
* onStdout: (data) => console.log(data),
* });
*
* // Stream model — callbacks during wait
* const result = await handle.wait({
* onStdout: (data) => process.stdout.write(data),
* onStderr: (data) => process.stderr.write(data),
* });
*
* // Stream model — pipe to LSP, JSON-RPC, etc.
* const handle = await sandbox.processes.spawn('typescript-language-server --stdio');
* const connection = createMessageConnection(
* new StreamMessageReader(handle.reader),
* new StreamMessageWriter(handle.writer),
* );
* ```
*/
export declare abstract class ProcessHandle {
/** Process ID */
abstract readonly pid: string;
/** Exit code, undefined while the process is still running */
abstract readonly exitCode: number | undefined;
/** The command that was spawned (set by the process manager) */
command?: string;
/** Kill the running process (SIGKILL). Returns true if killed, false if not found. */
abstract kill(): Promise<boolean>;
/** Send data to the process's stdin */
abstract sendStdin(data: string): Promise<void>;
/**
* Close the process's stdin, signaling EOF.
*
* Providers that cannot close stdin throw {@link UnsupportedStdinCloseError}.
* The default implementation is the unsupported case, so providers only
* override this when their transport exposes a stdin close primitive.
*/
closeStdin(): Promise<void>;
/**
* Wait for the process to finish and return the result.
*
* Optionally pass `onStdout`/`onStderr` callbacks to stream output chunks
* while waiting. The callbacks are automatically removed when `wait()`
* resolves, so there's no cleanup needed by the caller.
*
* Optionally pass an `abortSignal` to couple the blocking wait to a caller
* lifetime: on abort the process is killed (mirroring the spawn-time
* `abortSignal` convention in {@link CommandOptions}), which lets the wait
* settle with the killed process's result instead of blocking forever.
*
* Subclasses implement `wait()` with platform-specific logic; the base
* constructor wraps it to handle the optional streaming callbacks.
*/
wait(_options?: {
onStdout?: (data: string) => void;
onStderr?: (data: string) => void;
abortSignal?: AbortSignal;
}): Promise<CommandResult>;
private _stdout;
private _stderr;
private _outputLimitError?;
private _killedByAbort;
private _abortKill?;
private _stdoutListeners;
private _stderrListeners;
private _reader?;
private _writer?;
constructor(options?: Pick<SpawnProcessOptions, 'maxRetainedBytes' | 'onStdout' | 'onStderr'> & {
/** @internal Lets tests reach the retention limit without producing 256 MiB of output. */
retainedOutputHardLimitBytes?: number;
});
/**
* @internal Whether the process was killed because an `abortSignal` passed to spawn or
* `wait()` fired while it was still running. A direct `kill()` does not set it.
*/
get killedByAbort(): boolean;
/** @internal Kill the process for a fired abort signal and record it in {@link killedByAbort}. */
killForAbort(): Promise<void>;
private runAbortKill;
/** Retained stdout so far */
get stdout(): string;
/** Retained stderr so far */
get stderr(): string;
/** Whether stdout has dropped older output due to the retention limit */
get stdoutTruncated(): boolean;
/** Whether stderr has dropped older output due to the retention limit */
get stderrTruncated(): boolean;
/** Number of stdout bytes dropped due to the retention limit */
get stdoutDroppedBytes(): number;
/** Number of stderr bytes dropped due to the retention limit */
get stderrDroppedBytes(): number;
/**
* Emit stdout data — accumulates, dispatches to user callback, and pushes to reader stream.
* @internal Called by subclasses and process managers to dispatch transport data.
*/
emitStdout(data: string): void;
/**
* Emit stderr data — accumulates and dispatches to user callback.
* @internal Called by subclasses and process managers to dispatch transport data.
*/
emitStderr(data: string): void;
private failForOutputLimit;
/** Readable stream of stdout (for use with StreamMessageReader, pipes, etc.) */
get reader(): Readable;
/** Writable stream to stdin (for use with StreamMessageWriter, pipes, etc.) */
get writer(): Writable;
}
//# sourceMappingURL=process-handle.d.ts.map