> 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/ch15-piagent-runtime-core/15.4-timeout-and-abort-mechanisms.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 15.4 Timeout and Abort Mechanisms

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

***

LLM calls are inherently uncertain—models may hang due to rate limiting, complex tool call chains may loop infinitely, or users may change their minds and want to cancel an ongoing operation. OpenClaw addresses these scenarios through multi-layer timeout and abort mechanisms, ensuring the system remains responsive at all times.

## 15.4.1 Agent Run Timeout (Default 600 Seconds)

Each Agent run has a maximum execution time limit. Exceeding this time causes the run to be forcibly terminated.

### Timeout Resolution

```typescript
// src/agents/timeout.ts
const DEFAULT_AGENT_TIMEOUT_SECONDS = 600; // 10 minutes

export function resolveAgentTimeoutSeconds(cfg?: OpenClawConfig): number {
  const raw = normalizeNumber(cfg?.agents?.defaults?.timeoutSeconds);
  const seconds = raw ?? DEFAULT_AGENT_TIMEOUT_SECONDS;
  return Math.max(seconds, 1);  // Minimum 1 second
}

export function resolveAgentTimeoutMs(opts: {
  cfg?: OpenClawConfig;
  overrideMs?: number | null;
  overrideSeconds?: number | null;
  minMs?: number;
}): number {
  const minMs = Math.max(normalizeNumber(opts.minMs) ?? 1, 1);
  const defaultMs = resolveAgentTimeoutSeconds(opts.cfg) * 1000;

  // Special value: 0 means "no timeout" (actually set to 30 days)
  const NO_TIMEOUT_MS = 30 * 24 * 60 * 60 * 1000;
  const overrideSeconds = normalizeNumber(opts.overrideSeconds);
  if (overrideSeconds === 0) return NO_TIMEOUT_MS;
  if (overrideSeconds && overrideSeconds > 0) {
    return Math.max(overrideSeconds * 1000, minMs);
  }
  return Math.max(defaultMs, minMs);
}
```

Timeout configuration has three sources, with priority from high to low:

| Source            | Config Path                      | Description                      |
| ----------------- | -------------------------------- | -------------------------------- |
| Request parameter | `timeout` field in `agent` RPC   | Timeout override for single call |
| Global config     | `agents.defaults.timeoutSeconds` | Default timeout for all Agents   |
| Hardcoded default | 600 seconds                      | Fallback when no config          |

Setting timeout to `0` is a special value meaning "actually no timeout". Since JavaScript's `setTimeout` doesn't support `Infinity`, the system uses 30 days (approximately 2.6 million seconds) as a substitute.

## 15.4.2 `agent.wait` Wait Timeout (Default 30 Seconds)

`agent.wait` is an RPC method provided by Gateway that allows callers to block and wait for an Agent run to complete. It's primarily used by the subagent registry to wait for subagent completion.

```typescript
// src/gateway/server-methods/agent.ts
"agent.wait": async ({ params, respond }) => {
  const runId = params.runId.trim();
  const timeoutMs = typeof params.timeoutMs === "number" && Number.isFinite(params.timeoutMs)
    ? Math.max(0, Math.floor(params.timeoutMs))
    : 30_000;  // Default 30 seconds

  const snapshot = await waitForAgentJob({ runId, timeoutMs });
  if (!snapshot) {
    respond(true, { runId, status: "timeout" });
    return;
  }
  respond(true, {
    runId,
    status: snapshot.status,
    startedAt: snapshot.startedAt,
    endedAt: snapshot.endedAt,
    error: snapshot.error,
  });
};
```

### Internal Implementation of Wait Mechanism

`waitForAgentJob` uses an event-listener-based wait pattern:

```typescript
// src/gateway/server-methods/agent-job.ts
export async function waitForAgentJob(params: {
  runId: string;
  timeoutMs: number;
}): Promise<AgentRunSnapshot | null> {
  // 1. Check cache first (run may have already completed)
  const cached = getCachedAgentRun(params.runId);
  if (cached) return cached;

  // 2. Subscribe to lifecycle events and wait
  return await new Promise((resolve) => {
    let settled = false;
    const finish = (entry: AgentRunSnapshot | null) => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      unsubscribe();
      resolve(entry);
    };

    // Listen for Agent run end/error events
    const unsubscribe = onAgentEvent((evt) => {
      if (evt?.stream !== "lifecycle" || evt.runId !== params.runId) return;
      if (evt.data?.phase !== "end" && evt.data?.phase !== "error") return;
      finish(getCachedAgentRun(params.runId) ?? buildSnapshot(evt));
    });

    // Timeout fallback
    const timer = setTimeout(() => finish(null), Math.max(1, params.timeoutMs));
  });
}
```

This implementation has several noteworthy design decisions:

