Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

9.6 KB
Raw Blame
import type { ChildProcess } from 'node:child_process';
import { createInterface } from 'node:readline';
import { Transform } from 'node:stream';
import { spawnProvider, stopProvider } from '../provider-process';

export interface ProviderLogger {
  debug(message: string, context?: Record<string, unknown>): void;
  warn(message: string, context?: Record<string, unknown>): void;
  error(message: string, context?: Record<string, unknown>): void;
}

export const noopLogger: ProviderLogger = {
  debug: () => {},
  warn: () => {},
  error: () => {},
};

export interface StdioJsonRpcClientOptions {
  command: string;
  args: string[];
  cwd: string;
  /** Complete environment for the child; never merged with `process.env`. */
  env: Record<string, string>;
  logger: ProviderLogger;
  /** Called once when the process goes away, whether or not it was asked to. */
  onExit: (reason: string) => void;
  rejectOutputLine?: (line: string) => string | undefined;
}

export class JsonRpcError extends Error {
  constructor(
    readonly code: number,
    message: string,
    readonly data?: unknown
  ) {
    super(message);
    this.name = 'JsonRpcError';
  }
}

interface PendingRequest {
  resolve: (value: unknown) => void;
  reject: (error: Error) => void;
  method: string;
  timer: ReturnType<typeof setTimeout>;
}

type NotificationHandler = (params: unknown) => void;
type ServerRequestHandler = (params: unknown) => Promise<unknown>;

interface JsonRpcMessage {
  id?: number | string;
  method?: string;
  params?: unknown;
  result?: unknown;
  error?: { code: number; message: string; data?: unknown };
}

const STDERR_TAIL_LIMIT = 8_000;

/**
 * Newline-delimited JSON-RPC 2.0 over a child process' stdio. Server-initiated
 * requests (approvals, questions) arrive with both `id` and `method` and are
 * answered on the same channel, which is what separates them from responses.
 */
export class StdioJsonRpcClient {
  private readonly child: ChildProcess;
  private readonly pending = new Map<number, PendingRequest>();
  private readonly notificationHandlers = new Map<string, NotificationHandler[]>();
  private readonly serverRequestHandlers = new Map<string, ServerRequestHandler>();
  private readonly logger: ProviderLogger;
  private readonly onExit: (reason: string) => void;
  private stderrTail = '';
  private nextId = 0;
  private exited = false;
  private processExited = false;

  constructor(options: StdioJsonRpcClientOptions) {
    this.logger = options.logger;
    this.onExit = options.onExit;
    this.child = spawnProvider(options.command, options.args, {
      cwd: options.cwd,
      env: options.env,
      stdio: ['pipe', 'pipe', 'pipe'],
    });

    const stdout = this.child.stdout;
    const stderr = this.child.stderr;
    if (!stdout || !stderr) throw new Error('provider process was spawned without stdio pipes');

    let lineBytes = 0;
    const bounded = new Transform({
      transform(chunk: Buffer, _encoding, callback) {
        for (const byte of chunk) {
          lineBytes = byte === 10 ? 0 : lineBytes + 1;
          if (lineBytes > 16 * 1024 * 1024) {
            callback(
              new Error('Provider protocol line exceeds 16 MiB. Execution was interrupted.')
            );
            return;
          }
        }
        callback(null, chunk);
      },
    });
    bounded.on('error', (error) => {
      stopProvider(this.child, 'SIGKILL');
      this.handleExit(error.message);
    });
    stdout.pipe(bounded);
    createInterface({ input: bounded })
      .on('line', (line) => {
        const error = options.rejectOutputLine?.(line);
        if (error) {
          this.handleExit(error);
          stopProvider(this.child, 'SIGTERM');
        } else this.handleLine(line);
      })
      .on('error', (error) => this.handleExit(error.message));
    stderr.on('data', (chunk: Buffer) => {
      this.stderrTail = `${this.stderrTail}${chunk.toString('utf8')}`.slice(-STDERR_TAIL_LIMIT);
      const error = options.rejectOutputLine?.(this.stderrTail);
      if (error) {
        this.stderrTail = error;
        this.handleExit(error);
        stopProvider(this.child, 'SIGTERM');
      }
    });

    this.child.on('error', (error) => {
      this.processExited = true;
      this.handleExit(`spawn failed: ${error.message}`);
    });
    this.child.on('exit', (code, signal) => {
      this.processExited = true;
      this.handleExit(
        `provider process exited (code ${code ?? 'null'}, signal ${signal ?? 'null'})`
      );
    });
  }

  get stderr(): string {
    return this.stderrTail;
  }

  get isAlive(): boolean {
    return !this.exited;
  }

