feat: bootstrap OpenChamber native Android client

Add a Go client for OpenChamber built with Asuka's native widgets.

- internal/ocapi: health, password-to-device-token auth, session and
  message paging, prompt/interrupt/model/agent, permissions, SSE events,
  HTTP/SOCKS5 proxies and certificate pinning
- internal/storage: connection settings plus a device token in the
  platform keystore, with a per-install id for server-side dedupe
- internal/appui: connect, session list and chat screens with streaming
  Markdown, reasoning/tool folding, permission cards and session actions
- netcfg: native module that enables cleartext HTTP in release builds
- cmd/ocprobe: terminal probe for the API
- headless UI tests (uitest) and the research/plan document
This commit is contained in:
blumia committed 2026-11-16 09:09:09 +08:00
commit 254d08b1bd
35 files changed
+4922

No files matched your search

+157
View File
@@ -0,0 +1,157 @@
package ocapi
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestCatalogAndPermissions(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/model":
if got := r.URL.Query().Get("location[directory]"); got != "/home/me/p" {
t.Errorf("model directory = %q", got)
}
fmt.Fprint(w, `{"data":[{"id":"gpt","providerID":"openai","name":"GPT"}]}`)
case "/api/agent":
fmt.Fprint(w, `{"data":[{"id":"build","name":"Build","mode":"primary"}]}`)
case "/api/permission/request":
fmt.Fprint(w, `{"data":[{"id":"per_1","sessionID":"ses_1","action":"bash","resources":["rm -rf x"]}]}`)
case "/api/session/ses_1/permission/per_1/reply":
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
if body["decision"] != "always" || body["message"] != "ok" {
t.Errorf("reply body = %v", body)
}
w.WriteHeader(http.StatusNoContent)
case "/api/session/ses_1/model":
var body struct {
Model ModelRef `json:"model"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
if body.Model.ID != "gpt" || body.Model.ProviderID != "openai" {
t.Errorf("model switch = %+v", body.Model)
}
w.WriteHeader(http.StatusNoContent)
case "/api/session/ses_1/agent":
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
if body["agent"] != "plan" {
t.Errorf("agent switch = %v", body)
}
w.WriteHeader(http.StatusNoContent)
case "/api/session/ses_1":
if r.Method != http.MethodPatch {
t.Errorf("method = %s", r.Method)
}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
if body["title"] != "renamed" {
t.Errorf("patch = %v", body)
}
w.WriteHeader(http.StatusNoContent)
default:
t.Errorf("unexpected path %q", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
}))
defer srv.Close()
ctx := context.Background()
c, _ := New(srv.URL, Options{})
models, err := c.Models(ctx, "/home/me/p")
if err != nil || len(models) != 1 || models[0].ID != "gpt" {
t.Fatalf("models: %+v %v", models, err)
}
agents, err := c.Agents(ctx, "")
if err != nil || len(agents) != 1 || agents[0].ID != "build" {
t.Fatalf("agents: %+v %v", agents, err)
}
perms, err := c.PendingPermissions(ctx, "")
if err != nil || len(perms) != 1 || perms[0].Action != "bash" {
t.Fatalf("permissions: %+v %v", perms, err)
}
if err := c.ReplyPermission(ctx, "ses_1", "per_1", PermissionAlways, "ok"); err != nil {
t.Fatal(err)
}
if err := c.SwitchModel(ctx, "ses_1", "", ModelRef{ID: "gpt", ProviderID: "openai"}); err != nil {
t.Fatal(err)
}
if err := c.SwitchAgent(ctx, "ses_1", "", "plan"); err != nil {
t.Fatal(err)
}
title := "renamed"
if err := c.UpdateSession(ctx, "ses_1", "", SessionPatch{Title: &title}); err != nil {
t.Fatal(err)
}
}
func TestCreateAndDeleteSession(t *testing.T) {
var createBody map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/session" && r.Method == http.MethodPost:
_ = json.NewDecoder(r.Body).Decode(&createBody)
fmt.Fprint(w, `{"data":{"id":"ses_new","title":"New","time":{"created":1,"updated":1}}}`)
case r.URL.Path == "/api/session/ses_new" && r.Method == http.MethodDelete:
w.WriteHeader(http.StatusNoContent)
default:
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
}
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
s, err := c.CreateSession(context.Background(), CreateSessionOptions{Directory: "/p", Title: "New"})
if err != nil || s.ID != "ses_new" {
t.Fatalf("create: %+v %v", s, err)
}
if loc, _ := createBody["location"].(map[string]any); loc["directory"] != "/p" {
t.Errorf("create location: %v", createBody)
}
if err := c.DeleteSession(context.Background(), "ses_new", ""); err != nil {
t.Fatal(err)
}
}
func TestWaitReady(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.URL.Query().Get("wait"); got != "1500" {
t.Errorf("wait = %q", got)
}
fmt.Fprint(w, `{"healthy":true}`)
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
if err := c.WaitReady(context.Background(), 1500*time.Millisecond); err != nil {
t.Fatal(err)
}
}
func TestCertificateFingerprint(t *testing.T) {
// A TLS server with a self-signed certificate; pinning its fingerprint
// (or skipping verification) is the only way to reach it.
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"status":"ok"}`)
}))
defer srv.Close()
if _, err := New(srv.URL, Options{}); err != nil {
t.Fatal(err)
}
c, _ := New(srv.URL, Options{})
if _, err := c.Health(context.Background()); err == nil {
t.Fatal("self-signed certificate accepted without opting in")
}
c2, _ := New(srv.URL, Options{InsecureSkipVerify: true})
if _, err := c2.Health(context.Background()); err != nil {
t.Fatalf("insecure option did not work: %v", err)
}
}
+379
View File
@@ -0,0 +1,379 @@
package ocapi
import (
"context"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
xproxy "golang.org/x/net/proxy"
)
// Options configures a Client.
type Options struct {
// Proxy is an optional HTTP(S) or SOCKS5 proxy URL, e.g.
// "http://127.0.0.1:7890" or "socks5://127.0.0.1:1080". No proxy
// authentication is supported.
Proxy string
// InsecureSkipVerify disables certificate verification. Prefer
// CertFingerprint for a self-signed server.
InsecureSkipVerify bool
// CertFingerprint pins the server's leaf certificate: the SHA-256 of
// its DER bytes, as hex, with or without colons.
CertFingerprint string
// Timeout bounds normal requests. Streaming requests ignore it.
Timeout time.Duration
// UserAgent is sent on every request.
UserAgent string
// HTTPClient replaces the constructed client (tests).
HTTPClient *http.Client
}
// Client talks to one OpenChamber server.
type Client struct {
base *url.URL
token string
http *http.Client
ua string
}
// New builds a client for base. A base without a scheme gets https, except
// for loopback and private addresses, which get http.
func New(base string, opts Options) (*Client, error) {
normalized, err := NormalizeBaseURL(base)
if err != nil {
return nil, err
}
u, err := url.Parse(normalized)
if err != nil {
return nil, fmt.Errorf("ocapi: invalid server URL: %w", err)
}
ua := opts.UserAgent
if ua == "" {
ua = "OpenChamber-Native/0.1"
}
hc := opts.HTTPClient
if hc == nil {
tr, err := newTransport(opts)
if err != nil {
return nil, err
}
timeout := opts.Timeout
if timeout <= 0 {
timeout = 30 * time.Second
}
hc = &http.Client{Transport: tr, Timeout: timeout}
}
return &Client{base: u, http: hc, ua: ua}, nil
}
// NormalizeBaseURL trims a user-entered server address, adds a scheme when
// missing, and drops trailing slashes.
func NormalizeBaseURL(raw string) (string, error) {
s := strings.TrimSpace(raw)
if s == "" {
return "", errors.New("ocapi: server URL is empty")
}
if !strings.Contains(s, "://") {
if isPrivateHost(s) {
s = "http://" + s
} else {
s = "https://" + s
}
}
u, err := url.Parse(s)
if err != nil {
return "", fmt.Errorf("ocapi: invalid server URL: %w", err)
}
if u.Scheme != "http" && u.Scheme != "https" {
return "", fmt.Errorf("ocapi: unsupported scheme %q", u.Scheme)
}
if u.Host == "" {
return "", errors.New("ocapi: server URL has no host")
}
u.Path = strings.TrimRight(u.Path, "/")
return u.String(), nil
}
func isPrivateHost(s string) bool {
host := s
if h, _, err := net.SplitHostPort(s); err == nil {
host = h
}
host = strings.Trim(host, "[]")
if host == "localhost" || strings.HasSuffix(host, ".local") {
return true
}
ip := net.ParseIP(host)
if ip == nil {
return false
}
return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast()
}
func newTransport(opts Options) (*http.Transport, error) {
tr := &http.Transport{
// No overall dial timeout for streaming; normal requests carry a
// per-request deadline through context.
DialContext: (&net.Dialer{Timeout: 15 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
TLSHandshakeTimeout: 15 * time.Second,
IdleConnTimeout: 90 * time.Second,
ForceAttemptHTTP2: true,
}
if raw := strings.TrimSpace(opts.Proxy); raw != "" {
pu, err := url.Parse(raw)
if err != nil {
return nil, fmt.Errorf("ocapi: invalid proxy URL: %w", err)
}
switch pu.Scheme {
case "http", "https":
tr.Proxy = http.ProxyURL(pu)
case "socks5", "socks5h":
dialer, err := xproxy.SOCKS5("tcp", pu.Host, nil, xproxy.Direct)
if err != nil {
return nil, fmt.Errorf("ocapi: socks5 proxy: %w", err)
}
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
type ctxDialer interface {
DialContext(context.Context, string, string) (net.Conn, error)
}
if cd, ok := dialer.(ctxDialer); ok {
return cd.DialContext(ctx, network, addr)
}
return dialer.Dial(network, addr)
}
tr.Proxy = nil
default:
return nil, fmt.Errorf("ocapi: unsupported proxy scheme %q", pu.Scheme)
}
}
if opts.InsecureSkipVerify || opts.CertFingerprint != "" {
cfg := &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: opts.InsecureSkipVerify}
if fp := normalizeFingerprint(opts.CertFingerprint); fp != "" {
cfg.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
if len(rawCerts) == 0 {
return errors.New("ocapi: server sent no certificate")
}
sum := sha256.Sum256(rawCerts[0])
if got := hex.EncodeToString(sum[:]); got != fp {
return fmt.Errorf("ocapi: certificate fingerprint mismatch: got %s", formatFingerprint(got))
}
return nil
}
}
tr.TLSClientConfig = cfg
}
return tr, nil
}
func normalizeFingerprint(s string) string {
clean := strings.ToLower(strings.NewReplacer(":", "", " ", "").Replace(strings.TrimSpace(s)))
if clean == "" {
return ""
}
if _, err := hex.DecodeString(clean); err != nil || len(clean) != 64 {
return ""
}
return clean
}
func formatFingerprint(hexString string) string {
var b strings.Builder
for i := 0; i < len(hexString); i += 2 {
if i > 0 {
b.WriteByte(':')
}
b.WriteString(strings.ToUpper(hexString[i : i+2]))
}
return b.String()
}
// SetToken sets the bearer token used for subsequent requests.
func (c *Client) SetToken(token string) { c.token = strings.TrimSpace(token) }
// Token returns the current bearer token.
func (c *Client) Token() string { return c.token }
// BaseURL returns the client's base URL.
func (c *Client) BaseURL() string { return c.base.String() }
// APIError is a non-2xx answer.
type APIError struct {
Status int
Message string
RetryAfter time.Duration
Locked bool
Raw string
}
func (e *APIError) Error() string {
if e.Message != "" {
return fmt.Sprintf("ocapi: %s (HTTP %d)", e.Message, e.Status)
}
return fmt.Sprintf("ocapi: HTTP %d", e.Status)
}
// IsUnauthorized reports whether err is a 401 (token expired or wrong).
func IsUnauthorized(err error) bool {
var apiErr *APIError
return errors.As(err, &apiErr) && apiErr.Status == http.StatusUnauthorized
}
// IsRateLimited reports whether err is a 429, and how long to wait.
func IsRateLimited(err error) (time.Duration, bool) {
var apiErr *APIError
if errors.As(err, &apiErr) && apiErr.Status == http.StatusTooManyRequests {
return apiErr.RetryAfter, true
}
return 0, false
}
type requestOptions struct {
directory string
query url.Values
rawQuery bool
}
func (c *Client) buildURL(path string, ro requestOptions) string {
u := *c.base
u.Path = strings.TrimRight(u.Path, "/") + "/" + strings.TrimLeft(path, "/")
q := u.Query()
for k, vs := range ro.query {
for _, v := range vs {
q.Add(k, v)
}
}
u.RawQuery = q.Encode()
return u.String()
}
func (c *Client) newRequest(ctx context.Context, method, path string, ro requestOptions, body any) (*http.Request, error) {
var rdr io.Reader
if body != nil {
buf, err := json.Marshal(body)
if err != nil {
return nil, err
}
rdr = strings.NewReader(string(buf))
}
req, err := http.NewRequestWithContext(ctx, method, c.buildURL(path, ro), rdr)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", c.ua)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if c.token != "" {
req.Header.Set("Authorization", "Bearer "+c.token)
}
if ro.directory != "" {
req.Header.Set("x-opencode-directory", url.PathEscape(ro.directory))
}
return req, nil
}
func (c *Client) do(ctx context.Context, method, path string, ro requestOptions, body, out any) error {
req, err := c.newRequest(ctx, method, path, ro, body)
if err != nil {
return err
}
res, err := c.http.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode < 200 || res.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<16))
apiErr := &APIError{Status: res.StatusCode, Raw: string(raw)}
var payload struct {
Error string `json:"error"`
Locked bool `json:"locked"`
RetryAfter json.RawMessage `json:"retryAfter"`
}
if json.Unmarshal(raw, &payload) == nil {
apiErr.Message = payload.Error
apiErr.Locked = payload.Locked
apiErr.RetryAfter = parseRetryAfter(payload.RetryAfter, res.Header.Get("Retry-After"))
}
return apiErr
}
if out == nil || res.StatusCode == http.StatusNoContent {
_, _ = io.Copy(io.Discard, res.Body)
return nil
}
dec := json.NewDecoder(io.LimitReader(res.Body, 64<<20))
if err := dec.Decode(out); err != nil && !errors.Is(err, io.EOF) {
return fmt.Errorf("ocapi: decode response: %w", err)
}
return nil
}
func parseRetryAfter(raw json.RawMessage, header string) time.Duration {
if len(raw) > 0 {
var secs float64
if json.Unmarshal(raw, &secs) == nil && secs > 0 {
return time.Duration(secs * float64(time.Second))
}
var text string
if json.Unmarshal(raw, &text) == nil {
if n, err := strconv.Atoi(strings.TrimSpace(text)); err == nil && n > 0 {
return time.Duration(n) * time.Second
}
}
}
if n, err := strconv.Atoi(strings.TrimSpace(header)); err == nil && n > 0 {
return time.Duration(n) * time.Second
}
return 0
}
// Health reads the server's unauthenticated health document.
func (c *Client) Health(ctx context.Context) (Health, error) {
var h Health
err := c.do(ctx, http.MethodGet, "/health", requestOptions{}, nil, &h)
return h, err
}
// SessionStatus probes /auth/session.
func (c *Client) SessionStatus(ctx context.Context) (AuthStatus, error) {
var s AuthStatus
err := c.do(ctx, http.MethodGet, "/auth/session", requestOptions{}, nil, &s)
return s, err
}
// Login exchanges the UI password for a device client token and stores it.
func (c *Client) Login(ctx context.Context, req LoginRequest) (LoginResult, error) {
if !req.TrustDevice {
req.TrustDevice = true
}
if !req.IssueClientToken {
req.IssueClientToken = true
}
if req.ClientKind == "" {
req.ClientKind = "mobile"
}
if req.ClientLabel == "" {
req.ClientLabel = "OpenChamber Native"
}
var out LoginResult
if err := c.do(ctx, http.MethodPost, "/auth/session", requestOptions{}, req, &out); err != nil {
return LoginResult{}, err
}
if out.ClientToken != "" {
c.SetToken(out.ClientToken)
}
return out, nil
}
+295
View File
@@ -0,0 +1,295 @@
package ocapi
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestNormalizeBaseURL(t *testing.T) {
cases := []struct {
in, want string
}{
{"127.0.0.1:3000", "http://127.0.0.1:3000"},
{"192.168.1.5:3000/", "http://192.168.1.5:3000"},
{"http://host:3000/", "http://host:3000"},
{"https://oc.example.com", "https://oc.example.com"},
{"oc.example.com", "https://oc.example.com"},
}
for _, c := range cases {
got, err := NormalizeBaseURL(c.in)
if err != nil {
t.Fatalf("NormalizeBaseURL(%q): %v", c.in, err)
}
if got != c.want {
t.Errorf("NormalizeBaseURL(%q) = %q, want %q", c.in, got, c.want)
}
}
if _, err := NormalizeBaseURL(" "); err == nil {
t.Error("empty URL accepted")
}
if _, err := NormalizeBaseURL("ftp://host"); err == nil {
t.Error("ftp scheme accepted")
}
}
func TestHealth(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/health" {
t.Errorf("path = %q", r.URL.Path)
}
fmt.Fprint(w, `{"status":"ok","openchamberVersion":"2.7.0","serverId":"abc","isOpenCodeReady":true}`)
}))
defer srv.Close()
c, err := New(srv.URL, Options{})
if err != nil {
t.Fatal(err)
}
h, err := c.Health(context.Background())
if err != nil {
t.Fatal(err)
}
if h.OpenChamberVersion != "2.7.0" || h.ServerID != "abc" || !h.IsOpenCodeReady {
t.Fatalf("unexpected health: %+v", h)
}
}
func TestSessionStatusAndLogin(t *testing.T) {
var loginBody map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/auth/session":
if r.Method == http.MethodGet {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, `{"authenticated":false,"locked":true}`)
return
}
if err := json.NewDecoder(r.Body).Decode(&loginBody); err != nil {
t.Errorf("login body: %v", err)
}
fmt.Fprint(w, `{"authenticated":true,"clientToken":"oc_client_test"}`)
default:
t.Errorf("unexpected path %q", r.URL.Path)
}
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
_, err := c.SessionStatus(context.Background())
if !IsUnauthorized(err) {
t.Fatalf("want 401, got %v", err)
}
res, err := c.Login(context.Background(), LoginRequest{Password: "pw", DedupeKey: "install-1"})
if err != nil {
t.Fatal(err)
}
if res.ClientToken != "oc_client_test" || c.Token() != "oc_client_test" {
t.Fatalf("token not stored: %+v, %q", res, c.Token())
}
if loginBody["trustDevice"] != true || loginBody["issueClientToken"] != true {
t.Errorf("login defaults missing: %v", loginBody)
}
if loginBody["clientKind"] != "mobile" || loginBody["password"] != "pw" {
t.Errorf("login body: %v", loginBody)
}
}
func TestListSessionsScoped(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/session" {
t.Errorf("path = %q", r.URL.Path)
}
if got := r.URL.Query().Get("directory"); got != "/home/me/proj" {
t.Errorf("directory query = %q", got)
}
if got := r.Header.Get("x-opencode-directory"); got != "%2Fhome%2Fme%2Fproj" {
t.Errorf("directory header = %q", got)
}
if got := r.URL.Query().Get("limit"); got != "50" {
t.Errorf("limit = %q", got)
}
fmt.Fprint(w, `{"data":[{"id":"ses_1","title":"Hi","time":{"created":1,"updated":2},"location":{"directory":"/home/me/proj"}}],"cursor":{"next":"n1"}}`)
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
page, err := c.ListSessions(context.Background(), ListSessionsOptions{Directory: "/home/me/proj", Limit: 50})
if err != nil {
t.Fatal(err)
}
if len(page.Data) != 1 || page.Data[0].ID != "ses_1" || page.Cursor.Next != "n1" {
t.Fatalf("unexpected page: %+v", page)
}
}
func TestMessagesAndTurn(t *testing.T) {
var promptBody map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/session/ses_1/message":
if got := r.URL.Query().Get("order"); got != "desc" {
t.Errorf("order = %q", got)
}
fmt.Fprint(w, `{"data":[{"id":"msg_1","type":"assistant","content":[{"type":"text","text":"hello"}]}],"cursor":{"next":"m1"}}`)
case "/api/session/ses_1/prompt":
_ = json.NewDecoder(r.Body).Decode(&promptBody)
fmt.Fprint(w, `{"data":{}}`)
case "/api/session/ses_1/interrupt":
fmt.Fprint(w, `{"interrupted":true}`)
default:
t.Errorf("unexpected path %q", r.URL.Path)
}
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
page, err := c.ListMessages(context.Background(), "ses_1", ListMessagesOptions{Limit: 20, Order: "desc"})
if err != nil {
t.Fatal(err)
}
if len(page.Data) != 1 || page.Data[0].Content[0].Text != "hello" {
t.Fatalf("unexpected messages: %+v", page)
}
if err := c.Prompt(context.Background(), "ses_1", PromptOptions{Text: "ping", MessageID: "msg_9"}); err != nil {
t.Fatal(err)
}
if promptBody["text"] != "ping" || promptBody["id"] != "msg_9" {
t.Errorf("prompt body: %v", promptBody)
}
ok, err := c.Interrupt(context.Background(), "ses_1", "")
if err != nil || !ok {
t.Fatalf("interrupt: %v %v", ok, err)
}
}
func TestRateLimit(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusTooManyRequests)
fmt.Fprint(w, `{"error":"Too many login attempts, please try again later","retryAfter":12}`)
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
_, err := c.Login(context.Background(), LoginRequest{Password: "x"})
wait, ok := IsRateLimited(err)
if !ok || wait != 12*time.Second {
t.Fatalf("rate limit: %v %v", wait, err)
}
}
func TestStreamEvents(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.URL.Query()["types"]; len(got) != 2 {
t.Errorf("types = %v", got)
}
w.Header().Set("Content-Type", "text/event-stream")
flusher := w.(http.Flusher)
// Split an event across writes and use two data lines, which
// SSE joins with a newline.
fmt.Fprint(w, "event: message\n")
flusher.Flush()
fmt.Fprint(w, "data: {\"id\":\"evt_1\",")
flusher.Flush()
fmt.Fprint(w, "\"type\":\"session.text.delta\",")
flusher.Flush()
fmt.Fprint(w, "\"data\":{\"delta\":\"hi\"}}\n\n")
flusher.Flush()
<-r.Context().Done()
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
got := make(chan Event, 1)
go func() {
_ = c.StreamEvents(ctx, []string{"session.text.delta", "permission.asked"}, func(ev Event) error {
got <- ev
cancel()
return nil
})
}()
select {
case ev := <-got:
if ev.ID != "evt_1" || ev.Type != "session.text.delta" {
t.Fatalf("event: %+v", ev)
}
var data SessionEventData
if err := ev.UnmarshalData(&data); err != nil || data.Delta != "hi" {
t.Fatalf("data: %+v %v", data, err)
}
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for an event")
}
}
func TestProxyDialer(t *testing.T) {
// A SOCKS5 address is accepted; the connection itself is not made.
c, err := New("http://127.0.0.1:3000", Options{Proxy: "socks5://127.0.0.1:1080"})
if err != nil {
t.Fatal(err)
}
if c.http.Transport == nil {
t.Fatal("no transport")
}
if _, err := New("http://127.0.0.1:3000", Options{Proxy: "ftp://x"}); err == nil {
t.Fatal("unsupported proxy scheme accepted")
}
}
func TestDecodeMessageContent(t *testing.T) {
body := `{"data":[{"id":"msg_1","type":"assistant","content":[
{"type":"reasoning","text":"think"},
{"type":"text","text":"answer"},
{"type":"tool","id":"call_1","name":"shell","state":{"status":"completed","input":{"command":"ls"},"content":[{"type":"text","text":"a.txt"}]}}]}]}`
var page MessagePage
if err := json.Unmarshal([]byte(body), &page); err != nil {
t.Fatal(err)
}
m := page.Data[0]
if len(m.Content) != 3 || m.Content[2].State == nil || m.Content[2].State.Status != "completed" {
t.Fatalf("content: %+v", m.Content)
}
if m.Content[2].State.Input["command"] != "ls" {
t.Fatalf("input: %+v", m.Content[2].State.Input)
}
if m.Content[2].State.Content[0].Text != "a.txt" {
t.Fatalf("tool content: %+v", m.Content[2].State.Content)
}
}
func TestErrorBodyKept(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, `{"error":"bad thing"}`)
}))
defer srv.Close()
c, _ := New(srv.URL, Options{})
err := c.DeleteSession(context.Background(), "ses_x", "")
var apiErr *APIError
if !strings.Contains(err.Error(), "bad thing") || !asAPIError(err, &apiErr) || apiErr.Status != 400 {
t.Fatalf("error: %v", err)
}
}
func asAPIError(err error, target **APIError) bool {
for err != nil {
if e, ok := err.(*APIError); ok {
*target = e
return true
}
u, ok := err.(interface{ Unwrap() error })
if !ok {
return false
}
err = u.Unwrap()
}
return false
}
+180
View File
@@ -0,0 +1,180 @@
package ocapi
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"net/url"
"strings"
"time"
)
// StreamEvents subscribes to GET /api/event and calls fn for each event
// until ctx is done or the connection fails. types filters the event
// types; nil means every type.
func (c *Client) StreamEvents(ctx context.Context, types []string, fn func(Event) error) error {
return c.streamEvents(ctx, types, nil, fn)
}
func (c *Client) streamEvents(ctx context.Context, types []string, onOpen func(), fn func(Event) error) error {
q := url.Values{}
for _, t := range types {
q.Add("types", t)
}
req, err := c.newRequest(ctx, http.MethodGet, "/api/event", requestOptions{query: q}, nil)
if err != nil {
return err
}
req.Header.Set("Accept", "text/event-stream")
req.Header.Set("Cache-Control", "no-cache")
// A streaming request must not inherit the client's overall timeout.
hc := *c.http
hc.Timeout = 0
res, err := hc.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<14))
return &APIError{Status: res.StatusCode, Raw: string(raw), Message: strings.TrimSpace(string(raw))}
}
if onOpen != nil {
onOpen()
}
reader := bufio.NewReaderSize(res.Body, 64<<10)
var data []byte
for {
line, err := reader.ReadString('\n')
if err != nil {
if errors.Is(err, io.EOF) || ctx.Err() != nil {
return ctx.Err()
}
return err
}
line = strings.TrimRight(line, "\r\n")
if line == "" {
if len(data) == 0 {
continue
}
var ev Event
parseErr := json.Unmarshal(data, &ev)
data = data[:0]
if parseErr != nil {
continue
}
if err := fn(ev); err != nil {
return err
}
continue
}
if strings.HasPrefix(line, "data:") {
chunk := strings.TrimPrefix(line, "data:")
chunk = strings.TrimPrefix(chunk, " ")
if len(data) > 0 {
data = append(data, '\n')
}
data = append(data, chunk...)
}
}
}
// SubscriptionState reports the event stream's connection state.
type SubscriptionState int
const (
Subscribing SubscriptionState = iota
Subscribed
Disconnected
)
// Subscription is a resilient event stream.
type Subscription struct {
Types []string
OnEvent func(Event)
OnState func(SubscriptionState, error)
// MinBackoff and MaxBackoff bound the reconnect delay.
MinBackoff time.Duration
MaxBackoff time.Duration
}
// Subscribe keeps an event stream open until ctx is done, reconnecting with
// exponential backoff. It blocks, so run it in a goroutine.
func (c *Client) Subscribe(ctx context.Context, s Subscription) {
minB, maxB := s.MinBackoff, s.MaxBackoff
if minB <= 0 {
minB = time.Second
}
if maxB <= 0 {
maxB = 30 * time.Second
}
state := func(st SubscriptionState, err error) {
if s.OnState != nil {
s.OnState(st, err)
}
}
backoff := minB
for ctx.Err() == nil {
state(Subscribing, nil)
started := time.Now()
err := c.streamEvents(ctx, s.Types, func() {
state(Subscribed, nil)
}, func(ev Event) error {
if s.OnEvent != nil {
s.OnEvent(ev)
}
return nil
})
if ctx.Err() != nil {
return
}
state(Disconnected, err)
// A stream that stayed up for a while restarts at the minimum
// delay; a failing one backs off.
if time.Since(started) > 30*time.Second {
backoff = minB
}
delay := backoff/2 + time.Duration(rand.Int63n(int64(backoff/2+1)))
select {
case <-ctx.Done():
return
case <-time.After(delay):
}
if backoff < maxB {
backoff *= 2
if backoff > maxB {
backoff = maxB
}
}
}
}
// WaitReady polls /api/opencode/health until OpenCode is ready or ctx ends.
func (c *Client) WaitReady(ctx context.Context, wait time.Duration) error {
if wait <= 0 {
wait = 20 * time.Second
}
q := url.Values{}
q.Set("wait", fmt.Sprint(wait.Milliseconds()))
var payload struct {
Healthy bool `json:"healthy"`
Error string `json:"error"`
}
if err := c.do(ctx, http.MethodGet, "/api/opencode/health", requestOptions{query: q}, nil, &payload); err != nil {
return err
}
if !payload.Healthy {
if payload.Error != "" {
return fmt.Errorf("ocapi: opencode not ready: %s", payload.Error)
}
return errors.New("ocapi: opencode not ready")
}
return nil
}
+249
View File
@@ -0,0 +1,249 @@
package ocapi
import (
"context"
"encoding/json"
"net/http"
"net/url"
"strconv"
)
// ListSessionsOptions configures ListSessions.
type ListSessionsOptions struct {
// Directory scopes the list to one absolute path. Empty means all
// projects (each Session carries its own Location).
Directory string
Limit int
Cursor string
Order string // "asc" or "desc"
Search string
ParentID string
Archived *bool
}
// ListSessions lists sessions, newest first by default.
func (c *Client) ListSessions(ctx context.Context, o ListSessionsOptions) (SessionPage, error) {
q := url.Values{}
if o.Limit > 0 {
q.Set("limit", strconv.Itoa(o.Limit))
}
if o.Directory != "" {
q.Set("directory", o.Directory)
}
if o.Cursor != "" {
q.Set("cursor", o.Cursor)
}
if o.Order != "" {
q.Set("order", o.Order)
}
if o.Search != "" {
q.Set("search", o.Search)
}
if o.ParentID != "" {
q.Set("parentID", o.ParentID)
}
if o.Archived != nil {
q.Set("archived", strconv.FormatBool(*o.Archived))
}
var page SessionPage
err := c.do(ctx, http.MethodGet, "/api/session", requestOptions{directory: o.Directory, query: q}, nil, &page)
return page, err
}
// ActiveSessions returns the sessions running right now, keyed by id.
func (c *Client) ActiveSessions(ctx context.Context) (map[string]string, error) {
var payload struct {
Data map[string]struct {
Type string `json:"type"`
} `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/api/session/active", requestOptions{}, nil, &payload); err != nil {
return nil, err
}
out := make(map[string]string, len(payload.Data))
for id, v := range payload.Data {
out[id] = v.Type
}
return out, nil
}
// GetSession reads one session.
func (c *Client) GetSession(ctx context.Context, id, directory string) (Session, error) {
var payload struct {
Data Session `json:"data"`
}
err := c.do(ctx, http.MethodGet, "/api/session/"+url.PathEscape(id), requestOptions{directory: directory}, nil, &payload)
return payload.Data, err
}
// CreateSessionOptions configures CreateSession.
type CreateSessionOptions struct {
Directory string
Title string
Agent string
Model *ModelRef
}
// CreateSession makes a new session, optionally in a directory.
func (c *Client) CreateSession(ctx context.Context, o CreateSessionOptions) (Session, error) {
body := map[string]any{}
if o.Title != "" {
body["title"] = o.Title
}
if o.Agent != "" {
body["agent"] = o.Agent
}
if o.Model != nil {
body["model"] = o.Model
}
if o.Directory != "" {
body["location"] = map[string]string{"directory": o.Directory}
}
var payload struct {
Data Session `json:"data"`
}
err := c.do(ctx, http.MethodPost, "/api/session", requestOptions{directory: o.Directory}, body, &payload)
return payload.Data, err
}
// SessionPatch is PATCH /api/session/{id}: both fields are optional.
type SessionPatch struct {
Title *string `json:"title,omitempty"`
Archived *bool `json:"archived,omitempty"`
}
// UpdateSession renames or archives one session.
func (c *Client) UpdateSession(ctx context.Context, id, directory string, patch SessionPatch) error {
return c.do(ctx, http.MethodPatch, "/api/session/"+url.PathEscape(id), requestOptions{directory: directory}, patch, nil)
}
// DeleteSession removes a session and its children.
func (c *Client) DeleteSession(ctx context.Context, id, directory string) error {
return c.do(ctx, http.MethodDelete, "/api/session/"+url.PathEscape(id), requestOptions{directory: directory}, nil, nil)
}
// ListMessagesOptions configures ListMessages.
type ListMessagesOptions struct {
Directory string
Limit int
Cursor string
Order string // "asc" or "desc"
}
// ListMessages reads one page of a session's messages. Newest first by
// default, which is what a chat pages backwards with.
func (c *Client) ListMessages(ctx context.Context, id string, o ListMessagesOptions) (MessagePage, error) {
q := url.Values{}
if o.Limit > 0 {
q.Set("limit", strconv.Itoa(o.Limit))
}
if o.Cursor != "" {
q.Set("cursor", o.Cursor)
}
if o.Order != "" {
q.Set("order", o.Order)
}
var page MessagePage
err := c.do(ctx, http.MethodGet, "/api/session/"+url.PathEscape(id)+"/message",
requestOptions{directory: o.Directory, query: q}, nil, &page)
return page, err
}
// ModelSelection lists the models the server offers for a directory.
func (c *Client) Models(ctx context.Context, directory string) ([]ModelRef, error) {
q := url.Values{}
if directory != "" {
q.Set("location[directory]", directory)
}
var payload struct {
Data []struct {
ID string `json:"id"`
ProviderID string `json:"providerID"`
Name string `json:"name"`
Variant string `json:"variant"`
} `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/api/model", requestOptions{query: q}, nil, &payload); err != nil {
return nil, err
}
out := make([]ModelRef, 0, len(payload.Data))
for _, m := range payload.Data {
out = append(out, ModelRef{ID: m.ID, ProviderID: m.ProviderID, Variant: m.Variant})
}
return out, nil
}
// AgentInfo is one entry of GET /api/agent.
type AgentInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Mode string `json:"mode"`
Hidden bool `json:"hidden"`
}
// Agents lists the agents available for a directory.
func (c *Client) Agents(ctx context.Context, directory string) ([]AgentInfo, error) {
q := url.Values{}
if directory != "" {
q.Set("location[directory]", directory)
}
var payload struct {
Data []AgentInfo `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/api/agent", requestOptions{query: q}, nil, &payload); err != nil {
return nil, err
}
return payload.Data, nil
}
// PermissionRequest is a pending tool permission.
type PermissionRequest struct {
ID string `json:"id"`
SessionID string `json:"sessionID"`
Action string `json:"action"`
Resources []string `json:"resources"`
Message string `json:"message,omitempty"`
}
// PendingPermissions lists the pending permission requests for a directory.
func (c *Client) PendingPermissions(ctx context.Context, directory string) ([]PermissionRequest, error) {
q := url.Values{}
if directory != "" {
q.Set("location[directory]", directory)
}
var payload struct {
Data []PermissionRequest `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/api/permission/request", requestOptions{query: q}, nil, &payload); err != nil {
return nil, err
}
return payload.Data, nil
}
// PermissionDecision is how a permission request is answered.
type PermissionDecision string
const (
PermissionOnce PermissionDecision = "once"
PermissionAlways PermissionDecision = "always"
PermissionReject PermissionDecision = "reject"
)
// ReplyPermission answers a pending permission request.
func (c *Client) ReplyPermission(ctx context.Context, sessionID, requestID string, decision PermissionDecision, message string) error {
body := map[string]any{"decision": decision}
if message != "" {
body["message"] = message
}
path := "/api/session/" + url.PathEscape(sessionID) + "/permission/" + url.PathEscape(requestID) + "/reply"
return c.do(ctx, http.MethodPost, path, requestOptions{}, body, nil)
}
// EventData unmarshals an event's payload into v.
func (e Event) UnmarshalData(v any) error {
if len(e.Data) == 0 {
return nil
}
return json.Unmarshal(e.Data, v)
}
+49
View File
@@ -0,0 +1,49 @@
package ocapi
import (
"context"
"net/http"
"net/url"
)
// PromptOptions configures Prompt.
type PromptOptions struct {
Directory string
// MessageID is an optional client-minted id (msg_…), which makes a
// retry after a lost response a no-op instead of a duplicate.
MessageID string
Text string
}
// Prompt sends a user message to a session. The reply arrives through the
// event stream, not this call.
func (c *Client) Prompt(ctx context.Context, sessionID string, o PromptOptions) error {
body := map[string]any{"text": o.Text}
if o.MessageID != "" {
body["id"] = o.MessageID
}
path := "/api/session/" + url.PathEscape(sessionID) + "/prompt"
return c.do(ctx, http.MethodPost, path, requestOptions{directory: o.Directory}, body, nil)
}
// Interrupt stops the turn the session is running.
func (c *Client) Interrupt(ctx context.Context, sessionID, directory string) (bool, error) {
var payload struct {
Interrupted bool `json:"interrupted"`
}
path := "/api/session/" + url.PathEscape(sessionID) + "/interrupt"
err := c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, map[string]any{}, &payload)
return payload.Interrupted, err
}
// SwitchModel changes the model later turns run on.
func (c *Client) SwitchModel(ctx context.Context, sessionID, directory string, model ModelRef) error {
path := "/api/session/" + url.PathEscape(sessionID) + "/model"
return c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, map[string]any{"model": model}, nil)
}
// SwitchAgent changes the agent later turns run with.
func (c *Client) SwitchAgent(ctx context.Context, sessionID, directory, agent string) error {
path := "/api/session/" + url.PathEscape(sessionID) + "/agent"
return c.do(ctx, http.MethodPost, path, requestOptions{directory: directory}, map[string]any{"agent": agent}, nil)
}
+219
View File
@@ -0,0 +1,219 @@
// Package ocapi is a small HTTP client for the OpenChamber server API
// (which proxies OpenCode v2 under /api/*). It has no UI dependencies, so
// it can be tested with httptest and reused by the CLI probe.
package ocapi
import "encoding/json"
// Health is GET /health.
type Health struct {
Status string `json:"status"`
Timestamp string `json:"timestamp"`
OpenChamberVersion string `json:"openchamberVersion"`
Runtime string `json:"runtime"`
ServerID string `json:"serverId"`
IsOpenCodeReady bool `json:"isOpenCodeReady"`
OpenCodePort int `json:"openCodePort"`
Compatibility struct {
APIVersion int `json:"apiVersion"`
MinClientAPIVersion int `json:"minClientApiVersion"`
Capabilities []string `json:"capabilities"`
} `json:"compatibility"`
}
// AuthStatus is GET /auth/session.
type AuthStatus struct {
Authenticated bool `json:"authenticated"`
Disabled bool `json:"disabled"`
Locked bool `json:"locked"`
Scope string `json:"scope"`
ClientAuthRequired bool `json:"clientAuthRequired"`
}
// LoginRequest is POST /auth/session. Password is the only secret; the rest
// names this device so repeated logins collapse into one server-side record.
type LoginRequest struct {
Password string `json:"password"`
TrustDevice bool `json:"trustDevice"`
IssueClientToken bool `json:"issueClientToken"`
ClientLabel string `json:"clientLabel,omitempty"`
ClientKind string `json:"clientKind,omitempty"`
DeviceName string `json:"deviceName,omitempty"`
DevicePlatform string `json:"devicePlatform,omitempty"`
DeviceModel string `json:"deviceModel,omitempty"`
AppVersion string `json:"appVersion,omitempty"`
DedupeKey string `json:"dedupeKey,omitempty"`
}
// LoginResult is the answer to POST /auth/session.
type LoginResult struct {
Authenticated bool `json:"authenticated"`
ClientToken string `json:"clientToken"`
Client json.RawMessage `json:"client"`
}
// ModelRef identifies a model as OpenCode names it.
type ModelRef struct {
ID string `json:"id"`
ProviderID string `json:"providerID"`
Variant string `json:"variant,omitempty"`
}
// TokenUsage is a session's or message's token counters.
type TokenUsage struct {
Input int64 `json:"input"`
Output int64 `json:"output"`
Reasoning int64 `json:"reasoning"`
Cache struct {
Read int64 `json:"read"`
Write int64 `json:"write"`
} `json:"cache"`
}
// Location is where a session lives.
type Location struct {
Directory string `json:"directory"`
ProjectID string `json:"projectID"`
Subpath string `json:"subpath,omitempty"`
}
// SessionTime carries the millisecond timestamps OpenCode reports.
type SessionTime struct {
Created int64 `json:"created"`
Updated int64 `json:"updated"`
Busy int64 `json:"busy,omitempty"`
Idle int64 `json:"idle,omitempty"`
Viewed int64 `json:"viewed,omitempty"`
Archived int64 `json:"archived,omitempty"`
}
// Session is one entry of GET /api/session.
type Session struct {
ID string `json:"id"`
ParentID string `json:"parentID,omitempty"`
ProjectID string `json:"projectID"`
Title string `json:"title"`
Agent string `json:"agent,omitempty"`
Model *ModelRef `json:"model,omitempty"`
Cost float64 `json:"cost"`
Tokens *TokenUsage `json:"tokens,omitempty"`
Time SessionTime `json:"time"`
Location *Location `json:"location,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
// PageCursor is the opaque pagination cursor of session and message lists.
type PageCursor struct {
Next string `json:"next,omitempty"`
Previous string `json:"previous,omitempty"`
}
// SessionPage is GET /api/session.
type SessionPage struct {
Data []Session `json:"data"`
Cursor PageCursor `json:"cursor"`
}
// Message is one entry of GET /api/session/{id}/message. The server's union
// is wide; fields the client does not need stay zero.
type Message struct {
ID string `json:"id"`
Type string `json:"type"`
Time MessageTime `json:"time"`
Agent string `json:"agent,omitempty"`
Model *ModelRef `json:"model,omitempty"`
Content []ContentPart `json:"content,omitempty"`
Text string `json:"text,omitempty"`
Files []FileAttachment `json:"files,omitempty"`
Finish string `json:"finish,omitempty"`
Cost float64 `json:"cost,omitempty"`
Tokens *TokenUsage `json:"tokens,omitempty"`
Error json.RawMessage `json:"error,omitempty"`
// Shell messages
Command string `json:"command,omitempty"`
Status string `json:"status,omitempty"`
Exit *int `json:"exit,omitempty"`
Output string `json:"output,omitempty"`
}
// MessageTime carries the millisecond timestamps of a message.
type MessageTime struct {
Created int64 `json:"created"`
Streamed int64 `json:"streamed,omitempty"`
Completed int64 `json:"completed,omitempty"`
}
// ContentPart is a block of an assistant message.
type ContentPart struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
State *ToolState `json:"state,omitempty"`
Time *PartTime `json:"time,omitempty"`
}
// PartTime is when a reasoning/text block was written.
type PartTime struct {
Created int64 `json:"created,omitempty"`
Completed int64 `json:"completed,omitempty"`
}
// ToolState is a tool call's state machine.
type ToolState struct {
Status string `json:"status"`
Input map[string]any `json:"input,omitempty"`
Content []ContentPart `json:"content,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
Error json.RawMessage `json:"error,omitempty"`
}
// FileAttachment is a file attached to a user prompt.
type FileAttachment struct {
URI string `json:"uri"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
MIME string `json:"mime,omitempty"`
}
// MessagePage is GET /api/session/{id}/message.
type MessagePage struct {
Data []Message `json:"data"`
Cursor PageCursor `json:"cursor"`
}
// Event is one server-sent event of GET /api/event.
type Event struct {
ID string `json:"id"`
Created int64 `json:"created"`
Type string `json:"type"`
Location *Location `json:"location,omitempty"`
Durable *EventDurable `json:"durable,omitempty"`
Data json.RawMessage `json:"data"`
}
// EventDurable is the durable envelope some events carry.
type EventDurable struct {
AggregateID string `json:"aggregateID"`
Seq int64 `json:"seq"`
Version int `json:"version"`
}
// SessionEventData covers the payload fields this client reads. Use
// Event.UnmarshalData into a wider struct when more is needed.
type SessionEventData struct {
SessionID string `json:"sessionID"`
AssistantMessageID string `json:"assistantMessageID"`
Ordinal int `json:"ordinal"`
Delta string `json:"delta"`
Text string `json:"text"`
MessageID string `json:"messageID"`
PartID string `json:"partID"`
Agent string `json:"agent"`
Model *ModelRef `json:"model"`
RequestID string `json:"requestID"`
Reply string `json:"reply"`
Action string `json:"action"`
Resources []string `json:"resources"`
}