Skip to content
p3botPublic

About

Open source Golang modules for extensibility

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

20 Commits

Folders and files

Repository files navigation

p3bot/x

Open source Go library packages shared by the p3bot command-line tools. This repository is library only: it ships no binaries.

Packages

The repository is one Go module, github.com/p3bot/x, versioned as a whole. Its packages fall in two groups:

Group Import path Purpose
clikit github.com/p3bot/x/clikit/... The tool-agnostic parts of the p3bot CLI design: exit codes and error payloads, runtime modes, output, signals, durations, versions, user directories, and atomic file writes and locks
skill github.com/p3bot/x/skill/... Agent skill install, list, and uninstall for a CLI, on top of the agent catalog and installed-agent detection

clikit packages:

Package What it provides
clikit/fault Exit code constants, the error and warning payloads with their details, the canonical error-code table, the coded-error interfaces, fault.Ambiguous for an input that matches more than one item, fault.WithResult to carry a partial result on an error, and fault.ExitCode(err) for main
clikit/mode Detection of interactive, decorated, animated, and debug modes from flags and the environment, and the colour switch for fatih/color
clikit/output An Output value per invocation that writes results, errors, warnings, notices, hints, and progress in text or JSON, and an error together with the result it carries
clikit/interrupt interrupt.Run for main: a context cancelled by SIGINT or SIGTERM, a second signal that kills, and the 128+signum exit code; interrupt.Outcome so an interrupted run reports INTERRUPTED
clikit/duration Parse and format the duration grammar (30s, 1h30m, 7d, 0), and a flag value for cobra/pflag
clikit/version The reported version from a CLI's ldflags value or the module build info, plus the VCS revision and time for diagnostics
clikit/xdg Per-user config, data, state, and cache directories with macOS defaults, and system config lookup across $XDG_CONFIG_DIRS
clikit/atomicfile Replace a file through a temp file and rename, so readers never see a partial write
clikit/filelock An exclusive cross-process lock on a named file, with a context-aware blocking acquire and a non-blocking try, on flock(2) or Windows LockFileEx

skill packages:

Package What it provides
skill A CLI's agent skill built from its embedded SKILL.md: install into, list, and uninstall from agent skills roots, touching only copies the CLI owns, with coded errors (AGENT_UNKNOWN, NO_SKILLS_CONCEPT, NO_SKILLS_ROOT, NO_AGENTS, CONFLICT)
skill/catalog The known AI coding agents (binary, config directories, skills roots, providers) from an embedded agents.json, and detection of which are installed with their paths resolved

The catalog is skill/catalog/agents.json, edited by hand and validated by the package tests. It needs no network, no CUE, and no first-run fetch. While start still reads the agentdex registry catalog, agents.json is frozen: it must stay equivalent to agentdex's catalog/agents.cue, and neither file is edited.

Using the module

Require the module; @latest resolves to the newest tagged version:

go get github.com/p3bot/x@latest

A coded error needs no import of clikit. Any error type that implements Code() string becomes an error payload; a code that is not UPPER_SNAKE_CASE reads as UNKNOWN. It may add any of Fix() string, ValidValues() []string, RetryAfter() string, ExitCode() int, and Details() [][2]string:

type lockedError struct {
	branch  string
	holder  string
	expires time.Time
}

func (e lockedError) Error() string { return e.branch + " is locked" }
func (e lockedError) Code() string  { return "BRANCH_LOCKED" }
func (e lockedError) Fix() string   { return "mycli unlock " + e.branch }
func (e lockedError) ExitCode() int { return 5 }

Details are the facts an agent needs to act on the error, as ordered snake_case key-value pairs. Text output renders each as a labelled line before Fix, and JSON as an object under details:

func (e lockedError) Details() [][2]string {
	return [][2]string{{"holder", e.holder}, {"expires", e.expires.Format(time.RFC3339)}}
}