  request<T>(method: string, params: unknown): Promise<T> {
    if (this.exited) {
      return Promise.reject(new Error(`provider process is gone; cannot call ${method}`));
    }
    const id = ++this.nextId;
    return new Promise<T>((resolve, reject) => {
      const timeoutMs = method === 'session/prompt' ? 12 * 60 * 60 * 1000 : 60000;
      const timer = setTimeout(() => {
        this.pending.delete(id);
        reject(
          new Error(
            `Provider request ${method} timed out; its outcome is unknown and it was not resent.`
          )
        );
      }, timeoutMs);
      timer.unref();
      this.pending.set(id, {
        resolve: resolve as (value: unknown) => void,
        reject,
        method,
        timer,
      });
      try {
        this.write({ jsonrpc: '2.0', id, method, params });
      } catch (error) {
        clearTimeout(timer);
        this.pending.delete(id);
        reject(error instanceof Error ? error : new Error(String(error)));
      }
    });
  }

  notify(method: string, params: unknown): void {
    if (this.exited) return;
    this.write({ jsonrpc: '2.0', method, params });
  }

  onNotification(method: string, handler: NotificationHandler): void {
    const handlers = this.notificationHandlers.get(method) ?? [];
    handlers.push(handler);
    this.notificationHandlers.set(method, handlers);
  }

  onServerRequest(method: string, handler: ServerRequestHandler): void {
    this.serverRequestHandlers.set(method, handler);
  }

  async dispose(): Promise<void> {
    if (this.processExited) return;
    await new Promise<void>((resolve, reject) => {
      const kill = setTimeout(() => stopProvider(this.child, 'SIGKILL'), 2000);
      const timeout = setTimeout(() => {
        cleanup();
        reject(new Error('Provider process did not exit after termination.'));
      }, 5000);
      const cleanup = () => {
        clearTimeout(kill);
        clearTimeout(timeout);
        this.child.removeListener('exit', exited);
      };
      const exited = () => {
        cleanup();
        resolve();
      };
      this.child.once('exit', exited);
      this.child.stdin?.end();
      // On Windows any kill is immediate: the closed stdin is the request to
      // stop, and the kill above is what follows it.
      if (process.platform !== 'win32') this.child.kill('SIGTERM');
    });
  }

  private write(message: Record<string, unknown>): void {
    const stdin = this.child.stdin;
    if (!stdin || !stdin.writable)
      throw new Error('Provider input is closed; command was not written.');
    stdin.write(`${JSON.stringify(message)}\n`);
  }

  private handleLine(line: string): void {
    if (!line.trim()) return;
    let message: JsonRpcMessage;
    try {
      message = JSON.parse(line) as JsonRpcMessage;
    } catch {
      this.logger.warn('provider process emitted a line that is not JSON', { line });
      return;
    }

    if (message.id !== undefined && message.method !== undefined) {
      this.handleServerRequest(message.id, message.method, message.params);
      return;
    }
    if (message.id !== undefined) {
      this.handleResponse(message);
      return;
    }
    if (message.method === undefined) return;

    for (const handler of this.notificationHandlers.get(message.method) ?? []) {
      try {
        handler(message.params);
      } catch (cause) {
        this.logger.error('provider notification handler threw', {
          method: message.method,
          error: String(cause),
        });
      }
    }
  }

  private handleResponse(message: JsonRpcMessage): void {
    const id = typeof message.id === 'number' ? message.id : Number(message.id);
    const pending = this.pending.get(id);
    if (!pending) return;
    this.pending.delete(id);
    clearTimeout(pending.timer);
    if (message.error) {
      pending.reject(
        new JsonRpcError(message.error.code, message.error.message, message.error.data)
      );
      return;
    }
    pending.resolve(message.result);
  }

  private handleServerRequest(id: number | string, method: string, params: unknown): void {
    const handler = this.serverRequestHandlers.get(method);
    if (!handler) {
      this.logger.warn('provider process sent an unhandled request', { method });
      this.write({
        jsonrpc: '2.0',
        id,
        error: { code: -32601, message: `Unhandled server request ${method}` },
      });
      return;
    }
    handler(params)
      .then(
        (result) => this.write({ jsonrpc: '2.0', id, result }),
        (cause: unknown) =>
          this.write({
            jsonrpc: '2.0',
            id,
            error: { code: -32603, message: String(cause) },
          })
      )
      .catch((error: unknown) => {
        this.logger.error('Provider response could not be delivered; its outcome is unknown.', {
          method,
          error: String(error),
        });
      });
  }

  private handleExit(reason: string): void {
    if (this.exited) return;
    this.exited = true;
    for (const [id, pending] of this.pending) {
      this.pending.delete(id);
      clearTimeout(pending.timer);
      pending.reject(new Error(`${reason} while awaiting ${pending.method}`));
    }
    this.onExit(reason);
  }
}