client

package
v1.9.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 7, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

README

client/ — Go HTTP client for the Warden API

A ready-made Go client for interacting with a running warden server over HTTP.

Who is this for?

Go developers who want to control Warden from their own application without embedding the engine. You run the warden binary as a headless server and use this package to talk to it.

If you want to embed the engine directly (no separate server process), use warden.New() from the root package instead.

Usage

import "github.com/thesimonho/warden/client"

c := client.New("http://localhost:8090")

// List all projects
projects, err := c.ListProjects(ctx)

// Create a worktree
resp, err := c.CreateWorktree(ctx, projectID, "feature-branch")

// Stop a project
err = c.StopProject(ctx, projectID)

Error handling

Non-2xx responses are returned as *client.APIError, which includes the HTTP status code and the error message from the server:

_, err := c.CreateContainer(ctx, req)
if err != nil {
    var apiErr *client.APIError
    if errors.As(err, &apiErr) {
        fmt.Printf("API error %d: %s\n", apiErr.StatusCode, apiErr.Message)
    }
}

Relationship to web/src/lib/api.ts

This package is the Go equivalent of the TypeScript API client used by the web dashboard. Both make the same HTTP calls to the same endpoints. If you're building a web frontend, look at api.ts instead. If you're building a Go frontend or CLI, use this package.

Documentation

Overview

Package client provides a Go HTTP client for the Warden API.

Use New to create a client pointing at a running warden server:

c := client.New("http://localhost:8090")
projects, err := c.ListProjects(ctx)

This package is the Go equivalent of web/src/lib/api.ts. If you're building a Go application that consumes Warden over HTTP (rather than embedding the engine via warden.New()), this is the package to use.

Key types

Methods return types from the engine and [service] packages:

  • engine.Project: ID, Name, State ("running"/"exited"), NeedsInput, NotificationType, ActiveWorktreeCount, TotalCost, NetworkMode
  • engine.Worktree: ID, State ("connected"/"shell"/"background"/"stopped"), Branch, ExitCode, NotificationType
  • api.ContainerResult: ContainerID, Name (output of create/update)
  • api.SettingsResponse: Runtime, AuditLogMode

Error handling

All non-2xx responses are returned as *APIError with a machine-readable Code field. Use errors.As to inspect:

var apiErr *client.APIError
if errors.As(err, &apiErr) {
    switch apiErr.Code {
    case "NAME_TAKEN":
        // handle name collision
    case "NOT_FOUND":
        // handle missing resource
    }
}

HTTP configuration

The client uses a 30-second timeout for standard requests. SSE connections ([SubscribeEvents]) use no timeout. All POST/PUT requests send Content-Type: application/json.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	// StatusCode is the HTTP status code (400, 404, 409, 500, 503).
	StatusCode int
	// Code is a machine-readable error identifier (e.g. "NOT_FOUND").
	// May be empty for non-JSON responses.
	Code string
	// Message is a human-readable error description.
	Message string
}

APIError represents a non-2xx response from the Warden API. Use errors.As to extract it from returned errors. Match on the Code field for programmatic handling instead of parsing Message.

Common error codes:

  • "NOT_FOUND": resource (project, worktree, container) does not exist
  • "NAME_TAKEN": container or project name is already in use
  • "INVALID_BODY": malformed request body
  • "NOT_CONFIGURED": Docker runtime not available
  • "INTERNAL": unexpected server error

Code may be empty for non-JSON error responses. See the integration guide for the full list of error codes.

func (*APIError) Error

func (e *APIError) Error() string

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client talks to a running Warden server over HTTP.

func New

func New(baseURL string) *Client

New creates a Client pointing at the given Warden server URL (e.g. "http://localhost:8090").

func (*Client) AddProject

func (c *Client) AddProject(ctx context.Context, req api.AddProjectRequest) (*api.AddProjectResponse, error)

AddProject registers a project directory in Warden. When the request includes Container config, the container is created atomically.

func (*Client) AttachTerminal

func (c *Client) AttachTerminal(ctx context.Context, projectID, agentType, worktreeID string) (TerminalConnection, error)

AttachTerminal opens a WebSocket connection to a worktree's terminal and returns a TerminalConnection for bidirectional PTY I/O.

Prerequisites: [ConnectTerminal] must be called first to ensure the terminal process (tmux session) is running. AttachTerminal creates a viewer into the existing session.

The terminal lifecycle:

  1. [ConnectTerminal] — start the tmux session (idempotent)
  2. AttachTerminal — open a viewer connection
  3. Read/Write on the TerminalConnection — PTY I/O
  4. Close the connection (or the user presses the disconnect key)
  5. [DisconnectTerminal] — notify the server the viewer closed

