> 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/ch13-session-management/13.5-inter-session-communication.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 13.5 Inter-Session Communication (Agent-to-Agent)

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

***

In previous sections, we saw that each session is an independent conversation container. But in practical use, Agents often need to collaborate with Agents in other sessions — for example, the main Agent delegating a coding task to a sub-agent, or querying the history of another session. OpenClaw implements this cross-session communication capability through a set of **session tools** (`sessions_list`, `sessions_history`, `sessions_send`).

> **Sidebar**: Agent-to-Agent (A2A) communication is a core concept in multi-agent systems. Unlike traditional function calls, in A2A communication each Agent is an independent "intelligent entity" with its own conversation context and behavior patterns. Their interactions are more like conversations between two people rather than simple RPC calls. OpenClaw's A2A communication is built on top of the session system — each Agent runs in its own session, with the Gateway relaying messages between them.

## 13.5.1 `sessions_list` / `sessions_history` / `sessions_send` Tools

These three tools form the infrastructure for A2A communication, responsible for **discovery**, **viewing**, and **sending** respectively.

### sessions\_list: Session Discovery

`sessions_list` allows an Agent to see which sessions currently exist, including sub-agent sessions it has spawned and sessions of other Agents.

```typescript
// src/agents/tools/sessions-list-tool.ts
const SessionsListToolSchema = Type.Object({
  kinds: Type.Optional(Type.Array(Type.String())),   // Filter types: main/group/cron/hook/node/other
  limit: Type.Optional(Type.Number({ minimum: 1 })),
  activeMinutes: Type.Optional(Type.Number({ minimum: 1 })),  // Only return sessions active in last N minutes
  messageLimit: Type.Optional(Type.Number({ minimum: 0 })),    // Include last N messages
});

export function createSessionsListTool(opts?: {
  agentSessionKey?: string;
  sandboxed?: boolean;
}): AnyAgentTool {
  return {
    name: "sessions_list",
    description: "List sessions with optional filters and last messages.",
    execute: async (_toolCallId, args) => {
      const cfg = loadConfig();
      const a2aPolicy = createAgentToAgentPolicy(cfg);

      // Sandboxed Agents can only see sub-agent sessions they spawned
      const restrictToSpawned = opts?.sandboxed === true
        && visibility === "spawned" && ...;

      const list = await callGateway({
        method: "sessions.list",
        params: { limit, activeMinutes, spawnedBy: restrictToSpawned ? requesterInternalKey : undefined },
      });

      for (const entry of sessions) {
        // Cross-Agent access: check A2A policy
        const crossAgent = entryAgentId !== requesterAgentId;
        if (crossAgent && !a2aPolicy.isAllowed(requesterAgentId, entryAgentId)) {
          continue;  // Skip if not authorized
        }

        // Filter by type
        const kind = classifySessionKind({ key, gatewayKind, alias, mainKey });
        if (allowedKinds && !allowedKinds.has(kind)) continue;

        // Optional: include recent messages
        if (messageLimit > 0) {
          const history = await callGateway({
            method: "chat.history",
            params: { sessionKey: resolvedKey, limit: messageLimit },
          });
          row.messages = stripToolMessages(rawMessages);  // Filter out tool messages
        }

        rows.push(row);
      }
      return jsonResult({ count: rows.length, sessions: rows });
    },
  };
}
```

Each returned session entry contains: session key, type, channel, label, last update time, model override, token usage, and other metadata. The `messageLimit` parameter allows an Agent to preview recent messages of each session directly in the list, avoiding additional `sessions_history` calls.

### sessions\_history: History Viewing

`sessions_history` retrieves the conversation history of a specified session. Since conversation history can be very large, this tool has multiple layers of truncation protection:

```typescript
// src/agents/tools/sessions-history-tool.ts
const SESSIONS_HISTORY_MAX_BYTES = 80 * 1024;       // Total response limit: 80KB
const SESSIONS_HISTORY_TEXT_MAX_CHARS = 4000;        // Single message text limit: 4000 chars

export function createSessionsHistoryTool(opts?: {
  agentSessionKey?: string;
  sandboxed?: boolean;
}): AnyAgentTool {
  return {
    name: "sessions_history",
    description: "Fetch message history for a session.",
    execute: async (_toolCallId, args) => {
      // 1. Cross-Agent access control
      if (isCrossAgent && !a2aPolicy.isAllowed(requesterAgentId, targetAgentId)) {
        return jsonResult({ status: "forbidden", error: "Agent-to-agent history denied." });
      }

      // 2. Fetch raw history
      const result = await callGateway({
        method: "chat.history",
        params: { sessionKey: resolvedKey, limit },
      });

      // 3. Sanitize: truncate long text, remove image base64 data, delete thinkingSignature
      const sanitizedMessages = selectedMessages.map(
        (msg) => sanitizeHistoryMessage(msg)
      );

      // 4. Total size protection: discard old messages from head if exceeds 80KB
      const cappedMessages = capArrayByJsonBytes(
        sanitizedMessages, SESSIONS_HISTORY_MAX_BYTES
      );

      return jsonResult({
        sessionKey: displayKey,
        messages: cappedMessages.items,
        truncated: /* ... */,
      });
    },
  };
}
```

The sanitization function `sanitizeHistoryMessage()` performs the following processing:

| Processing         | Description                                                                     |
| ------------------ | ------------------------------------------------------------------------------- |
| Text truncation    | Text content exceeding 4000 characters is truncated with `…(truncated)…` marker |
| Image removal      | Remove base64-encoded image data, replace with `{ omitted: true, bytes: N }`    |
| Signature deletion | Remove `thinkingSignature` field (encrypted signature data is huge and useless) |
| Metadata cleanup   | Delete large nested fields like `details`, `usage`, `cost`                      |

### sessions\_send: Message Sending

`sessions_send` is the core of A2A communication — it sends a message to a target session, triggering the target Agent to process it, and optionally waits for a reply.

```typescript
// src/agents/tools/sessions-send-tool.ts
const SessionsSendToolSchema = Type.Object({
  sessionKey: Type.Optional(Type.String()),   // Target session key
  label: Type.Optional(Type.String()),         // Or locate by label
  agentId: Type.Optional(Type.String()),       // Agent scope for label lookup
  message: Type.String(),                      // Message content
  timeoutSeconds: Type.Optional(Type.Number({ minimum: 0 })),  // Wait timeout
});
```

This tool supports two target location methods: precise location via `sessionKey`, or fuzzy search via `label` (session label). Both cannot be used simultaneously.

Message sending has two modes:

**Fire-and-Forget**: `timeoutSeconds = 0`

```typescript
// src/agents/tools/sessions-send-tool.ts (fire-and-forget mode)
if (timeoutSeconds === 0) {
  const response = await callGateway({
    method: "agent",
    params: sendParams,
    timeoutMs: 10_000,
  });
  startA2AFlow(undefined, runId);  // Start background A2A flow
  return jsonResult({ runId, status: "accepted", sessionKey: displayKey });
}
```

**Wait for Reply**: `timeoutSeconds > 0` (default 30 seconds)

```typescript
// src/agents/tools/sessions-send-tool.ts (wait for reply mode)
// 1. Send message, trigger target Agent
await callGateway({ method: "agent", params: sendParams });

// 2. Wait for target Agent to complete
const wait = await callGateway({
  method: "agent.wait",
  params: { runId, timeoutMs },
});

// 3. Read target Agent's last reply
const history = await callGateway({
  method: "chat.history",
  params: { sessionKey: resolvedKey, limit: 50 },
});
const reply = extractAssistantText(lastMessage);

// 4. Start A2A follow-up flow (ping-pong + announce)
startA2AFlow(reply);

return jsonResult({ runId, status: "ok", reply, sessionKey: displayKey });
```

### Cross-Agent Access Control

All three tools follow a unified **A2A policy** control. By default, cross-Agent access is **forbidden** — it must be explicitly enabled in configuration:

```json5
// openclaw.json5
{
  "tools": {
    "agentToAgent": {
      "enabled": true,           // Enable cross-Agent communication
      "allow": [
        { "from": "main", "to": "coding-assistant" },
        { "from": "coding-assistant", "to": "main" }
      ]
    }
  }
}
```

`createAgentToAgentPolicy()` parses this configuration and generates a policy object. Each cross-Agent operation checks whether `isAllowed(fromAgentId, toAgentId)` returns `true`.