A domain code is declared once, by the package that raises it, with fault.MustDomain. The declaration binds the exit code and fails at start for a name that is not UPPER_SNAKE_CASE, a canonical name, or an exit code outside the taxonomy. A fault.Error is built only by New on a fault.Code, canonical or declared, so a misspelled or undeclared code does not compile: fault.CodeNotFound.New(message, fix). A hand-written error type can still return any exit code. ErrorPayload.Exit turns one outside the taxonomy into 1. fault does not detect a name declared twice: single ownership is a rule each author keeps, and a repeat with a different exit code is not reported. A CLI returns a shared module's coded errors unchanged and never declares their codes again:

var codeBranchLocked = fault.MustDomain("BRANCH_LOCKED", fault.ExitConflict)

func errLocked(branch string) error {
	return codeBranchLocked.New(branch+" is locked", "mycli unlock "+branch)
}

An input that matches more than one item is fault.Ambiguous, which lists up to fault.MaxCandidates candidates as valid values and reports a larger set as a count, so every CLI reports ambiguity the same way.

A CLI's main hands the signal-aware run to fault.ExitCode, which decides the exit code for errors and signals alike. The CLI prints its errors through its Output and turns off cobra's own error printing (SilenceErrors), so each error is printed once; main prints any error that still reaches it unprinted, as plain text on stderr, so none is lost. An exit code fixed earlier, such as 128+signum, survives that print:

func main() {
	err := interrupt.Run(cli.Execute)
	err = output.New(os.Stdout, os.Stderr, mode.Modes{}).Err(err)
	os.Exit(fault.ExitCode(err))
}

Work usually returns the cancellation error it saw when a signal arrives. The error boundary passes its error through interrupt.Outcome, so an interrupted run reports the INTERRUPTED code, owned by clikit/interrupt, rather than an UNKNOWN cancellation. A failure other than the cancellation, such as a failed cleanup, is wrapped and shown after it. The process still exits 128+signum:

return out.Err(interrupt.Outcome(ctx, err))

A command that acts on several items and fails part-way still reports what it did. It returns its error wrapped by fault.WithResult with the result and warnings it would have passed to Output.Data, and fault.Result reads them back. Output.Err then writes one reply: with --json, one envelope with status error, error, data, and warnings; in text mode, the result on stdout, then the warnings and the error on stderr. The code and exit code are the wrapped error's, and an interrupted run keeps the result:

if failed > 0 {
	return fault.WithResult(codePartialFailure.New(msg, fix), report, warnings...)
}
return out.Data(report, warnings...)

A CLI's skill commands are thin calls into skill. Its errors already carry their code and fix, so the CLI's error boundary passes them through.

catalog.ProcessEnv leaves a home or working directory it cannot read empty and records the reason in HomeErr or WorkingDirErr. Install, List, and Uninstall return NO_SKILLS_ROOT when the directory their location needs is missing: the home directory for skill.Global, the working directory for skill.Local. The other directory may be missing.

//go:embed skill.md
var skillText string

func runSkillInstall(cmd *cobra.Command, args []string) error {
	s, err := skill.New("mycli", skillText)
	if err != nil {
		return err
	}
	written, err := s.Install(catalog.ProcessEnv(), skill.Global, args)
	for _, path := range written {
		fmt.Fprintln(cmd.OutOrStdout(), path)
	}
	return err
}

Versions and tags

Releases are tagged vX.Y.Z at the repository root, starting at v0.1.0. The v is required. From v2 the import paths gain the major version suffix (github.com/p3bot/x/v2/clikit/fault).

The module stays on v0 while the first CLIs migrate to it, so its APIs may still change between minor versions. The coded-error interfaces in clikit/fault are the exception: they are frozen from v0.1.0.

Developing

The module requires Go 1.27. Run commands from the repository root:

go test ./...
golangci-lint run ./...

To work on x and a consumer together, create a go.work in a parent directory. go.work is ignored by git. Before committing, test against the versions go.mod requires by running with GOWORK=off; AGENTS.md lists the full set of checks.

License

MPL-2.0

About

Open source Golang modules for extensibility

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages