Documentation
¶
Overview ¶
Package contract holds the agent contract that every command shares: exit codes, the error registry, answers and their verdict, modes, and command declarations. docs/north-star/contract.md is the source of truth.
A change to a machine-readable value or a stored format adds a consumer case to compat_test.go that proves the promised meaning holds, as Compatibility in contract.md asks.
Index ¶
- Constants
- Variables
- func AnswerSchema(kind ResultKind, data map[string]any) map[string]any
- func IsDataSchema(schema map[string]any) bool
- func IsDomain(name string) bool
- func IsService(name string) bool
- func IsSlug(slug string) bool
- func Keys(kind ResultKind, data map[string]any) []string
- func ResolveSchema(schema map[string]any) (map[string]any, error)
- type Answer
- type Arg
- type Code
- type Command
- type Effect
- type Effects
- type ExitCode
- type ExtensionAnswer
- type Flag
- type FlagGroup
- type Item
- type KeyEntry
- type Manifest
- func (m Manifest) CheckCatalog(has func(id string) bool) error
- func (m Manifest) Command(path string) (Command, bool)
- func (m Manifest) IsStatus(c Command) bool
- func (m Manifest) Optional(service string) bool
- func (m Manifest) Owns(path []string) bool
- func (m Manifest) Qualifies(c Command) bool
- func (m Manifest) Registry() Registry
- func (m Manifest) Root() []string
- func (m Manifest) Runs(c Command) bool
- func (m Manifest) Slug() string
- type Mode
- type Modes
- type Outcome
- type OwnCode
- type Problem
- type Registry
- type Reply
- type Requirement
- type Requires
- type Result
- type ResultKind
- type RuleError
- type Signal
- type Type
- type ValuesFrom
- type Verdict
Constants ¶
const ManifestFormat = 1
ManifestFormat is the only manifest format that this version reads.
const SchemaDialect = "https://json-schema.org/draft/2020-12/schema"
SchemaDialect is the JSON Schema draft of every schema that ncly describe returns.
const Version = 1
Version is the integer version of the public protocol, carried by every answer as contract_version.
Variables ¶
var ( DryRunFlag = Flag{Name: "dry-run", Shorthand: "n", Summary: "flag.dry_run", Type: TypeBoolean, Default: false} RunIDFlag = Flag{Name: "run-id", Summary: "flag.run_id", Value: "id", Type: TypeString} )
DryRunFlag and RunIDFlag are the flags that a command accepts when its modes set dry_run or recorded, as Global flags in contract.md defines.
var Core = Registry{/* contains filtered or unexported fields */}
Core is the registry of core's own commands.
var GlobalFlags = []Flag{
{Name: "help", Shorthand: "h", Summary: "flag.help"},
{Name: "json", Summary: "flag.json", Env: "NCLY_JSON"},
{Name: "no-input", Summary: "flag.no_input", Env: "NCLY_NO_INPUT"},
{Name: "no-color", Summary: "flag.no_color", Env: "NO_COLOR"},
{Name: "lang", Summary: "flag.lang", Value: "tag", Env: "NCLY_LANG"},
{Name: "verbose", Shorthand: "v", Summary: "flag.verbose", Env: "NCLY_VERBOSE"},
{Name: "version", Summary: "flag.version"},
}
GlobalFlags declares the flags that every command accepts.
var Types = []Type{TypeString, TypeBoolean, TypeInteger, TypeNumber}
Types lists the types of values, in the order of the spec.
Functions ¶
func AnswerSchema ¶ added in v0.18.0
func AnswerSchema(kind ResultKind, data map[string]any) map[string]any
AnswerSchema returns the JSON Schema of a whole answer of a result whose data keys data describes, or nil for a text result. The envelope adds ok, contract_version, errors, warnings, and, for a batch, results, whose items add ok and errors to the item that data's results describes. A success holds the keys that data requires and no error, nor a failed item for a batch, and a failure other than a report's holds at least one error. Unknown keys stay allowed, as Compatibility asks. A nil data describes no key.
func IsDataSchema ¶ added in v0.18.0
IsDataSchema reports whether a resolved schema can describe the data keys of an answer: an object schema whose top level holds only dataKeywords, so that AnswerSchema drops no constraint. The item of a batch's results, when declared, follows the same rule.
func IsDomain ¶
IsDomain reports whether an identity part starts with a lowercase letter and contains only lowercase letters and digits.
func IsService ¶ added in v0.18.0
IsService reports whether name is a service name, as Keys in contract.md defines it: lowercase letters and digits that start with a letter, other than keychain and grants, which name checks of doctor.
func Keys ¶ added in v0.18.0
func Keys(kind ResultKind, data map[string]any) []string
Keys returns the top-level data keys of a successful answer that data describes, sorted: its properties without the keys of the envelope, and results for a batch.
func ResolveSchema ¶ added in v0.18.0
ResolveSchema returns a copy of a schema whose references are resolved within it: each $ref, which must be local, such as #/$defs/item, gives way to the schema that it points to, and $defs goes. Keywords beside a $ref still apply, through allOf. Only the keywords that hold schemas are walked, so a literal value, such as a const that holds $defs, stays as it is. A $schema other than draft 2020-12 at the root, or any $schema below it, a schema that is not valid draft 2020-12, a remote reference, $id, $anchor, $dynamicRef, a reference that points nowhere, a cycle, and a root that resolves to no object are errors.
Types ¶
type Answer ¶
type Answer struct {
Verdict
// contains filtered or unexported fields
}
Answer is a decided outcome, ready to print.
func (Answer) MarshalJSON ¶
MarshalJSON renders ok and contract_version, the command's keys, then results, errors, and warnings when they hold entries.
type Arg ¶
type Arg struct {
Name string
Summary string
// Type is the type of the value. An empty Type means TypeString.
Type Type
Required bool
// Values lists the only accepted values, which completion also offers.
// An empty list accepts any value.
Values []string
// Variadic takes every remaining word. Only the last argument may be
// variadic.
Variadic bool
// ValuesFrom names the list command whose answer completion suggests
// values from, or is nil.
ValuesFrom *ValuesFrom
}
Arg is one positional argument.
type Code ¶
type Code string
Code is a stable machine identifier of an error or a warning.
const ( UsageInvalid Code = "USAGE_INVALID" ConfirmationRequired Code = "CONFIRMATION_REQUIRED" ConfigInvalid Code = "CONFIG_INVALID" ExtensionInvalid Code = "EXTENSION_INVALID" TerminalRequired Code = "TERMINAL_REQUIRED" Runtime Code = "RUNTIME" Temporary Code = "TEMPORARY" Interrupted Code = "INTERRUPTED" Terminated Code = "TERMINATED" NotFound Code = "NOT_FOUND" PrereqMissing Code = "PREREQ_MISSING" CheckTimeout Code = "CHECK_TIMEOUT" AuthMissing Code = "AUTH_MISSING" KeyNotGranted Code = "KEY_NOT_GRANTED" // AuthRejected is a key that a service refused, such as Deepgram // answering 401. AuthRejected Code = "AUTH_REJECTED" // CapabilityUnsupported is a mode or a protocol that the selected // program cannot enforce, such as a harness that cannot turn tools off. CapabilityUnsupported Code = "CAPABILITY_UNSUPPORTED" // ResumeUnsafe is a run that cannot safely continue, because its // evidence is missing, changed, uncertain, or unsupported. ResumeUnsafe Code = "RESUME_UNSAFE" ConfigUnknownKey Code = "CONFIG_UNKNOWN_KEY" ConfigDefaultsUsed Code = "CONFIG_DEFAULTS_USED" KeyringEnvOnly Code = "KEYRING_ENV_ONLY" GrantUnused Code = "GRANT_UNUSED" )
type Command ¶
type Command struct {
// Path holds the words after ncly, such as {"completion"}.
Path []string
Summary string
Args []Arg
Flags []Flag
// FlagGroups bounds how many flags of each group a call may set.
FlagGroups []FlagGroup
// Examples holds full command lines. Commands are never translated.
Examples []string
// Effects holds the effects that the command declares. A nil Effects
// declares none, which permits no assumption: the command may have
// every effect.
Effects *Effects
Modes Modes
Requires Requires
// Config holds the config keys that the command reads, as dotted paths
// under its domain, such as agent.profiles, which covers every key
// beneath it.
Config []string
Result Result
// Doctor marks the status command of a domain, which doctor runs to
// collect the extension's own checks, from M05.
Doctor bool
}
Command declares one command once, for help, completion, validation, and discovery. Text fields hold catalog IDs, never text. The declaration does not describe steps: the domain owns its behavior.
func (Command) DeclaredEffects ¶ added in v0.18.0
DeclaredEffects returns the effects of a command, every effect when it declares none, as Command descriptions in contract.md permits no assumption.
type Effect ¶
type Effect int
Effect is the strongest change an invocation has made so far, from harmless to unsafe to repeat. It covers the whole invocation, including the items of a batch that succeeded.
const ( // NoEffect means nothing changed outside Nicely's cache and the run's // own temporary files. NoEffect Effect = iota // RepeatableEffect means every change is covered by a demonstrated // idempotent operation. RepeatableEffect // NonRepeatableEffect means a second invocation would repeat or conflict // with a change. NonRepeatableEffect // UnknownEffect means a change may have happened, with no known result. UnknownEffect // PaidEffect means a paid request started, even if its response was lost. PaidEffect )
type ExtensionAnswer ¶
type ExtensionAnswer struct {
// Line is the answer as the extension wrote it, on the stream that
// OnStdout names.
Line []byte
// contains filtered or unexported fields
}
ExtensionAnswer is an answer that passed the answer check.
func CheckAnswer ¶
func CheckAnswer(m Manifest, kind ResultKind, r Reply) (ExtensionAnswer, error)
CheckAnswer applies the rules of Answer check in contract.md to the reply of a command of the extension that the manifest declares. A broken rule returns a *RuleError.
func (ExtensionAnswer) Failed ¶
func (a ExtensionAnswer) Failed(lead Problem) ([]byte, error)
Failed renders the answer as a failure that lead decides: ok false, an error with lead's code first, and every other key kept, so the caller keeps the data of the work that happened, as Output in contract.md asks. lead goes first when the answer holds no error with its code.
type Flag ¶
type Flag struct {
Name string
Shorthand string
Summary string
// Value names the value, such as tag. A flag without a value is a switch.
Value string
Env string
// Type is the type of the value. An empty Type means TypeBoolean for a
// switch and TypeString otherwise.
Type Type
Required bool
// Variadic takes several values, one per occurrence of the flag.
Variadic bool
// Values lists the only accepted values. An empty list accepts any value.
Values []string
// Default is the typed default, or nil when none applies. A switch
// defaults to false.
Default any
// ValuesFrom names the list command whose answer completion suggests
// values from, or is nil.
ValuesFrom *ValuesFrom
}
Flag is one flag. Env names the variable with the same effect, for a global flag.
func (Flag) FlagDefault ¶ added in v0.18.0
FlagDefault returns the typed default of a flag: its declared one, false for a switch without one, and nil otherwise.
type FlagGroup ¶ added in v0.18.0
FlagGroup bounds how many of its flags, by long name, a call may set.
type Item ¶
type Item struct {
// Data holds the keys of the item, such as url. It marshals to an object.
Data any
Errors []Problem
}
Item is the result of one input of a batch.
func (Item) MarshalJSON ¶
MarshalJSON renders the item's own ok, its keys, then its errors.
type KeyEntry ¶ added in v0.18.0
type KeyEntry struct {
// Optional marks a key that each command that declares the service
// runs without, such as a harness that falls back to its own login.
Optional bool
}
KeyEntry is a service's entry in the keys table of a manifest, as Manifest in contract.md defines it.
type Manifest ¶
type Manifest struct {
Domain string
Name string
Commands []Command
// Errors holds the own codes in the order that decides which one leads.
Errors []OwnCode
// Programs holds the name of each program that a command may run, the
// keys of the manifest's programs table, sorted.
Programs []string
// Requirements holds the entry of each program, by name, from M05.
Requirements map[string]Requirement
// Keys holds the entry of each service of the keys table, by name, from
// M08.
Keys map[string]KeyEntry
}
Manifest declares an extension's commands and its own error codes, as the Manifest section of contract.md defines.
func ParseManifest ¶
ParseManifest reads an extension manifest and checks every rule of the Manifest section of contract.md, except the catalog IDs, which need the catalog. An empty slug takes the identity that the manifest declares, as for an extension whose manifest is embedded. The versions come first, so a manifest of another format is rejected before its other keys are read.
func (Manifest) CheckCatalog ¶
CheckCatalog reports the first catalog ID of the manifest that the en catalog lacks.
func (Manifest) IsStatus ¶ added in v0.18.0
IsStatus checks the status command under the extension root, as Status command in contract.md defines it. It runs, answers a report, and takes no argument or flag group. Its only own flags are live and timeout, neither required nor limited to values. Live is a switch that defaults to false, and timeout is a string, so each doctor call passes validation. Declared effects neither write nor bill, and network use requires live. It sets no mode.
func (Manifest) Optional ¶ added in v0.18.0
Optional reports whether the keys table marks the key of a service optional.
func (Manifest) Owns ¶ added in v0.23.0
Owns reports whether path is the extension root or one of its descendants.
func (Manifest) Qualifies ¶ added in v0.18.0
Qualifies reports whether a command of the manifest may give completion its values, as Completion values in contract.md defines: a list command that runs, takes no argument, answers an object, and declares effects that neither write user files nor bill. A command of core never qualifies, which the caller checks.
func (Manifest) Registry ¶
Registry returns the registry of the extension that the manifest declares, ordered as Output in contract.md defines: each own code comes after core's codes of its exit, except for exit 1, where the own codes come before RUNTIME. Own warnings use the slug's uppercase prefix with hyphens replaced by underscores.
func (Manifest) Root ¶ added in v0.23.0
Root returns the complete command root that this extension owns.
type Mode ¶
type Mode int
Mode says whether ncly may ask a human questions.
func DetectMode ¶
func DetectMode(stdinTerminal, stdoutTerminal, noInput, json bool, lookupEnv func(string) (string, bool)) Mode
DetectMode applies the Modes section of contract.md. noInput and json are the resolved values of --no-input and --json, each flag over its variable: machine output never waits for a human. A set CI variable, even empty, means a machine runs ncly.
type Modes ¶
Modes lists the execution modes a command supports. A mode it does not declare is unsupported.
type Outcome ¶
type Outcome struct {
// Data holds the command's keys, kept on failure when they still apply,
// such as output_dir. It marshals to an object.
Data any
// Results holds one item per attempted input, in input order. It stays
// nil for a command that does not process several items.
Results []Item
Errors []Problem
Warnings []Problem
Effect Effect
Signal Signal
// HumanNeeded marks a report whose findings need a human, such as a
// failed check of doctor. The report answers ok false and exit 78 on
// stdout, without errors.
HumanNeeded bool
}
Outcome is everything a command reports once its work stops.
type Problem ¶
type Problem struct {
Code Code `json:"code"`
Message string `json:"message"`
Hint string `json:"hint"`
// Next holds the command that Hint names, as words, only when that
// command runs as is. An empty Next leaves the key out.
Next []string `json:"next,omitempty"`
}
Problem is one entry of errors or warnings.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry holds the codes that an answer may use, as Error codes in contract.md defines: core's, and those of the extension that answers. Its error codes compete to lead in its order.
func (Registry) Codes ¶ added in v0.18.0
Codes returns the error codes of the registry, in the order in which they compete to lead, then its warning codes. A warning that only the slug's prefix admits has no entry.
func (Registry) Decide ¶
Decide computes the verdict of an outcome. The order in which failures arrived never changes it.
func (Registry) Exit ¶ added in v0.18.0
Exit returns the exit code that an error code maps to, and whether the registry holds it.
type Reply ¶
type Reply struct {
Exit int
Stdout []byte
// Last is the last line of stderr, the answer of a failure.
Last []byte
}
Reply is what an extension wrote under --json, as core holds it once the extension has exited.
func (Reply) OnStdout ¶
func (r Reply) OnStdout(kind ResultKind) bool
OnStdout reports whether the answer of a command of this kind belongs on stdout: a success, and a report whose findings need a human.
type Requirement ¶ added in v0.18.0
type Requirement struct {
// Conditional marks a program that only some configs or invocations
// need, which doctor never checks.
Conditional bool `toml:"conditional" json:"conditional,omitempty"`
// Version is the oldest version that works, such as 6.0, or empty when
// finding the program is enough.
Version string `toml:"version" json:"version,omitempty"`
// Probe holds the arguments that make the program print its version,
// or nil for the default, --version.
Probe []string `toml:"probe" json:"probe,omitempty"`
// Install holds one install command per package manager, by its name.
Install map[string][]string `toml:"install" json:"install,omitempty"`
}
Requirement is a program's entry in the programs table of a manifest, as Manifest in contract.md defines it.
func (Requirement) ProbeArgs ¶ added in v0.18.0
func (r Requirement) ProbeArgs() []string
ProbeArgs returns the arguments of the version probe.
type Requires ¶ added in v0.18.0
type Requires struct {
// Bins holds names of programs, each a key of the manifest's programs.
Bins []string
// Keys holds service names, as Keys in contract.md defines them.
Keys []string
}
Requires names the programs and the services whose keys a command may need.
type Result ¶
type Result struct {
Kind ResultKind
// Schema is the JSON Schema of the data keys of a normal answer, an
// object schema whose references are resolved, or nil when the
// declaration gives none. AnswerSchema adds the envelope.
Schema map[string]any
// DryRunSchema is the same for the answer of a dry run.
DryRunSchema map[string]any
}
Result describes what a command answers.
type ResultKind ¶
type ResultKind string
ResultKind tells how a command answers, and so how core checks the answer of an extension's command. A manifest that names no kind gets ResultObject.
const ( ResultObject ResultKind = "object" ResultBatch ResultKind = "batch" ResultReport ResultKind = "report" ResultText ResultKind = "text" )
type RuleError ¶
RuleError names the first rule that a manifest or an answer breaks. Rule is the catalog ID of the message that explains it, and Data fills that message.
type Signal ¶
type Signal int
Signal records the signal that stopped an invocation, if any.
func StopSignal ¶
StopSignal names the signal that stopped an invocation: Interrupt for Ctrl-C, and Terminate for any other, such as SIGTERM.
type Type ¶ added in v0.18.0
type Type string
Type is the type of the value of an argument or a flag.
type ValuesFrom ¶ added in v0.18.0
ValuesFrom names where completion finds the values that only an extension knows, as Completion values in contract.md defines: the path of a list command, the key of its answer that holds an array of objects, and the string key of each object to suggest. It only suggests: the command still accepts any value.