client

A websocket client for the OpenClaw Gateway.

The Gateway is the surface an OpenClaw agent publishes for other programs to drive it: chat.send starts a run, the chat event stream follows it, sessions.steer redirects it, and chat.abort stops it. A NemoClaw sandbox republishes that socket on the host, which is how a bot outside the sandbox talks to an agent inside one.

This module deals in runs and events. Turning those into frames is OpenClawGatewayService’s job.

The client targets the Gateway as OpenClaw v2026.6.1 speaks it. Where the Gateway does something surprising, the surprise is written down at the method that has to cope with it rather than summarized here.

pipecat.services.openclaw.client.PROTOCOL_VERSION = 4

The Gateway protocol version this client negotiates.

pipecat.services.openclaw.client.DEFAULT_GATEWAY_URL = 'ws://127.0.0.1:18789'

Where OpenClaw’s Gateway listens.

A NemoClaw sandbox republishes it on the host at 18790, so a client reaching an agent inside a sandbox goes through that published port instead.

pipecat.services.openclaw.client.GATEWAY_CLIENT_ID = 'gateway-client'

What the Gateway calls a program driving an agent from outside.

The id comes from a closed set the Gateway validates the handshake against, so it names a kind of client rather than this one; pipecat rides along as the display name.

Paired with the backend mode, this is also what earns a token-only client its operator scopes: only a backend client may skip device pairing on a loopback connection. Any other identity connects and is then refused chat.send for want of operator.write.

The Gateway puts this identity in the message envelope it shows the agent, and marks it untrusted. An agent will remark on that in its answer unless the caller’s own framing tells it not to describe how the message arrived.

pipecat.services.openclaw.client.DEFAULT_SESSION_KEY = 'agent:main:main'

OpenClaw’s default session.

Sessions are durable and hold conversation history, so two runs against the same key share context. Tests and parallel callers want distinct keys.

pipecat.services.openclaw.client.DEFAULT_CONNECT_TIMEOUT = 15.0

Seconds to wait for the handshake.

Sits below a pipeline’s setup budget, so a service reports an unreachable Gateway itself rather than timing out the whole setup.

pipecat.services.openclaw.client.DEFAULT_REQUEST_TIMEOUT = 30.0

Seconds to wait for a Gateway method to answer.

pipecat.services.openclaw.client.DEFAULT_RUN_TIMEOUT = 300.0

Seconds the agent is given to finish a run.

pipecat.services.openclaw.client.DEFAULT_ROLE = 'operator'

Handshake role.

pipecat.services.openclaw.client.DEFAULT_MAX_MESSAGE_SIZE = 26214400

Largest websocket frame to accept. Agent output can be large.

pipecat.services.openclaw.client.MAX_BUFFERED_FRAMES = 100

How many unrouted chat frames to hold for replay. See _route().

pipecat.services.openclaw.client.EventKind

What a run’s event reports.

alias of Literal[‘text_delta’, ‘completed’, ‘cancelled’, ‘failed’]

pipecat.services.openclaw.client.RunStatus

How a run ended.

alias of Literal[‘completed’, ‘cancelled’, ‘failed’]

exception pipecat.services.openclaw.client.OpenClawError(message: str, code: str | int | None = None)[source]

Bases: Exception

An error returned by the Gateway, or raised while talking to it.

__init__(message: str, code: str | int | None = None)[source]

Initialize the error.

Parameters:
  • message – Human-readable description.

  • code – The Gateway’s error code, when it sent one.

class pipecat.services.openclaw.client.OpenClawEvent(kind: Literal['text_delta', 'completed', 'cancelled', 'failed'], text: str = '')[source]

Bases: object

One thing that happened during a run.

Parameters:
  • kind – What happened.

  • text – The chunk of the answer, or the reason the run ended.

text: str = ''
class pipecat.services.openclaw.client.OpenClawResult(summary: str, status: Literal['completed', 'cancelled', 'failed'] = 'completed')[source]

Bases: object

A finished run, folded into the single answer it produced.

Parameters:
  • summary – The agent’s final answer, or why there isn’t one.

  • status – How the run ended, in the same words as OpenClawEndFrame.

status: Literal['completed', 'cancelled', 'failed'] = 'completed'
class pipecat.services.openclaw.client.OpenClawRun(run_id: str, session_key: str)[source]

Bases: object

A run in flight, and the events arriving for it.

Mutable on purpose. Steering does not merge a follow-up into the running turn, it interrupts that run and starts a new one, so run_id moves to the replacement and the stream follows it. See OpenClawGatewayClient.steer().

__init__(run_id: str, session_key: str)[source]

Initialize the run.

Parameters:
  • run_id – The id the run is addressed by.

  • session_key – The session it runs in. Steering and aborting address the session, so a run started somewhere other than the client’s default has to carry where that was.

ids: set[str]
queue: Queue[OpenClawEvent]
async pipecat.services.openclaw.client.collect_result(events: AsyncIterator[OpenClawEvent]) → OpenClawResult[source]

Fold a run’s event stream into one answer.

Parameters:

events – The stream from OpenClawGatewayClient.events().

Returns:

The agent’s answer and how the run ended.

