commandcode

package
v0.0.195 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package commandcode reads Command Code (cmd) account data over the public HTTP API, so account commands work without the Node CLI installed.

Index

Constants

View Source
const (
	// DefaultBaseURL is the production Command Code API endpoint.
	DefaultBaseURL = "https://api.commandcode.ai"
	// DefaultStudioHost serves the account usage page opened by --open.
	DefaultStudioHost = "https://commandcode.ai"
	// APIKeyEnvVar overrides the apiKey stored in auth.json.
	APIKeyEnvVar = "COMMAND_CODE_API_KEY"
	// AuthFileName is the credentials file the cmd CLI writes.
	AuthFileName = "auth.json"
	// UserAgent is sent on every request. Cloudflare answers key-only
	// requests that carry no User-Agent with 403 error code: 1010.
	UserAgent = "cli"
)
View Source
const (
	PathWhoami        = "/alpha/whoami"
	PathCredits       = "/alpha/billing/credits"
	PathSubscriptions = "/alpha/billing/subscriptions"
	PathUsageSummary  = "/alpha/usage/summary"
	PathNamespaces    = "/alpha/namespaces"
)

API paths. These are the read-only alpha endpoints the cmd CLI's usage overlay calls.

View Source
const (
	ErrNotAuthenticated = "Not authenticated"
	ErrSessionExpired   = "Session expired"
	ErrNetwork          = "Network error: unable to reach API"
)

Send-error strings the cmd CLI surfaces in its usage overlay.

View Source
const DefaultTerminalWidth = 80

DefaultTerminalWidth is the fallback width for --width.

Variables

View Source
var PlanCredits = map[string]float64{
	"individual-go":       10,
	"individual-goat":     70,
	"individual-pro":      30,
	"individual-pro-v1":   80,
	"individual-provider": 15,
	"individual-max":      150,
	"individual-ultra":    300,
	"teams-pro":           40,
}

PlanCredits maps a plan id to its monthly credit allowance.

View Source
var PlanNames = map[string]string{
	"individual-go":       "Go",
	"individual-goat":     "GOAT",
	"individual-pro":      "Pro",
	"individual-pro-v1":   "Pro",
	"individual-provider": "Provider",
	"individual-max":      "Max",
	"individual-ultra":    "Ultra",
	"teams-pro":           "Teams Pro",
}

PlanNames maps a plan id to its display name.

Functions

func AuthPath

func AuthPath(home string) string

AuthPath returns the auth.json path inside home.

func DefaultHome

func DefaultHome() string

DefaultHome returns the Command Code config directory (~/.commandcode).

func FormatCost

func FormatCost(value float64) string

FormatCost renders a dollar amount that stays readable below one cent, where the CLI's two-decimal FormatCredits would collapse to $0.00.

func FormatCredits

func FormatCredits(amount float64) string

FormatCredits renders a credit amount the way the CLI does ($X.XX).

func FormatCreditsView

func FormatCreditsView(credits *Credits) string

FormatCreditsView renders the credit balance and rate-limit windows.

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration renders a duration the way the CLI does: the largest two units, rounded up to a whole minute and never shorter than "1m".

func FormatNamespacesView

func FormatNamespacesView(namespaces *Namespaces) string

FormatNamespacesView renders the account's namespaces.

func FormatSubscriptionView

func FormatSubscriptionView(sub *Subscription) string

FormatSubscriptionView renders the current subscription.

func FormatSummaryView

func FormatSummaryView(summary *UsageSummary) string

FormatSummaryView renders the usage summary totals.

func FormatUsage

func FormatUsage(view *View, opts FormatOptions) string

FormatUsage renders the usage view with the same content, bars, colors, and spacing as the cmd CLI's usage overlay, minus its interactive footer.

func FormatUsageJSON

func FormatUsageJSON(data *UsageData) ([]byte, error)

FormatUsageJSON renders the merged usage payload as indented JSON.

func FormatWhoami

