client

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package client is a thin HTTP client for the ProteOS control-plane API. It authenticates with a personal access token (Authorization: Bearer), decodes the server's {error,detail} envelope into a typed error, and maps HTTP status to the CLI's documented exit codes.

Index

Constants

View Source
const (
	ExitOK       = 0
	ExitError    = 1 // generic/runtime failure
	ExitUsage    = 2 // bad invocation
	ExitAuth     = 3 // 401/403
	ExitNotFound = 4 // 404
	ExitTaskFail = 5 // a task ended failed/canceled
)

Exit codes the CLI returns. Commands translate an *APIError via ExitCode(); other failures use ExitError / ExitUsage directly.

View Source
const (
	DefaultMaxAttempts    = 3
	DefaultRetryBaseDelay = 200 * time.Millisecond
	DefaultRetryMaxDelay  = 2 * time.Second
)

Retry defaults for Do: three attempts (one original + two retries), starting at 200ms and doubling up to 2s. Deliberately gentler than the SSE stream's backoff (sse.go) since a foreground CLI command has a human waiting on it.

Variables

This section is empty.

Functions

func ExitCodeFor

func ExitCodeFor(err error) int

ExitCodeFor returns the appropriate process exit code for err: an *APIError's mapped code, ExitOK for nil, else ExitError.

func SetUserAgent

func SetUserAgent(ua string)

SetUserAgent overrides the User-Agent (called from main with the build version).

Types

type APIError

type APIError struct {
	Status int
	Code   string
	Detail string
}

APIError is a non-2xx response decoded from the {error,detail} envelope.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) ExitCode

func (e *APIError) ExitCode() int

ExitCode maps the HTTP status to a CLI exit code.

type Client

type Client struct {
	BaseURL string
	Token   string
	HTTP    *http.Client

	// MaxAttempts bounds how many times Do tries a request, including the first
	// (so 1 disables retries). Zero means DefaultMaxAttempts.
	MaxAttempts int
	// RetryBaseDelay / RetryMaxDelay bound the exponential backoff between
	// retries. Zero means the Default* constants.
	RetryBaseDelay time.Duration
	RetryMaxDelay  time.Duration
}

Client talks to one control-plane base URL with one bearer token.

func New

func New(baseURL, token string) *Client

New returns a client for baseURL authenticating with token. baseURL may carry a trailing slash; it is trimmed.

func (*Client) CancelTask

func (c *Client) CancelTask(ctx context.Context, machineID, taskID string) (string, error)

CancelTask requests cancellation of a running task (idempotent server-side).

func (*Client) Clone

func (c *Client) Clone(ctx context.Context, machineID, ref string) (string, error)

Clone dispatches an asynchronous clone into a machine's workspace. ref is either owner/repo (cloned from the server's GitHub host) or a full https://host/owner/repo URL targeting one of the server's allowlisted public hosts — anything containing "://" is sent as a URL. It returns an op id immediately; the clone completes in the background (observe by polling ListProjects until the repo appears).

func (*Client) CommentPR

func (c *Client) CommentPR(ctx context.Context, owner, repo string, number int, body string) (PRComment, error)

CommentPR posts a plain comment on a pull request.

func (*Client) CreateMachine

func (c *Client) CreateMachine(ctx context.Context, req CreateMachineRequest) (Machine, error)

CreateMachine provisions a new machine and returns its summary. The server replies 202: the machine boots asynchronously, so State is typically still a provisioning state on return.

func (*Client) CreateTask

func (c *Client) CreateTask(ctx context.Context, machineID string, req CreateTaskRequest) (string, error)

CreateTask dispatches a headless agent run and returns its task id.

func (*Client) DeleteGitHostToken

func (c *Client) DeleteGitHostToken(ctx context.Context, host string) error

DeleteGitHostToken removes the stored PAT for host. Idempotent.

func (*Client) DeleteProviderKey

func (c *Client) DeleteProviderKey(ctx context.Context, key string) error

DeleteProviderKey removes the caller's stored secret for the provider identified by key.

func (*Client) DialSSH

func (c *Client) DialSSH(ctx context.Context, machineID string) (io.ReadWriteCloser, error)

