Skip to content

yuchou87/openclaw-go

Repository files navigation

openclaw-go

Go SDK CI Go Reference codecov License: MIT

English | 中文

Go SDK for the OpenClaw gateway protocol.

Installation

go get github.com/yuchou87/openclaw-go

Quick Start

import (
    "context"
    "fmt"
    "log"

    gateway "github.com/yuchou87/openclaw-go/client"
)

func main() {
    c := gateway.New("ws://localhost:5555", "my-token", "")
    ctx := context.Background()

    if err := c.Connect(ctx); err != nil {
        log.Fatal(err)
    }
    defer c.Close()

    // Check gateway status
    if err := c.Status(ctx); err != nil {
        log.Fatal(err)
    }
    fmt.Println("Gateway is healthy ✓")
}

Packages

Package Description
github.com/yuchou87/openclaw-go/client WebSocket client — connection, request/response, event streaming, typed API methods
github.com/yuchou87/openclaw-go/protocol All protocol structs and constants (translated from the TypeScript schema)

Usage

Connect

c := client.New(url, token, password)
// token and password are mutually exclusive; leave unused field empty.
if err := c.Connect(ctx); err != nil { ... }
defer c.Close()

// Access the HelloOk snapshot (presence, health, features)
snap := c.Snapshot()
fmt.Println("Gateway version:", snap.Server["version"])

Send an Agent Message

err := c.SendAgent(ctx, protocol.AgentParams{
    Message:        "Help me write a hello world",
    SessionKey:     &sessionKey,
    IdempotencyKey: uuid.NewString(), // auto-generated if empty
})

Chat

// History
raw, err := c.ChatHistory(ctx, "main", &limit)

// Send
resp, err := c.ChatSend(ctx, protocol.ChatSendParams{
    SessionKey:     "main",
    Message:        "Hello",
    IdempotencyKey: uuid.NewString(),
})

// Abort
err = c.ChatAbort(ctx, "main", nil)

Subscribe to Events

events, err := c.Subscribe(ctx)
for evt := range events {
    switch evt.Event {
    case "chat":    // streaming LLM tokens
    case "agent":   // agent lifecycle events
    case "heartbeat", "tick": // periodic signals
    }
}

Config

raw, err := c.ConfigGet(ctx)
err = c.ConfigPatch(ctx, protocol.ConfigPatchParams{Raw: "..."})

Cron

jobs, err := c.CronList(ctx, true)
err = c.CronRun(ctx, "job-id", true) // force=true

Sessions

list, _ := c.SessionsList(ctx, protocol.SessionsListParams{Limit: &limit})
err = c.SessionsPatch(ctx, protocol.SessionsPatchParams{Key: "main", Label: &labelJSON})
err = c.SessionsDelete(ctx, protocol.SessionsDeleteParams{Key: "main"})

Error Handling

Gateway errors are returned as *client.GatewayError:

raw, err := c.Request(ctx, "agent", params)
if err != nil {
    var gwErr *client.GatewayError
    if errors.As(err, &gwErr) {
        fmt.Println("Code:", gwErr.Code)    // e.g. "NOT_LINKED", "AGENT_TIMEOUT"
        fmt.Println("Msg:", gwErr.Message)
    }
}

Error codes are defined in protocol.ErrorCode* constants.

Examples

Example Description
examples/basic Connect, check status, print health snapshot
examples/agent Send an agent message and stream events
examples/chat Fetch chat history, send a message, stream reply
examples/events Subscribe and print all push events

Run any example with environment variables:

GATEWAY_URL=ws://localhost:5555 \
  GATEWAY_TOKEN=mytoken \
  go run ./examples/basic/

Running Tests

go test ./... -v

Architecture

openclaw-go/
├── protocol/               # Protocol types & constants (one file per domain)
│   ├── frames.go           # Wire frame types
│   ├── agent.go            # Single-agent types
│   ├── agents.go           # Multi-agent listing types
│   ├── skills.go           # Skill/model listing types
│   ├── sessions.go         # Session + Presence/Snapshot types
│   ├── config.go           # Config types
│   ├── cron.go             # Cron job types
│   ├── channels.go         # Channel and Talk types
│   ├── nodes.go            # Node management types
│   ├── devices.go          # Device types
│   ├── exec_approvals.go   # Exec approval types
│   ├── chat.go             # Chat history/send types
│   ├── push.go             # Push test types
│   ├── constants.go        # Protocol version, error codes, frame type constants
│   └── models_test.go
├── client/                 # WebSocket client
│   ├── client.go           # GatewayClient, connection, read loop
│   ├── request.go          # Request / RequestDecoded / RequestVoid
│   ├── subscribe.go        # Event channel subscription
│   ├── methods_agent.go    # SendAgent, AbortAgent
│   ├── methods_agents.go   # Agent listing & management
│   ├── methods_channels.go # Channel operations
│   ├── methods_chat.go     # Chat history, send, abort
│   ├── methods_config.go   # Config get/patch
│   ├── methods_cron.go     # Cron list/run
│   ├── methods_devices.go  # Device operations
│   ├── methods_exec.go     # Exec approval operations
│   ├── methods_misc.go     # Miscellaneous (Status, etc.)
│   ├── methods_nodes.go    # Node operations
│   ├── methods_sessions.go # Session list/patch/delete
│   └── client_test.go
└── examples/
    ├── basic/
    ├── agent/
    ├── chat/
    └── events/

Protocol

OpenClaw gateway uses WebSocket with JSON frames:

  • req — Client request: {type, id, method, params}
  • resp — Server response: {type, id, ok, payload|error}
  • event — Server push: {type, event, payload, seq}

Current protocol version: 3

License

MIT

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors