> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch34-infrastructure/34.2-media-pipeline.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 34.2 Media Pipeline

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~58k tokens, Output \~8k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

Chatbots don't just handle text—users send images, audio, PDF documents, and Agents may reply with messages containing media attachments. OpenClaw's media pipeline (`src/media/`) manages the entire media lifecycle: fetching from remote sources, MIME type detection, local storage, image scaling and format conversion, to providing temporary download links via HTTP server. This section will dissect each stage of this pipeline.

## 34.2.1 Media Fetching (`src/media/fetch.ts`)

### Remote Media Pulling

When an Agent outputs a token like `MEDIA: https://example.com/photo.jpg` in its response, the Gateway needs to download the resource pointed to by that URL to local storage. `fetchRemoteMedia` is the entry point for this path:

```typescript
// src/media/fetch.ts (simplified)
export type FetchMediaResult = {
  buffer: Buffer;        // File binary content
  contentType?: string;  // Detected MIME type
  fileName?: string;     // Inferred filename
};

export async function fetchRemoteMedia(options: FetchMediaOptions): Promise<FetchMediaResult> {
  // 1. SSRF protection: initiate request via fetchWithSsrfGuard
  const { response, finalUrl, release } = await fetchWithSsrfGuard({
    url: options.url,
    fetchImpl: options.fetchImpl,
    maxRedirects: options.maxRedirects,
    policy: options.ssrfPolicy,
    lookupFn: options.lookupFn,
  });

  // 2. HTTP status check (non-2xx throws MediaFetchError)
  if (!response.ok) {
    throw new MediaFetchError("http_error", `HTTP ${response.status}...`);
  }

  // 3. Pre-check Content-Length, reject early if exceeds limit
  if (maxBytes && contentLength > maxBytes) {
    throw new MediaFetchError("max_bytes", `content length exceeds maxBytes`);
  }

  // 4. Stream reading + real-time byte limiting
  const buffer = maxBytes
    ? await readResponseWithLimit(response, maxBytes)
    : Buffer.from(await response.arrayBuffer());

  // 5. Filename inference: Content-Disposition > URL path > filePathHint
  const fileName = headerFileName || fileNameFromUrl || filePathHint;

  // 6. MIME detection + extension completion
  const contentType = await detectMime({ buffer, headerMime, filePath });
  return { buffer, contentType, fileName };
}
```

### SSRF Protection

> **Sidebar — SSRF (Server-Side Request Forgery)**
>
> SSRF is a security vulnerability where an attacker tricks a server into requesting internal network resources (such as `http://169.254.169.254/` to fetch cloud metadata). OpenClaw protects against this through `fetchWithSsrfGuard`, which performs DNS pre-resolution and rejects requests pointing to private IP address ranges (10.x, 172.16-31.x, 192.168.x), and limits redirect counts to prevent bypass via 302 redirects.

### Stream Byte Limiting

`readResponseWithLimit` uses the `ReadableStream` `getReader()` API to read the response body in chunks. Each chunk read increments a byte counter. Once the `maxBytes` threshold is exceeded, it immediately calls `reader.cancel()` to terminate stream transmission and throws a `max_bytes` error—this avoids the waste of downloading an entire large file to memory before checking its size:

```typescript
// src/media/fetch.ts
async function readResponseWithLimit(res: Response, maxBytes: number): Promise<Buffer> {
  const reader = res.body!.getReader();
  const chunks: Uint8Array[] = [];
  let total = 0;
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    total += value.length;
    if (total > maxBytes) {
      await reader.cancel();
      throw new MediaFetchError("max_bytes", `payload exceeds maxBytes ${maxBytes}`);
    }
    chunks.push(value);
  }
  return Buffer.concat(chunks.map(c => Buffer.from(c)), total);
}
```

### Filename Inference Strategy

Filename determination follows a three-level priority:

| Priority    | Source                                | Example                                               |
| ----------- | ------------------------------------- | ----------------------------------------------------- |
| 1 (highest) | `Content-Disposition` response header | `filename*=UTF-8''%E5%9B%BE%E7%89%87.png`             |
| 2           | URL path `basename`                   | `https://cdn.example.com/img/photo.jpg` → `photo.jpg` |
| 3 (lowest)  | `filePathHint` passed by caller       | Original path from user message                       |

