Skip to main content

Execution Engine API

Implementation Reference​

Source Files:

  • packages/core/src/core/execution-engine.ts - Main engine implementation
  • packages/core/src/core/execution-context.ts - Execution context
  • packages/core/src/adapters/base-adapter.ts - Base adapter interface
  • packages/core/src/core/command-builder.ts - Command construction

Class: ExecutionEngine​

The main execution engine that provides universal command execution across different environments.

Constructor​

class ExecutionEngine {
constructor(options?: ExecutionEngineOptions)
}

interface ExecutionEngineOptions {
defaultTimeout?: number; // Default timeout in ms
defaultShell?: string; // Default shell to use
defaultCwd?: string; // Default working directory
connectionPool?: PoolConfig; // SSH connection pool config
dockerOptions?: DockerOptions; // Docker client options
k8sOptions?: K8sOptions; // Kubernetes client options
}

Methods​

execute()​

Execute a command in the current context.

execute(command: string, options?: ExecutionOptions): ProcessPromise

Parameters:

  • command - Command string to execute
  • options - Optional execution options

Returns: ProcessPromise - Chainable promise with execution result

Example:

const engine = new ExecutionEngine();
const result = await engine.execute('ls -la');
console.log(result.stdout);

ssh()​

Create an SSH execution context.

ssh(target: string | SSHTarget): ExecutionEngine

Parameters:

  • target - SSH target as string (user@host) or SSHTarget object

Returns: ExecutionEngine - New engine with SSH context

Example:

const sshEngine = engine.ssh('user@server.example.com');
await sshEngine.execute('uptime');

// With detailed target
const sshEngine2 = engine.ssh({
host: 'server.example.com',
user: 'deploy',
port: 2222,
privateKey: '/path/to/key'
});

docker()​

Create a Docker execution context.

docker(container: string | DockerTarget): ExecutionEngine

Parameters:

  • container - Container name/ID or DockerTarget object

Returns: ExecutionEngine - New engine with Docker context

Example:

const dockerEngine = engine.docker('my-app');
await dockerEngine.execute('npm test');

// With detailed target
const dockerEngine2 = engine.docker({
container: 'my-app',
user: 'node',
workingDir: '/app'
});

k8s() / kubernetes()​

Create a Kubernetes execution context.

k8s(pod: string | KubernetesTarget): ExecutionEngine
kubernetes(pod: string | KubernetesTarget): ExecutionEngine

Parameters:

  • pod - Pod name or KubernetesTarget object

Returns: ExecutionEngine - New engine with Kubernetes context

Example:

const k8sEngine = engine.k8s('app-pod');
await k8sEngine.execute('ls /app');

// With detailed target
const k8sEngine2 = engine.k8s({
pod: 'app-pod',
container: 'main',
namespace: 'production',
context: 'prod-cluster'
});

local()​

Create a local execution context.

local(): ExecutionEngine

Returns: ExecutionEngine - New engine with local context

Example:

const localEngine = engine.local();
await localEngine.execute('npm install');

cd()​

Change working directory.

cd(path: string): ExecutionEngine

Parameters:

  • path - Directory path

Returns: ExecutionEngine - Engine with new working directory

Example:

await engine.cd('/project').execute('npm build');

env()​

Set environment variables.

env(variables: Record<string, string>): ExecutionEngine

Parameters:

  • variables - Environment variables object

Returns: ExecutionEngine - Engine with environment variables

Example:

await engine
.env({ NODE_ENV: 'production' })
.execute('npm start');

timeout()​

Set execution timeout.

timeout(ms: number): ExecutionEngine

Parameters:

  • ms - Timeout in milliseconds

Returns: ExecutionEngine - Engine with timeout

Example:

await engine
.timeout(60000) // 1 minute
.execute('long-running-task');

pipe()​

Pipe commands together.

pipe(...commands: string[]): ProcessPromise

Parameters:

  • commands - Commands to pipe

Returns: ProcessPromise - Result of piped execution

Example:

const result = await engine.pipe(
'cat file.txt',
'grep pattern',
'wc -l'
);

parallel()​

Execute commands in parallel.

