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
- Variables
- func AuthPath(home string) string
- func DefaultHome() string
- func FormatCost(value float64) string
- func FormatCredits(amount float64) string
- func FormatCreditsView(credits *Credits) string
- func FormatDuration(d time.Duration) string
- func FormatNamespacesView(namespaces *Namespaces) string
- func FormatSubscriptionView(sub *Subscription) string
- func FormatSummaryView(summary *UsageSummary) string
- func FormatUsage(view *View, opts FormatOptions) string
- func FormatUsageJSON(data *UsageData) ([]byte, error)
- func FormatWhoami(whoami *Whoami) string
- func ProgressBarWidth(terminalWidth int) int
- func ResolveBaseURL(apiURL string) string
- func ResolveHome(home string) (string, error)
- type APIError
- type Auth
- type Bar
- type Client
- func (c *Client) Credits(ctx context.Context, orgID string) (*Credits, error)
- func (c *Client) Endpoint(path string, params map[string]string) string
- func (c *Client) FetchUsage(ctx context.Context) (*UsageData, error)
- func (c *Client) FetchUsageWithOptions(ctx context.Context, opts UsageOptions) (*UsageData, error)
- func (c *Client) Get(ctx context.Context, path string, params map[string]string, out any) error
- func (c *Client) Namespaces(ctx context.Context) (*Namespaces, error)
- func (c *Client) Subscription(ctx context.Context, orgID string) (*Subscription, error)
- func (c *Client) Summary(ctx context.Context, orgID, since string) (*UsageSummary, error)
- func (c *Client) Whoami(ctx context.Context, orgID string) (*Whoami, error)
- type CreditBalance
- type Credits
- type CreditsView
- type FormatOptions
- type Namespaces
- type NetworkError
- type Org
- type OrgLimit
- type Plan
- type Subscription
- type SubscriptionResponse
- type UsageData
- type UsageOptions
- type UsageSummary
- type User
- type View
- type Whoami
- type WindowLimits
- type WindowSpan
Constants ¶
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" )
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.
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.
const DefaultTerminalWidth = 80
DefaultTerminalWidth is the fallback width for --width.
Variables ¶
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.
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 DefaultHome ¶
func DefaultHome() string
DefaultHome returns the Command Code config directory (~/.commandcode).
func FormatCost ¶
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 ¶
FormatCredits renders a credit amount the way the CLI does ($X.XX).
func FormatCreditsView ¶
FormatCreditsView renders the credit balance and rate-limit windows.
func FormatDuration ¶
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 ¶
FormatUsageJSON renders the merged usage payload as indented JSON.
func FormatWhoami ¶
FormatWhoami renders account identity as aligned key/value lines.
func ProgressBarWidth ¶
ProgressBarWidth reproduces the cmd CLI's bar width for a terminal width.
func ResolveBaseURL ¶
ResolveBaseURL returns apiURL when set, else the sandbox override the cmd CLI honors, else DefaultBaseURL.
func ResolveHome ¶
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) Unauthorized ¶
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.
type Bar ¶
Bar is a rendered two-tone progress bar.
func BuildBlockBar ¶
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 ¶
Client calls the Command Code HTTP API for one home.
func NewClient ¶
NewClient reads credentials for home and returns a client for baseURL. baseURL is resolved with ResolveBaseURL when empty.
func (*Client) Endpoint ¶
Endpoint builds the request URL, omitting empty parameters the way the cmd CLI does (an empty orgId= is rejected with 400).
func (*Client) FetchUsage ¶
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 ¶
FetchUsageWithOptions is FetchUsage with explicit org and period overrides.
func (*Client) Get ¶
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 ¶
Subscription fetches the current subscription, or nil when the account has none.
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 ¶
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 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 ¶
Plan is a resolved plan identity.
func GetPlanInfo ¶
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.
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.