The `Content-Disposition` header supports RFC 5987's `filename*` extended encoding format (`charset'language'encoded-value`). `parseContentDispositionFileName` first attempts to decode the `filename*` parameter, then falls back to plain `filename`. If the inferred filename lacks an extension, it's auto-completed based on the detected MIME type (e.g., `image/jpeg` → `.jpg`).

## 34.2.2 Media Parsing (`src/media/parse.ts`)

### MEDIA Token Protocol

Agents embed tokens like `MEDIA: <url>` in their output text to indicate that the Gateway should attach media. `splitMediaFromOutput` extracts these tokens from the Agent's raw output while preserving the remaining text content:

```typescript
// src/media/parse.ts
export const MEDIA_TOKEN_RE = /\bMEDIA:\s*`?([^\n]+)`?/gi;

export function splitMediaFromOutput(raw: string): {
  text: string;          // Pure text after removing tokens
  mediaUrls?: string[];  // Extracted media URL list
  mediaUrl?: string;     // First URL (backward compatible)
  audioAsVoice?: boolean;
}
```

### Parsing Process

The parsing process must handle multiple edge cases:

**1. Fenced Code Block Protection**: If `MEDIA:` appears inside Markdown's ` ``` ` fenced code blocks, it's a code example, not a real media token. The parser first calls `parseFenceSpans` to compute all fence intervals, then when scanning line by line, checks whether the character offset of the current line falls within a fence interval—if so, it skips extraction.

**2. URL Validation and Cleaning**: Extracted candidates go through `cleanCandidate` (removing wrapping quotes and parentheses) and `isValidMedia` validation. Valid media sources come in only two forms:

* HTTP(S) URL: `https://example.com/image.png`
* Safe relative path: must start with `./` and contain no `..` (prevents directory traversal)

**3. Fallback Strategy for Paths with Spaces**: When a token value looks like a local path (starting with `/`, `./`, `~/`, `file://`) and contains spaces, the parser attempts to validate the entire value (rather than space-split fragments) as a single path.

**4. Audio Tag Detection**: After parsing completes, the parser checks whether the text contains the `[[audio_as_voice]]` directive tag. This tag tells the Gateway to send audio as a "voice message bubble" (rather than a regular file attachment) to the chat platform.

### Cleaned Text

After extracting all `MEDIA:` lines, the remaining text goes through multiple rounds of cleaning:

```
Original line → Remove MEDIA tokens → Merge excess whitespace → Remove consecutive blank lines → Remove [[audio_as_voice]] tags
```

The final `text` field returned is clean, ready-to-send plain text/Markdown content for users.

## 34.2.3 Media Storage (`src/media/store.ts`)

### Storage Directory

Media files are saved in the `media/` subdirectory under OpenClaw's config directory (typically `~/.config/openclaw/media/`), created on-demand by `ensureMediaDir` with permissions set to `0o700` (accessible only by the current user).

### Storage Methods

`store.ts` provides two storage entry points:

| Function                  | Input             | Purpose                                                   |
| ------------------------- | ----------------- | --------------------------------------------------------- |
| `saveMediaSource(source)` | URL or local path | Resources pointed to by `MEDIA:` tokens in Agent output   |
| `saveMediaBuffer(buffer)` | Buffer in memory  | Inbound media received by platform (images sent by users) |

**Dual-path handling in `saveMediaSource`**:

```typescript
// src/media/store.ts (simplified)
export async function saveMediaSource(source: string): Promise<SavedMedia> {
  const baseId = crypto.randomUUID();
  
  if (looksLikeUrl(source)) {
    // URL path: stream download to temp file → MIME detection → rename to final file
    const tempDest = path.join(dir, `${baseId}.tmp`);
    const { headerMime, sniffBuffer, size } = await downloadToFile(source, tempDest, headers);
    const mime = await detectMime({ buffer: sniffBuffer, headerMime, filePath: source });
    const ext = extensionForMime(mime) ?? path.extname(new URL(source).pathname);
    await fs.rename(tempDest, path.join(dir, `${baseId}${ext}`));
    return { id, path: finalDest, size, contentType: mime };
  }
  
  // Local path: read file to memory → MIME detection → write to storage directory
  const buffer = await fs.readFile(source);
  const mime = await detectMime({ buffer, filePath: source });
  await fs.writeFile(dest, buffer, { mode: 0o600 });
  return { id, path: dest, size: stat.size, contentType: mime };
}
```