parallel(...commands: string[]): Promise<ExecutionResult[]>

Parameters:

  • commands - Commands to run in parallel

Returns: Promise<ExecutionResult[]> - Array of results

Example:

const results = await engine.parallel(
'npm test',
'npm run lint',
'npm run type-check'
);

ProcessPromise API​

The chainable promise returned by execution methods.

Properties​

interface ProcessPromise extends Promise<ExecutionResult> {
stdin: Writable; // stdin stream
stdout: Readable; // stdout stream
stderr: Readable; // stderr stream
exitCode: Promise<number>; // Exit code promise
}

Methods​

pipe()​

Pipe output to another command.

pipe(command: string): ProcessPromise

Example:

await $`cat file.txt`.pipe('grep pattern');

nothrow()​

Don't throw on non-zero exit code.

nothrow(): ProcessPromise

Example:

const result = await $`test -f file.txt`.nothrow();
if (result.exitCode !== 0) {
console.log('File does not exist');
}

quiet()​

Suppress output.

quiet(): ProcessPromise

Example:

await $`npm install`.quiet();

timeout()​

Set timeout for this execution.

timeout(ms: number): ProcessPromise

Example:

await $`slow-command`.timeout(5000);

cwd()​

Set working directory for this execution.

cwd(path: string): ProcessPromise

Example:

await $`npm build`.cwd('/project');

env()​

Set environment variables for this execution.

env(variables: Record<string, string>): ProcessPromise

Example:

await $`npm start`.env({ PORT: '3000' });

stdin()​

Provide stdin input.

stdin(input: string | Buffer | Readable): ProcessPromise

Example:

await $`cat`.stdin('Hello, World!');

lines()​

Get output as array of lines.

lines(): Promise<string[]>

Example:

const lines = await $`ls -la`.lines();
lines.forEach(line => console.log(line));

json()​

Parse output as JSON.

json<T = any>(): Promise<T>

Example:

const data = await $`cat package.json`.json();
console.log(data.name, data.version);

text()​

Get output as text string.

text(): Promise<string>

Example:

const content = await $`cat README.md`.text();

Execution Result​

The result object returned by executions.

interface ExecutionResult {
stdout: string; // Standard output
stderr: string; // Standard error
exitCode: number; // Exit code
signal?: string; // Termination signal
duration: number; // Execution time in ms
command: string; // Executed command
target?: Target; // Execution target
}

Error Handling​

ExecutionError​

Thrown when command execution fails.

class ExecutionError extends Error {
exitCode: number;
stderr: string;
stdout: string;
command: string;
duration: number;
}

Example:

try {
await $`exit 1`;
} catch (error) {
if (error instanceof ExecutionError) {
console.log('Command failed with exit code:', error.exitCode);
console.log('Error output:', error.stderr);
}
}

Advanced Features​

Connection Pooling​

SSH connections are automatically pooled for performance.

const engine = new ExecutionEngine({
connectionPool: {
max: 10, // Maximum connections
min: 2, // Minimum connections
idleTimeoutMillis: 30000 // Idle timeout
}
});

// Connections are reused automatically
for (let i = 0; i < 100; i++) {
await engine.ssh('server').execute('echo test');
}

Stream Processing​

Process output as it arrives.

const proc = $`tail -f /var/log/app.log`;

proc.stdout.on('data', chunk => {
console.log('Log:', chunk.toString());
});

// Or use async iteration
for await (const line of proc.lines()) {
console.log('Line:', line);
}

Abort Signal​

Cancel long-running operations.

const controller = new AbortController();

// Cancel after 5 seconds
setTimeout(() => controller.abort(), 5000);

try {
await $`long-task`.signal(controller.signal);
} catch (error) {
if (error.name === 'AbortError') {
console.log('Operation cancelled');
}
}

Performance Characteristics​

Based on Implementation Analysis:

Overhead​

  • Engine creation: <1ms
  • Context switching: <1ms
  • Command parsing: <1ms
  • Connection pooling: ~100ms initial, <10ms reused

Memory​

  • Engine instance: ~500KB
  • Per execution: ~1MB
  • Connection pool: ~2MB per connection