Skip to content

Latest commit

 

History

History
225 lines (176 loc) · 6.74 KB

File metadata and controls

225 lines (176 loc) · 6.74 KB

openclaw-go

Go SDK CI Go Reference codecov License: MIT

OpenClaw 网关协议的 Go SDK。

English | 中文

安装

go get github.com/yuchou87/openclaw-go

快速开始

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()

    // 检查网关状态
    if err := c.Status(ctx); err != nil {
        log.Fatal(err)
    }
    fmt.Println("网关连接正常 ✓")
}

包说明

包路径 说明
github.com/yuchou87/openclaw-go/client WebSocket 客户端 — 连接管理、请求/响应、事件流、类型化 API 方法
github.com/yuchou87/openclaw-go/protocol 所有协议结构体与常量(从 TypeScript schema 转译而来)

使用方式

连接

c := client.New(url, token, password)
// token 和 password 互斥,未使用的字段传空字符串
if err := c.Connect(ctx); err != nil { ... }
defer c.Close()

// 获取 HelloOk 快照(在线状态、健康信息、功能特性)
snap := c.Snapshot()
fmt.Println("网关版本:", snap.Server["version"])

发送 Agent 消息

err := c.SendAgent(ctx, protocol.AgentParams{
    Message:        "帮我写一个 Hello World",
    SessionKey:     &sessionKey,
    IdempotencyKey: uuid.NewString(), // 若为空则自动生成
})

聊天

// 获取历史记录
raw, err := c.ChatHistory(ctx, "main", &limit)

// 发送消息
resp, err := c.ChatSend(ctx, protocol.ChatSendParams{
    SessionKey:     "main",
    Message:        "你好",
    IdempotencyKey: uuid.NewString(),
})

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

订阅事件

events, err := c.Subscribe(ctx)
for evt := range events {
    switch evt.Event {
    case "chat":              // LLM 流式 token
    case "agent":             // Agent 生命周期事件
    case "heartbeat", "tick": // 周期性信号
    }
}

配置

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

Session 管理

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"})

错误处理

网关错误以 *client.GatewayError 形式返回,携带结构化错误码:

raw, err := c.Request(ctx, "agent", params)
if err != nil {
    var gwErr *client.GatewayError
    if errors.As(err, &gwErr) {
        fmt.Println("错误码:", gwErr.Code)    // 例如 "NOT_LINKED"、"AGENT_TIMEOUT"
        fmt.Println("错误信息:", gwErr.Message)
    }
}

错误码常量定义在 protocol.ErrorCode* 中。

示例

示例 说明
examples/basic 连接、检查状态、打印健康快照
examples/agent 发送 Agent 消息并流式接收事件
examples/chat 获取聊天历史、发送消息、流式接收回复
examples/events 订阅并打印所有推送事件

通过环境变量运行任意示例:

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

运行测试

go test ./... -v

项目结构

openclaw-go/
├── protocol/               # 协议类型与常量(每个域对应一个文件)
│   ├── frames.go           # 帧类型
│   ├── agent.go            # 单 Agent 类型
│   ├── agents.go           # 多 Agent 列表类型
│   ├── skills.go           # 技能/模型列表类型
│   ├── sessions.go         # Session 与 Presence/Snapshot 类型
│   ├── config.go           # 配置类型
│   ├── cron.go             # Cron 任务类型
│   ├── channels.go         # 频道与 Talk 类型
│   ├── nodes.go            # 节点管理类型
│   ├── devices.go          # 设备类型
│   ├── exec_approvals.go   # 执行审批类型
│   ├── chat.go             # 聊天历史/发送类型
│   ├── push.go             # 推送测试类型
│   ├── constants.go        # 协议版本、错误码、帧类型常量
│   └── models_test.go
├── client/                 # WebSocket 客户端
│   ├── client.go           # GatewayClient、连接、读取循环
│   ├── request.go          # Request / RequestDecoded / RequestVoid
│   ├── subscribe.go        # 事件频道订阅
│   ├── methods_agent.go    # SendAgent、AbortAgent
│   ├── methods_agents.go   # Agent 列表与管理
│   ├── methods_channels.go # 频道操作
│   ├── methods_chat.go     # 聊天历史、发送、中断
│   ├── methods_config.go   # 配置获取/更新
│   ├── methods_cron.go     # Cron 列表/运行
│   ├── methods_devices.go  # 设备操作
│   ├── methods_exec.go     # 执行审批操作
│   ├── methods_misc.go     # 其他(Status 等)
│   ├── methods_nodes.go    # 节点操作
│   ├── methods_sessions.go # Session 列表/更新/删除
│   └── client_test.go
└── examples/
    ├── basic/
    ├── agent/
    ├── chat/
    └── events/

协议说明

OpenClaw 网关使用 WebSocket + JSON 帧通信:

  • req — 客户端请求:{type, id, method, params}
  • resp — 服务端响应:{type, id, ok, payload|error}
  • event — 服务端推送:{type, event, payload, seq}

当前协议版本:3

许可证

MIT