**Original filename embedding in `saveMediaBuffer`**: When receiving inbound media, the original filename is embedded in the storage filename using the format `{sanitized}---{uuid}.{ext}`. `sanitizeFilename` filters out cross-platform unsafe characters (preserving only letters, numbers, `.`, `-`, `_`), truncating to 60 characters. When reverse-extracting, `extractOriginalFilename` uses regex matching on the `---{uuid}` pattern to restore the original name.

### TTL Cleanup Mechanism

All media files are temporary with a default TTL of 2 minutes. `cleanOldMedia` is triggered each time a new file is saved, iterating through all files in the storage directory and deleting those whose modification time exceeds the TTL:

```typescript
export async function cleanOldMedia(ttlMs = 2 * 60 * 1000) {
  const entries = await fs.readdir(mediaDir);
  await Promise.all(entries.map(async (file) => {
    const stat = await fs.stat(full);
    if (Date.now() - stat.mtimeMs > ttlMs) {
      await fs.rm(full).catch(() => {});  // silent delete
    }
  }));
}
```

### Stream Download to Disk

`downloadToFile` uses Node.js native `http.request` / `https.request` (rather than `fetch`) for downloading, because fine-grained control over stream transmission is needed:

1. **SSRF Protection**: DNS pre-resolves the target hostname and pins the IP via `resolvePinnedHostname`, passing the resolution result to the underlying request's `lookup` parameter
2. **Manual Redirect Tracking**: Up to 5 redirects, each time parsing the `Location` header and recursively calling
3. **Stream Writing**: Uses `pipeline(res, createWriteStream(dest))` to stream the response body directly to disk
4. **MIME Sniffing Cache**: Simultaneously caches the first 16KB of data to memory (`sniffChunks`) for subsequent MIME detection
5. **Size Limiting**: When cumulative bytes exceed 5MB (`MEDIA_MAX_BYTES`), calls `req.destroy()` to terminate the connection

## 34.2.4 Image Processing: Dual Backend Architecture (`src/media/image-ops.ts`)

### Sharp and sips Dual Backend

OpenClaw's image processing supports two backends, automatically selected based on the runtime environment:

| Backend   | Condition                             | Technology                                        |
| --------- | ------------------------------------- | ------------------------------------------------- |
| **Sharp** | Default backend (Node.js environment) | High-performance image library based on libvips   |
| **sips**  | Bun runtime + macOS                   | macOS built-in Scriptable Image Processing System |

> **Sidebar — Sharp**
>
> Sharp is the most popular image processing library in the Node.js ecosystem, with C library libvips at its core. It supports reading, scaling, rotating, and format conversion for JPEG, PNG, WebP, HEIC and other formats, with performance far exceeding pure JavaScript solutions (like Jimp). However, Sharp depends on native binary modules (`.node` files), which may have compatibility issues in certain runtimes (like Bun).

> **Sidebar — sips**
>
> sips (Scriptable Image Processing System) is a command-line image processing tool built into macOS, located at `/usr/bin/sips`. It supports querying and converting JPEG, PNG, HEIC and other formats through the Core Image framework. OpenClaw prioritizes sips as a Sharp alternative in the Bun + macOS combination, avoiding native module compatibility issues.

Backend selection logic is controlled by the `prefersSips` function:

```typescript
function prefersSips(): boolean {
  return (
    process.env.OPENCLAW_IMAGE_BACKEND === "sips" ||       // environment variable override
    (process.env.OPENCLAW_IMAGE_BACKEND !== "sharp" &&     // not forced to Sharp
     isBun() && process.platform === "darwin")             // Bun + macOS
  );
}
```

### Core Operations

**1. Get Image Metadata**

```typescript
export async function getImageMetadata(buffer: Buffer): Promise<ImageMetadata | null> {
  if (prefersSips()) {
    // sips -g pixelWidth -g pixelHeight input.img → parse stdout
    return await sipsMetadataFromBuffer(buffer);
  }
  const sharp = await loadSharp();
  const meta = await sharp(buffer).metadata();
  return { width: meta.width, height: meta.height };
}
```