class pipecat.services.openclaw.client.OpenClawGatewayClient(*, url: str = 'ws://127.0.0.1:18789', token: str | None = None, password: str | None = None, session_key: str = 'agent:main:main', connect_timeout: float = 15.0, request_timeout: float = 30.0, run_timeout: float = 300.0, scopes: list[str] | None = None, role: str = 'operator', max_message_size: int = 26214400, reconnect_on_error: bool = True, **kwargs)[source]

Bases: BaseObject, WebsocketService

Drives an OpenClaw agent over its Gateway websocket.

One connection serves every run. That is not an optimization: aborting a run has to work after its event stream has ended, and a request written to a socket whose reader has stopped never gets a reply.

A dropped socket cannot be carried back into a running turn, because the Gateway has no way to resume a run’s event stream. Runs in flight therefore end as failed, while the socket underneath them reconnects for the next one.

A session runs one turn at a time. Starting a run while another is live is the caller’s business; steer() is the supported way to redirect work already in flight.

Event handlers available:

  • on_connected: Called once the socket is open.

  • on_disconnected: Called once it is closed.

  • on_connection_error: Called with a message and whether the failure will keep recurring, when the connection fails.

Example:

client = OpenClawGatewayClient(token=os.getenv("OPENCLAW_TOKEN"))
run = await client.start("What changed in the parser this week?")
result = await collect_result(client.events(run))
await client.disconnect()
__init__(*, url: str = 'ws://127.0.0.1:18789', token: str | None = None, password: str | None = None, session_key: str = 'agent:main:main', connect_timeout: float = 15.0, request_timeout: float = 30.0, run_timeout: float = 300.0, scopes: list[str] | None = None, role: str = 'operator', max_message_size: int = 26214400, reconnect_on_error: bool = True, **kwargs)[source]

Initialize the client.

Parameters:
  • url – The Gateway websocket, or the port a NemoClaw sandbox republishes it on.

  • token – The Gateway’s shared token, from gateway.auth.token in ~/.openclaw/openclaw.json; a NemoClaw sandbox prints its own with nemoclaw <sandbox> gateway-token --quiet. Required even on loopback: without a shared secret the Gateway asks a backend client for a paired device identity instead, which this client does not carry, and refuses the handshake with NOT_PAIRED.

  • password – Gateway password, if the deployment uses one instead.

  • session_key – Which OpenClaw session to run in. Runs against the same key share conversation history.

  • connect_timeout – Seconds to wait for the handshake. The service connects while the pipeline sets up, which the pipeline bounds by its own setup_timeout_secs, so a value above that budget never gets to report an unreachable Gateway itself.

  • request_timeout – Seconds to wait for a Gateway method to answer. Does not apply to a run, which streams for as long as it takes.

  • run_timeout – Seconds the agent is given to finish a run, sent to the Gateway as timeoutMs. Enforced by the agent, not here.

  • scopes – Handshake scopes. operator.write covers everything this client does — starting a run, steering it, and aborting it. The Gateway offers wider ones (operator.admin) and narrower (operator.read, which cannot start a run).

  • role – Handshake role.

  • max_message_size – Largest websocket frame to accept. Agent output can be large.

  • reconnect_on_error – Whether to reconnect after the socket fails.

  • **kwargs – Additional arguments passed to BaseObject and WebsocketService, such as the reconnect backoff and the websocket timeouts.

property session_key: str

The session this client runs in.

async connect()[source]

Open the Gateway connection and complete the handshake.

Called automatically by start(). Call it directly to fail fast on a bad token or an unreachable sandbox rather than on the first run.

async disconnect()[source]

Close the connection and fail any run still streaming.

async cleanup()[source]

Release the connection at teardown.

async start(message: str, *, session_key: str | None = None) → OpenClawRun[source]

Start a run and return a handle to its event stream.

Parameters:
  • message – What to send the agent, verbatim. Any framing the agent needs belongs in here; this client adds none.

  • session_key – Run in this session instead of the client’s default.

Returns:

The run, ready to pass to events().

async events(run: OpenClawRun) → AsyncIterator[OpenClawEvent][source]

Stream a run’s events until it reaches a terminal state.

The stream ends after exactly one of completed, cancelled, or failed. A dropped connection arrives as failed rather than hanging.

Parameters:

run – The run to follow.

Yields:

Each event as it arrives.

async steer(run: OpenClawRun, message: str) → None[source]

Redirect the session onto a follow-up, and follow it.

sessions.steer does not inject into the running turn. It answers {"status": "started", "interruptedActiveRun": true}: the active run is aborted and a new run carries the follow-up. Its frames arrive on the same connection, so moving the run’s id onto the replacement is enough for events() to keep streaming.

The id moves before the request is sent, not after. The old run’s aborted frame can arrive first, and if the run still answered to it the stream would end there: the caller would be told the task was cancelled while the steered run continued unwatched.

Parameters:
  • run – The run to redirect.

  • message – The follow-up, verbatim.

async abort(run: OpenClawRun, reason: str | None = None) → bool[source]

Stop a run.

The Gateway answers a live run with {"ok": true, "aborted": true, "runIds": [id]}, and answers both a finished run and an unknown one with aborted: false. So False means there was nothing to stop, which is the routine race when a caller aborts a moment after the agent finished, and not a failure. A real Gateway error arrives as ok: false and is raised.

Parameters:
  • run – The run to stop.

  • reason – Logged, for working out later why something was aborted.

Returns:

Whether a run was actually stopped.