Documentation
¶
Index ¶
- Constants
- Variables
- func ApplyHostMutations(out map[string]any)
- func ClassifyMCPResponseText(text string) error
- func ClassifyToolResultContent(content map[string]any) error
- func ExitCode(err error) int
- func HostControlBlock() map[string]any
- func IsPATError(err error) bool
- func IsPATNoPermissionCode(code string) bool
- func NewAPI(message string, opts ...Option) error
- func NewAuth(message string, opts ...Option) error
- func NewDiscovery(message string, opts ...Option) error
- func NewInternal(message string, opts ...Option) error
- func NewValidation(message string, opts ...Option) error
- func PATOpenBrowserValue() bool
- func PrintHuman(w io.Writer, err error) error
- func PrintHumanAt(w io.Writer, err error, v Verbosity) error
- func PrintJSON(w io.Writer, err error) error
- func RejectCRLF(value, fieldName string) error
- func RejectControlChars(value, flagName string) error
- func ResourceName(name string) error
- func SafeInputPath(path string) (string, error)
- func SafeLocalFlagPath(flagName, value string) (string, error)
- func SafeOutputPath(path string) (string, error)
- func SafePath(path string) error
- func SetHostControlProvider(fn func() string)
- func SetPATOpenBrowserProvider(fn func() bool)
- func StripQueryFragment(path string) string
- type Category
- type Error
- type ExitCoder
- type Option
- func WithActions(actions ...string) Option
- func WithCause(err error) Option
- func WithHint(hint string) Option
- func WithOperation(operation string) Option
- func WithRPCCode(code int) Option
- func WithRPCData(data json.RawMessage) Option
- func WithReason(reason string) Option
- func WithRetryable(retryable bool) Option
- func WithServerDiag(diag ServerDiagnostics) Option
- func WithServerKey(serverKey string) Option
- func WithSnapshot(path string) Option
- func WithTraceID(id string) Option
- type PATError
- type RawStderrError
- type ServerDiagnostics
- type Verbosity
Constants ¶
const ExitCodePermission = 4
ExitCodePermission is the process exit code for PAT authorisation failures.
Variables ¶
var ( ErrInvalidResourceName = stderrors.New("invalid resource name") ErrUnsafePath = stderrors.New("unsafe path detected") )
Functions ¶
func ApplyHostMutations ¶ added in v1.0.18
ApplyHostMutations writes the two stderr-JSON fields the host integration contract requires onto out["data"]:
- data.hostControl: present iff the CLI is in host-owned mode (i.e. HostControlBlock returns non-nil); legacy data.callbacks is stripped in the same pass so passive classifier and active retry paths stay byte-for-byte aligned.
- data.openBrowser: always present; reflects the user's PAT browser policy.
Centralizing the two writes here is the single-injection invariant — any caller that produces a PAT-shaped stderr payload (cleanPATJSON, active-retry enrichers, scope-required builders) MUST go through this function instead of writing the fields directly. out["data"] is promoted to map[string]any if missing or of the wrong type.
func ClassifyMCPResponseText ¶ added in v1.0.11
ClassifyMCPResponseText classifies a text response returned by an MCP tool call. Returns a typed error for known gateway auth failures, PAT interceptions, and business-level errors embedded in HTTP-200 JSON bodies.
Check order: DWS gateway > PAT permission > generic business error.
func ClassifyToolResultContent ¶ added in v1.0.11
ClassifyToolResultContent checks a raw MCP tool result content map for DWS gateway auth errors and PAT permission error codes. This is intended for use as the edition.Hooks.ClassifyToolResult callback so the framework's runner returns a typed error before its generic business-error classification.
Check order: DWS gateway auth > PAT permission.
func HostControlBlock ¶ added in v1.0.18
HostControlBlock returns the canonical hostControl map injected into PAT stderr JSON when the CLI is operating in host-owned mode, or nil when it is not. The returned map is safe for the caller to mutate because a new map is constructed on each call.
callbackOwner is kept as a legacy compatibility key for hosts that adopted it before the contract converged on the hostControl single injection point.
func IsPATError ¶ added in v1.0.11
IsPATError reports whether err is a *PATError.
func IsPATNoPermissionCode ¶ added in v1.0.11
IsPATNoPermissionCode reports whether code is a known PAT permission error code.
func NewDiscovery ¶
NewDiscovery returns a discovery-category error.
func NewInternal ¶
NewInternal returns an internal-category error.
func NewValidation ¶
NewValidation returns a validation-category error.
func PATOpenBrowserValue ¶ added in v1.0.18
func PATOpenBrowserValue() bool
PATOpenBrowserValue returns the effective browser-open recommendation to embed in PAT JSON payloads. The open-source fallback is true to preserve historical behavior when no provider is wired.
func PrintHuman ¶
PrintHuman writes a concise human-readable error rendering at normal verbosity.
func PrintHumanAt ¶ added in v1.0.5
PrintHumanAt writes a human-readable error rendering at the given verbosity level.
func RejectCRLF ¶
RejectCRLF rejects strings containing carriage return (\r) or line feed (\n). These characters enable MIME/HTTP header injection and must never appear in header field names, values, Content-ID, or filename parameters.
func RejectControlChars ¶
RejectControlChars rejects C0 control characters (except \t and \n) and dangerous Unicode characters from user input.
Control characters cause subtle security issues:
- Null bytes truncate strings at the C layer
- \r\n enables HTTP header injection
- Unicode Bidi characters allow visual spoofing (e.g. making "report.exe" display as "report.txt")
Tab and newline are allowed as they may appear in legitimate multi-line input.
func ResourceName ¶
func SafeInputPath ¶
SafeInputPath validates an upload/read source path for --file flags. It applies the same rules as SafeOutputPath — rejecting absolute paths, resolving symlinks, and enforcing working directory containment — to prevent an AI Agent from being tricked into reading sensitive files like /etc/passwd.
func SafeLocalFlagPath ¶
SafeLocalFlagPath validates a flag value as a local file path. Empty values and http/https URLs are returned unchanged without validation, allowing the caller to handle non-path inputs (e.g. API keys, URLs) upstream. For all other values, SafeInputPath rules apply. The original relative path is returned unchanged (not resolved to absolute) so upload helpers can re-validate at the actual I/O point via SafeUploadPath.
func SafeOutputPath ¶
SafeOutputPath validates a download/export target path for --output flags. It rejects absolute paths, resolves symlinks to their real location, and verifies the canonical result is still under the current working directory. This prevents an AI Agent from being tricked into writing files outside the working directory (e.g. "../../.ssh/authorized_keys") or following symlinks to sensitive locations.
The returned absolute path MUST be used for all subsequent I/O to prevent time-of-check-to-time-of-use (TOCTOU) race conditions.
func SafePath ¶
SafePath performs basic path validation checking for dangerous patterns. For full security (symlink resolution, CWD containment), use SafeOutputPath or SafeInputPath.
func SetHostControlProvider ¶ added in v1.0.18
func SetHostControlProvider(fn func() string)
SetHostControlProvider wires up the classifier's hostControl injection. It MUST be called once during CLI bootstrap (e.g. from internal/app init()) so that the first cleanPATJSON call observes a valid provider. Passing nil disables injection (useful for isolated tests).
func SetPATOpenBrowserProvider ¶ added in v1.0.18
func SetPATOpenBrowserProvider(fn func() bool)
SetPATOpenBrowserProvider wires the PAT JSON serializer to the current browser policy. Passing nil restores the open-source fallback (true).
func StripQueryFragment ¶
StripQueryFragment removes any ?query or #fragment suffix from a URL path. API parameters must go through structured --params flags, not embedded in the path, to prevent parameter injection and behaviour confusion.
Types ¶
type Category ¶
type Category string
Category represents a stable error class with a documented exit code.
type Error ¶
type Error struct {
Category Category
Message string
Operation string
ServerKey string
Retryable bool
Reason string
Hint string
Actions []string
Snapshot string
RPCCode int `json:"rpc_code,omitempty"`
RPCData json.RawMessage `json:"rpc_data,omitempty"`
ServerDiag ServerDiagnostics `json:"-"`
Cause error `json:"-"`
}
Error is the structured repository-local error model for the Go rewrite.
func (*Error) ExitCode ¶
ExitCode returns the documented process exit code for the error category. exit=4 is reserved exclusively for PATError (see internal/errors/pat.go ExitCodePermission and the exit-code table in docs/reference.md); Discovery therefore uses 6 so hosts can tell "catalog lookup broke" apart from "PAT permission insufficient".
type ExitCoder ¶ added in v1.0.9
type ExitCoder interface {
ExitCode() int
}
ExitCoder is implemented by errors that provide their own exit code. Edition-specific error types (e.g. PATError, CLIError) implement this so the framework can resolve exit codes without importing edition packages.
type Option ¶
type Option func(*Error)
Option mutates a structured error before it is returned.
func WithActions ¶
WithActions records suggested next actions for recovery.
func WithOperation ¶
WithOperation records the operation that failed.
func WithRPCCode ¶
WithRPCCode records the original JSON-RPC error code.
func WithRPCData ¶
func WithRPCData(data json.RawMessage) Option
WithRPCData records the original JSON-RPC error data payload.
func WithReason ¶
WithReason records a stable machine-readable failure reason.
func WithRetryable ¶
WithRetryable marks whether the error can be retried safely.
func WithServerDiag ¶ added in v1.0.5
func WithServerDiag(diag ServerDiagnostics) Option
WithServerDiag attaches server diagnostics to the error.
func WithServerKey ¶
WithServerKey records the server identifier associated with the failure.
func WithSnapshot ¶
WithSnapshot records the recovery snapshot path associated with the failure.
func WithTraceID ¶ added in v1.0.5
WithTraceID records the server-provided trace identifier. Used when only the trace ID is available (e.g. from HTTP headers) without a full ServerDiagnostics struct.
type PATError ¶ added in v1.0.11
type PATError struct {
RawJSON string
}
PATError represents a PAT (Personal Action Token) authorization failure that should be passed through to stderr as raw JSON without any CLI-layer wrapping. The host application parses the JSON to display its own authorization UI. The wire schema is fixed: a single-line, directly json.Unmarshal-able payload of the form {"success":false,"code":<frozen enum>,"data":{...}}.
When the payload includes data.uri, that URL is the authoritative server-provided authorization link. Hosts must treat it as opaque and open it verbatim instead of parsing and reconstructing it locally, because required parameters may live in query, encoded hash, or fragment sections.
func AsPatAuthCheckError ¶ added in v1.0.11
AsPatAuthCheckError extracts a *PATError from an error chain.
func ClassifyPatAuthCheck ¶ added in v1.0.11
ClassifyPatAuthCheck is the open-source fallback that checks a tool-call Content map for PAT permission codes and auth-required codes. Returns a non-nil *PATError when the content carries a recognised PAT/auth error.
type RawStderrError ¶ added in v1.0.9
RawStderrError is implemented by errors that must output raw content directly to stderr, bypassing all CLI formatting (e.g. "Error:" prefix). PAT authorization errors use this to pass JSON through to the desktop runtime.
type ServerDiagnostics ¶ added in v1.0.5
type ServerDiagnostics struct {
TraceID string `json:"trace_id,omitempty"`
ServerErrorCode string `json:"server_error_code,omitempty"`
TechnicalDetail string `json:"technical_detail,omitempty"`
ServerRetryable *bool `json:"server_retryable,omitempty"`
}
ServerDiagnostics holds server-side diagnostic fields extracted from MCP response bodies or HTTP response headers. Fields are populated on a best-effort basis during error construction.
func (ServerDiagnostics) IsEmpty ¶ added in v1.0.5
func (d ServerDiagnostics) IsEmpty() bool
IsEmpty returns true when no diagnostic field has been populated.
type Verbosity ¶ added in v1.0.5
type Verbosity int
Verbosity controls how much detail PrintHuman includes.
const ( // VerbosityNormal shows essential info: error, hint, actions, trace_id, server_code. VerbosityNormal Verbosity = 0 // VerbosityVerbose adds technical_detail, snapshot, execution context. VerbosityVerbose Verbosity = 1 // VerbosityDebug adds all internal diagnostics (category, operation, reason, rpc_code). VerbosityDebug Verbosity = 2 )