The tmux session survives viewer disconnects. Call [KillWorktreeProcess] to fully terminate the session.

func (*Client) BaseURL added in v1.9.0

func (c *Client) BaseURL() string

BaseURL returns the HTTP base URL of the Warden server.

func (*Client) BatchProjectOperation added in v1.8.0

func (c *Client) BatchProjectOperation(ctx context.Context, req api.BatchProjectRequest) (*api.BatchProjectResponse, error)

BatchProjectOperation performs an action on multiple projects.

func (*Client) CleanupWorktrees

func (c *Client) CleanupWorktrees(ctx context.Context, projectID, agentType string) ([]string, error)

CleanupWorktrees removes orphaned worktree directories.

func (*Client) ConnectTerminal

func (c *Client) ConnectTerminal(ctx context.Context, projectID, agentType, worktreeID string) (*api.WorktreeResult, error)

ConnectTerminal starts or reconnects the terminal process (tmux session) for a worktree. Must be called before [AttachTerminal] to ensure the process exists. The terminal process continues running in the background even if no viewer is attached, allowing Claude Code to work independently.

If the terminal is already running, this is a no-op that returns success.

func (*Client) CreateAccessItem added in v0.4.0

func (c *Client) CreateAccessItem(ctx context.Context, req api.CreateAccessItemRequest) (*access.Item, error)

CreateAccessItem creates a user-defined access item. API: POST /api/v1/access

func (*Client) CreateContainer

func (c *Client) CreateContainer(ctx context.Context, projectID, agentType string, req api.CreateContainerRequest) (*api.ContainerResult, error)

CreateContainer creates a new container for the given project.

func (*Client) CreateWorktree

func (c *Client) CreateWorktree(ctx context.Context, projectID, agentType string, req api.CreateWorktreeRequest) (*api.WorktreeResult, error)

CreateWorktree creates a new git worktree and connects a terminal.

func (*Client) DeleteAccessItem added in v0.4.0

func (c *Client) DeleteAccessItem(ctx context.Context, id string) error

DeleteAccessItem removes a user-defined access item. API: DELETE /api/v1/access/{id}

func (*Client) DeleteAuditEvents

func (c *Client) DeleteAuditEvents(ctx context.Context, filters api.AuditFilters) error

DeleteAuditEvents removes events matching the given filters.

func (*Client) DeleteContainer

func (c *Client) DeleteContainer(ctx context.Context, projectID, agentType string) (*api.ContainerResult, error)

DeleteContainer stops and removes the container for the given project.

func (*Client) DisconnectTerminal

func (c *Client) DisconnectTerminal(ctx context.Context, projectID, agentType, worktreeID string) (*api.WorktreeResult, error)

DisconnectTerminal closes the terminal viewer for a worktree.

func (*Client) GetAccessItem added in v0.4.0

func (c *Client) GetAccessItem(ctx context.Context, id string) (*api.AccessItemResponse, error)

GetAccessItem returns a single access item by ID. API: GET /api/v1/access/{id}

func (*Client) GetAuditLog

func (c *Client) GetAuditLog(ctx context.Context, filters api.AuditFilters) ([]api.AuditEntry, error)

GetAuditLog returns filtered audit events.

func (*Client) GetAuditProjects

func (c *Client) GetAuditProjects(ctx context.Context) ([]string, error)

GetAuditProjects returns distinct project (container) names from the audit log.

func (*Client) GetAuditSummary

func (c *Client) GetAuditSummary(ctx context.Context, filters api.AuditFilters) (*api.AuditSummary, error)

GetAuditSummary returns aggregate audit statistics.

func (*Client) GetBudgetStatus added in v1.8.0

func (c *Client) GetBudgetStatus(ctx context.Context, projectID, agentType string) (*api.BudgetStatusResponse, error)

GetBudgetStatus returns the budget state for a project.

func (*Client) GetDefaults

func (c *Client) GetDefaults(ctx context.Context, projectPath string) (*api.DefaultsResponse, error)

GetDefaults returns server-resolved defaults for the create container form. When projectPath is non-empty, runtime detection scans that directory.

func (*Client) GetProject added in v1.8.0

func (c *Client) GetProject(ctx context.Context, projectID, agentType string) (*api.ProjectResponse, error)

GetProject returns a single project enriched with container state, cost, and attention data.

func (*Client) GetProjectCosts added in v1.8.0

func (c *Client) GetProjectCosts(ctx context.Context, projectID, agentType string) (*api.ProjectCostsResponse, error)

