cli

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 19 Imported by: ? 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 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

View Source
const FeedbackDescription = "" /* 315-byte string literal not displayed */

FeedbackDescription is the feedback command's description, as agents read it in its help.

View Source
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.

View Source
const Version = "0.2.0"

Variables

View Source
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

func AgentHeaders() map[string]string

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

func AgentThread(getenv func(string) string) string

AgentThread is the thread or conversation id an agent exposes, to group its commands into one session.

func CIProvider

func CIProvider(getenv func(string) string) string

CIProvider is the CI system running the CLI, "ci" for an unrecognised one, or "".

func FlagNames

func FlagNames(argv []string) []string

FlagNames returns flag names from argv: `--env=prod` becomes `--env`, values are skipped, `-pSECRET` keeps only `-p`. Stops at `--`.

func LeadingWords

func LeadingWords(argv []string) []string

LeadingWords are the words typed before the first flag, stopping at `--`: candidates for a command path.

func OptOutVariable

func OptOutVariable(cli string) string

OptOutVariable is ACME_TELEMETRY_DISABLED for a CLI named "acme".

func ParseAIAgent

func ParseAIAgent(value string) (agent, version string, ok bool)

ParseAIAgent reads AI_AGENT as agents set it: `claude-code_2-1-316_agent` or `devin@1`.

func SafeCommandName

func SafeCommandName(name string) string

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.

func DetectActor

func DetectActor(getenv func(string) string, interactive bool) Actor

DetectActor works out who runs the CLI from the environment and whether it's attached to a terminal.

type ArgSpec

type ArgSpec struct {
	Name        string   `json:"name"`
	Description string   `json:"description,omitempty"`
	Required    bool     `json:"required,omitempty"`
	Variadic    bool     `json:"variadic,omitempty"`
	Choices     []string `json:"choices,omitempty"`
}

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

type FeedbackArgs struct {
	Message, Command, From string
	Help                   bool
}

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

func New(opts Options) *Tracker

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) Actor

func (t *Tracker) Actor() Actor

Actor is who runs the CLI: a coding agent, a person, CI or unknown.

func (*Tracker) CLI

func (t *Tracker) CLI() string

CLI is the name events are recorded under.

func (*Tracker) Command

func (t *Tracker) Command(name string, flags ...string)

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

func (t *Tracker) Enabled() bool

Enabled reports whether events are recorded (a key is set and the user hasn't opted out).

func (*Tracker) Error

func (t *Tracker) Error(err 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) Exit

func (t *Tracker) Exit(code int)

Exit records the run with this exit code, then calls os.Exit.

func (*Tracker) Feedback

func (t *Tracker) Feedback(message, command, from string) bool

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

func (t *Tracker) FeedbackName() string

FeedbackName is the feedback command's name, or "" when Options.NoFeedback is set.

func (*Tracker) Finish

func (t *Tracker) Finish(exitCode int)

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

func (t *Tracker) Help(name string)

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

func (t *Tracker) RunFeedback(args []string)

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

func (t *Tracker) SetEnabled(on bool)

SetEnabled persists the user's choice, e.g. from `acme telemetry disable`, for the next run.

func (*Tracker) UnknownCommand

func (t *Tracker) UnknownCommand(name string)

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.

Directories

Path Synopsis
Package cobracli records cobra commands with AgentStats: one call in place of root.Execute().
Package cobracli records cobra commands with AgentStats: one call in place of root.Execute().

Jump to

Keyboard shortcuts

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