Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

6.4 KB
Raw Blame
import { PassThrough } from 'node:stream';

import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';

import type { AgentPromptInput } from '../protocol';
import type { UploadHeterogeneousImage } from '../spawn/agentStreamPipeline';
import { normalizeImage } from '../spawn/input/normalizeImage';
import type { PiRpcImage } from './piRpcProtocol';
import { PiRpcSession } from './piRpcSession';

/** Options mirroring the `spawnAgent` shape the CLI passes for one agent run. */
export interface PiRpcAgentHandleOptions {
  args: string[];
  commandPath: string;
  cwd: string;
  detached?: boolean;
  env: NodeJS.ProcessEnv;
  /** Raw RPC stdout tee, installed before the process is spawned. */
  onRawStdout?: (chunk: Buffer) => void;
  /** Exposes cancellation synchronously, before the eager startup await. */
  onStartupControl?: (control: PiRpcStartupControl) => void;
  operationId: string;
  /** Text + base64 images for the RPC `prompt` command. */
  prompt: { text: string; images?: PiRpcImage[] };
  resumeSessionId?: string;
  uploadImage?: UploadHeterogeneousImage;
}

export interface PiRpcStartupControl {
  cancel: (signal: NodeJS.Signals) => Promise<void>;
}

/**
 * Result shaped like `spawnAgent`'s `SpawnAgentHandle` so the `lh hetero exec`
 * CLI can route pi runs through the RPC transport without changing its event
 * loop, signal handling, or finish/classification plumbing.
 */
export interface PiRpcAgentHandle {
  events: AsyncIterable<AgentStreamEvent>;
  exit: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;
  /** Protocol-level cancel (RPC abort/close) β€” safe alongside an OS signal the process group already delivered. */
  interrupt: (signal?: NodeJS.Signals) => void;
  kill: (signal?: NodeJS.Signals) => void;
  pid: number | undefined;
  readonly sessionId: string | undefined;
  stderr: NodeJS.ReadableStream;
}

interface EventQueue {
  [Symbol.asyncIterator]: () => AsyncIterator<AgentStreamEvent>;
  close: () => void;
  push: (batch: AgentStreamEvent[]) => void;
}

/** Buffered async iterator with a close signal β€” bridges push to pull. */
const createEventQueue = (): EventQueue => {
  const items: AgentStreamEvent[] = [];
  const waiters: Array<() => void> = [];
  let closed = false;

  const notify = () => {
    for (const waiter of waiters.splice(0)) waiter();
  };

  return {
    push(batch) {
      items.push(...batch);
      notify();
    },
    close() {
      closed = true;
      notify();
    },
    async *[Symbol.asyncIterator]() {
      while (true) {
        while (items.length > 0) {
          yield items.shift()!;
        }
        if (closed) return;
        await new Promise<void>((resolve) => waiters.push(resolve));
      }
    },
  };
};

/**
 * Convert `AgentPromptInput` (string | text/image blocks) into the RPC prompt
 * payload: text blocks joined, image blocks normalized to base64 (URL fetch /
 * path read / base64 passthrough, cached under the agent cache dir).
 */
export const toPiRpcPrompt = async (
  input: AgentPromptInput,
  options: { cacheDir?: string } = {},
): Promise<{ images?: PiRpcImage[]; text: string }> => {
  const blocks = typeof input === 'string' ? [{ text: input, type: 'text' as const }] : input;
  const text: string[] = [];
  const images: PiRpcImage[] = [];

  for (const block of blocks) {
    if (block.type === 'text') {
      if (block.text) text.push(block.text);
      continue;
    }
    const image = await normalizeImage(block.source, options);
    images.push({
      data: image.buffer.toString('base64'),
      mimeType: image.mediaType,
      type: 'image',
    });
  }

  return {
    ...(images.length > 0 ? { images } : {}),
    text: text.join('\n\n'),
  };
};

/**
 * Spawn one pi run over the RPC transport and expose it as a `spawnAgent`
 *-shaped handle. Eagerly starts the process + handshake (rejects on
 * spawn/handshake failure β€” the CLI surfaces it via its existing catch), then
 * runs the prompt. `kill('SIGINT')` maps to a graceful `abort`; other signals
 * escalate through the EOF-first shutdown.
 */
export const createPiRpcAgentHandle = async (
  options: PiRpcAgentHandleOptions,
): Promise<PiRpcAgentHandle> => {
  const queue = createEventQueue();
  const stderr = new PassThrough();
  let nativeSessionId: string | undefined;
  let runStarted = false;
  let cancelledSignal: NodeJS.Signals | undefined;

  const sessionOptions = {
    args: options.args,
    commandPath: options.commandPath,
    cwd: options.cwd,
    detached: options.detached,
    env: options.env,
    operationId: options.operationId,
    resumeSessionId: options.resumeSessionId,
    sessionId: options.operationId,
    uploadImage: options.uploadImage,
    onEvents: (events: AgentStreamEvent[]) => queue.push(events),
    onRawStdout: options.onRawStdout,
    onRuntimeStatus: () => {
      /* no-op β€” the CLI surfaces state via events */
    },
    onSessionId: (id: string) => {
      nativeSessionId = id;
    },
    onStderr: (data: string) => {
      stderr.write(data);
    },
  };
  const session = new PiRpcSession(sessionOptions);

  const cancel = async (signal: NodeJS.Signals) => {
    cancelledSignal = signal;
    if (signal === 'SIGKILL') {
      await session.close({ force: true });
    } else if (signal === 'SIGTERM' || !runStarted) {
      await session.close();
    } else {
      await session.abort();
    }
  };
  options.onStartupControl?.({ cancel });

  // Eager spawn + handshake: a missing/broken pi install rejects here so the
  // CLI's existing spawn-failure classification runs.
  await session.start();

  runStarted = true;
  const exit = session
    .run(options.prompt)
    .then(() => {
      queue.close();
      stderr.end();
      return cancelledSignal
        ? { code: null, signal: cancelledSignal }
        : { code: 0, signal: null as NodeJS.Signals | null };
    })
    .catch((error) => {
      queue.close();
      stderr.end(`${error instanceof Error ? error.message : String(error)}\n`);
      return cancelledSignal
        ? { code: null, signal: cancelledSignal }
        : { code: 1, signal: null as NodeJS.Signals | null };
    });

  const signalSession = (signal?: NodeJS.Signals) => {
    void cancel(signal ?? 'SIGINT').catch(() => {
      /* legacy synchronous handle contract is best-effort */
    });
  };

  return {
    events: queue,
    exit,
    interrupt: signalSession,
    kill: signalSession,
    pid: session.pid,
    get sessionId() {
      return nativeSessionId;
    },
    stderr,
  };
};