> ## Documentation Index
> Fetch the complete documentation index at: https://openclaw.veiseule.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent Loop

# Agent Loop (OpenClaw)

Agentik loop — bu agentning to‘liq “haqiqiy” ishga tushirilishi: qabul qilish → kontekstni yig‘ish → model inferensiyasi → asboblarni bajarish → javoblarni stream qilish → saqlash. Bu xabarni harakatlarga va yakuniy javobga aylantiradigan, shu bilan birga sessiya holatini izchil saqlaydigan asosiy yo‘ldir.

OpenClaw’da loop — bu har bir sessiya uchun bitta, ketma-ket bajariladigan ishga tushirish bo‘lib, model o‘ylashi, asboblarni chaqirishi va chiqishni stream qilishi davomida hayotiy sikl va stream hodisalarini chiqaradi. Ushbu hujjat ushbu haqiqiy loop qanday qilib boshidan oxirigacha ulanganini tushuntiradi.

## Kirish nuqtalari

* OpenClaw’da ikkita hook tizimi mavjud:
* CLI: `agent` buyrug‘i.

## Qanday ishlaydi (yuqori darajada)

1. `agent` RPC parametrlarni tekshiradi, sessiyani aniqlaydi (sessionKey/sessionId), sessiya metama’lumotlarini saqlaydi va darhol `{ runId, acceptedAt }` ni qaytaradi.
2. `agentCommand` agentni ishga tushiradi:
   * modelni hamda thinking/verbose standartlarini aniqlaydi
   * skills snapshot’ni yuklaydi
   * `runEmbeddedPiAgent` (pi-agent-core runtime) ni chaqiradi
   * agar ichki loop **lifecycle end/error** hodisasini chiqarmasa, uni chiqaradi
3. `runEmbeddedPiAgent`:
   * ishni sessiya bo‘yicha va global navbatlar orqali ketma-ket bajaradi
   * model va autentifikatsiya profilini aniqlaydi hamda pi sessiyasini yaratadi
   * pi hodisalariga obuna bo‘ladi va assistant/tool delta oqimlarini uzatadi
   * timeout’ni majburiy qo‘llaydi -> oshib ketilsa, ishni bekor qiladi
   * payloadlar va foydalanish metama’lumotlarini qaytaradi
4. `subscribeEmbeddedPiSession` pi-agent-core hodisalarini OpenClaw `agent` oqimiga bog‘laydi:
   * tool hodisalari => `stream: "tool"`
   * assistant deltas => `stream: "assistant"`
   * lifecycle events => `stream: "lifecycle"` (`phase: "start" | "end" | "error"`)
5. `agent.wait` uses `waitForAgentJob`:
   * waits for **lifecycle end/error** for `runId`
   * returns `{ status: ok|error|timeout, startedAt, endedAt, error? }`

## Queueing + concurrency

* Runs are serialized per session key (session lane) and optionally through a global lane.
* This prevents tool/session races and keeps session history consistent.
* Messaging channels can choose queue modes (collect/steer/followup) that feed this lane system.
  See [Command Queue](/concepts/queue).

## Session + workspace preparation

* Workspace is resolved and created; sandboxed runs may redirect to a sandbox workspace root.
* Skills are loaded (or reused from a snapshot) and injected into env and prompt.
* Bootstrap/context files are resolved and injected into the system prompt report.
* A session write lock is acquired; `SessionManager` is opened and prepared before streaming.

## Prompt assembly + system prompt

* System prompt is built from OpenClaw’s base prompt, skills prompt, bootstrap context, and per-run overrides.
* Model-specific limits and compaction reserve tokens are enforced.
* See [System prompt](/concepts/system-prompt) for what the model sees.

## Hook points (where you can intercept)

**Plugin hooklari**: agent/asbob hayotiy sikli va gateway pipeline ichidagi kengaytirish nuqtalari.

* **Internal hooks** (Gateway hooks): event-driven scripts for commands and lifecycle events.
* Agar izolyatsiya kerak bo‘lsa, [`agents.defaults.sandbox`](/gateway/sandboxing) (va/yoki har bir agent uchun sandbox konfiguratsiyasi) dan foydalaning.

### Internal hooks (Gateway hooks)

* **`agent:bootstrap`**: runs while building bootstrap files before the system prompt is finalized.
  Use this to add/remove bootstrap context files.
* **Command hooks**: `/new`, `/reset`, `/stop`, and other command events (see Hooks doc).

See [Hooks](/automation/hooks) for setup and examples.

### Plugin hooks (agent + gateway lifecycle)

These run inside the agent loop or gateway pipeline:

* **`before_agent_start`**: inject context or override system prompt before the run starts.
* **`agent_end`**: inspect the final message list and run metadata after completion.
* **`before_compaction` / `after_compaction`**: observe or annotate compaction cycles.
* **`before_tool_call` / `after_tool_call`**: intercept tool params/results.
* **`tool_result_persist`**: synchronously transform tool results before they are written to the session transcript.
* **`message_received` / `message_sending` / `message_sent`**: inbound + outbound message hooks.
* **`session_start` / `session_end`**: session lifecycle boundaries.
* **`gateway_start` / `gateway_stop`**: gateway lifecycle events.

See [Plugins](/tools/plugin#plugin-hooks) for the hook API and registration details.

## Streaming + partial replies

* Assistant deltas are streamed from pi-agent-core and emitted as `assistant` events.
* Block streaming can emit partial replies either on `text_end` or `message_end`.
* Reasoning streaming can be emitted as a separate stream or as block replies.
* See [Streaming](/concepts/streaming) for chunking and block reply behavior.

## Tool execution + messaging tools

* Tool start/update/end events are emitted on the `tool` stream.
* Tool results are sanitized for size and image payloads before logging/emitting.
* Messaging tool sends are tracked to suppress duplicate assistant confirmations.

## Reply shaping + suppression

* Final payloads are assembled from:
  * assistant text (and optional reasoning)
  * inline tool summaries (when verbose + allowed)
  * assistant error text when the model errors
* `NO_REPLY` is treated as a silent token and filtered from outgoing payloads.
* Messaging tool duplicates are removed from the final payload list.
* If no renderable payloads remain and a tool errored, a fallback tool error reply is emitted
  (unless a messaging tool already sent a user-visible reply).

## Compaction + retries

* Auto-compaction emits `compaction` stream events and can trigger a retry.
* On retry, in-memory buffers and tool summaries are reset to avoid duplicate output.
* See [Compaction](/concepts/compaction) for the compaction pipeline.

## Event streams (today)

* `lifecycle`: emitted by `subscribeEmbeddedPiSession` (and as a fallback by `agentCommand`)
* `assistant`: streamed deltas from pi-agent-core
* `tool`: streamed tool events from pi-agent-core

## Chat channel handling

* Assistant deltas are buffered into chat `delta` messages.
* A chat `final` is emitted on **lifecycle end/error**.

## Timeouts

* `agent.wait` default: 30s (just the wait). `timeoutMs` param overrides.
* Agent runtime: `agents.defaults.timeoutSeconds` default 600s; enforced in `runEmbeddedPiAgent` abort timer.

## Where things can end early

* Agent timeout (abort)
* AbortSignal (cancel)
* Gateway disconnect or RPC timeout
* `agent.wait` timeout (wait-only, does not stop agent)
