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.

7.0 KB
Raw Blame
import { tmpdir } from 'node:os';
import path from 'node:path';

import type {
  AgentContentBlock,
  AgentImageBlock,
  AgentPromptInput,
  AgentTextBlock,
} from '../../protocol';
import type { NormalizedImage, NormalizeImageOptions } from './normalizeImage';
import { materializeImageToPath, normalizeImage } from './normalizeImage';

export interface BuildAgentInputOptions extends NormalizeImageOptions {
  /**
   * Directory used to materialize images for path-based agents (Codex/OpenCode). When
   * unset, falls back to `cacheDir`, then to a per-agent subdirectory under
   * the OS tmpdir. Path-input images skip materialization entirely.
   */
  imageMaterializeDir?: string;
}

/**
 * Result of preparing input for a child agent process.
 *
 * `args` is appended to the agent's CLI argv (e.g. Codex `--image <path>`
 * pairs); `stdin` is the payload written to the child's stdin (stream-json
 * for Amp / Claude Code / CodeBuddy, raw text for Codex).
 */
export interface AgentInputPlan {
  args: string[];
  stdin: string;
}

const toBlocks = (input: AgentPromptInput): AgentContentBlock[] => {
  if (typeof input === 'string') return input ? [{ text: input, type: 'text' }] : [];
  return input;
};

const isTextBlock = (b: AgentContentBlock): b is AgentTextBlock => b.type === 'text';
const isImageBlock = (b: AgentContentBlock): b is AgentImageBlock => b.type === 'image';

const collectText = (blocks: AgentContentBlock[]): string =>
  blocks
    .filter(isTextBlock)
    .map((b) => b.text)
    .filter((t) => t.length > 0)
    .join('\n\n');

const buildClaudeCompatibleStdin = async (
  blocks: AgentContentBlock[],
  options: BuildAgentInputOptions,
): Promise<AgentInputPlan> => {
  const content: Array<
    | { text: string; type: 'text' }
    | { source: { data: string; media_type: string; type: 'base64' }; type: 'image' }
  > = [];

  for (const block of blocks) {
    if (isTextBlock(block)) {
      if (block.text.length > 0) content.push({ text: block.text, type: 'text' });
      continue;
    }
    if (isImageBlock(block)) {
      const image = await normalizeImage(block.source, options);
      content.push({
        source: {
          data: image.buffer.toString('base64'),
          media_type: image.mediaType,
          type: 'base64',
        },
        type: 'image',
      });
    }
  }

  return {
    args: [],
    stdin: `${JSON.stringify({
      message: { content, role: 'user' },
      type: 'user',
    })}\n`,
  };
};

const resolvePathInputImagePaths = async (
  blocks: AgentContentBlock[],
  options: BuildAgentInputOptions,
): Promise<string[]> => {
  const imageBlocks = blocks.filter(isImageBlock);
  if (imageBlocks.length === 0) return [];

  const materializeDir =
    options.imageMaterializeDir ||
    options.cacheDir ||
    path.join(tmpdir(), 'lobehub-hetero-agent-images');

  const results = await Promise.allSettled(
    imageBlocks.map(async (block) => {
      const image: NormalizedImage = await normalizeImage(block.source, options);
      return materializeImageToPath(image, materializeDir);
    }),
  );
  const failure = results.find(
    (result): result is PromiseRejectedResult => result.status === 'rejected',
  );
  if (failure) throw failure.reason;

  return results.map((result) => (result as PromiseFulfilledResult<string>).value);
};

const buildCodexInput = async (
  blocks: AgentContentBlock[],
  options: BuildAgentInputOptions,
): Promise<AgentInputPlan> => {
  const text = collectText(blocks);
  const imagePaths = await resolvePathInputImagePaths(blocks, options);

  return {
    args: imagePaths.flatMap((p) => ['--image', p]),
    stdin: text,
  };
};

const buildOpenCodeInput = async (
  blocks: AgentContentBlock[],
  options: BuildAgentInputOptions,
): Promise<AgentInputPlan> => {
  const imagePaths = await resolvePathInputImagePaths(blocks, options);
  return {
    args: imagePaths.flatMap((imagePath) => ['--file', imagePath]),
    stdin: collectText(blocks),
  };
};

const buildPiInput = async (): Promise<AgentInputPlan> => {
  // pi runs exclusively over the RPC transport (PiRpcSession /
  // createPiRpcAgentHandle) — the legacy `--mode json` stdin input is gone.
  throw new Error(
    'pi runs over the RPC transport only — use PiRpcSession / createPiRpcAgentHandle',
  );
};

const buildKimiCodeInput = async (
  blocks: AgentContentBlock[],
  options: BuildAgentInputOptions,
): Promise<AgentInputPlan> => {
  const imagePaths = await resolvePathInputImagePaths(blocks, options);
  const text = collectText(blocks);

  // One-shot `--prompt` mode has no attachment flag, but the model reads local
  // images via its builtin ReadMediaFile tool when the prompt references a path.
  const imageSection = imagePaths
    .map((p) => `[Image attached: ${p}] Use the ReadMediaFile tool to view this image.`)
    .join('\n');
  const prompt = [text, imageSection].filter(Boolean).join('\n\n');

  return { args: ['--prompt', prompt], stdin: '' };
};

const buildQoderInput = async (
  blocks: AgentContentBlock[],
  options: BuildAgentInputOptions,
): Promise<AgentInputPlan> => {
  const imagePaths = await resolvePathInputImagePaths(blocks, options);
  const text = collectText(blocks);

  return {
    args: imagePaths.flatMap((imagePath) => ['--attachment', imagePath]),
    stdin: `${JSON.stringify({
      message: {
        content: text ? [{ text, type: 'text' }] : [],
        role: 'user',
      },
      parent_tool_use_id: null,
      type: 'user',
    })}\n`,
  };
};

/**
 * Convert a unified `AgentPromptInput` into the per-agent stdin payload + any
 * extra CLI args required to attach images. The single source of truth for
 * how each external agent CLI receives multimodal input.
 *
 * - `amp` / `claude-code` / `codebuddy`: stream-json on stdin with text + base64 image content blocks
 * - `codex`: raw text on stdin + repeatable `--image <path>` flags
 * - `kimi-code`: `--prompt <text>` with materialized image paths referenced in the text
 * - `opencode`: raw text on stdin + repeatable `--file <path>` flags
 * - `pi`: raw text on stdin + repeatable `@<path>` arguments
 * - `qoder`: stream-json text on stdin + repeatable `--attachment <path>` flags
 *
 * Path-mode agents materialize URL / base64 images via `materializeImageToPath`
 * into `imageMaterializeDir` (defaults to `cacheDir` then `os.tmpdir()`).
 */
export const buildAgentInput = async (
  agentType: string,
  prompt: AgentPromptInput,
  options: BuildAgentInputOptions = {},
): Promise<AgentInputPlan> => {
  const blocks = toBlocks(prompt);

  switch (agentType) {
    case 'amp':
    case 'claude-code':
    case 'codebuddy': {
      return buildClaudeCompatibleStdin(blocks, options);
    }
    case 'codex': {
      return buildCodexInput(blocks, options);
    }
    case 'kimi-code': {
      return buildKimiCodeInput(blocks, options);
    }
    case 'opencode': {
      return buildOpenCodeInput(blocks, options);
    }
    case 'pi': {
      return buildPiInput();
    }
    case 'qoder': {
      return buildQoderInput(blocks, options);
    }
    default: {
      throw new Error(`buildAgentInput: unsupported agent type "${agentType}"`);
    }
  }
};