Skip to Content
DevelopWebSocket client

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.

The Golem TypeScript SDK provides a WebSocket client API. connectWebsocket opens a connection and returns a WebSocketHandle with send, receive, receiveWithTimeout, and close methods. Received messages are { tag: "text", val } / { tag: "binary", val }, and a graceful close surfaces as a WebsocketError with tag === "closed" and a closeInfo.

import { z } from "zod"; import { defineAgent, method, connectWebsocket, WebsocketError } from "@golemcloud/golem-ts-sdk"; export const ExampleAgent = defineAgent({ name: "ExampleAgent", id: { name: z.string() }, methods: { run: method({ input: {}, returns: z.void() }), }, }); export const ExampleAgentImpl = ExampleAgent.implement({ init: () => ({}), methods: { async run() { const ws = await connectWebsocket("wss://example.com/chat"); console.log("Connected"); ws.send("Hello, server!"); try { for (;;) { const message = await ws.receive(); if (message.tag === "text") { console.log("Text:", message.val); } else { console.log("Binary:", message.val); } } } catch (err) { if (err instanceof WebsocketError && err.tag === "closed") { const info = err.closeInfo; if (info) { console.log(`Closed [${info.code}] "${info.reason}"`); } } else { throw err; } } }, }, });

WIT interface reference

The underlying package is golem:websocket@1.5.0; its golem:websocket/client@1.5.0 interface defines the websocket-connection resource type with the following methods:

  • connect — opens a WebSocket connection to the given URL, with optional headers
  • send — sends a text or binary message
  • receive — asynchronously waits for the next message
  • receive-with-timeout — waits up to the given number of milliseconds and returns none on expiry
  • close — initiates a graceful close handshake