GetProjectCosts returns session-level cost data for a project.

func (*Client) GetSettings

func (c *Client) GetSettings(ctx context.Context) (*api.SettingsResponse, error)

GetSettings returns the server-side settings.

func (*Client) GetWorktree added in v1.8.0

func (c *Client) GetWorktree(ctx context.Context, projectID, agentType, worktreeID string) (*engine.Worktree, error)

GetWorktree returns a single worktree by ID with terminal state.

func (*Client) GetWorktreeDiff

func (c *Client) GetWorktreeDiff(ctx context.Context, projectID, agentType, worktreeID string) (*api.DiffResponse, error)

GetWorktreeDiff returns uncommitted changes for a worktree.

func (*Client) InspectContainer

func (c *Client) InspectContainer(ctx context.Context, projectID, agentType string) (*api.ContainerConfig, error)

InspectContainer returns the configuration of the project's container.

func (*Client) KillWorktreeProcess

func (c *Client) KillWorktreeProcess(ctx context.Context, projectID, agentType, worktreeID string) (*api.WorktreeResult, error)

KillWorktreeProcess kills the terminal process for a worktree.

func (*Client) ListAccessItems added in v0.4.0

func (c *Client) ListAccessItems(ctx context.Context) (*api.AccessItemListResponse, error)

ListAccessItems returns all access items (built-in + user-created) with host detection status. API: GET /api/v1/access

func (*Client) ListDirectories

func (c *Client) ListDirectories(ctx context.Context, path string, includeFiles bool) ([]api.DirEntry, error)

ListDirectories returns filesystem entries at a path for the browser. When includeFiles is true, files are returned alongside directories.

func (*Client) ListProjects

func (c *Client) ListProjects(ctx context.Context) ([]api.ProjectResponse, error)

ListProjects returns all configured projects with container state, cost, and attention data. Each api.ProjectResponse includes State ("running", "exited", "not-found"), NeedsInput (true when Claude needs attention), NotificationType ("permission_prompt", "idle_prompt", "elicitation_dialog"), ActiveWorktreeCount, TotalCost (USD), and NetworkMode.

func (*Client) ListRuntimes

func (c *Client) ListRuntimes(ctx context.Context) (*docker.Info, error)

ListRuntimes returns available container runtimes.

func (*Client) ListWorktrees

func (c *Client) ListWorktrees(ctx context.Context, projectID, agentType string) ([]engine.Worktree, error)

ListWorktrees returns all worktrees for the given container.

func (*Client) PostAuditEvent

func (c *Client) PostAuditEvent(ctx context.Context, req api.PostAuditEventRequest) error

PostAuditEvent writes a frontend event to the audit log.

func (*Client) PurgeProjectAudit

func (c *Client) PurgeProjectAudit(ctx context.Context, projectID, agentType string) error

PurgeProjectAudit removes all audit events for a project.

func (*Client) ReadProjectTemplate added in v1.5.0

func (c *Client) ReadProjectTemplate(ctx context.Context, filePath string) (*api.ProjectTemplate, error)

ReadProjectTemplate reads a .warden.json project template from an arbitrary file path. Used by the import feature.

func (*Client) RemoveProject

func (c *Client) RemoveProject(ctx context.Context, projectID, agentType string) (*api.ProjectResult, error)

RemoveProject removes a project from the database by project ID.

func (*Client) RemoveWorktree

func (c *Client) RemoveWorktree(ctx context.Context, projectID, agentType, worktreeID string) (*api.WorktreeResult, error)

RemoveWorktree fully removes a worktree.

func (*Client) ResetAccessItem added in v0.4.0

func (c *Client) ResetAccessItem(ctx context.Context, id string) (*access.Item, error)

ResetAccessItem restores a built-in access item to its default. API: POST /api/v1/access/{id}/reset

func (*Client) ResetProjectCosts

func (c *Client) ResetProjectCosts(ctx context.Context, projectID, agentType string) error

ResetProjectCosts removes all cost history for a project.

func (*Client) ResetWorktree added in v1.5.0

func (c *Client) ResetWorktree(ctx context.Context, projectID, agentType, worktreeID string) (*api.WorktreeResult, error)

ResetWorktree clears all history for a worktree without removing it.

func (*Client) ResolveAccessItems added in v0.4.0

ResolveAccessItems resolves the given access items for preview/testing. API: POST /api/v1/access/resolve

func (*Client) RestartProject

func (c *Client) RestartProject(ctx context.Context, id, agentType string) (*api.ProjectResult, error)

