Documentation
¶
Index ¶
- Constants
- func ApplyJQ(w io.Writer, payload any, expr string) error
- func EmitResult(cmd *cobra.Command, result CommandResult) (int, error)
- func EmitStoredResult(cmd *cobra.Command) (int, bool, error)
- func ExitCodeForEnvelope(env *Envelope) int
- func NewCount(n int) *int
- func ResetResultStore(ctx context.Context) error
- func ResolveFields(cmd *cobra.Command) string
- func ResolveJQ(cmd *cobra.Command) string
- func SanitizeForTerminal(text string) string
- func SelectFields(payload any, fields []string) any
- func SetCommandRollout(cmd *cobra.Command, state RolloutState)
- func StoreResult(ctx context.Context, result CommandResult) error
- func StoredEmissionState(store *ResultStore) (exitCode int, attempted, emitted, bytesRisk bool)
- func StoredExitCode(store *ResultStore) (int, bool)
- func UsesUnifiedResult(cmd *cobra.Command) bool
- func ValidateResult(result CommandResult) error
- func ValidateRolloutTransition(from, to RolloutState, rollback bool) error
- func ValidateUnifiedFormat(cmd *cobra.Command) error
- func Write(w io.Writer, format Format, payload any) error
- func WriteCommandPayload(cmd *cobra.Command, payload any, fallback Format) error
- func WriteEnvelope(cmd *cobra.Command, env *Envelope, fallback Format) error
- func WriteEnvelopeTo(w io.Writer, env *Envelope, format Format, fields, jq string) error
- func WriteFiltered(w io.Writer, format Format, payload any, fields, jq string) error
- func WriteJSON(w io.Writer, payload any) error
- type CommandResult
- func Failure(info *ErrorInfo, opts ...ResultOption) CommandResult
- func FailureWithExitCode(info *ErrorInfo, exitCode int, opts ...ResultOption) CommandResult
- func Partial(data *PartialData, opts ...ResultOption) CommandResult
- func Pending(data any, operation *OperationInfo, opts ...ResultOption) CommandResult
- func Success(data any, opts ...ResultOption) CommandResult
- func WithOutcome(result CommandResult, outcome Outcome, opts ...ResultOption) CommandResult
- type ContractMode
- type Emitter
- type Envelope
- func EnvelopeFromResult(result CommandResult) (*Envelope, error)
- func NewFailureEnvelope(info *ErrorInfo) *Envelope
- func NewPartialEnvelope(data any) *Envelope
- func NewPendingEnvelope(op *OperationInfo) *Envelope
- func NewPendingEnvelopeForPolling(op *OperationInfo) (*Envelope, error)
- func NewSuccessEnvelope(data any) *Envelope
- type ErrorInfo
- type Format
- type MCPResult
- type Meta
- type OperationInfo
- type Outcome
- type Pagination
- type PartialData
- type PartialFailedEntry
- type PartialUnknownEntry
- type ResultOption
- func WithDryRun() ResultOption
- func WithErrorInfo(info *ErrorInfo) ResultOption
- func WithIdentity(identity string) ResultOption
- func WithMeta(meta *Meta) ResultOption
- func WithOperationTerminalState(state string) ResultOption
- func WithOperationTimedOut(state string) ResultOption
- func WithTablePresentation(renderer func(io.Writer, any) error) ResultOption
- type ResultStore
- type RolloutState
Constants ¶
const ( OperationStateProcessing = "processing" OperationStateCompleted = "completed" OperationStateFailed = "failed" )
operation.state 取值表(B150,契约规范 §2.2):state 描述异步操作所处阶段, 规范值为以下集合(开放枚举——业务特化阶段容忍,但以下三值是 Agent 必须能 分支的最小集)。timed_out:true 禁止与完成态共存(§2.2 规则1,见 OperationInfo.ValidateTimeoutState)。
Variables ¶
This section is empty.
Functions ¶
func ApplyJQ ¶
ApplyJQ applies a jq expression to a JSON-serialisable payload and writes the results to w. Each result value is written as a separate line of JSON.
The expression is compiled once and evaluated against the normalised payload. Multiple result values (e.g. from `.[]`) are each written as indented JSON followed by a newline.
func EmitResult ¶ added in v1.0.58
func EmitResult(cmd *cobra.Command, result CommandResult) (int, error)
EmitResult is the framework 2.0 CLI adapter. Unlike the legacy Emitter, machine-readable JSON/NDJSON always writes the primary result to stdout for every outcome; stderr is diagnostics-only. Human failure formats retain the conventional stderr path. The result is validated before any byte is rendered, and the returned exit code comes from the same immutable result.
func EmitStoredResult ¶ added in v1.0.58
EmitStoredResult is called from PersistentPostRunE before output cleanup.
func ExitCodeForEnvelope ¶ added in v1.0.58
ExitCodeForEnvelope 计算信封对应的进程退出码(B33,AC-10/I2;契约规范 §4)。 纯函数:只读信封字段、不做任何 I/O。映射规则:
- success / pending → 0(I2:exit 0 ⇔ ok;异步受理不是失败,§1/§4);
- partial_failure → 7(部分成功专用码,区别于普通失败,§4);
- failure → 按 Error.Type 类别映射,confirmation_required 子类恒 3;
- nil 信封 → 5(与 WriteEnvelopeTo 的 internal 类兜底信封同源);
- 非法 outcome → 5(非法信封属框架缺陷,归 internal)。
判定只看 outcome / error 类别,不看可能被命令层篡改的 OK 字段(与 IsOK 同口径,I1)。退出码由 runner 出口统一决定、命令层禁止自行 os.Exit (§4 规则);本函数为 Emitter 语义标注、runner 映射与测试提供同一依据。
func NewCount ¶ added in v1.0.58
NewCount 返回 n 的指针,供 Meta.Count 使用, 以区分「count:0」(空结果,必须输出)与「count 缺席」(非列表场景)。
func ResetResultStore ¶ added in v1.0.58
ResetResultStore starts a new command execution on a reusable Cobra tree.
NewRootCommand installs one store in the root context so process-level signal and exit-code tracking can retain a stable pointer. Library callers, however, may call ExecuteC more than once on that same root. Resetting the execution fields before PersistentPreRunE prevents a previous result or emission attempt from leaking into the next invocation while preserving the store identity used by the process boundary.
func ResolveFields ¶
ResolveFields extracts the --fields flag value from the command. It ensures that we do not mistakenly grab a business parameter also named "fields" by matching the flag's usage string against the global root definition.
func ResolveJQ ¶
ResolveJQ extracts the --jq flag value from the command. It ensures that we only grab the global output filter, not a similarly named business parameter.
func SanitizeForTerminal ¶
SanitizeForTerminal strips ANSI escape sequences, control characters, and dangerous Unicode from text before it is printed to a terminal. Delegates to the validate package which provides the canonical implementation.
func SelectFields ¶
SelectFields filters a JSON-serialisable payload to include only the specified field names, following the gh CLI convention:
- If the payload is an array of objects, filter each element.
- If the payload is an object containing a "data list" (a nested array under a well-known key like "value", "items", "data", "records", etc.), filter each element of that list.
- Otherwise, filter top-level keys.
This approach lets callers write `--fields title,memberCount` and get the right result regardless of the response envelope structure. Field names are matched case-insensitively.
func SetCommandRollout ¶ added in v1.0.58
func SetCommandRollout(cmd *cobra.Command, state RolloutState)
func StoreResult ¶ added in v1.0.58
func StoreResult(ctx context.Context, result CommandResult) error
StoreResult records exactly one terminal framework result for this command.
func StoredEmissionState ¶ added in v1.0.58
func StoredEmissionState(store *ResultStore) (exitCode int, attempted, emitted, bytesRisk bool)
StoredEmissionState reports whether result emission was attempted. Once an attempt starts, callers must not try another envelope because a writer may have accepted bytes even when it returned an error.
func StoredExitCode ¶ added in v1.0.58
func StoredExitCode(store *ResultStore) (int, bool)
StoredExitCode returns the code produced by PersistentPostRunE.
func UsesUnifiedResult ¶ added in v1.0.58
func ValidateResult ¶ added in v1.0.58
func ValidateResult(result CommandResult) error
ValidateResult is the mandatory pre-emission policy boundary.
func ValidateRolloutTransition ¶ added in v1.0.58
func ValidateRolloutTransition(from, to RolloutState, rollback bool) error
ValidateRolloutTransition defines the release order for rollout tooling. It is not an end-user capability. CI/ledger enforcement is wired separately.
func ValidateUnifiedFormat ¶ added in v1.0.58
ValidateUnifiedFormat is retained for compatibility. All commands normalize an unknown presentation value to their fallback and emit a diagnostic warning.
func WriteCommandPayload ¶
func WriteEnvelope ¶ added in v1.0.58
WriteEnvelope 是统一信封的出口函数(B0 dev 试点桥接,WS1 改动点2/4)。 它复用 envelope.go 的权威 Envelope 类型,把信封按当前 --format 分发写出。 Phase B 的 Emitter 类型将在此之上泛化(渲染先进 buffer、exit code 映射等); 本函数仅提供 Phase F dev 域迁移所需的「信封 → cmd 流」出口,不重复定义类型。
format 分发(契约规范 §5.2,经 renderEnvelope 实现):
- json(默认):输出完整信封——唯一 JSON 契约(§5.2 首行)。
- table/pretty:业务数据人读视图 + meta 摘要(不输出信封外壳)。
- csv/ndjson:裸记录(无信封);meta.pagination 走 stderr 诊断行。
- raw:数据载荷透传(与 Write 的 raw 语义一致)。
数据出口一律写 cmd.OutOrStdout()、诊断出口写 cmd.ErrOrStderr()(均可被 测试重定向),不硬编码 os.Stdout/os.Stderr。未知 --format 值按 §5.2/AC-09 降级 fallback 并在此向 stderr 写一条 warning(不崩不静默)。
func WriteEnvelopeTo ¶ added in v1.0.58
WriteEnvelopeTo 是 WriteEnvelope 的 writer 级实现(签名自 B205 保持不变), 供不持有 *cobra.Command 的调用方与单测直接使用。B37 起收编到 renderEnvelope 统一分发:json/空 format 输出完整信封(唯一 JSON 契约);table/pretty 输出 业务数据人读视图 + meta 摘要;csv/ndjson 输出裸记录(分页诊断行在本签名下 无 stderr 出口可走,按 io.Discard 处理——需要诊断行的调用方走 WriteEnvelope 的 cmd 路径或 Emitter)。nil 信封降级为 I3 合法的 failure 兜底信封(B208): 携带 internal 类 ErrorInfo——框架最后的兜底不得产出被自身 Validate() 拒绝的形态。
func WriteFiltered ¶
WriteFiltered applies field selection and/or jq filtering before writing the payload. If jq is non-empty, the jq result is written directly (bypassing format). If fields is non-empty, the payload is filtered to those fields before normal output.
Types ¶
type CommandResult ¶ added in v1.0.58
type CommandResult interface {
Outcome() Outcome
ExitCode() int
// Data returns the accepted payload (already deep-copied). The wait
// phase reads it to resolve the resource identifier an event stream
// correlates against.
Data() any
// contains filtered or unexported methods
}
CommandResult is the immutable framework result consumed by CLI and MCP adapters. The unexported envelope method prevents product packages from implementing ad-hoc result shapes.
func Failure ¶ added in v1.0.58
func Failure(info *ErrorInfo, opts ...ResultOption) CommandResult
Failure constructs an immutable typed failure result.
func FailureWithExitCode ¶ added in v1.0.58
func FailureWithExitCode(info *ErrorInfo, exitCode int, opts ...ResultOption) CommandResult
FailureWithExitCode adapts an existing repository error whose historical process status is part of a compatibility contract (for example SIGINT=130). Product handlers must use Failure; only the root legacy-error adapter should call this function.
func Partial ¶ added in v1.0.58
func Partial(data *PartialData, opts ...ResultOption) CommandResult
Partial constructs an immutable multi-status result with exit code 7.
func Pending ¶ added in v1.0.58
func Pending(data any, operation *OperationInfo, opts ...ResultOption) CommandResult
Pending constructs an immutable accepted-but-not-terminal result.
func Success ¶ added in v1.0.58
func Success(data any, opts ...ResultOption) CommandResult
Success constructs an immutable success result.
func WithOutcome ¶ added in v1.0.63
func WithOutcome(result CommandResult, outcome Outcome, opts ...ResultOption) CommandResult
WithOutcome rewraps an existing result with a new outcome, preserving data, meta, identity, and any error info (subject to the opts). The corecmd wait phase uses it to close an accepted result into its terminal (or timed-out pending) outcome; the exit code is re-derived from the new envelope.
type ContractMode ¶ added in v1.0.58
type ContractMode string
ContractMode is an internal renderer identity. It is deliberately not a CLI flag: one command has exactly one externally active contract in one release.
const ( ContractLegacy ContractMode = "legacy" // ContractUnified is the single framework-owned result shape. It is not a // consumer-selectable protocol version: a command either still renders its // historical legacy shape or has been promoted to the unified result. ContractUnified ContractMode = "unified" )
func ActiveContract ¶ added in v1.0.58
func ActiveContract(cmd *cobra.Command) ContractMode
ActiveContract is the only contract exposed by a command in this release.
type Emitter ¶ added in v1.0.58
type Emitter struct {
// contains filtered or unexported fields
}
Emitter 是统一信封的双向出口(B24,WS1 改动点2)。它持有 stdout/stderr 两个 写入目标与当前 format/fields/jq 配置,按契约规范 §5.1 流向纪律把信封分发到 正确的流:
- success / pending / partial_failure → stdout(数据通道);
- failure(含 nil 信封降级)→ stderr,stdout 严格零字节(AC-11)。
每次写出都经过「先渲染进内存 buffer、再一次性写出」(B25,契约规范 §5.2 末条),写一半失败不产生残缺 JSON。渲染复用 WriteEnvelopeTo(B205), Emitter 不重新定义信封类型或 wire 键。
func NewEmitter ¶ added in v1.0.58
NewEmitter 构造 Emitter(B24)。nil writer 按 io.Discard 处理(等价丢弃, 防 panic)。format 是解析后的当前 format(空值由 WriteEnvelopeTo 按 json 处理);fields/jq 为命令解析出的 --fields/--jq 过滤条件。
func (*Emitter) Emit ¶ added in v1.0.58
Emit 按 env 的 outcome 把信封写到对应流(B26/B27/B28,契约规范 §5.1):
- success / pending:完整信封落 stdout(B26,ok:true,§2.1/§2.2);
- partial_failure:三通道明细落 stdout、stderr 零输出(B28,§2.3);
- failure:信封落 stderr、stdout 严格零字节(B27,AC-11);
- nil 信封由 WriteEnvelopeTo 降级为 failure,同样落 stderr。
exit 0 语义标注(B32 收口,契约规范 §4/I2):Emit 的流路由与 ExitCodeForEnvelope 的退出码语义一一对应——落 stdout 的信封 (success/pending/partial_failure 中 ok:true 的前两者)对应 exit 0, 落 stderr 的 failure(含 nil 降级)对应非零退出码。Emitter 只负责写出, 不自行 os.Exit;进程退出码由 runner 出口按同一映射统一决定(§4 规则)。
失败信封恒以完整 JSON 信封渲染并绕过 format/fields/jq:失败信封没有数据 载荷(I3),§5.1 要求 stderr 上的失败信封恒为结构化信封;「非 json 只渲染 data」的分发规则只适用于携带数据的信封。若 --jq 作用于失败信封会把错误 通道过滤为空,Agent 将丢失错误明细,故同样绕过。
type Envelope ¶ added in v1.0.58
type Envelope struct {
// OK 为框架计算值:ok == (outcome ∈ {success, pending})(不变量 I1)。
// 恒序列化(无 omitempty),类型为 bool,禁止字符串布尔。
OK bool `json:"ok"`
// Outcome 仅四值(见 Outcome 常量)。恒序列化。
Outcome Outcome `json:"outcome"`
// Identity 为执行身份(user/app),空则省略(§2.5)。
Identity string `json:"identity,omitempty"`
// DryRun 在 dry-run 预览时为 true,默认省略(§6 场景6)。
DryRun bool `json:"dry_run,omitempty"`
// Data 是业务载荷(L2):强类型 DTO 序列化,禁止手拼 JSON。
// 可为 object 或 array;空数组 [] 是合法载荷(原样序列化,
// 见空结果表达 data:[] + count:0)。
Data any `json:"data,omitempty"`
// Meta 是元数据层(count/operation/pagination),整体 omitempty。
Meta *Meta `json:"meta,omitempty"`
// Error 是失败明细(L1):非空 ⇔ outcome==failure(不变量 I3)。
Error *ErrorInfo `json:"error,omitempty"`
// Notice 是系统级通知注入位(_notice,如升级提示),空则省略。
// 契约仅规定 object 注入位;具体通知 shape 由后续批次定型。
Notice any `json:"_notice,omitempty"`
}
Envelope 是统一输出信封(契约规范 §2 信封结构)。 字段声明顺序对齐 §2.5 字段总表;Go 序列化按声明顺序输出, 由此得到稳定的顶层键顺序(golden 断言的前提)。
func EnvelopeFromResult ¶ added in v1.0.58
func EnvelopeFromResult(result CommandResult) (*Envelope, error)
EnvelopeFromResult returns a detached envelope copy for adapters/tests.
func NewFailureEnvelope ¶ added in v1.0.58
NewFailureEnvelope 构造失败信封(B20,契约规范 §2.4)。 error 非空 ⇔ outcome==failure(I3):info 为 nil 的失败信封无法通过 Validate(),调用侧不得提交;data 必须缺席(I3 字段级推论)。
func NewPartialEnvelope ¶ added in v1.0.58
NewPartialEnvelope 构造部分成功信封(B20,契约规范 §2.3)。 三通道明细(total/succeeded/failed/unknown)进 data,不携带顶层 error。 通道规则(B140/B141/B144 已落盘):推荐以 NewPartialData 装配明细—— 构造期拒绝空 succeeded(全失败禁用 partial_failure);Envelope.Validate 对 *PartialData 载荷追加通道校验(同 id 跨通道互斥、total 对账等)。
func NewPendingEnvelope ¶ added in v1.0.58
func NewPendingEnvelope(op *OperationInfo) *Envelope
NewPendingEnvelope 构造异步受理信封(B19,契约规范 §2.2)。 op 携带 id/state/timed_out/next_command;op 为 nil 时 meta 整体缺席。 轮询超时必须保持 State 真实值并置 TimedOut:true,禁止伪装 success; NextCommand 必须是可直接执行的完整命令(§2.2 规则)。
本构造器保持「构造宽松 + 校验严格」分层(轮6裁决⑨):§2.2 两条硬规则 不在构造期拦截,由 OperationInfo.Validate 与严格装配助手 NewPendingEnvelopeForPolling(B147/B148)把守。
func NewPendingEnvelopeForPolling ¶ added in v1.0.58
func NewPendingEnvelopeForPolling(op *OperationInfo) (*Envelope, error)
NewPendingEnvelopeForPolling 装配轮询形态的 pending 信封(B147 增强, 契约规范 §2.2):比 NewPendingEnvelope 更严格——轮询形态的恢复方式只有 next_command 一条出口,故 op 与 next_command 必须非空且通过可执行形态 校验;state 必须遵守 timed_out 防伪装规则。返回 I1 一致(ok:true/ outcome:pending)的信封;装配失败返回 error(信封为 nil)。
func NewSuccessEnvelope ¶ added in v1.0.58
NewSuccessEnvelope 构造成功信封(B19,契约规范 §2.1)。 OK 由框架按 outcome 计算(I1),调用层不得自行改写。data 必须是强类型 DTO 序列化产物,禁止手拼 JSON(§2.5/§7);空数组 [] 是合法载荷(AC-06)。
func (*Envelope) IsOK ¶ added in v1.0.58
IsOK 计算不变量 I1(B21,契约规范 §1):ok == (outcome ∈ {success, pending})。 这是框架侧的唯一计算函数,命令层不可写或改写该结果;Envelope.OK 字段值 必须与 IsOK 一致(Validate 交叉校验,违反即 I1 缺陷)。 nil 信封视为不 ok:没有结果可言,不得汇报为成功/受理。 非法(非四值)outcome 必然返回 false:I1 只定义在四个规范值上, 非法值由 ParseOutcome/Validate/MarshalJSON 各自拒绝。
func (*Envelope) Validate ¶ added in v1.0.58
Validate 是信封的聚合校验入口(B18,契约规范 §1):一次性收集全部违反项 (errors.Join)而非命中即返回,便于装配侧一轮定位所有契约缺陷。校验项:
- outcome 必须是四个规范值之一(§1/§2.5,复用 ParseOutcome);
- 不变量 I1:OK == (outcome ∈ {success, pending})——框架计算值一致性;
- 不变量 I3:Error 非空 ⇔ outcome == failure(双向);
- I3 字段级推论:data/error 互斥(复用 ValidateDataErrorExclusivity);
- Data 为类型化 *PartialData 时的三通道纪律(对账、非空 succeeded、 id 可标识与跨通道互斥,§2.3;裸 map 等业务载荷形态不做解释)。
outcome 非法时其派生检查(I1/I3)失去判定基准,仅报告 outcome 本身。 Validate 只做静态字段校验,不解释业务载荷内容(L3 真实性归产品命令,§9)。 nil 信封返回 nil:wire 出口(WriteEnvelopeTo)对 nil 已有降级 failure 信封的兜底,类型层不重复拦截。
func (*Envelope) ValidateDataErrorExclusivity ¶ added in v1.0.58
ValidateDataErrorExclusivity 校验 wire 层面的 data/error 互斥(契约规范 §1 不变量 I3 的字段级推论;§2.3/§2.4 形态):error 非空时 data 必须缺席—— 失败信封只承载 error 明细,部分成功明细走 data 且不携带顶层 error。 无违反返回 nil;聚合校验入口(B18 Envelope.Validate)将组合本检查。
type ErrorInfo ¶ added in v1.0.58
type ErrorInfo struct {
Type string `json:"type,omitempty"`
Subtype string `json:"subtype,omitempty"`
ExitCode int `json:"exit_code,omitempty"`
HTTPStatus int `json:"http_status,omitempty"`
UpstreamCode any `json:"upstream_code,omitempty"`
RPCCode int `json:"rpc_code,omitempty"`
Code int `json:"code,omitempty"`
Message string `json:"message,omitempty"`
Hint string `json:"hint,omitempty"`
// Retryable 仅为 true 时出现在 wire(§2.4;重试设计 §2.1):
// bool 零值 false 遇 omitempty 即字段缺席。CLI 不自动重放。
Retryable bool `json:"retryable,omitempty"`
// RetryAfterSeconds 是服务端给出的重试等待秒数。指针类型保留
// 零值语义:0 秒有意义(nil 缺席、&0 序列化为 0),负值应在
// 构造侧拒绝。
RetryAfterSeconds *int64 `json:"retry_after_seconds,omitempty"`
RequestID string `json:"request_id,omitempty"`
TraceID string `json:"trace_id,omitempty"`
Operation string `json:"operation,omitempty"`
ServerKey string `json:"server_key,omitempty"`
Origin string `json:"origin,omitempty"`
Stage string `json:"stage,omitempty"`
ExecutionStarted *bool `json:"execution_started,omitempty"`
NextRetryAt string `json:"next_retry_at,omitempty"`
AvailableFlags []string `json:"available_flags,omitempty"`
SnapshotPath string `json:"snapshot_path,omitempty"`
Details map[string]any `json:"details,omitempty"`
RPCData any `json:"rpc_data,omitempty"`
TechnicalDetail string `json:"technical_detail,omitempty"`
FriendlyHint string `json:"friendly_hint,omitempty"`
ActionURL string `json:"action_url,omitempty"`
Cause string `json:"cause,omitempty"`
// Param/Params 在校验错误时指明违规参数(§2.4)。
Param string `json:"param,omitempty"`
Params []string `json:"params,omitempty"`
// Actions 是可执行的补救命令(门禁拦截 subtype=confirmation_required
// 时携带,含 --yes 版本;§2.4)。
Actions []string `json:"actions,omitempty"`
}
ErrorInfo 是失败信封的错误明细(契约规范 §2.4)。 Type/Subtype/Code/Retryable/RetryAfterSeconds 为 wire-stable(Agent 可分支); Message/Hint/RequestID 为 informational(禁止分支)。
type Format ¶
type Format string
const ( FormatJSON Format = "json" FormatTable Format = "table" FormatRaw Format = "raw" FormatPretty Format = "pretty" // FormatNDJSON emits one JSON object per line — friendly for streaming / // piping list results into downstream tools. See ndjson.go. FormatNDJSON Format = "ndjson" // FormatCSV emits RFC-4180 comma-separated values for list-shaped results — // friendly for spreadsheets and non-technical consumers. See csv.go. FormatCSV Format = "csv" )
func ParseFormat ¶ added in v1.0.58
ParseFormat 把字符串形式的 format 值(来自 --format flag 或 caller 接口) 归一化为 Format 常量;大小写不敏感,未知/空值返回 fallback。它是不持有 *cobra.Command 的调用方(如主漏斗 callMCPToolInternalOpts)的 ResolveFormat 等价物,二者共用同一归一化规则。
func ResolveFormatWithJSONShorthand ¶ added in v1.0.58
ResolveFormatWithJSONShorthand 解析命令的输出 format,实现 --json 简写语义 (B43,契约规范 §5.2:「--json 自动注册为 --format json 简写(显式 --format 优先)」)。优先级链:
- 显式 --format(非空值)恒优先——含未知值(按 normalizeFormat 降级 fallback,--json 不 rescues 未知值);
- --format 缺席或为空时,--json 布尔 flag(Changed 且为 true)等价 --format json;
- 两者皆无 → fallback。
--json 判定只接受 bool 型 flag(GetBool 成功):业务层存在同名 string flag(如 table create --json 载荷参数)的命令不会被误判为简写。本函数 纯判定不做 I/O,供不直接走 WriteEnvelope 的调用方(如主漏斗桥接,B44) 复用;与 resolveFormatWithWarning 共用 formatValueFromFlagSet / normalizeFormat,归一化规则单一事实源。
type MCPResult ¶ added in v1.0.58
type MCPResult struct {
StructuredContent map[string]any `json:"structuredContent"`
IsError bool `json:"isError,omitempty"`
}
MCPResult is the protocol-neutral projection consumed by MCP transports. Both CLI and MCP adapters start from the same immutable CommandResult; MCP handlers must not rebuild a second business envelope.
func AdaptMCP ¶ added in v1.0.58
func AdaptMCP(result CommandResult) (*MCPResult, error)
AdaptMCP projects the exact unified envelope into MCP structuredContent. Failure and partial failure set isError, while pending remains a successfully accepted request whose terminal operation state is carried in the envelope.
type Meta ¶ added in v1.0.58
type Meta struct {
// Count 是列表结果条数。指针类型区分「未设置」与「0 条」:
// 空结果场景必须显式输出 count:0(§3 / AC-06),
// nil 时字段缺席(omitempty)。
Count *int `json:"count,omitempty"`
// Operation 是异步操作信息(pending 信封,§2.2)。
Operation *OperationInfo `json:"operation,omitempty"`
// Pagination 是分页元数据(§3)。
Pagination *Pagination `json:"pagination,omitempty"`
}
Meta 是信封元数据层(契约规范 §2.5)。 分页/异步操作元数据挂 meta 层而非 data 层(§3)。
type OperationInfo ¶ added in v1.0.58
type OperationInfo struct {
ID string `json:"id,omitempty"`
State string `json:"state,omitempty"`
TimedOut bool `json:"timed_out,omitempty"`
NextCommand string `json:"next_command,omitempty"`
}
OperationInfo 是异步操作元数据(契约规范 §2.2)。 轮询超时必须保持 State 真实值并置 TimedOut:true,禁止伪装 success; NextCommand 必须是可直接执行的完整命令(恢复方式)。
func (*OperationInfo) Validate ¶ added in v1.0.58
func (op *OperationInfo) Validate() error
Validate 聚合 operation 的 §2.2 形态校验。必填字段由新框架的 CommandResult 边界校验;这里保持旧 Envelope 构造 API 的兼容性。
func (*OperationInfo) ValidateNextCommand ¶ added in v1.0.58
func (op *OperationInfo) ValidateNextCommand() error
ValidateNextCommand 校验 next_command 的可执行形态(B148,契约规范 §2.2 规则2「next_command 必须是可直接执行的完整命令」):非空时必须是无前后 空白、不含换行的单行命令串——这是框架侧对「可直接执行」的形态代理; 命令真实可执行性(命令存在、参数有效)归装配侧保证(§9)。 空串在此不拦截:omitempty wire 允许无 operation 明细的裸 pending 信封, 轮询形态装配 NewPendingEnvelopeForPolling 才要求非空。
func (*OperationInfo) ValidateTimeoutState ¶ added in v1.0.58
func (op *OperationInfo) ValidateTimeoutState() error
ValidateTimeoutState 执行 §2.2 规则1 的防伪装校验(B149):轮询超时必须 保持 state 真实值并置 timed_out:true——TimedOut 时 State 必须非空(真实值 必报),且不得宣称任何完成态(completed/success):超时操作宣称完成态 即伪装 success(对齐 lark wiki_node_delete 教训)。
type Outcome ¶ added in v1.0.58
type Outcome string
Outcome 是一次 CLI 调用的结果类别(互斥,四值)。 门禁拦截(confirmation_required)是 failure 的子类,不占第五值 (契约规范 §1 结果总图)。
const ( OutcomeSuccess Outcome = "success" OutcomePending Outcome = "pending" OutcomePartialFailure Outcome = "partial_failure" OutcomeFailure Outcome = "failure" )
四个规范 Outcome 值。wire 值恒为这些小写字符串(契约规范 §2.5)。
func ParseOutcome ¶ added in v1.0.58
ParseOutcome 严格解析 s 为 Outcome:仅接受四个小写规范值, 拒绝大小写变体、前后空白与空串(契约规范 §1)。
func (Outcome) MarshalJSON ¶ added in v1.0.58
MarshalJSON 把 Outcome 序列化为小写规范字符串。仅接受四个规范值, 非法值(含零值)在序列化期即报错,杜绝静默产出无效 wire 值 (契约规范 §1/§2.5「仅四值」)。
type Pagination ¶ added in v1.0.58
type Pagination struct {
EndpointExhausted bool `json:"endpoint_exhausted"`
Pages int `json:"pages,omitempty"`
Items int `json:"items,omitempty"`
NextToken string `json:"next_token,omitempty"`
}
Pagination 是分页元数据(契约规范 §3)。 EndpointExhausted 仅表示「观察到服务端分页耗尽」,不承诺索引健康或 数据全覆盖;弃用 complete 键。EndpointExhausted:false 必须携带 NextToken(可续跑)——两者合起来即全部状态,不设 stop_reason。 EndpointExhausted 不加 omitempty:true/false 两态都必须在 wire 上显式出现。
func NewPagination ¶ added in v1.0.58
func NewPagination(endpointExhausted bool, nextToken string) (*Pagination, error)
NewPagination 装配分页元数据(B152,契约规范 §3):两态完备校验—— endpoint_exhausted:false 必须携带 next_token(可续跑:无 token 则 「可续跑」不可表达,破坏 §3 两态完备性);endpoint_exhausted:true 不得携带 next_token(耗尽即无续跑凭据,两者合起来即全部状态, 不设 stop_reason)。Pages/Items 为信息性计数(omitempty),由调用方 按观察到的页数/条数在返回结构上另行设置。
func (*Pagination) Validate ¶ added in v1.0.58
func (p *Pagination) Validate() error
type PartialData ¶ added in v1.0.58
type PartialData struct {
Total int `json:"total"`
Succeeded []any `json:"succeeded"`
Failed []PartialFailedEntry `json:"failed"`
Unknown []PartialUnknownEntry `json:"unknown"`
}
PartialData 是部分成功三通道明细的类型化形态(B139,契约规范 §2.3), 整体放入 Envelope.Data。声明顺序 = wire 顺序:total/succeeded/failed/ unknown(对齐契约示例)。三通道纪律(B140/B141/B144/B146)由 NewPartialData 构造期校验 + Validate 集中复验:
- succeeded 必须完整保留(构造器不接受丢弃明细,§2.3 规则1);
- unknown 条目禁止归入 succeeded/failed(同一 id 跨通道互斥,§2.3 规则2);
- 空 succeeded 禁用 partial_failure(全失败必须用普通 failure,§2.3 规则4)。
三个切片字段不带 omitempty:空通道以 [] 显式表达(不输出 null, §2.5 无 null 纪律),与 data:[] 空态合法载荷同口径。
func NewPartialData ¶ added in v1.0.58
func NewPartialData(total int, succeeded []any, failed []PartialFailedEntry, unknown []PartialUnknownEntry) (*PartialData, error)
NewPartialData 装配三通道明细(B139/B140/B141/B144/B146,契约规范 §2.3)。 装配期即校验通道纪律:
- succeeded 非空且原样保留——空 succeeded 的 partial_failure 被拒绝 (全部失败必须用 outcome:failure,§2.3 规则4;B141);构造器不丢弃、 不过滤任何 succeeded 条目(B146:Agent 需要知道哪些已生效,避免重复提交);
- failed/unknown 条目 id 必须非空(条目可标识是跨通道互斥的唯一依据); unknown 条目 reason 必须非空(诚实通道必须说明不确定原因,B144);
- 同一 id 不得跨通道或同通道重复出现——一个条目只有一个终态通道 (「unknown 禁止归入 succeeded/failed」,§2.3 规则2;B140)。succeeded 条目是异构业务 DTO,其 id 按 JSON 泛化形态的 "id" 键提取;无 id 或非 object 的条目不参与互斥判定(框架不解释业务载荷内容,§9);
- total 对账:total == len(succeeded)+len(failed)+len(unknown)—— 三通道明细是 total 的完整划分,不允许出现无明细的条目。
nil 的 failed/unknown 入参归一为空切片(空通道 wire 上是 [] 而非 null)。
func (*PartialData) Validate ¶ added in v1.0.58
func (d *PartialData) Validate() error
Validate 校验三通道纪律(B140)。NewPartialData 构造期已校验;本方法供 手工装配形态(绕过构造器)集中复验,并由 Envelope.Validate 在 outcome==partial_failure 且 Data 为 *PartialData 时聚合调用。
type PartialFailedEntry ¶ added in v1.0.58
PartialFailedEntry 是 partial 失败通道的单条明细(B139,契约规范 §2.3): id 标识条目,Error 携带该条目的失败明细(复用 §2.4 ErrorInfo 形态, wire-stable 字段组可供 Agent 分支)。
type PartialUnknownEntry ¶ added in v1.0.58
PartialUnknownEntry 是 partial unknown 通道的单条明细(B144,契约规范 §2.3/P0#9「报错却写入」类问题的诚实通道):shape = id + reason—— 已提交但终态无法确认的条目放这里;reason 必须非空,说明不确定的原因。
type ResultOption ¶ added in v1.0.58
type ResultOption struct {
// contains filtered or unexported fields
}
ResultOption enriches a result without exposing mutable framework fields.
func WithDryRun ¶ added in v1.0.58
func WithDryRun() ResultOption
func WithErrorInfo ¶ added in v1.0.63
func WithErrorInfo(info *ErrorInfo) ResultOption
WithErrorInfo replaces the error info of the envelope. Used when a wait phase closes an accepted result into failure: envelope invariant I3 requires an error iff the outcome is failure.
func WithIdentity ¶ added in v1.0.58
func WithIdentity(identity string) ResultOption
func WithMeta ¶ added in v1.0.58
func WithMeta(meta *Meta) ResultOption
func WithOperationTerminalState ¶ added in v1.0.63
func WithOperationTerminalState(state string) ResultOption
WithOperationTerminalState closes the envelope's async operation at the observed terminal status (契约规范 §2.2: 终态封装必须同步 operation.state — a success or failure close that kept the acceptance-phase state would emit a self-contradicting envelope such as outcome=success with operation.state=processing). The declared id / next_command facts are kept as the operation identity, and timed_out is cleared: the §2.2 anti-spoof rule forbids a timed-out claim on an operation that reached a terminal state. A result without operation info is left untouched.
func WithOperationTimedOut ¶ added in v1.0.63
func WithOperationTimedOut(state string) ResultOption
WithOperationTimedOut marks the envelope's async operation as timed out at the last observed state, preserving the declared id / next_command resume facts (契约规范 §2.2: 超时必须保持 State 真实值并置 TimedOut:true). A result without operation info keeps nil — the pending envelope invariant then fails at emission, surfacing the leaf bug instead of synthesizing fake resume facts.
func WithTablePresentation ¶ added in v1.0.62
func WithTablePresentation(renderer func(io.Writer, any) error) ResultOption
WithTablePresentation preserves a command-specific human table view while keeping JSON, jq and alternate formats on the same framework-owned result. The renderer receives only the immutable business data and writes through the emitter's buffer-first path; it must not perform business I/O.
type ResultStore ¶ added in v1.0.58
type ResultStore struct {
// contains filtered or unexported fields
}
ResultStore transfers a successful in-memory result through Cobra without pretending it is an error. The root PersistentPostRunE emits the result before closing output sinks, so normal cleanup always runs.
func WithResultStore ¶ added in v1.0.58
func WithResultStore(ctx context.Context) (context.Context, *ResultStore)
type RolloutState ¶ added in v1.0.58
type RolloutState string
RolloutState is internal release metadata. Consumers never select it. A command advances through validation and activation; rollback is performed by changing the command declaration/release, not by changing Agent argv.
const ( RolloutLegacyOnly RolloutState = "legacy_only" RolloutDualValidate RolloutState = "dual_validate" RolloutUnifiedActive RolloutState = "unified_active" RolloutUnifiedStable RolloutState = "unified_stable" RolloutUnifiedOnly RolloutState = "unified_only" )
func CommandRollout ¶ added in v1.0.58
func CommandRollout(cmd *cobra.Command) RolloutState
CommandRollout fails closed. Merely linking the unified result framework cannot change an undeclared command's wire contract.
func ParseRolloutState ¶ added in v1.0.58
func ParseRolloutState(raw string) (RolloutState, error)