Documentation
¶
Overview ¶
agents.go implements agent detection and skill installation for AI coding assistants.
command.go implements the command execution engine for incur CLIs.
completions.go implements shell completion generation and scripts for bash, zsh, fish, and nushell.
fetch.go implements the HTTP/Fetch handler for serving commands over HTTP.
filter.go implements the output filtering DSL for selecting and transforming command output.
help.go implements help text generation for commands and subcommands.
Package incur provides a CLI framework for building agent-friendly command-line tools. It supports multiple output formats, MCP integration, HTTP serving, and shell completions.
mcp.go implements the Model Context Protocol server over stdio and HTTP transports.
middleware.go defines middleware types and chain composition for command execution.
openapi.go implements automatic command generation from OpenAPI specifications.
parser.go implements argv, option, and environment variable parsing.
pm.go implements package-manager runner detection helpers.
schema.go provides JSON Schema utilities for command validation and codegen.
skill.go implements skill file generation for AI agent discovery.
syncmcp.go implements MCP server registration with AI agent configurations.
syncskills.go implements skill syncing between the CLI and agent configurations.
tokens.go implements token counting, limiting, and pagination.
typegen.go implements TypeScript declaration generation for registered commands.
Index ¶
- func ApplyFilter(data any, paths []FilterPath) any
- func BuildRequest(input *FetchInput) (*http.Request, error)
- func ComposeMiddleware(middlewares []MiddlewareFunc, final func() error) func() error
- func ComposeMiddlewareWithContext(ctx *Context, middlewares []MiddlewareFunc, final func() error) func() error
- func ConfigSchemaFromCli(cli *Cli) map[string]any
- func DetectPackageSpecifier(name string) string
- func DetectRunner(env map[string]string) string
- func EstimateTokenCount(text string) int
- func FormatCandidates(shell Shell, candidates []Candidate) string
- func FormatCommand(name string, opts CommandHelpOptions) string
- func FormatRoot(name string, opts RootHelpOptions) string
- func FormatValue(value any, format Format) (string, error)
- func Generate(name string, commands []CommandInfo, groups map[string]string) string
- func GenerateCommands(spec *openapi3.T, handler http.Handler, opts OpenAPIOptions) (map[string]*CommandDef, error)
- func HasInstalledSkills(name string, opts SyncOptions) bool
- func Hash(commands []CommandInfo) string
- func Index(name string, commands []CommandInfo, description string) string
- func IsStreamingResponse(resp *http.Response) bool
- func ParseEnv(schema *JSONSchema, source map[string]string) (map[string]any, error)
- func ParseStreamingResponse(resp *http.Response) (<-chan any, error)
- func ReadHash(name string) string
- func Register(shell Shell, name string) string
- func RegisterAmp(name, command string) (bool, error)
- func RemoveSkill(name string, opts RemoveOptions) error
- func ServeMCP(name, version string, commands map[string]*CommandEntry, opts MCPOptions) error
- func SliceByTokens(text string, offset int, limit int) string
- func TypegenFromCli(cli *Cli) (string, error)
- type Agent
- type AgentInstall
- type CTABlock
- type CallToolOptions
- type Candidate
- type Cli
- func (c *Cli) Command(name string, def *CommandDef) *Cli
- func (c *Cli) Fetch(req *http.Request) *http.Response
- func (c *Cli) Group(name string, sub *Cli) *Cli
- func (c *Cli) Handler() http.Handler
- func (c *Cli) Name() string
- func (c *Cli) Serve(argv []string) error
- func (c *Cli) ServeWithOptions(argv []string, opts ServeOptions) error
- func (c *Cli) Use(mw MiddlewareFunc) *Cli
- type CommandContext
- type CommandDef
- type CommandEntry
- type CommandError
- type CommandHandler
- type CommandHelpOptions
- type CommandInfo
- type ConfigLoader
- type ConfigOptions
- type Context
- type ErrorOpts
- type Example
- type ExecuteOptions
- type FetchInput
- type FetchOutput
- type FieldError
- type FilterPath
- type Format
- type HelpCommand
- type IncurError
- type IncurErrorOptions
- type InstallOptions
- type InstallResult
- type JSONSchema
- func (s *JSONSchema) EnumValues(name string) []string
- func (s *JSONSchema) IsArrayField(name string) bool
- func (s *JSONSchema) IsBooleanField(name string) bool
- func (s *JSONSchema) IsCountField(name string) bool
- func (s *JSONSchema) PropertyNames() []string
- func (s *JSONSchema) RequiredFields() []string
- func (s *JSONSchema) ResolveType(name string) string
- type KeySegment
- type ListedSkill
- type MCPOptions
- type MiddlewareFunc
- type OpenAPIOptions
- type Option
- func WithAliases(aliases ...string) Option
- func WithConfig(files ...string) Option
- func WithConfigFlag(flag string) Option
- func WithConfigOptions(opts ConfigOptions) Option
- func WithDescription(description string) Option
- func WithEnv(schema *JSONSchema) Option
- func WithFormat(format Format) Option
- func WithMCP(opts RegisterOptions) Option
- func WithMiddleware(middlewares ...MiddlewareFunc) Option
- func WithOutputPolicy(policy OutputPolicy) Option
- func WithRootCommand(def *CommandDef) Option
- func WithSync(opts SyncOptions) Option
- func WithVars(schema *JSONSchema) Option
- func WithVersion(version string) Option
- type OutputPolicy
- type ParseError
- type ParseErrorOptions
- type ParseMode
- type ParseOptions
- type ParseResult
- type RegisterOptions
- type RegisterResult
- type RemoveOptions
- type Result
- type ResultOptions
- type RootHelpOptions
- type Segment
- type ServeOptions
- type Shell
- type SkillFile
- type SliceSegment
- type StreamHandler
- type SyncOptions
- type SyncResult
- type SyncedSkill
- type ToolContent
- type ToolEntry
- type ToolResult
- type ValidationError
- type ValidationErrorOptions
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ApplyFilter ¶
func ApplyFilter(data any, paths []FilterPath) any
ApplyFilter applies parsed filter paths to data and returns a filtered copy.
func BuildRequest ¶
func BuildRequest(input *FetchInput) (*http.Request, error)
BuildRequest builds an http.Request from FetchInput.
func ComposeMiddleware ¶
func ComposeMiddleware(middlewares []MiddlewareFunc, final func() error) func() error
ComposeMiddleware composes middleware around a final command function. The first middleware in the slice is the outermost wrapper.
func ComposeMiddlewareWithContext ¶
func ComposeMiddlewareWithContext(ctx *Context, middlewares []MiddlewareFunc, final func() error) func() error
ComposeMiddlewareWithContext composes middleware around a final command function using the provided context.
func ConfigSchemaFromCli ¶
ConfigSchemaFromCli builds a JSON Schema for command config files.
func DetectPackageSpecifier ¶
DetectPackageSpecifier returns the command/package specifier for a CLI name.
func DetectRunner ¶
DetectRunner detects the package runner command from npm environment values.
func EstimateTokenCount ¶
EstimateTokenCount estimates LLM token count for text.
func FormatCandidates ¶
FormatCandidates formats completion candidates for a shell.
func FormatCommand ¶
func FormatCommand(name string, opts CommandHelpOptions) string
FormatCommand formats leaf command help text.
func FormatRoot ¶
func FormatRoot(name string, opts RootHelpOptions) string
FormatRoot formats root or group help text.
func FormatValue ¶
FormatValue serializes a value into the requested output format.
func Generate ¶
func Generate(name string, commands []CommandInfo, groups map[string]string) string
Generate renders a full Markdown skill document.
func GenerateCommands ¶
func GenerateCommands(spec *openapi3.T, handler http.Handler, opts OpenAPIOptions) (map[string]*CommandDef, error)
GenerateCommands converts an OpenAPI spec to incur command definitions.
func HasInstalledSkills ¶
func HasInstalledSkills(name string, opts SyncOptions) bool
HasInstalledSkills reports whether metadata and at least one installed path exist.
func Hash ¶
func Hash(commands []CommandInfo) string
Hash returns a stable hash of command metadata for staleness checks.
func Index ¶
func Index(name string, commands []CommandInfo, description string) string
Index renders a compact LLM command index.
func IsStreamingResponse ¶
IsStreamingResponse reports whether a response is newline-delimited JSON.
func ParseStreamingResponse ¶
ParseStreamingResponse parses an NDJSON response into a channel.
func RegisterAmp ¶
RegisterAmp writes Amp MCP settings directly.
func RemoveSkill ¶
func RemoveSkill(name string, opts RemoveOptions) error
RemoveSkill removes a skill from canonical and agent-specific directories.
func ServeMCP ¶
func ServeMCP(name, version string, commands map[string]*CommandEntry, opts MCPOptions) error
ServeMCP serves a minimal MCP-compatible JSON-RPC stdio server.
func SliceByTokens ¶
SliceByTokens returns a token-window approximation of text.
func TypegenFromCli ¶
TypegenFromCli generates a TypeScript module augmentation for a CLI's commands.
Types ¶
type Agent ¶
type Agent struct {
// Name is the display name.
Name string
// GlobalSkillsDir is the absolute global skills directory.
GlobalSkillsDir string
// ProjectSkillsDir is the project-relative skills directory.
ProjectSkillsDir string
// Universal means the agent uses .agents/skills directly.
Universal bool
// Detect checks whether the agent is installed.
Detect func() bool
}
Agent describes an AI coding assistant skill location.
type AgentInstall ¶
type AgentInstall struct {
// Agent is the display name.
Agent string
// Path is the installed skill path.
Path string
// Mode is "symlink" or "copy".
Mode string
}
AgentInstall describes a per-agent skill install.
type CTABlock ¶
type CTABlock struct {
// Commands is a list of suggested commands.
Commands []any `json:"commands"`
// Description is an optional human-readable CTA label.
Description string `json:"description,omitempty"`
}
CTABlock represents suggested follow-up commands for a result.
type CallToolOptions ¶
type CallToolOptions struct {
// Params are flat MCP tool arguments.
Params map[string]any
// EnvSchema is the CLI-level environment schema.
EnvSchema *JSONSchema
// VarsSchema is the CLI-level vars schema.
VarsSchema *JSONSchema
// Name is the root CLI name.
Name string
// Version is the CLI version.
Version string
// Middlewares are inherited middleware.
Middlewares []MiddlewareFunc
}
CallToolOptions configures CallTool.
type Candidate ¶
type Candidate struct {
// Value is the candidate value.
Value string `json:"value"`
// Description is optional shell-visible help text.
Description string `json:"description,omitempty"`
// NoSpace asks the shell not to append a space.
NoSpace bool `json:"-"`
}
Candidate is a completion candidate.
func Complete ¶
func Complete(commands map[string]*CommandEntry, root *CommandDef, argv []string, index int) []Candidate
Complete computes completion candidates from the command tree.
type Cli ¶
type Cli struct {
// contains filtered or unexported fields
}
Cli is the root command router and command execution surface.
func (*Cli) Command ¶
func (c *Cli) Command(name string, def *CommandDef) *Cli
Command registers a leaf command. Space-separated names create nested groups.
func (*Cli) ServeWithOptions ¶
func (c *Cli) ServeWithOptions(argv []string, opts ServeOptions) error
ServeWithOptions executes the CLI with testable IO/environment overrides.
type CommandContext ¶
type CommandContext struct {
// Agent indicates agent-oriented output mode.
Agent bool
// Args are parsed positional arguments.
Args map[string]any
// Argv contains raw command tokens before schema parsing.
Argv []string
// Options are parsed named options.
Options map[string]any
// Env is parsed environment data.
Env map[string]any
// Command is the resolved command path.
Command string
// DisplayName is the invoked binary name.
DisplayName string
// Format is the selected output format.
Format string
// FormatExplicit indicates whether Format was explicit.
FormatExplicit bool
// Name is the root CLI name.
Name string
// Version is the CLI version.
Version string
// Vars holds middleware-scoped variables.
Vars map[string]any
// contains filtered or unexported fields
}
CommandContext is passed to command handlers.
func (*CommandContext) Error ¶
func (ctx *CommandContext) Error(opts ErrorOpts) *Result
Error returns an unsuccessful structured result.
func (*CommandContext) Get ¶
func (ctx *CommandContext) Get(key string) any
Get returns a handler-scoped variable.
func (*CommandContext) OK ¶
func (ctx *CommandContext) OK(data any, opts ...ResultOptions) *Result
OK returns a successful structured result.
func (*CommandContext) Set ¶
func (ctx *CommandContext) Set(key string, value any)
Set stores a handler-scoped variable.
type CommandDef ¶
type CommandDef struct {
// Name is the command path or final command segment.
Name string
// Description is shown in help, completions, skills, and manifests.
Description string
// ArgsSchema validates positional arguments.
ArgsSchema *JSONSchema
// OptionsSchema validates named options.
OptionsSchema *JSONSchema
// EnvSchema validates environment variables.
EnvSchema *JSONSchema
// OutputSchema describes returned data.
OutputSchema *JSONSchema
// Format is the command-level default output format.
Format Format
// VarsSchema describes middleware vars produced before handler execution.
VarsSchema *JSONSchema
// Alias maps option names to short aliases.
Alias map[string]string
// Aliases are alternate command names.
Aliases []string
// Usage overrides generated usage text in help output.
Usage string
// Hint is shown after command help.
Hint string
// Examples are rendered in help and skills.
Examples []Example
// Middleware runs around this command after CLI-level middleware.
Middleware []MiddlewareFunc
// Handler executes a non-streaming command.
Handler CommandHandler
// StreamHandler executes a streaming command.
StreamHandler StreamHandler
// FetchHandler marks this command as a fetch gateway when set by OpenAPI/fetch integrations.
FetchHandler any
// FetchBasePath is prepended to fetch gateway request paths.
FetchBasePath string
// OutputPolicy controls when successful data is printed.
OutputPolicy OutputPolicy
}
CommandDef describes a leaf command.
type CommandEntry ¶
type CommandEntry struct {
// Name is the canonical segment name.
Name string
// Description is shown in help, skills, and completions.
Description string
// Def is set for leaf commands.
Def *CommandDef
// Group is set for command groups.
Group *Cli
// AliasTarget points to the canonical command name when this is an alias entry.
AliasTarget string
}
CommandEntry is a registered command tree node.
type CommandError ¶
type CommandError struct {
// Code is a machine-readable error code.
Code string `json:"code"`
// Message is a human-readable error message.
Message string `json:"message"`
// Retryable indicates whether retrying may succeed.
Retryable bool `json:"retryable,omitempty"`
}
CommandError is the structured error envelope for command results.
type CommandHandler ¶
type CommandHandler func(ctx *CommandContext) (any, error)
CommandHandler executes a command and returns either raw data or *Result.
type CommandHelpOptions ¶
type CommandHelpOptions struct {
// Description is shown in the header.
Description string
// Version is shown in the header when set.
Version string
// Args is the positional arg schema.
Args *JSONSchema
// Env is the env schema.
Env *JSONSchema
// EnvSource provides current env values for display.
EnvSource map[string]string
// Options is the named option schema.
Options *JSONSchema
// Alias maps option names to short aliases.
Alias map[string]string
// Aliases are executable aliases.
Aliases []string
// Usage overrides generated usage.
Usage string
// Hint is shown after tables.
Hint string
// Examples are command examples.
Examples []Example
// Commands are nested commands shown after usage.
Commands []HelpCommand
// Root shows root-only integrations and global flags.
Root bool
// HideGlobalOptions hides global flags.
HideGlobalOptions bool
// ConfigFlag is the configured config flag.
ConfigFlag string
}
CommandHelpOptions configures FormatCommand.
type CommandInfo ¶
type CommandInfo struct {
// Name is the full command path.
Name string
// Description describes the command.
Description string
// ArgsSchema describes positional args.
ArgsSchema *JSONSchema
// EnvSchema describes env vars.
EnvSchema *JSONSchema
// OptionsSchema describes named options.
OptionsSchema *JSONSchema
// OutputSchema describes output.
OutputSchema *JSONSchema
// Hint provides extra usage guidance.
Hint string
// Examples are usage examples.
Examples []Example
}
CommandInfo is command metadata used by skill and LLM manifests.
type ConfigLoader ¶
ConfigLoader loads command config defaults from an optional path.
type ConfigOptions ¶
type ConfigOptions struct {
// Enabled enables config discovery and loading.
Enabled bool
// Files is the ordered list of config files to search.
Files []string
// Flag is the override flag name, defaulting to "--config".
Flag string
// Loader replaces JSON file parsing when set.
Loader ConfigLoader
}
ConfigOptions configures config file loading.
type Context ¶
type Context struct {
// Agent indicates whether output is being consumed by an agent.
Agent bool
// Command is the resolved command path.
Command string
// DisplayName is the invoked binary name (e.g. alias).
DisplayName string
// Env holds parsed CLI-level environment variables.
Env map[string]any
// Format is the resolved output format (e.g. "toon", "json").
Format string
// FormatExplicit indicates whether the output format was explicitly requested.
FormatExplicit bool
// Name is the CLI name.
Name string
// Version is the CLI version string.
Version string
// Vars holds middleware-scoped variables.
Vars map[string]any
// contains filtered or unexported fields
}
Context is shared state available to middleware handlers.
type ErrorOpts ¶
type ErrorOpts struct {
// Code is a machine-readable error code.
Code string
// Message is a human-readable error message.
Message string
// Retryable indicates whether retrying may succeed.
Retryable bool
// CTA contains optional command suggestions.
CTA *CTABlock
// ExitCode overrides the default exit code when non-zero.
ExitCode int
}
ErrorOpts configures a middleware error result.
type Example ¶
type Example struct {
// Description explains the example.
Description string
// Command is the example command line.
Command string
}
Example documents a command invocation.
type ExecuteOptions ¶
type ExecuteOptions struct {
// Mode controls how inputs are parsed.
Mode ParseMode
// Argv is used by ParseModeArgv.
Argv []string
// Args is used by ParseModeSplit.
Args []string
// Options are raw options used by ParseModeSplit.
Options map[string]any
// Params are flat parameters used by ParseModeFlat.
Params map[string]any
// Defaults are option defaults from config files.
Defaults any
// EnvSource overrides process environment values.
EnvSource map[string]string
// EnvSchema is the CLI-level environment schema available to middleware.
EnvSchema *JSONSchema
// VarsSchema is the CLI-level vars schema available to middleware and handlers.
VarsSchema *JSONSchema
// Middlewares are CLI/group-level middleware.
Middlewares []MiddlewareFunc
// Agent indicates agent-oriented output mode.
Agent bool
// Command is the resolved command path.
Command string
// DisplayName is the invoked binary name.
DisplayName string
// Format is the selected output format.
Format string
// FormatExplicit indicates whether Format was set by the caller.
FormatExplicit bool
// Name is the root CLI name.
Name string
// Version is the CLI version.
Version string
// Vars contains initial middleware variables.
Vars map[string]any
}
ExecuteOptions configures command execution.
type FetchInput ¶
type FetchInput struct {
// Path is the URL path or full URL.
Path string
// Method is the HTTP method.
Method string
// Headers are request headers.
Headers map[string]string
// Body is the request body.
Body string
// Query is query string data.
Query map[string]string
// contains filtered or unexported fields
}
FetchInput is a curl-style request description.
func ParseArgv ¶
func ParseArgv(argv []string) (*FetchInput, error)
ParseArgv parses curl-style fetch argv.
type FetchOutput ¶
type FetchOutput struct {
// Data is the parsed response body.
Data any
// Headers are response headers.
Headers map[string]string
// OK reports 2xx status.
OK bool
// Status is the HTTP status code.
Status int
}
FetchOutput is a parsed HTTP response.
func ParseResponse ¶
func ParseResponse(resp *http.Response) (*FetchOutput, error)
ParseResponse parses an HTTP response body as JSON when possible.
type FieldError ¶
type FieldError struct {
// Path is the field path that failed validation (e.g. "user.email").
Path string `json:"path"`
// Expected is the expected value or type.
Expected string `json:"expected"`
// Received is the value that was actually received.
Received string `json:"received"`
// Message is a human-readable validation message.
Message string `json:"message"`
}
FieldError represents a single field-level validation error.
func Validate ¶
func Validate(schema *JSONSchema, data map[string]any) ([]FieldError, error)
Validate validates data against schema and returns field-level errors.
type FilterPath ¶
type FilterPath []Segment
FilterPath is an ordered list of segments to traverse.
func ParseFilter ¶
func ParseFilter(expression string) ([]FilterPath, error)
ParseFilter parses a filter expression into one or more filter paths.
type Format ¶
type Format string
Format is the output format used by FormatValue.
const ( // FormatTOON encodes values with TOON. FormatTOON Format = "toon" // FormatJSON encodes values as pretty JSON. FormatJSON Format = "json" // FormatYAML encodes values as YAML. FormatYAML Format = "yaml" // FormatMarkdown encodes values as Markdown. FormatMarkdown Format = "md" // FormatJSONL encodes values as JSON Lines. FormatJSONL Format = "jsonl" )
type HelpCommand ¶
type HelpCommand struct {
// Name is the command name.
Name string
// Description is the command description.
Description string
}
HelpCommand is a command row in root help output.
type IncurError ¶
type IncurError struct {
// Code is a machine-readable error code (e.g. "NOT_AUTHENTICATED").
Code string
// Message is a short, human-readable error message.
Message string
// Hint is an optional actionable hint for the user.
Hint string
// Retryable indicates whether the operation can be retried.
Retryable bool
// ExitCode, when non-zero, overrides the default exit code of 1.
ExitCode int
// contains filtered or unexported fields
}
IncurError is the primary CLI error type with a machine-readable code, optional hint, retryable flag, and configurable exit code.
func NewIncurError ¶
func NewIncurError(opts IncurErrorOptions) *IncurError
NewIncurError constructs an IncurError from the given options.
func (*IncurError) Error ¶
func (e *IncurError) Error() string
Error returns a human-readable representation. When a cause is present, its message is appended as a "Details:" section, mirroring the TypeScript BaseError behavior.
func (*IncurError) Unwrap ¶
func (e *IncurError) Unwrap() error
Unwrap returns the underlying cause, enabling errors.Is/errors.As chain traversal.
type IncurErrorOptions ¶
type IncurErrorOptions struct {
Code string
Message string
Hint string
Retryable bool
ExitCode int
Cause error
}
IncurErrorOptions holds the parameters for constructing an IncurError.
type InstallOptions ¶
type InstallOptions struct {
// Agents overrides detected agents.
Agents []Agent
// Cwd is the working directory for project installs.
Cwd string
// Global installs globally unless explicitly false.
Global *bool
}
InstallOptions configures InstallSkills.
type InstallResult ¶
type InstallResult struct {
// Paths are canonical installed skill paths.
Paths []string
// Agents are non-universal agent install details.
Agents []AgentInstall
}
InstallResult is returned by InstallSkills.
func InstallSkills ¶
func InstallSkills(sourceDir string, opts InstallOptions) (*InstallResult, error)
InstallSkills installs skill directories and links non-universal agents.
type JSONSchema ¶
type JSONSchema struct {
// Schema is the JSON Schema dialect URI.
Schema string `json:"$schema,omitempty"`
// Title is an optional human-readable schema title.
Title string `json:"title,omitempty"`
// Type is the JSON Schema type ("string", "number", "boolean", "array", "object"), or an array of types.
Type any `json:"type,omitempty"`
// Properties maps object property names to child schemas.
Properties map[string]*JSONSchema `json:"properties,omitempty"`
// Required lists required object property names.
Required []string `json:"required,omitempty"`
// Items is the schema for array items.
Items *JSONSchema `json:"items,omitempty"`
// Enum is the list of allowed values.
Enum []any `json:"enum,omitempty"`
// Default is the default value used when a field is omitted.
Default any `json:"default,omitempty"`
// Description is the schema description.
Description string `json:"description,omitempty"`
// Const is a single fixed value the field must equal.
Const any `json:"const,omitempty"`
// AnyOf stores alternate schema branches.
AnyOf []*JSONSchema `json:"anyOf,omitempty"`
// Ref is a JSON Schema $ref value.
Ref string `json:"$ref,omitempty"`
// Defs stores JSON Schema $defs.
Defs map[string]*JSONSchema `json:"$defs,omitempty"`
// Format is the JSON Schema format.
Format string `json:"format,omitempty"`
// Deprecated marks a schema as deprecated.
Deprecated bool `json:"deprecated,omitempty"`
// AdditionalProperties controls object keys outside Properties.
AdditionalProperties any `json:"additionalProperties,omitempty"`
// XCount marks a numeric option as a count flag.
XCount bool `json:"x-count,omitempty"`
// XOrder is an optional custom field order used for positional argument assignment.
XOrder []string `json:"x-order,omitempty"`
}
JSONSchema represents a JSON Schema object used for parsing and validation.
func LoadSchema ¶
func LoadSchema(path string) (*JSONSchema, error)
LoadSchema loads a JSON or YAML schema file from disk.
func ParseSchema ¶
func ParseSchema(data []byte) (*JSONSchema, error)
ParseSchema parses a JSON or YAML schema document.
func (*JSONSchema) EnumValues ¶
func (s *JSONSchema) EnumValues(name string) []string
EnumValues returns enum values for a property as strings.
func (*JSONSchema) IsArrayField ¶
func (s *JSONSchema) IsArrayField(name string) bool
IsArrayField reports whether name resolves to an array property.
func (*JSONSchema) IsBooleanField ¶
func (s *JSONSchema) IsBooleanField(name string) bool
IsBooleanField reports whether name resolves to a boolean property.
func (*JSONSchema) IsCountField ¶
func (s *JSONSchema) IsCountField(name string) bool
IsCountField reports whether name resolves to a count flag property.
func (*JSONSchema) PropertyNames ¶
func (s *JSONSchema) PropertyNames() []string
PropertyNames returns property names in deterministic schema order.
func (*JSONSchema) RequiredFields ¶
func (s *JSONSchema) RequiredFields() []string
RequiredFields returns required field names in schema order.
func (*JSONSchema) ResolveType ¶
func (s *JSONSchema) ResolveType(name string) string
ResolveType returns a human-readable JSON Schema type for a property.
type KeySegment ¶
type KeySegment struct {
Key string
}
KeySegment selects a named key from an object.
type ListedSkill ¶
type ListedSkill struct {
// Name is the skill name.
Name string
// Description describes the skill.
Description string
// Installed indicates whether metadata says it is installed.
Installed bool
}
ListedSkill describes a generated skill and whether it is installed.
func ListSkills ¶
func ListSkills(name string, commands map[string]*CommandEntry, opts SyncOptions) ([]ListedSkill, error)
ListSkills returns generated skills with installed status from metadata.
type MCPOptions ¶
type MCPOptions struct {
// Cli is the backing CLI.
Cli *Cli
// Reader overrides stdin.
Reader io.Reader
// Writer overrides stdout.
Writer io.Writer
}
MCPOptions configures ServeMCP.
type MiddlewareFunc ¶
MiddlewareFunc wraps command execution with before/after behavior.
type OpenAPIOptions ¶
type OpenAPIOptions struct {
// Prefix is prepended to generated command names.
Prefix string
// BasePath is prepended to generated request paths.
BasePath string
// BaseURL is used when generated handlers create outbound requests.
BaseURL string
}
OpenAPIOptions configures command generation.
type Option ¶
type Option func(*Cli)
Option configures a Cli.
func WithAliases ¶
WithAliases sets executable aliases for help and completions.
func WithConfig ¶
WithConfig enables config files and sets optional search paths.
func WithConfigFlag ¶
WithConfigFlag changes the config override flag.
func WithConfigOptions ¶
func WithConfigOptions(opts ConfigOptions) Option
WithConfigOptions enables config loading with explicit options.
func WithDescription ¶
WithDescription sets the CLI description.
func WithEnv ¶
func WithEnv(schema *JSONSchema) Option
WithEnv sets the CLI-level environment schema.
func WithMCP ¶
func WithMCP(opts RegisterOptions) Option
WithMCP configures MCP registration defaults.
func WithMiddleware ¶
func WithMiddleware(middlewares ...MiddlewareFunc) Option
WithMiddleware appends CLI-level middleware.
func WithOutputPolicy ¶
func WithOutputPolicy(policy OutputPolicy) Option
WithOutputPolicy sets the default output policy.
func WithRootCommand ¶
func WithRootCommand(def *CommandDef) Option
WithRootCommand sets the root command definition.
func WithVars ¶
func WithVars(schema *JSONSchema) Option
WithVars sets the CLI-level middleware vars schema.
type OutputPolicy ¶
type OutputPolicy string
OutputPolicy controls whether successful output is printed for humans, agents, or both.
const ( // OutputPolicyAgentOnly prints command data for non-TTY/agent consumers by default. OutputPolicyAgentOnly OutputPolicy = "agent-only" // OutputPolicyAll prints command data for every consumer. OutputPolicyAll OutputPolicy = "all" )
type ParseError ¶
type ParseError struct {
// Message is a short, human-readable error message.
Message string
// contains filtered or unexported fields
}
ParseError represents an argument-parsing failure (unknown flags, missing values, etc.).
func NewParseError ¶
func NewParseError(opts ParseErrorOptions) *ParseError
NewParseError constructs a ParseError from the given options.
func (*ParseError) Error ¶
func (e *ParseError) Error() string
Error returns a human-readable representation. When a cause is present, its message is appended as a "Details:" section.
func (*ParseError) Unwrap ¶
func (e *ParseError) Unwrap() error
Unwrap returns the underlying cause, enabling errors.Is/errors.As chain traversal.
type ParseErrorOptions ¶
ParseErrorOptions holds the parameters for constructing a ParseError.
type ParseMode ¶
type ParseMode string
ParseMode selects how Execute interprets input.
const ( // ParseModeArgv parses both positional args and options from argv tokens. ParseModeArgv ParseMode = "argv" // ParseModeSplit uses positional args from Args and options from Options. ParseModeSplit ParseMode = "split" // ParseModeFlat splits Params into args and options by schema membership. ParseModeFlat ParseMode = "flat" )
type ParseOptions ¶
type ParseOptions struct {
// Args is the schema for positional arguments.
Args *JSONSchema
// Options is the schema for named options/flags.
Options *JSONSchema
// Alias maps option names to one-character short aliases.
Alias map[string]string
// Defaults provides config-backed option defaults.
Defaults any
}
ParseOptions configures Parse behavior.
type ParseResult ¶
type ParseResult struct {
// Args are parsed positional argument values.
Args map[string]any
// Options are parsed named option values.
Options map[string]any
}
ParseResult is the parsed result of argv tokens.
func Parse ¶
func Parse(argv []string, opts ParseOptions) (ParseResult, error)
Parse parses argv tokens against positional arg and option schemas.
type RegisterOptions ¶
type RegisterOptions struct {
// Command overrides the command agents run.
Command string
// Global installs globally unless explicitly false.
Global *bool
// Agents targets specific agent names.
Agents []string
// AddMCPBin overrides the add-mcp executable.
AddMCPBin string
}
RegisterOptions configures MCP registration.
type RegisterResult ¶
type RegisterResult struct {
// Command is the command registered with agents.
Command string
// Agents are agent names reported as registered.
Agents []string
}
RegisterResult describes registered MCP agents.
func RegisterMCP ¶
func RegisterMCP(name string, opts RegisterOptions) (*RegisterResult, error)
RegisterMCP registers name as an MCP server with supported agents.
type RemoveOptions ¶
type RemoveOptions struct {
// Cwd is the working directory for project installs.
Cwd string
// Global removes globally unless explicitly false.
Global *bool
}
RemoveOptions configures RemoveSkill.
type Result ¶
type Result struct {
// OK indicates successful execution.
OK bool
// Data is the successful payload when OK is true.
Data any
// Error contains structured error information when OK is false.
Error *CommandError
// CTA contains optional command suggestions.
CTA *CTABlock
// Stream is an optional stream payload for streaming commands.
Stream <-chan any
// ExitCode is an optional process exit override for error results.
ExitCode int
// contains filtered or unexported fields
}
Result is the normalized output shape used by command execution.
func Execute ¶
func Execute(cmd *CommandDef, opts ExecuteOptions) (*Result, error)
Execute parses inputs, runs middleware, invokes the command, and returns a result.
type ResultOptions ¶
type ResultOptions struct {
// CTA contains suggested follow-up commands.
CTA *CTABlock
// ExitCode overrides the process exit code.
ExitCode int
}
ResultOptions configures ctx.OK.
type RootHelpOptions ¶
type RootHelpOptions struct {
// Aliases are executable aliases.
Aliases []string
// ConfigFlag is the configured config flag.
ConfigFlag string
// Description is shown in the header.
Description string
// Version is shown in the header when set.
Version string
// Commands are listed as subcommands.
Commands []HelpCommand
// Root shows root-only integrations and global flags.
Root bool
// RootCommand is an optional root command.
RootCommand *CommandDef
// EnvSource provides current env values for root command display.
EnvSource map[string]string
// HideGlobalOptions hides global flags.
HideGlobalOptions bool
}
RootHelpOptions configures FormatRoot.
type Segment ¶
type Segment interface {
// contains filtered or unexported methods
}
Segment is a single part of a filter path. Implementations are KeySegment and SliceSegment.
type ServeOptions ¶
type ServeOptions struct {
// Stdin provides input for streaming built-ins such as --mcp.
Stdin io.Reader
// Stdout receives normal command output.
Stdout io.Writer
// Stderr receives diagnostics.
Stderr io.Writer
// Env overrides process environment values.
Env map[string]string
// Cwd overrides the current working directory for config discovery.
Cwd string
// DisplayName overrides the rendered command name.
DisplayName string
// Human overrides TTY detection for readable human output.
Human *bool
}
ServeOptions configures ServeWithOptions.
type SkillFile ¶
type SkillFile struct {
// Dir is the skill directory name.
Dir string
// Name is the skill name.
Name string
// Description is a short description.
Description string
// Content is Markdown content.
Content string
}
SkillFile is a generated skill file.
type SliceSegment ¶
SliceSegment selects a range from an array, equivalent to JavaScript Array.prototype.slice(start, end).
type StreamHandler ¶
type StreamHandler func(ctx *CommandContext) (<-chan any, error)
StreamHandler executes a streaming command. Stream items may be payload values, Result terminal values, or errors.
type SyncOptions ¶
type SyncOptions struct {
// Cwd is the project working directory.
Cwd string
// Depth is the command grouping depth.
Depth int
// Description is the root skill description.
Description string
// Global installs globally unless explicitly false.
Global *bool
// Include contains glob patterns for external skill dirs/files.
Include []string
// RootCommand is an optional root command.
RootCommand *CommandDef
// Suggestions are example prompts shown after sync.
Suggestions []string
// Agents overrides detected agents.
Agents []Agent
}
SyncOptions configures skill syncing.
type SyncResult ¶
type SyncResult struct {
// Skills are generated skill records.
Skills []SyncedSkill
// Paths are canonical install paths.
Paths []string
// Agents are agent-specific install records.
Agents []AgentInstall
}
SyncResult is returned by Sync.
func Sync ¶
func Sync(name string, commands map[string]*CommandEntry, opts SyncOptions) (*SyncResult, error)
Sync generates skill files, installs them, and records metadata.
type SyncedSkill ¶
type SyncedSkill struct {
// Name is the skill name.
Name string
// Description describes the skill.
Description string
// Path is the canonical install path when available.
Path string
}
SyncedSkill describes a synced skill.
type ToolContent ¶
type ToolContent struct {
// Type is usually "text".
Type string `json:"type"`
// Text is content text.
Text string `json:"text"`
}
ToolContent is an MCP content item.
type ToolEntry ¶
type ToolEntry struct {
// Name is the MCP-safe tool name.
Name string
// Command is the full incur command path.
Command string
// Description describes the tool.
Description string
// InputSchema is the merged args/options JSON Schema.
InputSchema *JSONSchema
// OutputSchema describes the result payload.
OutputSchema *JSONSchema
// Def is the command definition.
Def *CommandDef
// Middlewares are middleware inherited from the command path.
Middlewares []MiddlewareFunc
}
ToolEntry is an MCP tool backed by an incur command.
func CollectTools ¶
func CollectTools(commands map[string]*CommandEntry, prefix []string) []ToolEntry
CollectTools recursively collects leaf commands as MCP tools.
type ToolResult ¶
type ToolResult struct {
// Content is MCP text content.
Content []ToolContent `json:"content"`
// IsError marks failed command calls.
IsError bool `json:"isError,omitempty"`
}
ToolResult is an MCP tool call result.
func CallTool ¶
func CallTool(tool *ToolEntry, params map[string]any, opts CallToolOptions) (*ToolResult, error)
CallTool executes a tool call.
type ValidationError ¶
type ValidationError struct {
// Message is a short, human-readable error message.
Message string
// FieldErrors holds per-field validation error details.
FieldErrors []FieldError
// contains filtered or unexported fields
}
ValidationError represents a validation failure, optionally carrying per-field error details.
func NewValidationError ¶
func NewValidationError(opts ValidationErrorOptions) *ValidationError
NewValidationError constructs a ValidationError from the given options.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error returns a human-readable representation. When a cause is present, its message is appended as a "Details:" section.
func (*ValidationError) Unwrap ¶
func (e *ValidationError) Unwrap() error
Unwrap returns the underlying cause, enabling errors.Is/errors.As chain traversal.
type ValidationErrorOptions ¶
type ValidationErrorOptions struct {
Message string
FieldErrors []FieldError
Cause error
}
ValidationErrorOptions holds the parameters for constructing a ValidationError.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
incur
command
Package main provides the incur CLI binary for code generation and tooling.
|
Package main provides the incur CLI binary for code generation and tooling. |
|
Package codegen implements code generation from JSON Schema definitions, producing typed Go structs, validation functions, and command bindings.
|
Package codegen implements code generation from JSON Schema definitions, producing typed Go structs, validation functions, and command bindings. |
|
examples
|
|
|
basic
command
|
|