The sips backend needs to first write the Buffer to a temporary file (using the `withTempDir` helper function to create a temporary directory, automatically cleaned up after the function returns), then call the command-line tool to parse the output.

**2. EXIF Orientation Correction**

JPEG files' EXIF metadata contains shooting orientation information (orientation, values 1-8). Photos taken vertically on a phone may be horizontally oriented in raw pixels. OpenClaw implements a pure JavaScript EXIF orientation reader `readJpegExifOrientation` that directly parses the JPEG binary format:

```
JPEG file structure:
[FFD8] SOI marker
[FFE1] APP1 marker → [Exif\0\0] header → TIFF header (II/MM byte order)
  → IFD0 (Image File Directory)
    → Tag 0x0112 = Orientation
      → Values 1-8 correspond to different rotation/flip combinations
```

| Orientation Value | Transform             | sips Parameter  |
| ----------------- | --------------------- | --------------- |
| 1                 | No transform          | (skip)          |
| 2                 | Horizontal flip       | `-f horizontal` |
| 3                 | Rotate 180°           | `-r 180`        |
| 6                 | Clockwise rotate 90°  | `-r 90`         |
| 8                 | Clockwise rotate 270° | `-r 270`        |

The Sharp backend is simpler: calling `.rotate()` (without parameters) automatically rotates based on EXIF.

**3. Image Scaling**

`resizeToJpeg` corrects EXIF orientation before scaling to avoid incorrect image orientation after scaling:

```typescript
export async function resizeToJpeg(params: {
  buffer: Buffer;
  maxSide: number;       // Maximum side length (pixels)
  quality: number;       // JPEG quality (1-100)
  withoutEnlargement?: boolean;
}): Promise<Buffer> {
  if (prefersSips()) {
    const normalized = await normalizeExifOrientationSips(buffer);
    return await sipsResizeToJpeg({ buffer: normalized, maxSide, quality });
  }
  // Sharp: .rotate() → .resize({ fit: "inside" }) → .jpeg({ mozjpeg: true })
  return await sharp(buffer).rotate().resize({ width: maxSide, height: maxSide, 
    fit: "inside", withoutEnlargement: true }).jpeg({ quality, mozjpeg: true }).toBuffer();
}
```

Sharp uses the `fit: "inside"` strategy—proportionally scaling the image to fit within a `maxSide × maxSide` bounding box. `mozjpeg: true` enables the Mozilla JPEG encoder for better compression ratio.

**4. PNG Optimization**

For images with alpha channels (transparency), OpenClaw uses PNG format rather than JPEG. `optimizeImageToPng` searches a 2D grid of size-compression level combinations to find the optimal combination satisfying the size limit:

```
Size dimension:   [2048, 1536, 1280, 1024, 800] pixels
Compression dimension: [6, 7, 8, 9] levels (0=fastest, 9=smallest)
```

Starting from the largest size, it returns the first combination where output size ≤ `maxBytes`. If all combinations exceed the limit, it returns the smallest result from the attempts.

**5. HEIC Conversion**

```typescript
export async function convertHeicToJpeg(buffer: Buffer): Promise<Buffer> {
  if (prefersSips()) {
    // sips -s format jpeg input.heic --out output.jpg
    return await sipsConvertToJpeg(buffer);
  }
  return await sharp(buffer).jpeg({ quality: 90, mozjpeg: true }).toBuffer();
}
```

## 34.2.5 Audio Processing (`src/media/audio.ts`)

The audio module is relatively lightweight, primarily responsible for determining whether an audio file is compatible with the chat platform's "voice message" format:

```typescript
// src/media/audio.ts
const VOICE_AUDIO_EXTENSIONS = new Set([".oga", ".ogg", ".opus"]);

export function isVoiceCompatibleAudio(opts: {
  contentType?: string | null;
  fileName?: string | null;
}): boolean {
  // Condition 1: MIME type contains ogg or opus
  const mime = opts.contentType?.toLowerCase();
  if (mime && (mime.includes("ogg") || mime.includes("opus"))) return true;
  
  // Condition 2: File extension is .oga / .ogg / .opus
  const ext = getFileExtension(opts.fileName);
  return VOICE_AUDIO_EXTENSIONS.has(ext);
}
```