1. **Check cache before waiting**—avoid race conditions: if the run completes before the Promise is created, cache lookup can return immediately
2. **settled flag ensures single resolve**—the `finish` function executes only once, whether triggered by event or timeout
3. **Automatic cleanup**—regardless of which path triggers resolve, both the timer and event subscription are cleaned up

### Run Snapshot Cache

Completed Agent runs are retained in cache for 10 minutes:

```typescript
// src/gateway/server-methods/agent-job.ts
const AGENT_RUN_CACHE_TTL_MS = 10 * 60_000;
const agentRunCache = new Map<string, AgentRunSnapshot>();

type AgentRunSnapshot = {
  runId: string;
  status: "ok" | "error";
  startedAt?: number;
  endedAt?: number;
  error?: string;
  ts: number;
};
```

The 10-minute TTL ensures that even if an `agent.wait` call comes slightly after Agent run completion, it can still get the result from cache rather than permanently blocking due to missing the event.

## 15.4.3 AbortSignal Cancellation Chain

JavaScript's `AbortSignal` / `AbortController` mechanism provides OpenClaw with a **cooperative cancellation** solution that spans the entire call stack.

> **Sidebar**: `AbortController` and `AbortSignal` are standard mechanisms in the Web API, fully implemented by Node.js. `AbortController` creates a controller that holds an `AbortSignal` object. When `controller.abort()` is called, the `signal` triggers an `abort` event, and all operations listening to that signal are notified of cancellation. This is similar to Go's `context.Context` or C#'s `CancellationToken`.

### Cancellation Chain Propagation Path

```
User sends /stop command
    │
    ▼
Gateway finds corresponding AbortController
    │
    ▼
controller.abort()
    │
    ▼
AbortSignal propagates to:
    ├── LLM HTTP request (fetch's signal parameter)
    ├── Tool execution (bash process kill)
    ├── Pi Agent conversation loop (check signal.aborted)
    └── Streaming output (stop sending delta events)
```

In `runEmbeddedPiAgent`, `abortSignal` is passed as a parameter through each layer:

```typescript
// src/agents/pi-embedded-runner/run.ts (parameter passing chain)
const attempt = await runEmbeddedAttempt({
  // ...other parameters
  abortSignal: params.abortSignal,  // Pass AbortSignal
});
```

