refactor(cli): symmetric envelope infrastructure (supersedes e623e820)
Re-introduce the agent-first symmetric envelope deleted in commite623e820(2026-05-15). Under the v0.7 constraint that AI agents are primary consumers, the bare-JSON shape can't carry protocol channels (_notice / risk / meta / request_id / profile) that agents need. Errors-on-stderr and typed exit codes frome623e820are preserved; the envelope wraps the success/error payloads on top. - cli/internal/output/envelope.go (new): Envelope / ErrorEnvelope / Meta / ErrDetail / RiskDetail structs; WriteEnvelope + WriteErrorEnvelope writers; PendingNotice plumbing for the open-map _notice channel (reserved infra; producer wiring planned for v0.8). - cli/internal/output/envelope_test.go (new): 7 tests covering success / error / TTY indent / Notice / Risk shapes. - cmdutil.Error extended with RetryCommand (directly-executable argv distinct from prose Hint), RetryAfterSeconds (HTTP Retry-After), *RiskInfo (nested level+action; ErrInternalServer- vs-NotFound distinction), Detail (open structured payload), Silent (suppress stderr emit while preserving Code for ExitCode). - ErrorToDetail single source of envelope.error construction; reused by stderr PrintError, MCP StructuredContent, and batch per-item error path. - WithHint / WithRetryCommand / WithRetryAfter / WithDetail / WithRisk builders. IsCancelled helper. AsError unwrap helper. - defaultHint covers ~21 codes; defaultRetryCommand symmetric counterpart for 6 keyway codes. DefaultHint / DefaultRetryCommand exported wrappers for cross-package callers. - ClassifyHTTPError tightened: rescues HTTP 500 with structured server-side code 1003 (ErrNotFound) into resource.not_found. Server's generic 1007 (ErrInternalServer) bucket stays as server.error — including it would mis-route validation failures (e.g. SQLSTATE 22001) as not-found. - PrintError dual-mode: text/human → prose with code:msg / hint / retry lines; json/ndjson → envelope on stderr. Mode pinned by root PersistentPreRunE via SetFormatMode. resolveFormatEarly() scans argv before cobra dispatch so cobra-side validators (unknown flag, arg-count) still surface as envelope when --format json is in effect. Silent typed errors short-circuit the stderr emit. FlagError mapped to input.invalid_argument for the envelope (exit code stays 2 via FlagError class). - Unknown-subcommand guard installed recursively at the root: parents with subcommands but no Run/RunE get a typed RunE that emits input.unknown_subcommand envelope with detail.{unknown, command_path, available[]} and retry_command "<parent> --help". cobra.ArbitraryArgs bypasses legacyArgs validation so the guard receives unmatched argv. - cmdutil.Error.Error() returns "<code>: <message>[: <cause>]" for chain debugging; ErrorToDetail strips the code prefix from envelope.message since the separate type field carries it (prevents the doubled-prefix "code: code: ..." that agents would see). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §0 / §4
This commit is contained in:
@@ -4,15 +4,42 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
)
|
||||
|
||||
// globalFormatMode tracks the resolved --format value for the current invocation.
|
||||
// Set by cmd/root.go in PersistentPreRunE; used by PrintError to choose text vs envelope.
|
||||
var globalFormatMode string
|
||||
|
||||
// SetFormatMode records the resolved --format mode for the current invocation.
|
||||
// Called by cmd/root.go PersistentPreRunE after FormatOptions.ResolveDefault.
|
||||
func SetFormatMode(mode string) {
|
||||
globalFormatMode = mode
|
||||
}
|
||||
|
||||
// globalProfile tracks the resolved profile name for the current invocation.
|
||||
// Set by cmd/root.go in PersistentPreRunE via SetProfile; read by Emit and
|
||||
// init events to populate envelope.profile / NDJSON init.profile.
|
||||
var globalProfile string
|
||||
|
||||
// SetProfile records the resolved profile name for the current invocation.
|
||||
// Called by cmd/root.go PersistentPreRunE after SetFormatMode.
|
||||
func SetProfile(name string) { globalProfile = name }
|
||||
|
||||
// GetProfile returns the profile name recorded for the current invocation.
|
||||
// Empty string when nothing is configured (omitempty fields suppress the field).
|
||||
func GetProfile() string { return globalProfile }
|
||||
|
||||
// ExitCode maps an error to the documented CLI exit code.
|
||||
// - 0 success
|
||||
// - 1 generic / unknown typed error - fallback bucket: resource.already_exists,
|
||||
// resource.locked, local.*, mcp.*, operation.failed, server.session_create_failed
|
||||
// (workflow-level, see special case below), and any code outside the named
|
||||
// buckets below
|
||||
// - 2 flag / argument problem (cobra parse / unknown subcommand)
|
||||
// - 2 cobra-parse problem (unrecognised flag, arg-count violation) —
|
||||
// typed input.unknown_subcommand from the guard maps to exit 5
|
||||
// (input.* bucket); only ungated cobra prose lands here
|
||||
// - 3 auth.*
|
||||
// - 4 resource.not_found
|
||||
// - 5 input.* (other than confirmation_required)
|
||||
@@ -64,14 +91,31 @@ func ExitCode(err error) int {
|
||||
return 1
|
||||
}
|
||||
|
||||
// PrintError writes err to w (typically stderr) as `code: message\nhint:
|
||||
// ...`. Typed *Error values surface their Hint as a second line so users
|
||||
// see the actionable next-step. Falls through to defaultHint when the
|
||||
// caller didn't set one.
|
||||
// PrintError writes err to w (typically stderr) in dual mode:
|
||||
// - text/human: code: msg\nhint: ...\nretry: ...
|
||||
// - json/ndjson: {ok:false, error:{...}, _notice?:...}
|
||||
//
|
||||
// Mode is read from globalFormatMode (set by root PersistentPreRunE).
|
||||
func PrintError(w io.Writer, err error) {
|
||||
if err == nil || errors.Is(err, SilentError) {
|
||||
return
|
||||
}
|
||||
// Typed *Error with Silent=true suppresses stderr emit while preserving
|
||||
// the Code for ExitCode. Used by batch paths that already wrote per-item
|
||||
// detail to stdout (cmdutil.RunBatch) — emitting a summary envelope on
|
||||
// stderr would duplicate the failure signal.
|
||||
if typed := AsError(err); typed != nil && typed.Silent {
|
||||
return
|
||||
}
|
||||
|
||||
if globalFormatMode == "json" || globalFormatMode == "ndjson" {
|
||||
printErrorEnvelope(w, err)
|
||||
return
|
||||
}
|
||||
printErrorProse(w, err)
|
||||
}
|
||||
|
||||
func printErrorProse(w io.Writer, err error) {
|
||||
fmt.Fprintln(w, err.Error())
|
||||
var typed *Error
|
||||
if errors.As(err, &typed) {
|
||||
@@ -82,9 +126,20 @@ func PrintError(w io.Writer, err error) {
|
||||
if hint != "" {
|
||||
fmt.Fprintf(w, "hint: %s\n", hint)
|
||||
}
|
||||
retry := typed.RetryCommand
|
||||
if retry == "" {
|
||||
retry = defaultRetryCommand(typed.Code)
|
||||
}
|
||||
if retry != "" {
|
||||
fmt.Fprintf(w, "retry: %s\n", retry)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func printErrorEnvelope(w io.Writer, err error) {
|
||||
_ = output.WriteErrorEnvelope(w, ErrorToDetail(err), false)
|
||||
}
|
||||
|
||||
// defaultHint returns a canonical actionable hint for known error codes
|
||||
// when the call site didn't set one. `auth.unauthenticated` always points
|
||||
// at `weknora auth login` - covers the broad surface (auth status / kb
|
||||
@@ -98,9 +153,9 @@ func defaultHint(code ErrorCode) string {
|
||||
case CodeAuthTokenExpired:
|
||||
return "your session expired; run `weknora auth login` to re-authenticate"
|
||||
case CodeAuthForbidden:
|
||||
return "active context lacks permission for this resource"
|
||||
return "active profile lacks permission for this resource"
|
||||
case CodeAuthCrossTenantBlocked, CodeAuthTenantMismatch:
|
||||
return "verify tenant context with `weknora auth status`"
|
||||
return "verify tenant profile with `weknora auth status`"
|
||||
case CodeNetworkError:
|
||||
return "check base URL reachability with `weknora doctor`"
|
||||
case CodeServerIncompatibleVersion:
|
||||
@@ -142,3 +197,30 @@ func defaultHint(code ErrorCode) string {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// defaultRetryCommand returns canonical retry argv for known codes.
|
||||
// Empty string for codes without a stable canonical retry.
|
||||
// Symmetric counterpart to defaultHint.
|
||||
func defaultRetryCommand(code ErrorCode) string {
|
||||
switch code {
|
||||
case CodeAuthUnauthenticated, CodeAuthBadCredential, CodeAuthTokenExpired:
|
||||
return "weknora auth login"
|
||||
case CodeKBIDRequired:
|
||||
return "weknora link"
|
||||
case CodeNetworkError, CodeServerTimeout:
|
||||
return "weknora doctor"
|
||||
case CodeProjectLinkCorrupt:
|
||||
return "weknora link" // 重新绑定
|
||||
case CodeLocalConfigCorrupt:
|
||||
// 删 config + 重 login 是两步;prose hint 已说明,retry argv 留空
|
||||
return ""
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// DefaultHint and DefaultRetryCommand are exported wrappers so that
|
||||
// cross-package callers (MCP handlers, batch envelope helpers) can
|
||||
// resolve hint/retry without duplicating the typed-code → string table.
|
||||
// Avoids drift between cmdutil and copies elsewhere.
|
||||
func DefaultHint(code ErrorCode) string { return defaultHint(code) }
|
||||
func DefaultRetryCommand(code ErrorCode) string { return defaultRetryCommand(code) }
|
||||
|
||||
Reference in New Issue
Block a user