Skip to content

client

View on pkg.go.dev

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

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.

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

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

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.

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.

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
}

func (e *APIError) Error() string

Client talks to a running Warden server over HTTP.

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

func New(baseURL string) *Client

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

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 (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 (c *Client) BaseURL() string

BaseURL returns the HTTP base URL of the Warden server.

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

BatchProjectOperation performs an action on multiple projects.

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

CleanupWorktrees removes orphaned worktree directories.

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 (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 (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 (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 (c *Client) DeleteAccessItem(ctx context.Context, id string) error

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

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

DeleteAuditEvents removes events matching the given filters.

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

DeleteContainer stops and removes the container for the given project.

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

DisconnectTerminal closes the terminal viewer for a worktree.

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 (c *Client) GetAuditLog(ctx context.Context, filters api.AuditFilters) ([]api.AuditEntry, error)

GetAuditLog returns filtered audit events.

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

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

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

GetAuditSummary returns aggregate audit statistics.

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

GetBudgetStatus returns the budget state for a project.

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 (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 (c *Client) GetProjectCosts(ctx context.Context, projectID, agentType string) (*api.ProjectCostsResponse, error)

GetProjectCosts returns session-level cost data for a project.

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

GetSettings returns the server-side settings.

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 (c *Client) GetWorktreeDiff(ctx context.Context, projectID, agentType, worktreeID string) (*api.DiffResponse, error)

GetWorktreeDiff returns uncommitted changes for a worktree.

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

InspectContainer returns the configuration of the project’s container.

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

KillWorktreeProcess kills the terminal process for a worktree.

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 (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 (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 (c *Client) ListRuntimes(ctx context.Context) (*docker.Info, error)

ListRuntimes returns available container runtimes.

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

ListWorktrees returns all worktrees for the given container.

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

PostAuditEvent writes a frontend event to the audit log.

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

PurgeProjectAudit removes all audit events for a project.

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 (c *Client) RemoveProject(ctx context.Context, projectID, agentType string) (*api.ProjectResult, error)

RemoveProject removes a project from the database by project ID.

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

RemoveWorktree fully removes a worktree.

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 (c *Client) ResetProjectCosts(ctx context.Context, projectID, agentType string) error

ResetProjectCosts removes all cost history for a project.

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 (c *Client) ResolveAccessItems(ctx context.Context, req api.ResolveAccessItemsRequest) (*api.ResolveAccessItemsResponse, error)

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

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

RestartProject restarts the container with the given ID.

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 (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 (c *Client) StopProject(ctx context.Context, id, agentType string) (*api.ProjectResult, error)

StopProject stops the container with the given ID.

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

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 (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 (c *Client) UpdateSettings(ctx context.Context, req api.UpdateSettingsRequest) (*api.UpdateSettingsResult, error)

UpdateSettings updates server-side settings.

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 (c *Client) ValidateContainer(ctx context.Context, projectID, agentType string) (*api.ValidateContainerResult, error)

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

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.

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 event.SSEWorktreeState:
// A worktree's state changed — refresh worktree list
case event.SSEProjectState:
// Cost updated — refresh project list
}
}

SubscribeEventsOptions controls SSE event filtering.

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
}

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]))
type TerminalConnection interface {
io.ReadWriteCloser
// Resize changes the terminal dimensions of the remote PTY.
Resize(cols, rows uint) error
}

Generated by gomarkdoc