contract

package
v0.18.3 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 15 Imported by: 0

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

View Source
const ManifestFormat = 1

ManifestFormat is the only manifest format that this version reads.

View Source
const SchemaDialect = "https://json-schema.org/draft/2020-12/schema"

SchemaDialect is the JSON Schema draft of every schema that ncly describe returns.

View Source
const Version = 1

Version is the integer version of the public protocol, carried by every answer as contract_version.

Variables

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

View Source
var Core = Registry{/* contains filtered or unexported fields */}

Core is the registry of core's own commands.

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

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

func IsDataSchema(schema map[string]any) bool

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

func IsDomain(name string) bool

IsDomain reports whether name can be a domain: lowercase letters and digits that start with a letter.

func IsService added in v0.18.0

func IsService(name string) bool

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

func ResolveSchema(schema map[string]any) (map[string]any, error)

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

func (a Answer) Errors() []Problem

Errors returns the errors, the leading one first.

func (Answer) MarshalJSON

func (a Answer) MarshalJSON() ([]byte, error)

MarshalJSON renders ok and contract_version, the command's keys, then results, errors, and warnings when they hold entries.

func (Answer) OK

func (a Answer) OK() bool

func (Answer) Warnings

func (a Answer) Warnings() []Problem

func (Answer) WriteJSON

func (a Answer) WriteJSON(stdout, stderr io.Writer) error

WriteJSON prints the answer as one line: on stdout for a success or a report, and at the end of stderr for an answer with errors, after any diagnostics.

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.

func (Arg) ArgType added in v0.18.0

func (a Arg) ArgType() Type

ArgType returns the type of an argument's value.

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"
	KeyringUnavailable   Code = "KEYRING_UNAVAILABLE"
	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"
)

func (Code) Exit

func (c Code) Exit() (ExitCode, bool)

Exit returns the exit code that one of core's error codes maps to, and false for any other code.

func (Code) IsWarning

func (c Code) IsWarning() bool

IsWarning reports whether c is one of core's warning codes.

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

func (c Command) DeclaredEffects() Effects

DeclaredEffects returns the effects of a command, every effect when it declares none, as Command descriptions in contract.md permits no assumption.

func (Command) ModeFlags added in v0.18.0

func (c Command) ModeFlags() []Flag

ModeFlags returns the flags that the modes of a command add after its own: --dry-run for dry_run, then --run-id for recorded.

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 Effects

type Effects struct {
	UserWrites bool
	Network    bool
	Paid       bool
}

Effects lists every effect a command can have.

type ExitCode

type ExitCode int

ExitCode is the process exit status of an invocation.

const (
	ExitOK          ExitCode = 0
	ExitRuntime     ExitCode = 1
	ExitUsage       ExitCode = 2
	ExitTemporary   ExitCode = 75
	ExitHuman       ExitCode = 78
	ExitInterrupted ExitCode = 130
	ExitTerminated  ExitCode = 143
)

func (ExitCode) Known

func (e ExitCode) Known() bool

Known reports whether e is one of the exit codes of the contract.

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

func (f Flag) FlagDefault() any

FlagDefault returns the typed default of a flag: its declared one, false for a switch without one, and nil otherwise.

func (Flag) FlagType added in v0.18.0

func (f Flag) FlagType() Type

FlagType returns the type of a flag's value.

type FlagGroup added in v0.18.0

type FlagGroup struct {
	Flags    []string
	Min, Max int
}

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

func (it Item) MarshalJSON() ([]byte, error)

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

func ParseManifest(data []byte, domain string) (Manifest, error)

ParseManifest reads the manifest of the extension of a domain and checks every rule of the Manifest section of contract.md, except the catalog IDs, which need the catalog. An empty domain takes the one 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

func (m Manifest) CheckCatalog(has func(id string) bool) error

CheckCatalog reports the first catalog ID of the manifest that the en catalog lacks.

func (Manifest) Command

func (m Manifest) Command(path string) (Command, bool)

Command returns the declaration of a path, such as "hello run".

func (Manifest) IsStatus added in v0.18.0

func (m Manifest) IsStatus(c Command) bool

IsStatus reports whether a command qualifies as the status command of its domain, as Status command in contract.md defines it: the domain followed by status, which runs, answers a report, takes no argument and no flag group, has live and timeout as its only own flags, neither required nor limited to values, with live a switch that defaults to false and timeout a string, so each call that doctor builds passes validation, declares effects that neither write nor bill, and live when they use the network, and sets no mode.

func (Manifest) Optional added in v0.18.0

func (m Manifest) Optional(service string) bool

Optional reports whether the keys table marks the key of a service optional.

func (Manifest) Qualifies added in v0.18.0

func (m Manifest) Qualifies(c Command) bool

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

func (m Manifest) Registry() 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. Every warning that starts with the domain and an underscore belongs to the extension too.

func (Manifest) Runs

func (m Manifest) Runs(c Command) bool

Runs reports whether a command starts the extension. The domain alone prints its help, as Usage in contract.md says, and so does a command with children and no arguments, which only groups them.

type Mode

type Mode int

Mode says whether ncly may ask a human questions.

const (
	NonInteractive Mode = iota
	Interactive
)

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

type Modes struct {
	DryRun   bool
	Recorded bool
	Resume   bool
}

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 OwnCode

type OwnCode struct {
	Code Code
	Exit ExitCode
}

OwnCode is an error code that an extension declares.

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

func (r Registry) Codes() []Code

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 domain's prefix admits has no entry.

func (Registry) Decide

func (r Registry) Decide(o Outcome) Verdict

Decide computes the verdict of an outcome. The order in which failures arrived never changes it.

func (Registry) Exit added in v0.18.0

func (r Registry) Exit(c Code) (ExitCode, bool)

Exit returns the exit code that an error code maps to, and whether the registry holds it.

func (Registry) Finish

func (r Registry) Finish(o Outcome, summarize func(Code) Problem) Answer

Finish decides an outcome and puts an error with the verdict's code first. When no error carries that code, as for an incomplete batch or a signal, summarize supplies one in the active language.

func (Registry) IsWarning added in v0.18.0

func (r Registry) IsWarning(c Code) bool

IsWarning reports whether c is a warning code of the registry.

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

type RuleError struct {
	Rule string
	Data map[string]any
}

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.

func (*RuleError) Error

func (e *RuleError) Error() string

type Signal

type Signal int

Signal records the signal that stopped an invocation, if any.

const (
	NoSignal Signal = iota
	Interrupt
	Terminate
)

func StopSignal

func StopSignal(sig os.Signal) Signal

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.

const (
	TypeString  Type = "string"
	TypeBoolean Type = "boolean"
	TypeInteger Type = "integer"
	TypeNumber  Type = "number"
)

func (Type) Reads added in v0.18.0

func (t Type) Reads(word string) bool

Reads reports whether a word, as a command line gives it, is a value of the type: any word for a string, and a finite number for a number, since JSON has no NaN or infinity.

type ValuesFrom added in v0.18.0

type ValuesFrom struct {
	Command []string
	Key     string
	Field   string
}

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.

type Verdict

type Verdict struct {
	Exit ExitCode
	Lead Code
}

Verdict is the exit code of an outcome and the code of its leading error.

Jump to

Keyboard shortcuts

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