> **Sidebar — OGG/Opus Format**
>
> OGG is an open-source multimedia container format, and Opus is the most widely used audio codec within it. Chat platforms like Telegram use OGG Opus format (`.ogg` or `.oga` extension) for voice messages. Compared to MP3, Opus maintains good voice quality even at low bitrates (such as 16kbps), making it ideal for real-time communication scenarios.

Combined with the `[[audio_as_voice]]` tag in `parse.ts`, the complete audio voice flow is:

```
Agent output: "MEDIA: ./voice.ogg\n[[audio_as_voice]]"
  ↓ splitMediaFromOutput parsing
mediaUrl = "./voice.ogg", audioAsVoice = true
  ↓ isVoiceCompatibleAudio check
true (.ogg is voice-compatible format)
  ↓ Gateway sends as voice bubble (not file attachment)
```

## 34.2.6 MIME Type Detection (`src/media/mime.ts`)

### Three-Source Detection Strategy

Accurate MIME type detection is the foundation of the entire media pipeline. `detectMime` synthesizes three information sources for judgment:

```typescript
export async function detectMime(opts: {
  buffer?: Buffer;         // File binary content (for magic number sniffing)
  headerMime?: string;     // HTTP Content-Type header
  filePath?: string;       // File path (for extension inference)
}): Promise<string | undefined>
```

> **Sidebar — Magic Number**
>
> Most file formats have fixed identifiers in their first few bytes, called "magic numbers". For example, JPEG files start with `FF D8`, PNG with `89 50 4E 47`. By checking these bytes, file type can be accurately determined without relying on file extensions. OpenClaw uses the `file-type` library to implement magic number detection.

Detection priority:

| Step | Source                                       | Description                                           |
| ---- | -------------------------------------------- | ----------------------------------------------------- |
| 1    | Magic number sniffing (`fileTypeFromBuffer`) | Most reliable, but cannot identify plain text formats |
| 2    | Extension mapping (`MIME_BY_EXT`)            | Covers 35+ common formats                             |
| 3    | HTTP Content-Type header                     | May be inaccurate, lowest priority                    |

There's an important special case: when magic number sniffing returns a "generic container type" (`application/octet-stream` or `application/zip`), extension mapping overrides the sniffing result. This solves a common problem—`.xlsx` (Excel files) are essentially ZIP archives at the binary level, so magic number detection identifies them as `application/zip`, while the correct MIME should be `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`.

### Type Classification and Size Limits

`constants.ts` defines four media classifications and their size limits:

| Classification | MIME Prefix                     | Max Bytes |
| -------------- | ------------------------------- | --------- |
| `image`        | `image/*`                       | 6 MB      |
| `audio`        | `audio/*`                       | 16 MB     |
| `video`        | `video/*`                       | 16 MB     |
| `document`     | `application/*` (including PDF) | 100 MB    |

`mediaKindFromMime` categorizes files into one of the above four based on MIME type. `maxBytesForKind` returns the corresponding size limit. These limits are consistently enforced across all stages of media fetching and storage.

## 34.2.7 Media Server (`src/media/server.ts` and `src/media/host.ts`)

### Express Media Routes

Media files stored on disk need to be provided for download via HTTP. `attachMediaRoutes` mounts a `GET /media/:id` route on the Express app:

```typescript
// src/media/server.ts (simplified)
export function attachMediaRoutes(app: Express, ttlMs = 2 * 60 * 1000) {
  app.get("/media/:id", async (req, res) => {
    // 1. Validate ID format (only alphanumeric and ._-, max 200 chars)
    if (!isValidMediaId(req.params.id)) return res.status(400).send("invalid path");
    
    // 2. Safely open file (openFileWithinRoot prevents directory traversal)
    const { handle, realPath, stat } = await openFileWithinRoot({
      rootDir: mediaDir, relativePath: id
    });
    
    // 3. TTL check (delete if expired and return 410 Gone)
    if (Date.now() - stat.mtimeMs > ttlMs) {
      await fs.rm(realPath);
      return res.status(410).send("expired");
    }
    
    // 4. Return file content (auto-detect MIME and set Content-Type)
    const data = await handle.readFile();
    res.type(await detectMime({ buffer: data, filePath: realPath }));
    res.send(data);
    
    // 5. Single-use cleanup: delete file 50ms after response completes
    res.on("finish", () => setTimeout(() => fs.rm(realPath), 50));
  });
  
  // Periodic cleanup task
  setInterval(() => cleanOldMedia(ttlMs), ttlMs).unref();
}
```

Key security measures include:

* **ID format whitelist**: Regex `/^[\p{L}\p{N}._-]+$/u` ensures no path separators
* **Root directory locking**: `openFileWithinRoot` resolves symlinks and verifies the real path is still within `mediaDir`
* **410 Gone response**: Expired files return HTTP 410 rather than 404, conforming to REST semantics

### Media Hosting Orchestration

The `ensureMediaHosted` function in `host.ts` orchestrates the entire hosting process:

```
saveMediaSource(source)   → Save file to disk
getTailnetHostname()      → Get Tailscale hostname
isPortFree(42873)         → Check if default port is free
  ├─ Port occupied → Assume webhook server already running, return URL directly
  └─ Port free + startServer=true → Start temporary media server
Final return: https://{tailnet-hostname}/media/{id}
```

> **Sidebar — Tailscale**
>
> Tailscale is a zero-configuration VPN network based on WireGuard (also called Tailnet). Each device joining a Tailnet gets a unique hostname (like `my-server.tailnet-xxxx.ts.net`) and HTTPS certificate. OpenClaw leverages Tailscale's Funnel feature to make the locally-running media server accessible to internet-facing chat platforms (like Telegram Webhook).

## 34.2.8 Input File Processing (`src/media/input-files.ts`)

### Inbound File Extraction

Besides outbound media from Agent output, OpenClaw must handle inbound files sent by users. `input-files.ts` defines a complete input file processing framework:

```typescript
export type InputFileSource = {
  type: "base64" | "url";   // base64 inline data or URL reference
  data?: string;             // base64-encoded file content
  url?: string;              // Remote file URL
  mediaType?: string;        // Declared MIME type
  filename?: string;
};
```

**Dual-mode strategy for PDF extraction**:

When the input file is a PDF, the extractor uses a "text-first, image-fallback" strategy:

1. Use `pdfjs-dist` to extract text content page by page
2. If extracted text exceeds the threshold (default 200 characters), consider the PDF primarily text-based and return the text directly
3. If text is too little (scanned documents, image-only PDFs), load `@napi-rs/canvas` to render each page as a PNG image

Both dependencies (`pdfjs-dist` and `@napi-rs/canvas`) are lazy-loaded—they're only `import()`ed when actually processing PDFs, avoiding startup overhead in non-PDF scenarios.

**Security Limits**:

| Parameter      | Default                     | Description                           |
| -------------- | --------------------------- | ------------------------------------- |
| `maxBytes`     | 5 MB (file) / 10 MB (image) | File size limit                       |
| `maxChars`     | 200,000                     | Character limit for extracted text    |
| `maxPages`     | 4                           | Maximum PDF pages to process          |
| `maxPixels`    | 4,000,000                   | Maximum pixels for PDF page rendering |
| `maxRedirects` | 3                           | Maximum redirects for URL sources     |
| `timeoutMs`    | 10,000                      | URL fetch timeout                     |

***

## Section Summary

1. **Media Fetching** pulls remote resources via SSRF-protected `fetch`, supporting stream byte limiting and three-level filename inference.
2. **Media Parsing** extracts `MEDIA:` tokens from Agent output, handling fenced code blocks, paths with spaces, voice tags, and other edge cases.
3. **Media Storage** uses UUID + original filename naming strategy, all files default to 2-minute TTL, auto-cleanup of expired files.
4. **Image Processing** employs Sharp/sips dual backend architecture, covering metadata queries, EXIF orientation correction, JPEG/PNG scaling, HEIC conversion.
5. **MIME Detection** synthesizes magic number sniffing, extension mapping, HTTP header three sources, resolving common issues like ZIP container misidentification via priority rules.
6. **Media Server** provides temporary HTTP endpoint, integrates Tailscale Funnel for external exposure, files auto-delete after single download.
7. **Input File Processing** supports base64/URL two sources, PDF extraction uses text-first, image-fallback dual-mode strategy.