When the signal is triggered, the running LLM request is cancelled (through `fetch`'s signal support), tool execution is interrupted, and the entire Agent loop exits at the next checkpoint.

### Active Run Abort

Each active Agent run registers an abort handle:

```typescript
// src/agents/pi-embedded-runner/runs.ts
export function abortEmbeddedPiRun(sessionId: string): boolean {
  const handle = ACTIVE_EMBEDDED_RUNS.get(sessionId);
  if (!handle) return false;
  handle.abort();
  return true;
}
```

The `abort()` call will:

1. Trigger the AbortSignal's abort event
2. Cancel ongoing HTTP requests
3. Mark the run as `aborted` (but not immediately delete—delete after cleanup completes)

## 15.4.4 Chat Abort (`src/gateway/chat-abort.ts`)

Abort management at the Gateway layer is more complex than single Agent run abort, as it needs to handle multi-run, cross-connection scenarios.

### Abort Controller Registration

Each Agent run in Gateway has a corresponding abort controller entry:

```typescript
// src/gateway/chat-abort.ts
export type ChatAbortControllerEntry = {
  controller: AbortController;
  sessionId: string;
  sessionKey: string;
  startedAtMs: number;
  expiresAtMs: number;  // Expiration time (auto-cleanup even if forgotten)
};
```

`expiresAtMs` is a safety net—even if abort logic has a bug causing the run not to be properly cleaned up, the expiration time ensures resources are eventually reclaimed. The expiration time calculation considers run timeout plus a grace period:

```typescript
// src/gateway/chat-abort.ts
export function resolveChatRunExpiresAtMs(params: {
  now: number;
  timeoutMs: number;
  graceMs?: number;   // Default 60 seconds grace
  minMs?: number;     // Default 2 minutes minimum
  maxMs?: number;     // Default 24 hours maximum
}): number {
  const target = params.now + params.timeoutMs + (params.graceMs ?? 60_000);
  const min = params.now + (params.minMs ?? 2 * 60_000);
  const max = params.now + (params.maxMs ?? 24 * 60 * 60_000);
  return Math.min(max, Math.max(min, target));
}
```

### Stop Command Detection

Users can abort the currently running Agent by sending a `/stop` command:

```typescript
// src/gateway/chat-abort.ts
export function isChatStopCommandText(text: string): boolean {
  const trimmed = text.trim();
  if (!trimmed) return false;
  return trimmed.toLowerCase() === "/stop" || isAbortTrigger(trimmed);
}
```

Besides `/stop`, `isAbortTrigger` also supports other trigger patterns (like custom-configured abort keywords).

### Abort by Run ID

```typescript
// src/gateway/chat-abort.ts
export function abortChatRunById(
  ops: ChatAbortOps,
  params: { runId: string; sessionKey: string; stopReason?: string },
): { aborted: boolean } {
  const active = ops.chatAbortControllers.get(params.runId);
  if (!active || active.sessionKey !== params.sessionKey) return { aborted: false };

  // 1. Log abort event
  ops.chatAbortedRuns.set(params.runId, Date.now());
  // 2. Trigger AbortController
  active.controller.abort();
  // 3. Clean up resources
  ops.chatAbortControllers.delete(params.runId);
  ops.chatRunBuffers.delete(params.runId);
  ops.chatDeltaSentAt.delete(params.runId);
  ops.removeChatRun(params.runId, params.runId, params.sessionKey);
  // 4. Broadcast abort event
  broadcastChatAborted(ops, { runId: params.runId, sessionKey: params.sessionKey, stopReason });
  return { aborted: true };
}
```

The four steps of the abort operation are atomic—once abort begins, all related state is cleaned up and the abort event is broadcast to all connected clients.

### Batch Abort by Session Key

When a user sends `/stop`, all running Agents in that session need to be aborted:

```typescript
// src/gateway/chat-abort.ts
export function abortChatRunsForSessionKey(
  ops: ChatAbortOps,
  params: { sessionKey: string; stopReason?: string },
): { aborted: boolean; runIds: string[] } {
  const runIds: string[] = [];
  for (const [runId, active] of ops.chatAbortControllers) {
    if (active.sessionKey !== params.sessionKey) continue;
    const res = abortChatRunById(ops, { runId, sessionKey: params.sessionKey, stopReason });
    if (res.aborted) runIds.push(runId);
  }
  return { aborted: runIds.length > 0, runIds };
}
```

This function iterates through all active abort controllers, finds all runs belonging to the target session, and aborts them one by one.

### Abort Event Broadcast

The abort operation broadcasts a `chat` event via WebSocket to notify all clients:

```typescript
function broadcastChatAborted(ops: ChatAbortOps, params: {
  runId: string;
  sessionKey: string;
  stopReason?: string;
}) {
  const payload = {
    runId: params.runId,
    sessionKey: params.sessionKey,
    seq: (ops.agentRunSeq.get(params.runId) ?? 0) + 1,
    state: "aborted" as const,
    stopReason: params.stopReason,
  };
  ops.broadcast("chat", payload);                           // Broadcast to all clients
  ops.nodeSendToSession(params.sessionKey, "chat", payload); // Also send to session node
}
```

After receiving an abort event, clients can:

* Stop displaying "typing..." indicator
* Mark message bubble as "cancelled"
* Clean up streaming output buffer

### Complete Picture of Multi-Layer Timeout and Abort

The following table summarizes all timeout and abort mechanisms in OpenClaw:

| Layer            | Mechanism                | Default                 | Trigger Method                  |
| ---------------- | ------------------------ | ----------------------- | ------------------------------- |
| LLM Request      | HTTP request timeout     | Provider SDK controlled | Auto-trigger on network timeout |
| Agent Run        | `resolveAgentTimeoutMs`  | 600 seconds             | Auto-trigger by timer           |
| Agent Wait       | `agent.wait`             | 30 seconds              | Return null on wait timeout     |
| User Abort       | `/stop` command          | None                    | Manual user trigger             |
| Resource Cleanup | `expiresAtMs`            | Timeout + 60 sec grace  | Auto-cleanup on expiration      |
| AbortSignal      | Cooperative cancellation | None                    | Propagate from upper layer      |

These mechanisms nest layer by layer, forming a complete safety net—even if one layer's timeout/abort fails, upper layer mechanisms will ultimately ensure resources are reclaimed.

***

## Summary of This Section

1. **Agent run timeout** defaults to 600 seconds, can be overridden via config file or request parameter. Special value `0` means no timeout (actually 30 days).
2. **`agent.wait` RPC method** allows callers to block and wait for Agent run completion, implemented using event-listener + timeout Promise pattern, with 10-minute run snapshot cache to prevent race conditions.
3. **AbortSignal cancellation chain** spans the entire call stack from Gateway to LLM HTTP requests, implementing cooperative cancellation.
4. **Gateway-level abort management** includes abort by run ID and batch abort by session, with abort operations atomically cleaning all related state and broadcasting events to notify clients.
5. **Multi-layer safety net** ensures that even if one mechanism fails, the system won't leak resources—expiration time mechanism is the final safeguard.

***

> ### 🔬 Going Deeper: 15.5 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: [**15.5 Source Deep Dive: The Full Journey of a Run**](https://www.openclawbook.xyz/en/ch15-piagent-runtime-core/15.5-source-deep-dive-full-journey-of-a-run.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.**
