WebSocket Client
Golem agents use WASI HTTP for outgoing HTTP requests, but WASI HTTP does not support WebSocket upgrades.
Golem 1.5 introduces a dedicated WebSocket client API (golem:websocket@1.5.0) that complements WASI HTTP and allows agents to open WebSocket connections, send and receive messages, and handle connection lifecycle events.
TypeScript
The TypeScript SDK exposes the standard browser WebSocket and WebSocketStream APIs,
so existing code and patterns work out of the box.
@agent()
class ExampleAgent extends BaseAgent {
async run(): Promise<void> {
return new Promise((resolve, reject) => {
const ws = new WebSocket("wss://example.com/chat");
ws.onopen = () => { console.log("Connected"); ws.send("Hello, server!"); };
ws.onmessage = (event: MessageEvent) => {
if (typeof event.data === "string") { console.log("Text:", event.data); }
else { console.log("Binary:", new Uint8Array(event.data)); }
};
ws.onerror = () => reject(new Error("WebSocket error"));
ws.onclose = (event: CloseEvent) => { console.log(`Closed [${event.code}] "${event.reason}"`); resolve(); };
});
}
}WIT interface reference
The underlying WIT interface is golem:websocket@1.5.0. It defines the websocket-connection resource type with the following methods:
connect— opens a WebSocket connection to the given URL, with optional headerssend— sends a text or binary messagereceive— blocks until the next message arrivesreceive-with-timeout— same asreceivebut with a timeoutclose— initiates a graceful close handshakesubscribe— returns a pollable that resolves when a message is available
Last updated on