> 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/ch17-system-prompts-and-context-assembly/17.3-identity-system.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 17.3 Identity System

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~450,000 tokens, Output \~36,000 tokens (Chapter 17 total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

Each Agent in OpenClaw is not just a "nameless assistant" — it can have a name, an emoji identifier, a custom avatar, and a unique reply style. This **identity system** allows users to give Agents personalized appearances while helping distinguish messages from different Agents in multi-Agent scenarios.

The identity system consists of three layers: configuration layer (`identity.ts`), file layer (`identity-file.ts`), and avatar layer (`identity-avatar.ts`).

## 17.3.1 AI Assistant Identity (`src/agents/identity.ts`)

### IdentityConfig: Identity Configuration Type

Agent identity is read from the OpenClaw configuration file. Each Agent can define identity information under `agents.[id].identity`:

```yaml
# openclaw.yaml example
agents:
  agents:
    - id: default
      identity:
        name: "Aria"
        emoji: "🦊"
```

`identity.ts` provides a set of parsing functions to extract identity information from configuration:

```typescript
// src/agents/identity.ts
const DEFAULT_ACK_REACTION = "👀";

export function resolveAgentIdentity(
  cfg: OpenClawConfig,
  agentId: string,
): IdentityConfig | undefined {
  return resolveAgentConfig(cfg, agentId)?.identity;
}
```

`resolveAgentConfig` comes from `agent-scope.ts`, which finds the corresponding entry in the configuration's agents list by Agent ID and returns the normalized configuration object.

### Acknowledgment Reaction (Ack Reaction)

When a user sends a message, OpenClaw first sends an "acknowledgment" emoji reaction (similar to iMessage's "read receipt"), informing the user that the message has been received. The default is 👀, but it can be customized:

```typescript
export function resolveAckReaction(
  cfg: OpenClawConfig, 
  agentId: string
): string {
  // Priority 1: Global configuration messages.ackReaction
  const configured = cfg.messages?.ackReaction;
  if (configured !== undefined) return configured.trim();
  
  // Priority 2: Agent identity emoji
  const emoji = resolveAgentIdentity(cfg, agentId)?.emoji?.trim();
  return emoji || DEFAULT_ACK_REACTION;
}
```

This means if an Agent has a custom emoji (like 🦊), the acknowledgment reaction becomes that emoji instead of the default 👀.

### Message Prefix System

In multi-Agent scenarios or group chats, it's necessary to distinguish which message comes from which Agent. OpenClaw implements this through **message prefixes**:

```typescript
// Generate identity name prefix, format: [Name]
export function resolveIdentityNamePrefix(
  cfg: OpenClawConfig,
  agentId: string,
): string | undefined {
  const name = resolveAgentIdentity(cfg, agentId)?.name?.trim();
  if (!name) return undefined;
  return `[${name}]`;  // e.g., "[Aria]"
}
```

Message prefix resolution has a complex priority logic:

```typescript
export function resolveMessagePrefix(
  cfg: OpenClawConfig,
  agentId: string,
  opts?: { configured?: string; hasAllowFrom?: boolean; fallback?: string },
): string {
  // Priority 1: Explicit configuration
  const configured = opts?.configured ?? cfg.messages?.messagePrefix;
  if (configured !== undefined) return configured;
  
  // Priority 2: Channels with allowFrom don't need prefix
  if (opts?.hasAllowFrom === true) return "";
  
  // Priority 3: Identity name prefix → fallback to default "[openclaw]"
  return resolveIdentityNamePrefix(cfg, agentId) ?? opts?.fallback ?? "[openclaw]";
}
```

> **Sidebar — Relationship Between allowFrom and Message Prefix**
>
> In some channels (like Signal, Telegram), OpenClaw uses dedicated phone numbers/bot accounts to send messages. If `allowFrom` is configured (specifying which phone numbers' messages are considered as coming from OpenClaw), the channel itself can already distinguish message sources, so no additional `[name]` prefix is needed.

### Response Prefix (Response Prefix)

Unlike message prefix, **response prefix** is used to identify the Agent when replying to user messages. It supports four-level priority configuration:

```typescript
export function resolveResponsePrefix(
  cfg: OpenClawConfig,
  agentId: string,
  opts?: { channel?: string; accountId?: string },
): string | undefined {
  // L1: Channel account level (highest priority)
  if (opts?.channel && opts?.accountId) {
    const accountPrefix = 
      channelCfg?.accounts?.[opts.accountId]?.responsePrefix;
    if (accountPrefix !== undefined) {
      if (accountPrefix === "auto") 
        return resolveIdentityNamePrefix(cfg, agentId);
      return accountPrefix;
    }
  }
  
  // L2: Channel level
  if (opts?.channel) {
    const channelPrefix = channelCfg?.responsePrefix;
    if (channelPrefix !== undefined) {
      if (channelPrefix === "auto") 
        return resolveIdentityNamePrefix(cfg, agentId);
      return channelPrefix;
    }
  }
  
  // L4: Global level
  const configured = cfg.messages?.responsePrefix;
  if (configured !== undefined) {
    if (configured === "auto") 
      return resolveIdentityNamePrefix(cfg, agentId);
    return configured;
  }
  return undefined;
}
```

`"auto"` is a special value meaning "automatically use Agent identity name". This configuration is both concise and flexible:

```yaml
# Set auto prefix globally
messages:
  responsePrefix: "auto"   # → automatically becomes "[Aria]"

# Or use custom prefix for Telegram channel
channels:
  telegram:
    responsePrefix: "🤖 "
```

### Human Delay (Humanized Delay)

The identity system also includes an interesting feature — **human delay**. It makes Agent replies no longer "instant" but simulates human typing delays:

```typescript
export function resolveHumanDelayConfig(
  cfg: OpenClawConfig,
  agentId: string,
): HumanDelayConfig | undefined {
  const defaults = cfg.agents?.defaults?.humanDelay;
  const overrides = resolveAgentConfig(cfg, agentId)?.humanDelay;
  if (!defaults && !overrides) return undefined;
  return {
    mode: overrides?.mode ?? defaults?.mode,
    minMs: overrides?.minMs ?? defaults?.minMs,
    maxMs: overrides?.maxMs ?? defaults?.maxMs,
  };
}
```

Configuration example:

```yaml
agents:
  defaults:
    humanDelay:
      mode: "typing"    # Show "typing" status
      minMs: 500        # Minimum delay 500ms
      maxMs: 3000       # Maximum delay 3s
```

## 17.3.2 Identity File (`src/agents/identity-file.ts`)

Besides configuration files, Agents can also define identity through the `IDENTITY.md` file in the workspace. This provides a more user-friendly way — users can directly edit the Markdown file to customize the Agent's appearance.

### AgentIdentityFile Type

```typescript
// src/agents/identity-file.ts
export type AgentIdentityFile = {
  name?: string;     // Agent name
  emoji?: string;    // Representative emoji
  theme?: string;    // Theme color/style
  creature?: string; // Character setting ("AI? robot? ghost in the machine?")
  vibe?: string;     // Tone ("sharp? warm? chaotic? calm?")
  avatar?: string;   // Avatar path or URL
};
```

### IDENTITY.md Parsing

`parseIdentityMarkdown` extracts key-value pairs from Markdown format:

```typescript
export function parseIdentityMarkdown(content: string): AgentIdentityFile {
  const identity: AgentIdentityFile = {};
  const lines = content.split(/\r?\n/);
  
  for (const line of lines) {
    // Clean list markers: remove leading "- "
    const cleaned = line.trim().replace(/^\s*-\s*/, "");
    const colonIndex = cleaned.indexOf(":");
    if (colonIndex === -1) continue;
    
    // Extract label and value, remove Markdown bold/italic markers
    const label = cleaned.slice(0, colonIndex)
      .replace(/[*_]/g, "").trim().toLowerCase();
    const value = cleaned.slice(colonIndex + 1)
      .replace(/^[*_]+|[*_]+$/g, "").trim();
    
    if (!value) continue;
    if (isIdentityPlaceholder(value)) continue; // Skip placeholders
    
    if (label === "name") identity.name = value;
    if (label === "emoji") identity.emoji = value;
    if (label === "creature") identity.creature = value;
    if (label === "vibe") identity.vibe = value;
    if (label === "theme") identity.theme = value;
    if (label === "avatar") identity.avatar = value;
  }
  return identity;
}
```

A typical `IDENTITY.md` file:

```markdown
# Identity

- **Name**: Aria
- **Emoji**: 🦊
- **Creature**: A curious fox spirit
- **Vibe**: Warm but precise
- **Theme**: sunset
- **Avatar**: avatar.png
```

### Placeholder Detection

Placeholder text in initial templates needs to be recognized and ignored, avoiding treating "pick something you like" as a real identity value:

```typescript
const IDENTITY_PLACEHOLDER_VALUES = new Set([
  "pick something you like",
  "ai? robot? familiar? ghost in the machine? something weirder?",
  "how do you come across? sharp? warm? chaotic? calm?",
  "your signature - pick one that feels right",
  "workspace-relative path, http(s) url, or data uri",
]);

function isIdentityPlaceholder(value: string): boolean {
  const normalized = normalizeIdentityValue(value);
  return IDENTITY_PLACEHOLDER_VALUES.has(normalized);
}
```

`normalizeIdentityValue` cleans Markdown format markers, parentheses, Unicode dashes, etc., ensuring that even if placeholder text is slightly modified by users, it's still correctly recognized:

```typescript
function normalizeIdentityValue(value: string): string {
  let normalized = value.trim();
  normalized = normalized.replace(/^[*_]+|[*_]+$/g, "").trim();
  if (normalized.startsWith("(") && normalized.endsWith(")")) {
    normalized = normalized.slice(1, -1).trim();
  }
  normalized = normalized.replace(/[\u2013\u2014]/g, "-"); // em/en dash → hyphen
  normalized = normalized.replace(/\s+/g, " ").toLowerCase();
  return normalized;
}
```

### Identity Validity Detection

`identityHasValues` checks whether the parsing result contains at least one meaningful value:

```typescript
export function identityHasValues(identity: AgentIdentityFile): boolean {
  return Boolean(
    identity.name || identity.emoji || identity.theme || 
    identity.creature || identity.vibe || identity.avatar
  );
}
```

### Loading Identity from Workspace

```typescript
export function loadAgentIdentityFromWorkspace(
  workspace: string
): AgentIdentityFile | null {
  const identityPath = path.join(workspace, DEFAULT_IDENTITY_FILENAME);
  return loadIdentityFromFile(identityPath);
}

export function loadIdentityFromFile(
  identityPath: string
): AgentIdentityFile | null {
  try {
    const content = fs.readFileSync(identityPath, "utf-8");
    const parsed = parseIdentityMarkdown(content);
    if (!identityHasValues(parsed)) return null;
    return parsed;
  } catch {
    return null; // File doesn't exist or read failed
  }
}
```

Note that **synchronous reading** (`readFileSync`) is used here. This is an intentional design choice — identity loading happens on the critical path of Agent startup, files are typically small (<1KB), and synchronous reading avoids the complexity of async flows.

## 17.3.3 Identity Avatar (`src/agents/identity-avatar.ts`)

Avatars give Agents a visual "face" in message channels (like Telegram, Signal). `identity-avatar.ts` is responsible for parsing and validating avatar sources.

### Avatar Resolution Result Type

```typescript
// src/agents/identity-avatar.ts
export type AgentAvatarResolution =
  | { kind: "none"; reason: string }      // No avatar
  | { kind: "local"; filePath: string }    // Local file
  | { kind: "remote"; url: string }        // Remote URL
  | { kind: "data"; url: string };         // Data URI
```

This union type covers four possible avatar states, using TypeScript's **discriminated union** pattern.

> **Sidebar — Discriminated Union**
>
> A discriminated union is a powerful type pattern in TypeScript. By using a common field (here `kind`) to distinguish different type branches, the compiler can automatically infer the types of other fields based on the `kind` value, achieving type-safe pattern matching:
>
> ```typescript
> function handleAvatar(avatar: AgentAvatarResolution) {
>   switch (avatar.kind) {
>     case "local":
>       // TypeScript knows avatar.filePath exists here
>       fs.readFileSync(avatar.filePath);
>       break;
>     case "remote":
>       // TypeScript knows avatar.url exists here
>       fetch(avatar.url);
>       break;
>   }
> }
> ```

### Avatar Source Resolution

Avatar values can come from two places: configuration file or IDENTITY.md file:

```typescript
function resolveAvatarSource(
  cfg: OpenClawConfig, 
  agentId: string
): string | null {
  // Priority 1: identity.avatar in configuration file
  const fromConfig = normalizeAvatarValue(
    resolveAgentIdentity(cfg, agentId)?.avatar
  );
  if (fromConfig) return fromConfig;
  
  // Priority 2: avatar field in IDENTITY.md file
  const workspace = resolveAgentWorkspaceDir(cfg, agentId);
  const fromIdentity = normalizeAvatarValue(
    loadAgentIdentityFromWorkspace(workspace)?.avatar
  );
  return fromIdentity;
}
```

### Avatar Type Detection

```typescript
function isRemoteAvatar(value: string): boolean {
  const lower = value.toLowerCase();
  return lower.startsWith("http://") || lower.startsWith("https://");
}

function isDataAvatar(value: string): boolean {
  return value.toLowerCase().startsWith("data:");
}
```

### Local Avatar Path Resolution and Security Checks

For local file paths, OpenClaw performs strict security validation:

```typescript
const ALLOWED_AVATAR_EXTS = new Set([
  ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg"
]);

function resolveLocalAvatarPath(params: {
  raw: string;
  workspaceDir: string;
}): { ok: true; filePath: string } | { ok: false; reason: string } {
  const workspaceRoot = resolveExistingPath(params.workspaceDir);
  
  // Resolve relative or absolute paths
  const resolved = raw.startsWith("~") || path.isAbsolute(raw)
    ? resolveUserPath(raw)
    : path.resolve(workspaceRoot, raw);
  const realPath = resolveExistingPath(resolved);
  
  // Security check 1: Must be within workspace directory
  if (!isPathWithin(workspaceRoot, realPath)) {
    return { ok: false, reason: "outside_workspace" };
  }
  
  // Security check 2: Must be allowed image extension
  const ext = path.extname(realPath).toLowerCase();
  if (!ALLOWED_AVATAR_EXTS.has(ext)) {
    return { ok: false, reason: "unsupported_extension" };
  }
  
  // Security check 3: File must exist and be a regular file
  try {
    if (!fs.statSync(realPath).isFile()) {
      return { ok: false, reason: "missing" };
    }
  } catch {
    return { ok: false, reason: "missing" };
  }
  
  return { ok: true, filePath: realPath };
}
```

Security checks include three dimensions:

1. **Path traversal protection**: Through `isPathWithin`, ensure the resolved real path (after `realpath` resolves symlinks) is still within the workspace directory. This prevents path traversal attacks like `../../etc/passwd`.
2. **Extension whitelist**: Only allow common image formats, blocking executable files or other dangerous formats.
3. **File existence**: Ensure the referenced file actually exists.

```typescript
function isPathWithin(root: string, target: string): boolean {
  const relative = path.relative(root, target);
  if (!relative) return true;
  return !relative.startsWith("..") && !path.isAbsolute(relative);
}
```

### Complete Avatar Resolution Flow

`resolveAgentAvatar` chains all steps together:

```typescript
export function resolveAgentAvatar(
  cfg: OpenClawConfig, 
  agentId: string
): AgentAvatarResolution {
  const source = resolveAvatarSource(cfg, agentId);
  if (!source) {
    return { kind: "none", reason: "missing" };
  }
  
  if (isRemoteAvatar(source)) {
    return { kind: "remote", url: source };
  }
  
  if (isDataAvatar(source)) {
    return { kind: "data", url: source };
  }
  
  // Local path → security validation
  const workspaceDir = resolveAgentWorkspaceDir(cfg, agentId);
  const resolved = resolveLocalAvatarPath({ raw: source, workspaceDir });
  if (!resolved.ok) {
    return { kind: "none", reason: resolved.reason };
  }
  
  return { kind: "local", filePath: resolved.filePath };
}
```

Decision tree:

```
avatar value
  │
  ├─ Empty/unset       → { kind: "none", reason: "missing" }
  ├─ http(s)://        → { kind: "remote", url }
  ├─ data:             → { kind: "data", url }
  └─ Other             → Treat as local path
       │
       ├─ Path outside workspace    → { kind: "none", reason: "outside_workspace" }
       ├─ Extension not allowed     → { kind: "none", reason: "unsupported_extension" }
       ├─ File doesn't exist        → { kind: "none", reason: "missing" }
       └─ Validation passed         → { kind: "local", filePath }
```

## 17.3.4 Channel-Specific Identity Prefix

In multi-channel scenarios, different message channels may need different identity presentations. OpenClaw handles message prefix and response prefix uniformly through `resolveEffectiveMessagesConfig`:

```typescript
// src/agents/identity.ts
export function resolveEffectiveMessagesConfig(
  cfg: OpenClawConfig,
  agentId: string,
  opts?: {
    hasAllowFrom?: boolean;
    fallbackMessagePrefix?: string;
    channel?: string;
    accountId?: string;
  },
): { messagePrefix: string; responsePrefix?: string } {
  return {
    messagePrefix: resolveMessagePrefix(cfg, agentId, {
      hasAllowFrom: opts?.hasAllowFrom,
      fallback: opts?.fallbackMessagePrefix,
    }),
    responsePrefix: resolveResponsePrefix(cfg, agentId, {
      channel: opts?.channel,
      accountId: opts?.accountId,
    }),
  };
}
```

### Four-Level Prefix Priority

Response prefix configuration supports four levels (highest to lowest):

```
L1: channels.{channel}.accounts.{accountId}.responsePrefix
L2: channels.{channel}.responsePrefix
L3: (skipped — reserved for future Agent-level configuration)
L4: messages.responsePrefix
```

Configuration example:

```yaml
# Global default: no prefix
messages:
  responsePrefix: ""

# Telegram channel: use Agent identity name
channels:
  telegram:
    responsePrefix: "auto"

# Telegram specific account: use custom prefix
channels:
  telegram:
    accounts:
      bot_123456:
        responsePrefix: "🤖 Aria: "
```

When the value is `"auto"`, the system automatically uses `resolveIdentityNamePrefix` to generate a `[Name]` format prefix. This makes configuration both concise and flexible — users only need to set `name` once in Agent identity, and all channels can reference it via `"auto"`.

### Identity Information Usage in Channels

When OpenClaw sends messages through Telegram, Signal, and other channels, various components of the identity system work together:

```
User message arrives
    │
    ├─ resolveAckReaction → Send emoji acknowledgment (e.g., 🦊)
    │
    ├─ Agent processes message...
    │
    └─ Send reply
         │
         ├─ resolveEffectiveMessagesConfig
         │    ├─ messagePrefix: "[Aria]" (proactive messages)
         │    └─ responsePrefix: "" (reply messages, auto-routed)
         │
         └─ resolveAgentAvatar → Set avatar in channel
```

***

## Section Summary

1. **Identity system** consists of three layers: configuration layer (`identity.ts`) handles priority resolution, file layer (`identity-file.ts`) parses IDENTITY.md Markdown, avatar layer (`identity-avatar.ts`) handles multiple avatar sources.
2. **Message prefix** supports four-level configuration priority (account > channel > global), `"auto"` value automatically references Agent identity name, achieving single-definition-multiple-reference.
3. **Avatar security validation** includes path traversal protection, extension whitelist, and file existence checks as triple safeguards.
4. **Placeholder detection** through normalized text comparison ensures template guidance text isn't mistaken for valid identity values.
5. **Human delay** makes Agent reply behavior more human-like, configurable at both Agent and global levels.
6. The entire identity system's design philosophy is **configuration priority, file fallback** — settings in configuration files always override those in IDENTITY.md.
