Entry points
- Gateway RPC:
agentandagent.wait. - CLI:
openclaw agent.
Run sequence
agentRPC validates params, resolves the session (sessionKey/sessionId), persists session metadata, and returns{ runId, acceptedAt }immediately.agentCommandruns the turn: resolves model + thinking/verbose/trace defaults, loads the skills snapshot, callsrunEmbeddedAgent, and emits a fallback lifecycle end/error if the embedded loop did not already emit one.runEmbeddedAgent: serializes runs via per-session and global queues, resolves model + auth profile, builds the OpenClaw session, subscribes to runtime events, streams assistant/tool deltas, enforces the run timeout (aborting on expiry), and returns payloads plus usage metadata. For Codex app-server turns, native Codex owns provider liveness and the exactturn/completedoutcome; quiet periods and assistant output do not end the turn.subscribeEmbeddedAgentSessionbridges runtime events to theagentstream: tool events tostream: "tool", assistant deltas tostream: "assistant", lifecycle events tostream: "lifecycle"(phase: "start" | "finishing" | "end" | "error").agent.wait(waitForAgentRun) waits for lifecycle end/error on arunIdand returns{ status: ok|error|timeout, startedAt, endedAt, error? }.
terminalReply and, when available,
terminalReceipt. A receipt with sourceReplyDelivered: true confirms a final
reply reached the external source conversation. A2A announcements consume that
fact instead of using display-history mirrors as delivery evidence.
Queueing and concurrency
Runs are serialized per session key (session lane) and optionally through a global lane, preventing tool/session races. Messaging channels choose a queue mode (steer/followup/collect/interrupt) that feeds this lane system; see Command Queue. Before streaming, an admitted run records its durableactiveWriterRunId claim. Every transcript append or rewrite supplies expectedWriterRunId, and the synchronous commit transaction verifies that it still matches the active claim. A superseded run therefore cannot commit stale transcript data. The SQLite writer queue orders per-agent mutations, while the Gateway state-directory lock prevents another Gateway or openclaw agent --local process from owning the same state directory concurrently.
Session and 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.
- The session transcript target and writer claim are prepared before streaming starts. Later rewrites, compaction, and truncation use the same in-transaction writer-claim fence.
Prompt assembly
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 for what the model sees.Hooks
OpenClaw has two in-process hook systems:- Internal hooks:
HOOK.mdscripts for command and lifecycle events such ascommand:new. - Plugin hooks: typed
api.on(...)handlers inside the agent/tool lifecycle and Gateway pipeline, such asbefore_tool_call.
Internal hooks (Gateway hooks)
agent:bootstrap: runs while building bootstrap files before the system prompt is finalized. Use it to add or remove bootstrap context files.- Command hooks: core emits
command:new,command:reset, andcommand:stop. Other command names do not automatically become hook events.
Plugin hooks
These run inside the agent loop or gateway pipeline:
Hook decision rules for outbound/tool guards:
before_tool_call:{ block: true }is terminal and stops lower-priority handlers.{ block: false }is a no-op and does not clear a prior block.before_install: same terminal/no-op semantics as above. Usesecurity.installPolicy, notbefore_install, for operator-owned install allow/warn/block decisions that must cover CLI install and update paths.message_sending:{ cancel: true }is terminal and stops lower-priority handlers.{ cancel: false }is a no-op and does not clear a prior cancel.
Streaming
- Assistant deltas stream from the agent runtime as
assistantevents. - Block streaming can emit partial replies on
text_endormessage_end. - Reasoning streaming can be a separate stream or block replies.
- See Streaming for chunking and block reply behavior.
Tool execution
- Tool start/update/end events emit on the
toolstream. - Tool results are sanitized for size and image payloads before logging/emitting.
- Messaging tool sends are tracked to suppress duplicate assistant confirmations.
Reply shaping
Final payloads are assembled from assistant text (plus optional reasoning), inline tool summaries (when verbose and allowed), and assistant error text when the model errors.- The exact silent token
NO_REPLYis filtered from outgoing payloads. - Messaging tool duplicates are removed from the final payload list.
- A fallback tool error warning appears only when a run ends with a tool failure and would otherwise leave the user with no reply. This guard is not configurable; a user-facing reply, including one already delivered by a messaging tool, prevents the warning.
Compaction and retries
Auto-compaction emitscompaction stream events and can trigger a retry. On retry, in-memory buffers and tool summaries reset to avoid duplicate output. See Compaction.
Event streams
lifecycle: emitted bysubscribeEmbeddedAgentSession(and as a fallback byagentCommand).assistant: streamed deltas from the agent runtime.tool: streamed tool events from the agent runtime.
Chat channel handling
Assistant deltas buffer into chatdelta messages. Terminal lifecycle events
produce chat final, error, or aborted messages. Definitive cancellation and
timeout events finalize immediately, including when the runtime reports them as
phase: "error". Retryable errors keep a 15-second grace window for a fallback
or restart of the same run. Once the outer execution owner has finished its
attempts, it publishes executionSettled: true. The Gateway and agent.wait
consume that fact immediately, including preparation failures that never reached
a model or emitted a fallback step. Unmarked timeout and bare-abort observations
retain their existing wait-layer retry handling.
Cron attempt completions remain finishing across model fallbacks and
interim-acknowledgment retries; worker finishing events do not claim execution
settlement. Completed execution facts are captured before cron bookkeeping, but
finality is published only after execution settles. A new attempt clears the
prior outcome before preparation. Later workflow errors or aborts cannot
reclassify completed execution; cron persistence, delivery, and yielded-parent
continuation retain their separate outcomes.
History keeps a run active while its terminal session write is pending. Once
that write succeeds, history and session activity show the recorded end time
and duration without waiting for retry grace.
Live snapshots are scoped to their assistant message. A correction can shorten or clear the current preview without erasing earlier messages. Pending text is flushed before the terminal event; pacing live updates does not delay tool execution or transcript writes.
Run-duration metadata belongs to the current run, including when preparation fails before the model starts. In Control UI completed-work rollups, independent sends have separate elapsed-time boundaries: a failed turn and the idle time before the next send are not part of that next turn’s work. Steering remains associated with its target run rather than being treated as an independent retry.
Timeouts
When no result is available before anagent.wait deadline, the response contains
only runId and status: "timeout".
It does not cancel the run or identify its execution phase; wait on the same
runId again to observe completion. A wait interrupted by Gateway lifecycle
shutdown includes timeoutPhase: "gateway_draining" without terminal metadata.
Known queued chat turns report status: "pending", timeoutPhase: "queue", and
providerStarted: false.
The built-in OpenClaw harness publishes its execution deadline to the queue.
Approval waits pause the unused budget; resolving all pending approvals resumes
that same budget. Compaction can receive one bounded grace period. A question
from
ask_user does not pause the overall execution budget. With 0, no
execution timer is armed, but provider liveness, Stop, and bounded abort cleanup
still apply. Isolated post-tool finalization gets its own deadline and cancellation
controls rather than inheriting callbacks from the completed attempt.
A terminal timeout is a failed turn, not a successful completion. Chat and
command results retain its timeout explanation; earlier tool errors do not
replace that explanation or restart an already-final timed-out turn.
The model idle and provider HTTP rows describe the built-in OpenClaw model
path. Codex owns its native stream deadlines and network retries. After exact
native terminal receipt, OpenClaw allows two minutes for local settlement.
After separately bounded abort cleanup, queued projection gets a five-second
drain grace. Neither window resets on progress. These cleanup limits still
apply when the execution budget is unlimited. See
Codex timeouts.
When a runtime reports a definitive timeout, the Gateway records its terminal
status and error for the session sidebar immediately, without waiting for
provider retry grace. Opening the failed session dismisses its sidebar attention
as usual. A later successful turn clears the previous error and is not replaced
by an older delayed failure.
Stuck session diagnostics
With diagnostics enabled, a built-in two-minute threshold classifies longprocessing sessions with no observed reply, tool, status, block, or ACP progress:
- Active embedded runs, model calls, and tool calls report as
session.long_running. Owned silent model calls staysession.long_runninguntil the abort threshold so slow or non-streaming providers are not flagged as stalled too early. - Active work with no recent progress reports as
session.stalled. Owned model calls switch tosession.stalledat or after the abort threshold; ownerless stale model/tool activity is not hidden as long-running. session.stuckis reserved for recoverable stale session bookkeeping, including idle queued sessions with stale ownerless model/tool activity.
session.stuck diagnostics back off while the session stays unchanged.
Pending human-input questions protect their exact active owner from stale-work
recovery. If checking a question expires it, or diagnostic reporting resumes or
replaces the run, that observation cannot authorize an abort of the resumed work.
Recovery revalidates the session generation captured with the observation.
A current Codex attempt waiting on native work is the exception to these idle
thresholds: it remains session.long_running with reason runtime_owned_wait
and is not aborted or taken over merely because it is quiet. Recovery and
steering revalidate that exact active owner and its execution budget. This does
not protect expired OpenClaw-owned requests or tools, cancellation, terminal
settlement, or ownerless state.
Where things can end early
- Agent timeout (abort)
- AbortSignal (cancel)
- Gateway disconnect or RPC timeout
agent.waittimeout (wait-only, does not stop the agent)
Related
- Tools - available agent tools
- Hooks - event-driven scripts triggered by agent lifecycle events
- Compaction - how long conversations are summarized
- Exec Approvals - approval gates for shell commands
- Thinking - thinking/reasoning level configuration