DialSSH opens the control plane's inbound-SSH gateway (GET /gw/ssh) for machineID and returns it as a plain byte stream: every Write becomes one binary WebSocket message, every Read drains the next one (via websocket.NetConn — see its doc for the exact framing contract). The caller bridges this to a local SSH client's transport (stdio, when used as an `ssh -o ProxyCommand` helper) or to os.Stdin/Stdout directly.

Authentication rides the same bearer token every other Client call uses; unlike a browser session this carries no Origin header at all, which the gateway's /gw/ssh handler treats as the CLI shape (not a rejection — see controlplane/internal/httpapi/gateway_ssh.go).

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, path string, body, out any) error

Do issues an authenticated JSON request. A non-nil body is JSON-encoded; a non-nil out is JSON-decoded from a 2xx response. Non-2xx yields an *APIError.

Transient failures are retried with exponential backoff (see MaxAttempts / RetryBaseDelay / RetryMaxDelay), but only for GET: a dropped connection can happen after the server already received and processed a POST/PUT/DELETE, so re-sending one risks a duplicate effect (there is no idempotency-key machinery here to make that safe). GET has no such risk either way — a lost response or a 429/5xx just means try the read again.

func (*Client) GetMachine

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

GetMachine returns one machine by id.

func (*Client) GetPR

func (c *Client) GetPR(ctx context.Context, owner, repo string, number int) (PRDetail, error)

GetPR returns one pull request's summary.

func (*Client) GetTask

func (c *Client) GetTask(ctx context.Context, machineID, taskID string) (Task, error)

GetTask returns one task's status + result.

func (*Client) GitBranch

func (c *Client) GitBranch(ctx context.Context, machineID string, req GitBranchRequest) (string, error)

GitBranch creates (and optionally checks out) a branch in a project, returning the current branch after the operation.

func (*Client) GitCommit

func (c *Client) GitCommit(ctx context.Context, machineID string, req GitCommitRequest) (GitCommit, error)

GitCommit stages and commits a project's changes (the explicit review gate; the agent never commits on its own).

func (*Client) GitDiffOf

func (c *Client) GitDiffOf(ctx context.Context, machineID, project string, staged bool) (GitDiff, error)

GitDiffOf returns a project's unified diff. staged selects the index diff over the worktree diff.

func (*Client) GitPR

func (c *Client) GitPR(ctx context.Context, machineID string, req GitPRRequest) (GitPR, error)

GitPR opens a pull request from Head into Base.

func (*Client) GitPush

func (c *Client) GitPush(ctx context.Context, machineID string, req GitPushRequest) (string, error)

GitPush dispatches an asynchronous push of a branch to origin, returning the op id that correlates the later completion event.

func (*Client) GitStatusOf

func (c *Client) GitStatusOf(ctx context.Context, machineID, project string) (GitStatus, error)

GitStatusOf returns a project's working-tree change set.

func (*Client) ListGitHosts

func (c *Client) ListGitHosts(ctx context.Context) ([]GitHost, error)

ListGitHosts returns the allowlisted hosts with this user's link state.

func (*Client) ListMachines

func (c *Client) ListMachines(ctx context.Context) ([]Machine, error)

ListMachines returns the caller's machines (GET /api/machines returns a bare array).

func (*Client) ListPRChecks

func (c *Client) ListPRChecks(ctx context.Context, owner, repo string, number int) (PRChecks, error)

ListPRChecks returns a pull request's check-run summary.

func (*Client) ListPRFiles

func (c *Client) ListPRFiles(ctx context.Context, owner, repo string, number int) (PRFiles, error)

ListPRFiles returns a pull request's changed files.

func (*Client) ListProjects

func (c *Client) ListProjects(ctx context.Context, machineID string) ([]Project, error)

ListProjects returns the repositories cloned in a running machine's workspace. The machine must be running (the list is fetched live over the control channel).

func (*Client) ListProviders

func (c *Client) ListProviders(ctx context.Context) ([]Provider, error)

ListProviders returns the provider catalog plus the caller's key_set status per provider.

func (*Client) ListRepos

func (c *Client) ListRepos(ctx context.Context) (ReposResult, error)

ListRepos returns the repositories the user can clone, plus the grants URL.

func (*Client) ListTasks

func (c *Client) ListTasks(ctx context.Context, machineID string) ([]Task, error)

ListTasks returns a machine's tasks, newest first.

func (*Client) ListTemplates

func (c *Client) ListTemplates(ctx context.Context) ([]Template, error)

ListTemplates returns the machine-template catalog. A legacy single-image deployment returns an empty array.

func (*Client) Me

func (c *Client) Me(ctx context.Context) (Me, error)

Me returns the authenticated user and their machines. A 401 here is how the CLI verifies a token at `auth login`.

func (*Client) MergePR

func (c *Client) MergePR(ctx context.Context, owner, repo string, number int, method string) (PRMerge, error)

MergePR merges a pull request using method (merge, squash, or rebase; empty defaults to merge).

func (*Client) NewRequest

func (c *Client) NewRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error)

NewRequest builds an authenticated request with the standard headers. Exposed so the SSE consumer can build a streaming GET.

func (*Client) SendMessage

func (c *Client) SendMessage(ctx context.Context, machineID, taskID, prompt string) (string, error)

SendMessage runs a follow-up turn on a finished task (resume).

func (*Client) SetGitHostToken

func (c *Client) SetGitHostToken(ctx context.Context, host, token string) (GitHost, error)

SetGitHostToken validates and stores a PAT for host, returning the linked view (with the login the host reported). 400 bad_token when the host rejects it; 404 unknown_host when the host is not allowlisted.

func (*Client) SetProviderKey

func (c *Client) SetProviderKey(ctx context.Context, key string, fields map[string]string) error

SetProviderKey stores (or replaces) the caller's secret fields for the provider identified by key. Values are write-only — the server responds 204 and never echoes them back.

func (*Client) StartMachine

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

StartMachine resumes a stopped machine and returns the updated summary.

func (*Client) StopMachine

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

StopMachine stops (hibernates) a running machine and returns the updated summary.

func (*Client) StreamEvents

func (c *Client) StreamEvents(ctx context.Context, machineID, taskID, startID string, h EventHandler) error

StreamEvents streams a task's events, reconnecting with Last-Event-ID on transient drops, until the terminal `result` event arrives, the handler returns an error, or ctx is done. startID is the initial Last-Event-ID ("" to begin from the server's snapshot).

type CreateMachineRequest

type CreateMachineRequest struct {
	Name       string `json:"name,omitempty"`
	TemplateID string `json:"template_id,omitempty"`
	Vcpus      *int   `json:"vcpus,omitempty"`
	MemMiB     *int   `json:"mem_mib,omitempty"`
	DiskMiB    *int   `json:"disk_mib,omitempty"`
}

CreateMachineRequest is the POST /api/machines body. A zero-value resource pointer (nil) falls back to the template's default server-side.

type CreateTaskRequest

type CreateTaskRequest struct {
	Prompt   string `json:"prompt"`
	Provider string `json:"provider"`
	Project  string `json:"project"`
}

CreateTaskRequest is the POST /api/machines/{id}/tasks body.

type Event

type Event struct {
	Kind       string          `json:"kind"`
	Text       string          `json:"text,omitempty"`
	Tool       string          `json:"tool,omitempty"`
	ToolID     string          `json:"tool_id,omitempty"`
	Input      json.RawMessage `json:"input,omitempty"`
	Output     string          `json:"output,omitempty"`
	IsError    bool            `json:"is_error,omitempty"`
	Status     string          `json:"status,omitempty"`
	CostUSD    float64         `json:"cost_usd,omitempty"`
	NumTurns   int             `json:"num_turns,omitempty"`
	DurationMS int64           `json:"duration_ms,omitempty"`
	Error      string          `json:"error,omitempty"`
}

Event is one normalized agent-task event from the task SSE stream. Different kinds populate different fields:

  • assistant_text: Text
  • tool_use: Tool, ToolID, Input
  • tool_result: ToolID, Output, IsError
  • result: Status, CostUSD, NumTurns, DurationMS, Error (terminal)

type EventHandler

type EventHandler func(id string, ev Event) error

EventHandler is invoked for each event with its SSE id. Returning an error stops streaming and is propagated by StreamEvents.

type GitBranchRequest

type GitBranchRequest struct {
	Project  string `json:"project"`
	Name     string `json:"name"`
	Checkout bool   `json:"checkout"`
	From     string `json:"from,omitempty"`
}

GitBranchRequest is the POST .../git/branch body.

type GitCommit

type GitCommit struct {
	Sha     string `json:"sha"`
	Subject string `json:"subject"`
}

GitCommit is the POST .../git/commit response: the new HEAD short sha and its subject line.

type GitCommitRequest

type GitCommitRequest struct {
	Project string   `json:"project"`
	Message string   `json:"message"`
	Paths   []string `json:"paths,omitempty"`
}

GitCommitRequest is the POST .../git/commit body. Empty Paths commits all changes; otherwise the commit is limited to the given repo-relative paths.

type GitDiff

type GitDiff struct {
	Diff      string `json:"diff"`
	Truncated bool   `json:"truncated"`
}

GitDiff is the GET .../git/diff response. Truncated reports the diff exceeded the server's byte budget.

type GitFileStatus

type GitFileStatus struct {
	Path     string `json:"path"`
	Orig     string `json:"orig,omitempty"`
	Index    string `json:"index"`
	Worktree string `json:"worktree"`
}

GitFileStatus is one changed path in a git status. Index is the staged (index-vs-HEAD) code and Worktree the unstaged (worktree-vs-index) code; each is a porcelain-v1 character (M, A, D, R, ?, space). Orig is set on renames.

type GitHost

type GitHost struct {
	Host   string `json:"host"`
	Linked bool   `json:"linked"`
	Login  string `json:"login,omitempty"`
}

GitHost is one row of GET /api/git/hosts: an operator-allowlisted additional git host (Gitea/Forgejo) and whether this user has a PAT saved for it. The token itself is write-only and never returned.

type GitPR

type GitPR struct {
	PRURL  string `json:"pr_url"`
	Number int    `json:"number"`
}

GitPR is the POST .../git/pr response: the opened PR's URL and number.

type GitPRRequest

type GitPRRequest struct {
	Project string `json:"project"`
	Title   string `json:"title"`
	Body    string `json:"body,omitempty"`
	Head    string `json:"head"`
	Base    string `json:"base,omitempty"`
}

GitPRRequest is the POST .../git/pr body. Base defaults to the repo's default branch when empty.

type GitPushRequest

type GitPushRequest struct {
	Project     string `json:"project"`
	Branch      string `json:"branch"`
	SetUpstream bool   `json:"set_upstream"`
}

GitPushRequest is the POST .../git/push body.

type GitStatus

type GitStatus struct {
	Branch string          `json:"branch,omitempty"`
	Files  []GitFileStatus `json:"files"`
}

GitStatus is the GET .../git/status response: the current branch and the working-tree change set (empty on a clean tree).

type Machine

type Machine struct {
	ID         string  `json:"id"`
	Name       string  `json:"name"`
	State      string  `json:"state"`
	GuestIP    *string `json:"guest_ip"`
	TemplateID *string `json:"template_id"`
	CreatedAt  string  `json:"created_at"`
}

Machine is a subset of the control-plane MachineSummary the CLI renders.

type Me

type Me struct {
	User     User      `json:"user"`
	Machines []Machine `json:"machines"`
}

Me is the GET /api/me response.

type PRAuthor

type PRAuthor struct {
	Login     string `json:"login"`
	AvatarURL string `json:"avatar_url"`
}

PRAuthor is a pull request's author, as returned within PRDetail.

type PRCheckRun

type PRCheckRun struct {
	Name       string `json:"name"`
	Status     string `json:"status"`
	Conclusion string `json:"conclusion,omitempty"`
}

PRCheckRun is one check run on a pull request's head commit.

type PRChecks

type PRChecks struct {
	Total   int          `json:"total"`
	Passed  int          `json:"passed"`
	Failed  int          `json:"failed"`
	Pending int          `json:"pending"`
	Runs    []PRCheckRun `json:"runs"`
}

PRChecks is the GET .../pulls/{number}/checks response: the head commit's check runs plus the counts by outcome.

type PRComment

type PRComment struct {
	ID      int64  `json:"id"`
	HTMLURL string `json:"html_url"`
}

PRComment is the POST .../pulls/{number}/comments response.

type PRDetail

type PRDetail struct {
	Number       int      `json:"number"`
	State        string   `json:"state"`
	Title        string   `json:"title"`
	Body         string   `json:"body,omitempty"`
	HTMLURL      string   `json:"html_url"`
	Head         string   `json:"head"`
	Base         string   `json:"base"`
	HeadSHA      string   `json:"head_sha"`
	Author       PRAuthor `json:"author"`
	Additions    int      `json:"additions"`
	Deletions    int      `json:"deletions"`
	ChangedFiles int      `json:"changed_files"`
}

PRDetail is the GET .../pulls/{number} response: a pull request's summary. State is one of open, draft, merged, closed.

type PRFile

type PRFile struct {
	Path      string `json:"path"`
	PrevPath  string `json:"prev_path,omitempty"`
	Status    string `json:"status"`
	Additions int    `json:"additions"`
	Deletions int    `json:"deletions"`
	Patch     string `json:"patch,omitempty"`
}

PRFile is one changed file in a pull request. Status is a single letter: A added, M modified, D deleted, R renamed. PrevPath is set on renames; Patch may be empty for binary or oversized files.

type PRFiles

type PRFiles struct {
	Files []PRFile `json:"files"`
}

PRFiles is the GET .../pulls/{number}/files response.

type PRMerge

type PRMerge struct {
	Merged bool   `json:"merged"`
	SHA    string `json:"sha"`
}

PRMerge is the POST .../pulls/{number}/merge response.

type Project

type Project struct {
	Name          string `json:"name"`
	Path          string `json:"path"`
	Remote        string `json:"remote,omitempty"`
	Branch        string `json:"branch,omitempty"`
	Dirty         bool   `json:"dirty"`
	LastCommitAt  string `json:"last_commit_at,omitempty"`
	LastCommitMsg string `json:"last_commit_msg,omitempty"`
}

Project is one cloned repository under /workspace on a machine, as returned by GET /api/projects. It mirrors the control-plane/guest Project shape.

type Provider

type Provider struct {
	Key          string        `json:"key"`
	DisplayName  string        `json:"display_name"`
	Enabled      bool          `json:"enabled"`
	KeySet       bool          `json:"key_set"`
	SecretFields []SecretField `json:"secret_fields"`
}

Provider is one row of GET /api/providers: the registry metadata plus whether the caller has a key stored for it. The key material itself is never part of this (or any) response — KeySet is the only signal.

type Repo

type Repo struct {
	FullName      string `json:"full_name"`
	Private       bool   `json:"private"`
	DefaultBranch string `json:"default_branch"`
	PushedAt      string `json:"pushed_at"`
}

Repo is one GitHub repository the user has granted ProteOS access to, as returned by GET /api/git/repos — the set available to clone.

type ReposResult

type ReposResult struct {
	Repos     []Repo `json:"repos"`
	GrantsURL string `json:"grants_url,omitempty"`
}

ReposResult is the GET /api/git/repos envelope. GrantsURL links to the GitHub App's installation settings so the user can choose which repos ProteOS may see.

type SecretField

type SecretField struct {
	Name  string `json:"name"`
	Label string `json:"label"`
	Env   string `json:"env"`
}

SecretField is one declared input a provider needs, as returned by GET /api/providers. Name/Label/Env are not secret — only the value the caller supplies (via SetProviderKey) is.

type Task

type Task struct {
	ID            string          `json:"id"`
	Status        string          `json:"status"`
	Provider      string          `json:"provider"`
	Project       string          `json:"project"`
	SessionID     string          `json:"agent_session_id,omitempty"`
	Usage         json.RawMessage `json:"usage,omitempty"`
	ResultSummary string          `json:"result_summary,omitempty"`
	Error         string          `json:"error,omitempty"`
	CreatedAt     string          `json:"created_at"`
	StartedAt     string          `json:"started_at,omitempty"`
	EndedAt       string          `json:"ended_at,omitempty"`
}

Task mirrors the control-plane taskView. Result fields are populated only once the run is terminal.

func (Task) Failed

func (t Task) Failed() bool

Failed reports whether the task ended unsuccessfully (failed or canceled), which the CLI maps to ExitTaskFail.

func (Task) IsTerminal

func (t Task) IsTerminal() bool

IsTerminal reports whether the task has reached a final state.

type Template

type Template struct {
	ID          string `json:"id"`
	Label       string `json:"label"`
	Description string `json:"description"`
}

Template is a machine template (the "type" of a machine: full-stack, go, …) as returned by GET /api/templates. Only the fields the CLI renders are kept.

type User

type User struct {
	Login     string `json:"login"`
	Email     string `json:"email"`
	AvatarURL string `json:"avatar_url"`
}

User is the authenticated identity from GET /api/me.

Jump to

Keyboard shortcuts

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