> 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.3-link-understanding-and-media-understanding.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 34.3 Link Understanding and Media Understanding

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

***

When a user sends a YouTube link in chat, or forwards a voice message or photo, a pure-text Agent cannot "see" or "hear" these contents. OpenClaw bridges this gap through two understanding systems: **Link Understanding** extracts content behind URLs as text summaries, and **Media Understanding** converts images, audio, and video into text descriptions or transcriptions. These additional pieces of information are ultimately injected into the message context, enabling the Agent to "understand" multimedia content.

## 34.3.1 Link Understanding (`src/link-understanding/`)

### Architecture Overview

The link understanding module is a lightweight pipeline with the following core flow:

```
User message → extractLinksFromMessage (URL extraction)
  → resolveScopeDecision (scope check)
    → runLinkEntries (CLI toolchain execution)
      → formatLinkUnderstandingBody (result injection into message body)
```

### URL Extraction

`extractLinksFromMessage` extracts bare URLs (URLs not within Markdown link syntax) from user messages:

```typescript
// src/link-understanding/detect.ts
const MARKDOWN_LINK_RE = /\[[^\]]*]\((https?:\/\/\S+?)\)/gi;
const BARE_LINK_RE = /https?:\/\/\S+/gi;

export function extractLinksFromMessage(message: string, opts?: { maxLinks?: number }): string[] {
  // 1. First remove Markdown links [text](url) to avoid duplicate extraction
  const sanitized = stripMarkdownLinks(message);
  
  // 2. Use regex to match all bare URLs
  const seen = new Set<string>();      // deduplication
  const results: string[] = [];
  for (const match of sanitized.matchAll(BARE_LINK_RE)) {
    if (!isAllowedUrl(match[0])) continue;  // filter internal addresses like 127.0.0.1
    if (seen.has(match[0])) continue;
    results.push(match[0]);
    if (results.length >= maxLinks) break;   // default max 3
  }
  return results;
}
```

**Design rationale**: The reason for removing Markdown link syntax first is that the URL in `[click here](https://example.com)` is a reference intentionally hidden behind text by the user and shouldn't be treated as an independent link to understand; whereas the bare URL in `see https://example.com` is what the user wants the Agent to understand.

### CLI Toolchain Driven

Link understanding doesn't have any built-in web parsing logic; instead, it executes through configured external CLI tools. Each tool entry (`LinkModelConfig`) defines a command and argument template:

```typescript
// Configuration example (YAML)
tools:
  links:
    enabled: true
    maxLinks: 3
    models:
      - type: cli
        command: "node"
        args: ["./scripts/fetch-url.js", "{{LinkUrl}}"]
        timeoutSeconds: 30
```

`runCliEntry` injects the URL into the template variable `{{LinkUrl}}`, then executes the subprocess via `runExec`. The template engine reuses the `applyTemplate` function introduced in Chapter 18, supporting all variables from the message context.

Multiple tool entries are tried in sequence (fallback chain):

```typescript
// src/link-understanding/runner.ts
async function runLinkEntries(params): Promise<string | null> {
  for (const entry of params.entries) {
    try {
      const output = await runCliEntry({ entry, url, ctx, config });
      if (output) return output;  // return first one with output
    } catch (err) {
      // log failure, try next
    }
  }
  return null;  // all tools failed
}
```

### Scope Control

Link understanding reuses the scope system from the media understanding module (`resolveMediaUnderstandingScope`), supporting enable/disable control by channel, chat type, and session prefix:

```yaml
# Enable link understanding only in Telegram private chats
tools:
  links:
    scope:
      default: deny
      rules:
        - match: { channel: telegram, chatType: private }
          action: allow
```

### Result Injection

When the CLI tool returns a link content summary, `applyLinkUnderstanding` appends the result to the end of the message body:

```typescript
// src/link-understanding/format.ts
export function formatLinkUnderstandingBody(params): string {
  const base = (params.body ?? "").trim();
  if (!base) return outputs.join("\n");
  return `${base}\n\n${outputs.join("\n")}`;
}
```

This way, the message the Agent receives becomes:

```
Original user text

[Link 1 content summary]
[Link 2 content summary]
```

## 34.3.2 Media Understanding (`src/media-understanding/`)

### Architecture Overview

The media understanding module is significantly larger and more complex than link understanding. It handles three media capabilities: image description (image.description), audio transcription (audio.transcription), and video description (video.description), plus accompanying file content extraction. The overall architecture can be divided into four layers:

```
                    ┌─────────────────────────┐
                    │   applyMediaUnderstanding│  ← Entry orchestration layer
                    │   (apply.ts)             │
                    └────────┬────────────────┘
                             │
              ┌──────────────┼──────────────┐
              ▼              ▼              ▼
         runCapability   runCapability  runCapability    ← Capability execution layer
         (image)         (audio)        (video)
              │              │              │
              ▼              ▼              ▼
      ┌───────────────────────────────────────┐
      │       Provider / CLI Dispatch Layer   │         ← Model dispatch layer
      │  runProviderEntry / runCliEntry        │
      └───────────────────────────────────────┘
              │              │              │
              ▼              ▼              ▼
      ┌─────────┐  ┌──────────┐  ┌─────────┐
      │ OpenAI  │  │ Deepgram │  │ Google  │  ...      ← Provider implementation layer
      │ Groq    │  │ Anthropic│  │ MiniMax │
      └─────────┘  └──────────┘  └─────────┘
```

### Type System

```typescript
// src/media-understanding/types.ts
export type MediaUnderstandingKind =
  | "audio.transcription"    // Transcribe audio to text
  | "video.description"      // Describe video content
  | "image.description";     // Describe image content

export type MediaUnderstandingCapability = "image" | "audio" | "video";

export type MediaUnderstandingProvider = {
  id: string;
  capabilities?: MediaUnderstandingCapability[];
  transcribeAudio?: (req: AudioTranscriptionRequest) => Promise<AudioTranscriptionResult>;
  describeVideo?: (req: VideoDescriptionRequest) => Promise<VideoDescriptionResult>;
  describeImage?: (req: ImageDescriptionRequest) => Promise<ImageDescriptionResult>;
};
```

Each Provider can implement one or more capability interfaces. For example, OpenAI supports both audio transcription (Whisper API) and image description (GPT-4o Vision), while Deepgram only supports audio transcription.

### Provider Registry

Six built-in Providers are registered in `providers/index.ts`:

| Provider  | Audio | Image | Video | Default Model          |
| --------- | ----- | ----- | ----- | ---------------------- |
| Groq      | ✓     | -     | -     | whisper-large-v3-turbo |
| OpenAI    | ✓     | ✓     | -     | gpt-4o-mini-transcribe |
| Google    | -     | ✓     | ✓     | gemini-3-flash-preview |
| Anthropic | -     | ✓     | -     | claude-opus-4-6        |
| MiniMax   | -     | ✓     | -     | MiniMax-VL-01          |
| Deepgram  | ✓     | -     | -     | nova-3                 |

### Automatic Model Discovery

When users don't explicitly specify media understanding models in the config file, the system automatically discovers available models through `resolveAutoEntries`, searching in this order:

```
1. The main model currently used by the Agent (if it supports the capability)
2. Local CLI tools (audio: sherpa-onnx → whisper-cli → whisper)
3. Gemini CLI (if `gemini` command is available)
4. Probe cloud API Keys by priority:
   - Audio: openai → groq → deepgram → google
   - Image: openai → anthropic → google → minimax
   - Video: google
```

> **Sidebar — Whisper**
>
> Whisper is an open-source automatic speech recognition (ASR) model from OpenAI, supporting multi-language transcription and translation. `whisper-cli` is its C++ port (whisper.cpp), running on local CPU without GPU. OpenClaw prioritizes detecting local Whisper installation to avoid API call overhead.

### Intelligent Skip Mechanism

A clever optimization: when the Agent's main model (like GPT-4o) itself supports vision capabilities, `runCapability` skips image description—because images will be passed directly as multimodal input to the main model, requiring no additional description step:

```typescript
// src/media-understanding/runner.ts (simplified)
if (capability === "image" && activeProvider) {
  const entry = findModelInCatalog(catalog, activeProvider, model);
  if (modelSupportsVision(entry)) {
    // Skip: main model natively supports vision, images will be injected directly into model context
    return { outputs: [], decision: { outcome: "skipped" } };
  }
}
```

### Attachment Caching

The `MediaAttachmentCache` class caches download results for each attachment, preventing the same attachment from being downloaded multiple times by different capabilities:

```typescript
export class MediaAttachmentCache {
  private readonly entries = new Map<number, AttachmentCacheEntry>();
  
  // Get Buffer (read from local path or download from URL)
  async getBuffer(params: { attachmentIndex, maxBytes, timeoutMs }): Promise<MediaBufferResult>
  
  // Get file path (if remote URL, download to temp file first)
  async getPath(params: { attachmentIndex, maxBytes, timeoutMs }): Promise<MediaPathResult>
  
  // Clean up all temp files
  async cleanup(): Promise<void>
}
```

CLI tools need file paths (`getPath`), API Providers need Buffers (`getBuffer`). The caching layer unifies handling of both access patterns and cleans up temp files at the end.

### Concurrency Control

Media understanding involves network I/O (downloading attachments, calling APIs), which can be time-consuming. `runWithConcurrency` implements a simple but effective worker pool model:

```typescript
// src/media-understanding/concurrency.ts
export async function runWithConcurrency<T>(
  tasks: Array<() => Promise<T>>,
  limit: number,
): Promise<T[]> {
  const results = Array.from({ length: tasks.length });
  let next = 0;
  const workers = Array.from({ length: limit }, async () => {
    while (true) {
      const index = next++;
      if (index >= tasks.length) return;
      results[index] = await tasks[index]();
    }
  });
  await Promise.allSettled(workers);
  return results;
}
```

The default concurrency is 2 (`DEFAULT_MEDIA_CONCURRENCY`), ensuring at most two concurrent executions among the three capabilities (image, audio, video).

### Scope Rules System

Media understanding controls its enabled state in different scenarios through a rule chain:

```typescript
// src/media-understanding/scope.ts
export function resolveMediaUnderstandingScope(params: {
  scope?: MediaUnderstandingScopeConfig;
  sessionKey?: string;
  channel?: string;
  chatType?: string;
}): "allow" | "deny" {
  for (const rule of scope.rules) {
    // Rule matching: three dimensions - channel + chatType + keyPrefix
    if (matchChannel && matchChannel !== channel) continue;
    if (matchChatType && matchChatType !== chatType) continue;
    if (matchPrefix && !sessionKey.startsWith(matchPrefix)) continue;
    return rule.action;  // first matching rule determines result
  }
  return scope.default ?? "allow";  // use default policy if no match
}
```

### CLI Output Parsing

When using CLI tools (like `whisper-cli`, `gemini`, `sherpa-onnx-offline`), different tools have different output formats. `resolveCliOutput` implements multi-strategy output parsing:

| Tool                  | Parsing Strategy                           |
| --------------------- | ------------------------------------------ |
| `whisper-cli`         | Read `{outputBase}.txt` file               |
| `whisper`             | Read `{outputDir}/{basename}.txt` file     |
| `gemini`              | Extract `response` field from JSON stdout  |
| `sherpa-onnx-offline` | Recursively extract `text` field from JSON |
| Others                | Use stdout text directly                   |

### Entry Orchestration

`applyMediaUnderstanding` is the entry point of the entire module, orchestrating the complete media understanding flow:

```typescript
// src/media-understanding/apply.ts (flow simplified)
export async function applyMediaUnderstanding(params): Promise<ApplyMediaUnderstandingResult> {
  const attachments = normalizeMediaAttachments(ctx);
  const cache = createMediaAttachmentCache(attachments);
  
  try {
    // 1. Concurrently execute three capabilities (image / audio / video)
    const tasks = ["image", "audio", "video"].map(capability => 
      () => runCapability({ capability, cfg, ctx, attachments: cache, ... })
    );
    const results = await runWithConcurrency(tasks, concurrency);
    
    // 2. Inject understanding results into message context
    if (outputs.length > 0) {
      ctx.Body = formatMediaUnderstandingBody({ body: ctx.Body, outputs });
      // Audio transcription replaces original message body (voice message scenario)
      if (audioOutputs.length > 0) {
        ctx.Transcript = formatAudioTranscripts(audioOutputs);
        ctx.CommandBody = originalUserText ?? transcript;
      }
    }
    
    // 3. Extract file content blocks (PDF, text files, etc.)
    const fileBlocks = await extractFileBlocks({
      attachments, cache, limits: resolveFileLimits(cfg),
      skipAttachmentIndexes: audioAttachmentIndexes,  // don't reprocess transcribed audio
    });
    if (fileBlocks.length > 0) {
      ctx.Body = appendFileBlocks(ctx.Body, fileBlocks);
    }
    
    // 4. Finalize inbound context
    finalizeInboundContext(ctx, { forceBodyForAgent: true });
  } finally {
    await cache.cleanup();  // clean up temp files
  }
}
```

### File Content Extraction

Besides images/audio/video, text-type attachments sent by users (PDF, CSV, JSON, Markdown, etc.) have their content extracted via `extractFileBlocks`. This function's processing logic includes extensive encoding detection:

1. **UTF-16 BOM Detection**: Identify UTF-16LE/BE encoding through byte order marks (BOM)
2. **Statistical Detection**: For files without BOM, infer UTF-16 encoding by analyzing the distribution of zero bytes in odd/even positions
3. **Legacy Encoding Fallback**: For non-UTF-8 Western text files, decode via CP1252 mapping table (Windows default encoding)
4. **CSV/TSV Guessing**: Infer delimiter format based on the count of commas and tabs in the first line

The extracted content is wrapped as an XML block and injected into the message body:

```xml
<file name="report.pdf" mime="application/pdf">
Extracted text content...
</file>
```

Filenames and MIME types are XML-escaped to prevent attribute value injection attacks.

### Decision Tracking

Each media understanding generates a `MediaUnderstandingDecision` structure, recording which models were attempted for each attachment and the reasons for success/skip/failure. This decision information is stored in the message context's `MediaUnderstandingDecisions` field for debugging and monitoring:

```typescript
export type MediaUnderstandingDecision = {
  capability: "image" | "audio" | "video";
  outcome: "success" | "skipped" | "disabled" | "no-attachment" | "scope-deny";
  attachments: Array<{
    attachmentIndex: number;
    attempts: Array<{ provider, model, type, outcome, reason }>;
    chosen?: { provider, model, outcome };
  }>;
};
```

***

## Section Summary

1. **Link Understanding** extracts bare URLs from messages, obtains content summaries through configurable CLI toolchains, and appends results to the message body.
2. **Media Understanding** supports three capabilities: image description, audio transcription, and video description, unifying six built-in backends (Groq, OpenAI, Google, Anthropic, MiniMax, Deepgram) through a Provider interface layer.
3. **Automatic Model Discovery** probes local CLI tools and cloud API Keys by priority when no explicit configuration is provided, selecting the best available model.
4. **Intelligent Skip** skips image description when the main model already supports vision, avoiding redundant processing.
5. **Attachment Caching** unifies Buffer and file path acquisition, with CLI and API consumption patterns sharing download results.
6. **Scope Rules** support enable policy control across three dimensions: channel, chat type, and session prefix.
7. **File Content Extraction** handles non-media attachments like PDF, CSV, text, including complex encoding detection for UTF-16 and CP1252.
8. **Decision Tracking** completely records model selection, success/failure reasons for each understanding, facilitating debugging and monitoring.