RestartProject restarts the container with the given ID.

func (*Client) SendWorktreeInput added in v1.8.0

func (c *Client) SendWorktreeInput(ctx context.Context, projectID, agentType, worktreeID string, req api.WorktreeInputRequest) error

SendWorktreeInput sends text to a worktree's tmux pane.

func (*Client) Shutdown added in v1.7.0

func (c *Client) Shutdown(ctx context.Context) error

Shutdown requests a graceful server shutdown. The server sends back a response before initiating the shutdown sequence.

func (*Client) StopProject

func (c *Client) StopProject(ctx context.Context, id, agentType string) (*api.ProjectResult, error)

StopProject stops the container with the given ID.

func (*Client) SubscribeEvents

func (c *Client) SubscribeEvents(ctx context.Context, opts ...SubscribeEventsOptions) (<-chan eventbus.SSEEvent, func(), error)

func (*Client) UpdateAccessItem added in v0.4.0

func (c *Client) UpdateAccessItem(ctx context.Context, id string, req api.UpdateAccessItemRequest) (*access.Item, error)

UpdateAccessItem updates a user-defined access item. API: PUT /api/v1/access/{id}

func (*Client) UpdateContainer

func (c *Client) UpdateContainer(ctx context.Context, projectID, agentType string, req api.CreateContainerRequest) (*api.ContainerResult, error)

UpdateContainer recreates the project's container with updated configuration.

func (*Client) UpdateSettings

func (c *Client) UpdateSettings(ctx context.Context, req api.UpdateSettingsRequest) (*api.UpdateSettingsResult, error)

UpdateSettings updates server-side settings.

func (*Client) UploadClipboard added in v0.5.0

func (c *Client) UploadClipboard(ctx context.Context, projectID, agentType string, content []byte, mimeType string) (*api.ClipboardUploadResponse, error)

UploadClipboard stages an image file in the container's clipboard directory for the xclip shim. Returns the path where the file was written.

func (*Client) ValidateContainer

func (c *Client) ValidateContainer(ctx context.Context, projectID, agentType string) (*api.ValidateContainerResult, error)

ValidateContainer checks whether the project's container has Warden infrastructure.

func (*Client) ValidateProjectTemplate added in v1.7.0

func (c *Client) ValidateProjectTemplate(ctx context.Context, data []byte) (*api.ProjectTemplate, error)

ValidateProjectTemplate sends a raw .warden.json body to the server for validation and sanitization. Returns the cleaned template.

type SubscribeEventsOptions added in v1.8.0

type SubscribeEventsOptions struct {
	// ProjectID filters events to a single project. Empty means all projects.
	ProjectID string
	// AgentType filters events to a single agent type. Empty means all agents.
	AgentType string
}

SubscribeEvents opens a Server-Sent Events connection and returns a channel of parsed events. The channel closes when the context is cancelled or the connection drops. Call the returned function to unsubscribe and clean up the connection.

Event types sent on the channel:

  • "worktree_state": worktree attention/session state changed (Data contains containerName, worktreeId, state fields)
  • "project_state": project cost updated (Data contains containerName, totalCost)
  • "worktree_list_changed": worktrees were created/removed (Data contains containerName)
  • "heartbeat": periodic keepalive (Data is empty object)

Each event's Data field is a json.RawMessage — unmarshal it based on the Event type.

Example:

ch, unsub, err := c.SubscribeEvents(ctx)
if err != nil { return err }
defer unsub()

for event := range ch {
    switch event.Event {
    case eventbus.SSEWorktreeState:
        // A worktree's state changed — refresh worktree list
    case eventbus.SSEProjectState:
        // Cost updated — refresh project list
    }
}

SubscribeEventsOptions controls SSE event filtering.

type TerminalConnection

type TerminalConnection interface {
	io.ReadWriteCloser

	// Resize changes the terminal dimensions of the remote PTY.
	Resize(cols, rows uint) error
}

TerminalConnection provides raw bidirectional I/O to a container terminal. Read returns PTY output, Write sends keyboard input, and Resize updates the remote terminal dimensions.

In HTTP mode, this wraps a WebSocket connection (binary frames for I/O, text frames for resize commands). In embedded mode, this wraps a docker exec session attached to the tmux session.

Example:

conn, err := c.AttachTerminal(ctx, projectID, agentType, worktreeID)
if err != nil { return err }
defer conn.Close()

conn.Resize(80, 24) // set initial terminal size
conn.Write([]byte("ls\n"))

buf := make([]byte, 4096)
n, _ := conn.Read(buf)
fmt.Print(string(buf[:n]))

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL