Documentation
¶
Overview ¶
Package cli is AgentStats analytics for command-line tools written in Go: which commands coding agents, people and CI run, and where they fail. A port of the Node SDK (@agentstats/cli); events, spool and session files are the same.
The CLI never waits on AgentStats. Finish appends one line to a spool file in the user's cache directory and starts the CLI's own binary again in the background to send it (New recognises that run and sends instead of starting the CLI). Anything that fails is dropped silently. Argument values are never sent: only the command name and flag names.
With cobra, use agentstats.io/go/cli/cobracli. Otherwise:
func main() {
stats := cli.New(cli.Options{CLI: "acme", Version: version}) // first thing in main
stats.MarkFeedbackCommand() // you answer it: failed commands hint at it
if len(os.Args) > 1 && os.Args[1] == stats.FeedbackName() {
stats.RunFeedback(os.Args[2:]) // the feedback command; exits
}
stats.Command("deploy")
err := deploy()
stats.Error(err)
stats.Exit(exitCode(err)) // records, then os.Exit
}
Index ¶
- Constants
- Variables
- func AgentHeaders() map[string]string
- func AgentHeadersFrom(getenv func(string) string, setenv func(string, string) error) map[string]string
- func AgentThread(getenv func(string) string) string
- func CIProvider(getenv func(string) string) string
- func FlagNames(argv []string) []string
- func LeadingWords(argv []string) []string
- func OptOutVariable(cli string) string
- func ParseAIAgent(value string) (agent, version string, ok bool)
- func SafeCommandName(name string) string
- type Actor
- type ArgSpec
- type CommandSpec
- type ErrorInfo
- type Event
- type Feedback
- type FeedbackArgs
- type OptSpec
- type Options
- type Tracker
- func (t *Tracker) Actor() Actor
- func (t *Tracker) CLI() string
- func (t *Tracker) Command(name string, flags ...string)
- func (t *Tracker) Commands(list []CommandSpec)
- func (t *Tracker) Enabled() bool
- func (t *Tracker) Error(err error)
- func (t *Tracker) Exit(code int)
- func (t *Tracker) Feedback(message, command, from string) bool
- func (t *Tracker) FeedbackName() string
- func (t *Tracker) Finish(exitCode int)
- func (t *Tracker) Help(name string)
- func (t *Tracker) MarkFeedbackCommand()
- func (t *Tracker) RunFeedback(args []string)
- func (t *Tracker) RunFeedbackWith(a FeedbackArgs)
- func (t *Tracker) SetEnabled(on bool)
- func (t *Tracker) UnknownCommand(name string)
Constants ¶
const FeedbackDescription = "" /* 315-byte string literal not displayed */
FeedbackDescription is the feedback command's description, as agents read it in its help.
const FeedbackSummary = "Tell the developers of this CLI when a command fails you or can't do what you need"
FeedbackSummary is the feedback command's line in a command list.
const Version = "0.2.0"
Variables ¶
var FeedbackHelp = struct{ Message, Command, From string }{
Message: "What you ran, what happened and what you expected, in a few sentences",
Command: `The command it is about, e.g. "deploy"`,
From: `"user" when the user asked you to send it, "agent" (default) when you report on your own`,
}
FeedbackHelp is the help text of the feedback command's message and options.
Functions ¶
func AgentHeaders ¶
AgentHeaders returns the headers that tell your API a coding agent is making the call, for your API client or SDK: X-AI-Agent ("claude-code/2.1.316") and X-AI-Agent-Run. Empty unless a coding agent (Claude Code, Cursor, Codex…) runs this process, so a deployed app sends nothing. Hints, not proof: never authorize with them. The AgentStats API middleware turns them into sessions.
for k, v := range cli.AgentHeaders() { req.Header.Set(k, v) }
func AgentHeadersFrom ¶
func AgentHeadersFrom(getenv func(string) string, setenv func(string, string) error) map[string]string
AgentHeadersFrom is AgentHeaders with the environment passed in; setenv keeps a new run id (AGENTSTATS_RUN_ID) so child processes inherit it, and may be nil.
func AgentThread ¶
AgentThread is the thread or conversation id an agent exposes, to group its commands into one session.
func CIProvider ¶
CIProvider is the CI system running the CLI, "ci" for an unrecognised one, or "".
func FlagNames ¶
FlagNames returns flag names from argv: `--env=prod` becomes `--env`, values are skipped, `-pSECRET` keeps only `-p`. Stops at `--`.
func LeadingWords ¶
LeadingWords are the words typed before the first flag, stopping at `--`: candidates for a command path.
func OptOutVariable ¶
OptOutVariable is ACME_TELEMETRY_DISABLED for a CLI named "acme".
func ParseAIAgent ¶
ParseAIAgent reads AI_AGENT as agents set it: `claude-code_2-1-316_agent` or `devin@1`.
func SafeCommandName ¶
SafeCommandName keeps "db push"; "postgres://user:secret@host" or a pasted sentence becomes "(invalid)".
Types ¶
type Actor ¶
type Actor struct {
Agent string // claude-code, cursor, codex, human, ci, unknown…
Version string // the agent's version when it says (from AI_AGENT)
Via string // the environment variable (or "tty") the answer came from
CI string // CI provider, also for an agent running inside CI
}
Actor is who runs the CLI.
type CommandSpec ¶
type CommandSpec struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Aliases []string `json:"aliases,omitempty"`
Arguments []ArgSpec `json:"arguments,omitempty"`
Options []OptSpec `json:"options,omitempty"`
}
CommandSpec is one command your CLI offers, for the command list. Only Name is required.
func NormalizeCatalog ¶
func NormalizeCatalog(list []CommandSpec) []CommandSpec
NormalizeCatalog trims a command list to what the server stores, dropping empty fields and duplicates.
type ErrorInfo ¶
type ErrorInfo struct {
Command string // "db migrate"
Message string // Err.Error()
ExitCode int
Err error
}
ErrorInfo is a failed command, as passed to Options.ErrorText.
type Event ¶
type Event struct {
Ts int64 `json:"ts"`
CLI string `json:"cli"`
CLIVersion *string `json:"cliVersion"`
Command string `json:"command"`
Flags []string `json:"flags"`
ExitCode int `json:"exitCode"`
DurationMs int64 `json:"durationMs"`
Unknown bool `json:"unknown"`
Help bool `json:"help"`
ErrorMessage *string `json:"errorMessage"`
Agent string `json:"agent"`
AgentVersion *string `json:"agentVersion"`
Via *string `json:"via"`
CI *string `json:"ci"`
SessionID string `json:"sessionId"`
OS string `json:"os"`
Arch string `json:"arch"`
Runtime string `json:"runtime"`
}
Event is one command, as written to the spool and sent to /api/ingest/cli.
type Feedback ¶
type Feedback struct {
Type string `json:"type"`
Ts int64 `json:"ts"`
CLI string `json:"cli"`
SessionID string `json:"sessionId"`
Agent string `json:"agent"`
AgentVersion *string `json:"agentVersion"`
Source string `json:"source"` // "user" or "agent"
Command *string `json:"command"`
Content string `json:"content"`
}
Feedback is what an agent or its user said through the feedback command, as written to the spool (Type "feedback" sets it apart from commands) and sent as the batch's feedback.
type FeedbackArgs ¶
FeedbackArgs is what the feedback command was given.
func ParseFeedbackArgs ¶
func ParseFeedbackArgs(args []string) FeedbackArgs
ParseFeedbackArgs reads the feedback command's arguments (after its name): the words are the message; --command <name> and --from <who> (or --command=name) the options; -- ends options.
type OptSpec ¶
type OptSpec struct {
Name string `json:"name"` // long form when there is one: "--env"
Short string `json:"short,omitempty"`
Description string `json:"description,omitempty"`
TakesValue bool `json:"takesValue,omitempty"`
Required bool `json:"required,omitempty"`
Choices []string `json:"choices,omitempty"`
}
type Options ¶
type Options struct {
CLI string // your CLI's name, e.g. "acme"
Version string // shown per command in the dashboard
// APIKey defaults to AGENTSTATS_CLI_KEY. Without a key the tracker is a no-op.
APIKey string
// PublishKey (al_sec_…, release CI only) replaces the command list on the dashboard before
// the process exits. Defaults to AGENTSTATS_CLI_PUBLISH_KEY. Never ship it.
PublishKey string
// Notice is printed once to stderr on the first run in a terminal. Empty uses the default
// text; NoNotice turns it off when your CLI already tells users about telemetry.
Notice string
NoNotice bool
// NoFlags stops flag names (never values) being sent; NoErrors stops error messages.
NoFlags bool
NoErrors bool
// ErrorText decides what is sent of a failed command's error: return the text to keep, or
// "" for none. Use errors.As on ErrorInfo.Err for codes. A panic keeps nothing.
ErrorText func(ErrorInfo) string
// FlagNames decides which flag names are sent; return nil for none.
FlagNames func(command string, flags []string) []string
// NoFeedback turns off the feedback command: `acme feedback "what happened" [--command deploy]
// [--from user]`, which agents run when a command fails them or can't do what the user needs, and
// users ask their agent to run to pass something on. The SDK answers it (it isn't recorded as a
// command) and the text shows on the CLI's Feedback page. cobracli adds it to your commands unless
// you have one of that name; without cobra, route it to RunFeedback.
NoFeedback bool
// FeedbackName names the feedback command. Default "feedback".
FeedbackName string
// NoFeedbackHint stops the one line on stderr, the first time a command an agent runs fails in a
// session, saying the feedback command is there.
NoFeedbackHint bool
// SessionIdle groups commands by the same actor in the same directory. Default 30 minutes.
SessionIdle time.Duration
Dir string // AGENTSTATS_CLI_DIR, else ~/.cache/agentstats (or $TMPDIR/agentstats)
Disabled bool
Debug bool // AGENTSTATS_DEBUG=1
// contains filtered or unexported fields
}
Options configure a Tracker. Zero values fall back to environment variables and defaults.
type Tracker ¶
type Tracker struct {
// contains filtered or unexported fields
}
Tracker records the one command a CLI run executes. Safe to use when disabled: every method is a no-op.
func New ¶
New creates the tracker. Call it first thing in main: when the CLI was started in the background to send events, New sends them and exits.
func (*Tracker) Command ¶
Command sets the command that is about to run, as a path: "deploy" or "db migrate". Flags are read from os.Args unless given.
func (*Tracker) Commands ¶
func (t *Tracker) Commands(list []CommandSpec)
Commands sets the CLI's full command list, sent the first time and whenever it changes.
func (*Tracker) Enabled ¶
Enabled reports whether events are recorded (a key is set and the user hasn't opted out).
func (*Tracker) Error ¶
Error attaches the error that made the command fail. Only its message is kept, as Options.NoErrors and Options.ErrorText decide. nil is ignored.
func (*Tracker) Feedback ¶
Feedback queues feedback about the CLI, sent in the background like commands. RunFeedback calls it; call it yourself to send feedback from a command of your own. from is "user" or "agent"; command, the command it's about, may be "". False when nothing was queued (no text, or disabled).
func (*Tracker) FeedbackName ¶
FeedbackName is the feedback command's name, or "" when Options.NoFeedback is set.
func (*Tracker) Finish ¶
Finish records the run: one append to the spool, then a background sender. Never blocks on the network (except with a publish key, in release CI) and never panics. Call it once, at exit.
func (*Tracker) Help ¶
Help records that help was shown, for a command or (with "") for the CLI itself.
func (*Tracker) MarkFeedbackCommand ¶
func (t *Tracker) MarkFeedbackCommand()
MarkFeedbackCommand says the CLI answers the feedback command, so a failed command an agent runs hints at it. cobracli calls it when it adds the command; call it yourself when you route it to RunFeedback.
func (*Tracker) RunFeedback ¶
RunFeedback runs the feedback command: queues what was given, prints the outcome and exits. cobracli calls it; without cobra, route your feedback command here: stats.RunFeedback(os.Args[2:]).
func (*Tracker) RunFeedbackWith ¶
func (t *Tracker) RunFeedbackWith(a FeedbackArgs)
RunFeedbackWith is RunFeedback with the arguments already parsed.
func (*Tracker) SetEnabled ¶
SetEnabled persists the user's choice, e.g. from `acme telemetry disable`, for the next run.
func (*Tracker) UnknownCommand ¶
UnknownCommand records a command that doesn't exist, as a failed call. What was typed is only kept when it looks like a command word: anything else could be a value.