func FormatWhoami(whoami *Whoami) string

FormatWhoami renders account identity as aligned key/value lines.

func ProgressBarWidth

func ProgressBarWidth(terminalWidth int) int

ProgressBarWidth reproduces the cmd CLI's bar width for a terminal width.

func ResolveBaseURL

func ResolveBaseURL(apiURL string) string

ResolveBaseURL returns apiURL when set, else the sandbox override the cmd CLI honors, else DefaultBaseURL.

func ResolveHome

func ResolveHome(home string) (string, error)

ResolveHome expands ~ and makes home absolute. An empty home means DefaultHome.

Types

type APIError

type APIError struct {
	Method  string
	Path    string
	Status  int
	Code    string
	Message string
	Docs    string
	// contains filtered or unexported fields
}

APIError is a non-2xx response from the Command Code API.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Unauthorized

func (e *APIError) Unauthorized() bool

Unauthorized reports whether the credential itself was rejected. A 403 is not an authentication failure: the credential is valid but lacks permission for the requested scope, so the caller reports the API's own message.

type Auth

type Auth struct {
	APIKey          string `json:"apiKey"`
	UserID          string `json:"userId"`
	UserName        string `json:"userName"`
	KeyName         string `json:"keyName"`
	AuthenticatedAt string `json:"authenticatedAt"`
	// Source is the origin of APIKey: "env" or the auth.json path.
	Source string `json:"-"`
}

Auth holds the credentials read for one Command Code home.

func ReadAuth

func ReadAuth(home string) (*Auth, error)

ReadAuth reads credentials for home, preferring $COMMAND_CODE_API_KEY.

type Bar

type Bar struct {
	Filled string
	Empty  string
}

Bar is a rendered two-tone progress bar.

func BuildBlockBar

func BuildBlockBar(percentage float64, width int) Bar

BuildBlockBar reproduces the cmd CLI's block bar, including its rounding guard so a nonzero percentage always shows one filled block and a sub-100 percentage never fills the entire bar.

type Client

type Client struct {
	BaseURL   string
	Home      string
	Auth      *Auth
	HTTP      *http.Client
	UserAgent string
}

Client calls the Command Code HTTP API for one home.

func NewClient

func NewClient(home, baseURL string) (*Client, error)

NewClient reads credentials for home and returns a client for baseURL. baseURL is resolved with ResolveBaseURL when empty.

func (*Client) Credits

func (c *Client) Credits(ctx context.Context, orgID string) (*Credits, error)

Credits fetches the credit balance and rate-limit windows.

func (*Client) Endpoint

func (c *Client) Endpoint(path string, params map[string]string) string

Endpoint builds the request URL, omitting empty parameters the way the cmd CLI does (an empty orgId= is rejected with 400).

func (*Client) FetchUsage

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

FetchUsage mirrors the cmd CLI's usage overlay fetch: whoami supplies the org scope, credits and subscription load concurrently, and the subscription period start bounds the summary. Per-endpoint failures are collected in UsageData.Errors instead of aborting, so a partial view still renders.

func (*Client) FetchUsageWithOptions

func (c *Client) FetchUsageWithOptions(ctx context.Context, opts UsageOptions) (*UsageData, error)

FetchUsageWithOptions is FetchUsage with explicit org and period overrides.

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string, params map[string]string, out any) error

Get performs a GET and decodes the JSON body into out. A nil out keeps the body undecoded.

func (*Client) Namespaces

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

Namespaces fetches the personal and team namespaces.

func (*Client) Subscription

func (c *Client) Subscription(ctx context.Context, orgID string) (*Subscription, error)

Subscription fetches the current subscription, or nil when the account has none.

func (*Client) Summary

func (c *Client) Summary(ctx context.Context, orgID, since string) (*UsageSummary, error)

Summary fetches usage totals, bounded by since (an RFC3339 timestamp) when set. An empty since reports the whole account history.

func (*Client) Whoami

func (c *Client) Whoami(ctx context.Context, orgID string) (*Whoami, error)

Whoami fetches account identity. orgID is optional and only meaningful for team namespaces.

type CreditBalance

type CreditBalance struct {
	BelowThreshold   bool    `json:"belowThreshold"`
	CreditThreshold  float64 `json:"creditThreshold"`
	MonthlyCredits   float64 `json:"monthlyCredits"`
	PurchasedCredits float64 `json:"purchasedCredits"`
	FreeCredits      float64 `json:"freeCredits"`
}

CreditBalance is the credits object of GET /alpha/billing/credits.

type Credits

type Credits struct {
	Credits      CreditBalance `json:"credits"`
	WindowLimits *WindowLimits `json:"windowLimits"`
}

Credits is the response of GET /alpha/billing/credits.

type CreditsView

type CreditsView struct {
	MonthlyRemaining   float64
	PurchasedRemaining float64
	FreeRemaining      float64
	TotalRemaining     float64
	TotalSpent         float64
	TotalPool          float64
	UsagePercent       float64
	HasCreditsInfo     bool
}

CreditsView mirrors the credential projection the cmd CLI's overlay uses.

type FormatOptions

type FormatOptions struct {
	// Width is the terminal width in columns; 0 uses DefaultTerminalWidth.
	Width int
	// Color enables ANSI styling.
	Color bool
}

FormatOptions controls rendered width and color.

type Namespaces

type Namespaces struct {
	Success bool   `json:"success"`
	Type    string `json:"type"`
	User    User   `json:"user"`
	Org     *Org   `json:"org,omitempty"`
	Orgs    []Org  `json:"orgs"`
}

Namespaces is the response of GET /alpha/namespaces.

type NetworkError

type NetworkError struct {
	URL string
	Err error
}

NetworkError is a transport failure or an unreachable API.

func (*NetworkError) Error

func (e *NetworkError) Error() string

func (*NetworkError) Unwrap

func (e *NetworkError) Unwrap() error

type Org

type Org struct {
	ID    string `json:"id"`
	Login string `json:"login"`
	Name  string `json:"name"`
}

Org identifies a team namespace.

type OrgLimit

type OrgLimit struct {
	Scope         string  `json:"scope"`
	Model         string  `json:"model"`
	ModelLabel    string  `json:"modelLabel"`
	Limit         float64 `json:"limit"`
	Spent         float64 `json:"spent"`
	Exceeded      bool    `json:"exceeded"`
	ResetInterval string  `json:"resetInterval"`
	ResetAt       string  `json:"resetAt"`
}

OrgLimit is one spend-limit row carried by whoami's orgLimits.

type Plan

type Plan struct {
	ID             string
	Name           string
	MonthlyCredits float64
}

Plan is a resolved plan identity.

func GetPlanInfo

func GetPlanInfo(planID string) *Plan

GetPlanInfo resolves a planId to its display name and credit allowance. Matching lowercases the id, maps underscores to dashes, and takes the longest known prefix. It returns nil for empty or unknown ids.

type Subscription

type Subscription struct {
	ID                 string          `json:"id"`
	Status             string          `json:"status"`
	UserID             string          `json:"userId"`
	OrgID              *string         `json:"orgId"`
	CreatedAt          string          `json:"createdAt"`
	PriceID            string          `json:"priceId"`
	Metadata           json.RawMessage `json:"metadata"`
	Quantity           int             `json:"quantity"`
	CancelAtPeriodEnd  bool            `json:"cancelAtPeriodEnd"`
	CurrentPeriodStart string          `json:"currentPeriodStart"`
	CurrentPeriodEnd   string          `json:"currentPeriodEnd"`
	EndedAt            *string         `json:"endedAt"`
	CancelAt           *string         `json:"cancelAt"`
	CanceledAt         *string         `json:"canceledAt"`
	PlanID             string          `json:"planId"`
	PendingPhase       json.RawMessage `json:"pendingPhase"`
}

Subscription is one subscription record.

type SubscriptionResponse

type SubscriptionResponse struct {
	Success bool          `json:"success"`
	Data    *Subscription `json:"data"`
}

SubscriptionResponse is the envelope of GET /alpha/billing/subscriptions.

type UsageData

type UsageData struct {
	Whoami       *Whoami       `json:"whoami"`
	Credits      *Credits      `json:"credits"`
	Subscription *Subscription `json:"subscription"`
	Summary      *UsageSummary `json:"summary"`
	Errors       []string      `json:"errors"`
}

UsageData is the merged result of the composite usage fetch. A nil field means that endpoint failed; Errors records one message per failure. The JSON tags match the shape the cmd CLI's fetchUsageData returns.

type UsageOptions

type UsageOptions struct {
	// OrgID pins the org scope. Empty uses whoami's org, else the personal
	// namespace.
	OrgID string
	// Since pins the summary period start (RFC3339). Empty uses the
	// subscription's current period start.
	Since string
}

UsageOptions overrides parts of the composite fetch.

type UsageSummary

type UsageSummary struct {
	TotalCount            int     `json:"totalCount"`
	TotalCost             float64 `json:"totalCost"`
	AverageCost           float64 `json:"averageCost"`
	SuccessRate           float64 `json:"successRate"`
	CompletedCount        int     `json:"completedCount"`
	FailedCount           int     `json:"failedCount"`
	TotalTokensIn         int64   `json:"totalTokensIn"`
	TotalTokensOut        int64   `json:"totalTokensOut"`
	TotalTokens           int64   `json:"totalTokens"`
	TotalCredits          float64 `json:"totalCredits"`
	TotalFreeCredits      float64 `json:"totalFreeCredits"`
	TotalMonthlyCredits   float64 `json:"totalMonthlyCredits"`
	TotalPurchasedCredits float64 `json:"totalPurchasedCredits"`
	PeriodBasis           string  `json:"periodBasis"`
}

UsageSummary is the response of GET /alpha/usage/summary. The numbers cover the billing period when since is the subscription's currentPeriodStart.

type User

type User struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Email    string `json:"email"`
	UserName string `json:"userName"`
}

User is the account identity embedded in several responses.

type View

type View struct {
	Subscription    *Subscription
	Plan            *Plan
	HasBillingData  bool
	UsageURL        string
	UsageURLDisplay string
	Credits         CreditsView
	WindowLimits    *WindowLimits
	OrgLimits       []OrgLimit
	Summary         *UsageSummary
	DaysLeft        *int
	Now             time.Time
}

View is the projected usage view that FormatUsage renders.

func ProjectUsageView

func ProjectUsageView(data *UsageData, now time.Time) *View

ProjectUsageView reproduces the cmd CLI's projectUsageView. now defaults to time.Now when zero.

type Whoami

type Whoami struct {
	Success   bool       `json:"success"`
	User      User       `json:"user"`
	Org       *Org       `json:"org"`
	OrgLimits []OrgLimit `json:"orgLimits,omitempty"`
}

Whoami is the response of GET /alpha/whoami?limits=1.

type WindowLimits

type WindowLimits struct {
	Limited  bool        `json:"limited"`
	Exceeded *bool       `json:"exceeded"`
	FiveHour *WindowSpan `json:"fiveHour"`
	Weekly   *WindowSpan `json:"weekly"`
}

WindowLimits is the windowLimits object of GET /alpha/billing/credits.

type WindowSpan

type WindowSpan struct {
	Used     float64 `json:"used"`
	Cap      float64 `json:"cap"`
	Exceeded bool    `json:"exceeded"`
	ResetAt  float64 `json:"resetAt"`
}

WindowSpan is one rate-limit window (fiveHour or weekly). ResetAt is a unix-millisecond timestamp, or 0 when the window has no pending reset.

Jump to

Keyboard shortcuts

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