## 13.5.2 Cross-Session Message Passing and Reply Ping-Pong

`sessions_send` is not just sending a message — it also supports a complete **multi-turn conversation flow** called reply ping-pong. This mechanism allows two Agents to automatically engage in multiple rounds of interaction after receiving a message, then publish the final result to the target channel.

### Complete A2A Flow

Here is a complete A2A interaction flow triggered by `sessions_send`:

```
  Agent A (requester)                Gateway                Agent B (target)
       |                              |                          |
       |--- sessions_send(msg) ------>|                          |
       |                              |--- agent(msg) --------->|
       |                              |<-- round 1 reply -------|
       |                              |                          |
       |    [Ping-Pong Phase]         |                          |
       |<-- reply context + msg ------|                          |
       |--- round 2 reply ----------->|                          |
       |                              |--- reply context ------->|
       |                              |<-- round 3 reply --------|
       |                              |   ... (up to 5 turns)    |
       |                              |                          |
       |    [Announce Phase]          |                          |
       |                              |--- announce context ---->|
       |                              |<-- final message --------|
       |                              |--- send to channel ----->|
       |                              |                          |
```

### A2A Flow Implementation

The `runSessionsSendA2AFlow()` in `src/agents/tools/sessions-send-tool.a2a.ts` implements the complete ping-pong and announce flow:

```typescript
// src/agents/tools/sessions-send-tool.a2a.ts
export async function runSessionsSendA2AFlow(params: {
  targetSessionKey: string;
  message: string;
  maxPingPongTurns: number;           // Max ping-pong turns (default 5)
  requesterSessionKey?: string;
  roundOneReply?: string;             // First round reply (if already waited)
}) {
  let latestReply = params.roundOneReply;
  if (!latestReply) return;  // Terminate if no reply

  // === Ping-Pong Phase ===
  if (params.maxPingPongTurns > 0 && params.requesterSessionKey) {
    let currentSessionKey = params.requesterSessionKey;
    let nextSessionKey = params.targetSessionKey;
    let incomingMessage = latestReply;

    for (let turn = 1; turn <= params.maxPingPongTurns; turn += 1) {
      const currentRole = currentSessionKey === params.requesterSessionKey
        ? "requester" : "target";

      // Build reply context prompt
      const replyPrompt = buildAgentToAgentReplyContext({
        requesterSessionKey: params.requesterSessionKey,
        targetSessionKey: params.displayKey,
        currentRole,
        turn,
        maxTurns: params.maxPingPongTurns,
      });

      // Run one step in current Agent's session
      const replyText = await runAgentStep({
        sessionKey: currentSessionKey,
        message: incomingMessage,
        extraSystemPrompt: replyPrompt,
      });

      // Agent can reply "REPLY_SKIP" to terminate ping-pong
      if (!replyText || isReplySkip(replyText)) break;

      latestReply = replyText;
      incomingMessage = replyText;

      // Swap roles: requester ↔ target
      const swap = currentSessionKey;
      currentSessionKey = nextSessionKey;
      nextSessionKey = swap;
    }
  }

  // === Announce Phase ===
  const announceTarget = await resolveAnnounceTarget({
    sessionKey: params.targetSessionKey,
  });

  const announcePrompt = buildAgentToAgentAnnounceContext({
    originalMessage: params.message,
    roundOneReply: primaryReply,
    latestReply,
  });

  const announceReply = await runAgentStep({
    sessionKey: params.targetSessionKey,
    message: "Agent-to-agent announce step.",
    extraSystemPrompt: announcePrompt,
  });

  // Publish to target channel (unless Agent replies "ANNOUNCE_SKIP")
  if (announceTarget && announceReply && !isAnnounceSkip(announceReply)) {
    await callGateway({
      method: "send",
      params: {
        to: announceTarget.to,
        message: announceReply.trim(),
        channel: announceTarget.channel,
      },
    });
  }
}
```

### Ping-Pong Context Injection

Each ping-pong round injects an additional system prompt telling the current Agent it's participating in an A2A conversation:

```typescript
// src/agents/tools/sessions-send-helpers.ts
export function buildAgentToAgentReplyContext(params: {
  requesterSessionKey?: string;
  targetSessionKey: string;
  currentRole: "requester" | "target";
  turn: number;
  maxTurns: number;
}) {
  return [
    "Agent-to-agent reply step:",
    `Current agent: ${currentLabel}.`,
    `Turn ${params.turn} of ${params.maxTurns}.`,
    `Agent 1 (requester) session: ${params.requesterSessionKey}.`,
    `Agent 2 (target) session: ${params.targetSessionKey}.`,
    `If you want to stop the ping-pong, reply exactly "REPLY_SKIP".`,
  ].filter(Boolean).join("\n");
}
```

This prompt lets the Agent know:

1. Its current role (requester or target)
2. Which round it's currently in
3. It can terminate the conversation by replying `REPLY_SKIP`

The upper limit of ping-pong rounds is controlled by the configuration option `session.agentToAgent.maxPingPongTurns`, which defaults to 5 and has a hard limit of 5:

```typescript
// src/agents/tools/sessions-send-helpers.ts
const DEFAULT_PING_PONG_TURNS = 5;
const MAX_PING_PONG_TURNS = 5;

export function resolvePingPongTurns(cfg?: OpenClawConfig) {
  const raw = cfg?.session?.agentToAgent?.maxPingPongTurns;
  return Math.max(0, Math.min(MAX_PING_PONG_TURNS, Math.floor(raw ?? DEFAULT_PING_PONG_TURNS)));
}
```

### Announce Phase

After ping-pong ends, the announce phase begins. The target Agent receives a prompt containing complete context and is asked to generate a message for the end user:

```typescript
// src/agents/tools/sessions-send-helpers.ts
export function buildAgentToAgentAnnounceContext(params: {
  originalMessage: string;
  roundOneReply?: string;
  latestReply?: string;
}) {
  return [
    "Agent-to-agent announce step:",
    `Original request: ${params.originalMessage}`,
    `Round 1 reply: ${params.roundOneReply ?? "(not available)"}`,
    `Latest reply: ${params.latestReply ?? "(not available)"}`,
    `If you want to remain silent, reply exactly "ANNOUNCE_SKIP".`,
    "Any other reply will be posted to the target channel.",
    "After this reply, the agent-to-agent conversation is over.",
  ].filter(Boolean).join("\n");
}
```

The target Agent can choose to:

* **Reply with a normal message**: The message will be published to the target channel via the `send` method (e.g., Telegram group, Slack channel)
* **Reply with `ANNOUNCE_SKIP`**: Remain silent, send no message to the user

***

## Summary of This Section

OpenClaw's inter-session communication system provides complete multi-agent collaboration capabilities:

1. **Three-tool infrastructure**: `sessions_list` (discovery), `sessions_history` (viewing), `sessions_send` (sending) form the complete primitives for A2A communication
2. **Fine-grained access control**: Cross-Agent communication is forbidden by default and requires explicit authorization via `tools.agentToAgent` configuration; sandboxed Agents have further restricted visibility
3. **Reply ping-pong mechanism**: Two Agents can automatically engage in up to 5 rounds of interactive conversation, either party can terminate early with `REPLY_SKIP`
4. **Announce phase**: After ping-pong ends, the target Agent can publish collaboration results to user-visible channels, or remain silent with `ANNOUNCE_SKIP`
5. **Safety protections**: Multiple layers of protection including 80KB response limit, history text truncation, and sandboxed session isolation ensure A2A communication doesn't lead to resource abuse

This mechanism makes OpenClaw not just a single AI assistant, but a platform that can host multiple collaborative Agents. In subsequent chapters, we will see how the sub-agent system leverages these primitives to implement task delegation and result reporting.

***

> ### 🔬 Going Deeper: 13.6 Source Deep Dive
>
> That's the end of the chapter's main text. If you're going to **modify this code**, or reproduce it in your own project, read on: [**13.6 Source Deep Dive: Two-Tier Lanes and Three Queue Semantics**](https://www.openclawbook.xyz/en/ch13-session-management/13.6-source-deep-dive-two-tier-lanes-and-queue-semantics.md) traces the real implementation line by line along with the issues behind it, at a noticeably higher information density.
>
> **The main text is for understanding structure; the deep dive is for understanding trade-offs.**
