helpers

package
v1.0.63 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: Apache-2.0 Imports: 102 Imported by: 0

Documentation

Overview

Copyright 2026 Alibaba Group Licensed under the Apache License, Version 2.0.

Copyright 2026 Alibaba Group Licensed under the Apache License, Version 2.0.

Copyright 2026 Alibaba Group SPDX-License-Identifier: Apache-2.0

Copyright 2026 Alibaba Group SPDX-License-Identifier: Apache-2.0

Copyright 2026 Alibaba Group Licensed under the Apache License, Version 2.0 (the "License");

Index

Constants

View Source
const (
	ExitSuccess    = 0
	ExitAPI        = 1
	ExitAuth       = 2
	ExitValidation = 3
	ExitPermission = 4
	ExitInternal   = 5
)
View Source
const (
	CodeAuthNotConfigured  = "AUTH_NOT_CONFIGURED"
	CodeAuthTokenExpired   = "AUTH_TOKEN_EXPIRED"
	CodeAuthPermission     = "AUTH_PERMISSION_DENIED"
	CodeNetworkTimeout     = "NETWORK_TIMEOUT"
	CodeNetworkUnreachable = "NETWORK_UNREACHABLE"
	CodeLockTimeout        = "LOCK_TIMEOUT"
	CodeResourceNotFound   = "RESOURCE_NOT_FOUND"
	CodeTableNotFound      = "TABLE_NOT_FOUND"
	CodeSheetNotFound      = "SHEET_NOT_FOUND"
	CodeFieldNotFound      = "FIELD_NOT_FOUND"
	CodeRecordNotFound     = "RECORD_NOT_FOUND"
	CodeInvalidJSON        = "INPUT_INVALID_JSON"
	CodeInvalidPath        = "INPUT_INVALID_PATH"
	CodeInputTooLarge      = "INPUT_TOO_LARGE"
	CodeMissingParam       = "INPUT_MISSING_PARAM"
	CodeInvalidParam       = "INPUT_INVALID_PARAM"
	CodeFileNotFound       = "INPUT_FILE_NOT_FOUND"
	CodeFileAlreadyExists  = "INPUT_FILE_ALREADY_EXISTS"
	CodeContentTruncated   = "CONTENT_TRUNCATED"
	CodeMCPServerError     = "MCP_SERVER_ERROR"
	CodeMCPToolError       = "MCP_TOOL_ERROR"
	CodeUnclassified       = "UNCLASSIFIED"
)
View Source
const (
	// LeafString 字符串 flag(默认)。
	LeafString = corecmd.KindString
	// LeafInt 整型 flag;仅在值 != 0 时进入 toolArgs(putInt 语义)。
	LeafInt = corecmd.KindInt
	// LeafBool 布尔 flag;仅在用户显式提供(Changed)时进入 toolArgs,显式
	// false 也下发;不参与别名/env 回退链。
	LeafBool = corecmd.KindBool
	// LeafStringSlice 字符串列表 flag;仅在存在非空元素时进入 toolArgs,元素
	// 恒 TrimSpace 后过滤空串。
	LeafStringSlice = corecmd.KindStringSlice
)
View Source
const (
	// LeafAtLeastOne 要求 Flags 至少提供一个。
	LeafAtLeastOne = corecmd.AtLeastOne
	// LeafExactlyOne 要求 Flags 必须且只能提供一个。
	LeafExactlyOne = corecmd.ExactlyOne
	// LeafMutuallyExclusive 允许 Flags 中最多提供一个。
	LeafMutuallyExclusive = corecmd.MutuallyExclusive
)
View Source
const (
	// DefaultMarkdownChunkRunes is the single source of truth for the markdown
	// append-mode chunk limit (rune count), shared by every write path that
	// chunks. The splitter budgets any injected repair (a re-emitted table
	// header, a reopened fence) against this limit, so a repaired chunk is still
	// guaranteed to be at most this many runes.
	DefaultMarkdownChunkRunes = 30000
)
View Source
const (
	FlagPrincipalUserID = "principal-user-id"
)

FlagPrincipalUserID is the persistent flag that enables doc-business delegation auth: when set, the first invocation of each doc-business tool key per node within a session is gated by a check_capability verification on behalf of the principal. Granting the capability to the current logged-in identity is an out-of-band action performed by the principal; the CLI never calls grant_capability.

View Source
const MaxBlockIDsPerDelete = 50

MaxBlockIDsPerDelete caps one batch delete. The backend validator enforces the same limit; this front check exists so an oversized request fails locally with an actionable message instead of after a round trip.

View Source
const RoleConfigExample = `` /* 858-byte string literal not displayed */

RoleConfigExample is a complete, copy-pasteable role definition users can follow when authoring their own. It is also parsed in tests to keep the example honest against the schema.

View Source
const RuntimeDefaultCorpID = "$corpId"

RuntimeDefaultCorpID is the runtimeDefault placeholder key for the current logged-in enterprise corpId. It is the single source of truth shared by the registration chain (internal/app registers a resolver under this key) and the read chain (resolveCurrentCorpID looks it up here), so both sides always agree. Changing the placeholder string in this one place updates both.

Variables

This section is empty.

Functions

func AITableQueryWithView added in v1.0.62

func AITableQueryWithView(ctx context.Context, params map[string]any, viewID string, restrict bool) (map[string]any, error)

AITableQueryWithView compiles an exact view's filter/sort into query_records arguments. Reads use explicit query options in preference to view defaults; writes intersect the view with the explicit selector and never widen scope. A view ID is never forwarded as an unsupported query_records parameter.

func AddPagedMCPFlags added in v1.0.58

func AddPagedMCPFlags(cmd *cobra.Command)

func AitableFormShareGetResultSpec added in v1.0.63

func AitableFormShareGetResultSpec() *contract.ResultSpec

AitableFormShareGetResultSpec is shared by the atomic command and its Shortcut alias.

func AitableFormShareUpdateResult added in v1.0.63

func AitableFormShareUpdateResult(data any, request map[string]any) output.CommandResult

AitableFormShareUpdateResult is the shared terminal projection for atomic and shortcut writes. It takes the whole update request: IDs must match exactly because another form's remote response is not proof of CP convergence for the requested target, and an explicitly requested value that the response echoes differently is not the update that was asked for.

func AitableFormShareUpdateResultSpec added in v1.0.63

func AitableFormShareUpdateResultSpec() *contract.ResultSpec

AitableFormShareUpdateResultSpec is shared by the atomic command and its Shortcut alias.

func AnnotateViewUpdateError added in v1.0.63

func AnnotateViewUpdateError(err error) error

AnnotateViewUpdateError 仅在服务端返回 INVALID_UPDATE_VIEW_REQUEST(视图类型与所传配置块 不匹配)时,补充与本地 requireViewType 一致口径的排错建议,避免出现两套说法;其余错误原样 返回,不重试、不改控制流。

func AtomicWrite

func AtomicWrite(path string, data []byte, perm os.FileMode) error

AtomicWrite writes data to path atomically by creating a temp file in the same directory, writing and fsyncing the data, then renaming over the target. It replaces os.WriteFile for all config and download file writes.

os.WriteFile truncates the target before writing, so a process kill (CI timeout, OOM, Ctrl+C) between truncate and completion leaves the file empty or partial. AtomicWrite avoids this: on any failure the temp file is cleaned up and the original file remains untouched.

func AtomicWriteFromReader

func AtomicWriteFromReader(path string, reader io.Reader, perm os.FileMode) (int64, error)

AtomicWriteFromReader atomically copies reader contents into path.

func AtomicWriteJSON

func AtomicWriteJSON(path string, data []byte) error

AtomicWriteJSON is a convenience wrapper for writing JSON data atomically. It uses 0600 permissions by default for sensitive data.

func BuildAddDimensionArgs added in v1.0.48

func BuildAddDimensionArgs(input map[string]any) map[string]any

BuildAddDimensionArgs converts CLI flags to MCP params for add_dimension.

func BuildBatchCreateCondFormatArgs added in v1.0.61

func BuildBatchCreateCondFormatArgs(input map[string]any) (map[string]any, error)

func BuildBatchCreateFilterArgs added in v1.0.61

func BuildBatchCreateFilterArgs(input map[string]any) (map[string]any, error)

func BuildBatchCreateFilterViewArgs added in v1.0.61

func BuildBatchCreateFilterViewArgs(input map[string]any) (map[string]any, error)

func BuildBatchCreateFloatImageArgs added in v1.0.61

func BuildBatchCreateFloatImageArgs(input map[string]any) (map[string]any, error)

func BuildBatchCreateSheetArgs added in v1.0.61

func BuildBatchCreateSheetArgs(input map[string]any) (map[string]any, error)

func BuildBatchDeleteCondFormatArgs added in v1.0.61

func BuildBatchDeleteCondFormatArgs(input map[string]any) (map[string]any, error)

func BuildBatchDeleteDimensionArgs added in v1.0.61

func BuildBatchDeleteDimensionArgs(input map[string]any) (map[string]any, error)

BuildBatchDeleteDimensionArgs converts the documented CLI-shaped input to the low-level 0-based delete_dimension request. The camelCase startIndex / count pair remains as an undocumented compatibility path for callers that already supplied the old low-level payload directly.

func BuildBatchDeleteFilterArgs added in v1.0.61

func BuildBatchDeleteFilterArgs(input map[string]any) (map[string]any, error)

func BuildBatchDeleteFilterViewArgs added in v1.0.61

func BuildBatchDeleteFilterViewArgs(input map[string]any) (map[string]any, error)

func BuildBatchDeleteFloatChartArgs added in v1.0.61

func BuildBatchDeleteFloatChartArgs(input map[string]any) (map[string]any, error)

func BuildBatchDeletePivotTableArgs added in v1.0.61

func BuildBatchDeletePivotTableArgs(input map[string]any) (map[string]any, error)

func BuildBatchDeleteSheetArgs added in v1.0.61

func BuildBatchDeleteSheetArgs(input map[string]any) (map[string]any, error)

func BuildBatchInsertDimensionArgs added in v1.0.61

func BuildBatchInsertDimensionArgs(input map[string]any) (map[string]any, error)

func BuildBatchMoveDimensionArgs added in v1.0.61

func BuildBatchMoveDimensionArgs(input map[string]any) (map[string]any, error)

BuildBatchMoveDimensionArgs converts the documented 1-based row numbers or column letters to the 0-based integer indexes consumed by batch_update. The camelCase fields preserve the previous low-level compatibility path.

func BuildBatchMoveRangeArgs added in v1.0.61

func BuildBatchMoveRangeArgs(input map[string]any) (map[string]any, error)

func BuildBatchReplaceArgs added in v1.0.61

func BuildBatchReplaceArgs(input map[string]any) (map[string]any, error)

func BuildBatchSetStyleArgs added in v1.0.61

func BuildBatchSetStyleArgs(input map[string]any) (map[string]any, error)

func BuildBatchSortRangeArgs added in v1.0.61

func BuildBatchSortRangeArgs(input map[string]any) (map[string]any, error)

func BuildBatchUpdateCondFormatArgs added in v1.0.61

func BuildBatchUpdateCondFormatArgs(input map[string]any) (map[string]any, error)

func BuildBatchUpdateFilterArgs added in v1.0.61

func BuildBatchUpdateFilterArgs(input map[string]any) (map[string]any, error)

func BuildBatchUpdateFilterViewArgs added in v1.0.61

func BuildBatchUpdateFilterViewArgs(input map[string]any) (map[string]any, error)

func BuildBatchUpdateFloatImageArgs added in v1.0.61

func BuildBatchUpdateFloatImageArgs(input map[string]any) (map[string]any, error)

func BuildBatchUpdateSheetArgs added in v1.0.61

func BuildBatchUpdateSheetArgs(input map[string]any) (map[string]any, error)

func BuildClearRangeArgs added in v1.0.48

func BuildClearRangeArgs(input map[string]any) map[string]any

BuildClearRangeArgs converts CLI flags to MCP params for clear_range.

func BuildConversationFileContent added in v1.0.56

func BuildConversationFileContent(
	dentryID, spaceID int64,
	meta ConversationLocalFileMeta,
) (string, error)

BuildConversationFileContent renders the exact file-message content accepted by send_personal_message.

func BuildCopyRangeArgs added in v1.0.48

func BuildCopyRangeArgs(input map[string]any) map[string]any

BuildCopyRangeArgs converts CLI flags to MCP params for copy_range.

func BuildCsvPutArgs added in v1.0.48

func BuildCsvPutArgs(input map[string]any) map[string]any

BuildCsvPutArgs converts CLI flags to MCP params for set_range_from_csv. Resolves @filepath and - stdin to CSV text.

func BuildDeleteDropdownArgs added in v1.0.48

func BuildDeleteDropdownArgs(input map[string]any) map[string]any

BuildDeleteDropdownArgs converts CLI flags to MCP params for delete_dropdown_lists.

func BuildDeleteFloatImageArgs added in v1.0.48

func BuildDeleteFloatImageArgs(input map[string]any) map[string]any

BuildDeleteFloatImageArgs converts CLI flags to MCP params for delete_float_image.

func BuildFillRangeArgs added in v1.0.48

func BuildFillRangeArgs(input map[string]any) map[string]any

BuildFillRangeArgs converts CLI flags to MCP params for fill_range.

func BuildGroupDimensionArgs added in v1.0.51

func BuildGroupDimensionArgs(input map[string]any) map[string]any

BuildGroupDimensionArgs converts CLI flags to MCP params for group_dimension.

func BuildMergeCellsArgs added in v1.0.48

func BuildMergeCellsArgs(input map[string]any) map[string]any

BuildMergeCellsArgs converts CLI flags to MCP params for merge_range.

func BuildSetCellRangeArgs added in v1.0.48

func BuildSetCellRangeArgs(input map[string]any) map[string]any

BuildSetCellRangeArgs converts CLI flags to MCP params for set_cell_range.

func BuildSetDropdownArgs added in v1.0.48

func BuildSetDropdownArgs(input map[string]any) map[string]any

BuildSetDropdownArgs converts CLI flags to MCP params for insert_dropdown_lists.

func BuildUngroupDimensionArgs added in v1.0.51

func BuildUngroupDimensionArgs(input map[string]any) map[string]any

BuildUngroupDimensionArgs converts CLI flags to MCP params for ungroup_dimension.

func BuildUnmergeCellsArgs added in v1.0.48

func BuildUnmergeCellsArgs(input map[string]any) map[string]any

BuildUnmergeCellsArgs converts CLI flags to MCP params for unmerge_range.

func BuildUpdateDimensionArgs added in v1.0.48

func BuildUpdateDimensionArgs(input map[string]any) map[string]any

BuildUpdateDimensionArgs converts CLI flags to MCP params for update_dimension. startIndex 传递 A1 表示法字符串(与独立工具一致),由服务端转换为 0-based 整数。

func BuildUpdateFilterArgs added in v1.0.61

func BuildUpdateFilterArgs(input map[string]any) (map[string]any, error)

BuildUpdateFilterArgs converts standalone filter update flags while preserving the historical behavior that an empty criteria array is accepted.

func BuildUpdateSheetArgs added in v1.0.61

func BuildUpdateSheetArgs(input map[string]any) (map[string]any, error)

func CallMCPReadToolTextOnServer added in v1.0.55

func CallMCPReadToolTextOnServer(serverID, toolName string, args map[string]any) (string, error)

CallMCPReadToolTextOnServer performs a read-only lookup needed to construct a semantic Shortcut dry-run plan. Under ordinary execution it is identical to CallMCPToolTextOnServer. Under --dry-run it requires the host's optional ReadToolCaller capability; if unavailable, it fails closed instead of returning a synthetic dry-run envelope that looks like business data.

func CallMCPReadToolTextOnServerContext added in v1.0.59

func CallMCPReadToolTextOnServerContext(ctx context.Context, serverID, toolName string, args map[string]any) (string, error)

CallMCPReadToolTextOnServerContext is the cancellable form used by Cobra commands and composite shortcuts. Keeping the caller context attached to the transport lets SIGTERM/parent deadlines stop an in-flight MCP read and return a structured error instead of leaving the CLI silent until the host kills it.

func CallMCPToolDataOnServer added in v1.0.58

func CallMCPToolDataOnServer(ctx context.Context, serverID, toolName string, args map[string]any) (any, error)

CallMCPToolDataOnServer invokes one tool without printing and decodes its JSON text payload. Framework renderers use this seam so the business request is executed exactly once and presentation remains a separate step.

func CallMCPToolOnServer added in v1.0.48

func CallMCPToolOnServer(serverID, toolName string, args map[string]any) error

CallMCPToolOnServer is the exported version of callMCPToolOnServer for use by extension packages that live in separate Go packages.

func CallMCPToolOnServerContext added in v1.0.59

func CallMCPToolOnServerContext(ctx context.Context, serverID, toolName string, args map[string]any) error

CallMCPToolOnServerContext is the cancellable print-path variant for Shortcut execution. It preserves the same output and error projection as the legacy wrapper while allowing the root signal context to abort transport.

func CallMCPToolTextOnServer added in v1.0.54

func CallMCPToolTextOnServer(serverID, toolName string, args map[string]any) (string, error)

CallMCPToolTextOnServer invokes an MCP tool and returns its raw text response WITHOUT printing anything, applying the same error classification as the print path. Exported for the shortcut layer's multi-step ("smart") shortcuts, which chain several tool calls and need each intermediate result as data.

func CallMCPToolTextOnServerContext added in v1.0.59

func CallMCPToolTextOnServerContext(ctx context.Context, serverID, toolName string, args map[string]any) (string, error)

CallMCPToolTextOnServerContext invokes one MCP tool while preserving the command's cancellation and deadline. Legacy callers may continue using CallMCPToolTextOnServer, which intentionally retains background context.

func ClassifyMCPResponseText added in v1.0.48

func ClassifyMCPResponseText(text string) error

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 matters: DWS gateway > PAT permission > generic business error.

func ClassifyToolResultContent added in v1.0.48

func ClassifyToolResultContent(content map[string]any) error

ClassifyToolResultContent checks a raw MCP tool result content map for DWS gateway auth errors and PAT permission error codes. This is used as the edition.Hooks.ClassifyToolResult callback so the framework's runner returns a typed error before its generic business-error classification.

Check order matches ClassifyMCPResponseText: DWS gateway > PAT permission > no-permission guidance.

func ContractValidate added in v1.0.57

func ContractValidate(cmd *cobra.Command) func(*cobra.Command, []string) error

ContractValidate returns the DeclareLeafMetadata Validate hook when present. Used by outer Sheet guards so Validate and confirmation stay on the RunE layer for proxy/direct RunE call sites.

func DeclareLeafMetadata added in v1.0.57

func DeclareLeafMetadata(cmd *cobra.Command, spec LeafSpec) *cobra.Command

DeclareLeafMetadata 是命令框架的「声明元数据模式」:把 LeafSpec 的声明面 (Safety + Contract)挂到既有命令上——不注册 flag、不接管参数投影。可选的 Validate 与 ConfirmSafety 同挂在 RunE 包装器内(Validate 在前),保证 本地可判定校验发生在确认之前(RFC §5.1 / §5.6),且直接调 RunE / proxySubCmd 委派不会跳过校验。

user_required 确认时机:

  • 提供 Validate:Validate → ConfirmSafety → 原 RunE(本地副作用命令)
  • 未提供 Validate:原 RunE 先跑(含缺参校验),ConfirmSafety 推迟到 首次 deps.Caller.CallTool。无 Caller 时回退 ConfirmSafety → 原 RunE。 有 Caller 但 RunE 成功返回且从未 CallTool:fail-closed(禁止「成功 返回却未确认」——此时副作用可能已发生,事后 Confirm 太晚)。本地 副作用叶必须补 Validate,或把副作用放进 gated CallTool。

该模式是迁移态而非终态:命令具备条件时应升级为 NewLeafCommand。传入 Flags/Constraints/ConstParams/Call/RunE/PostMount 或空 Contract 会 panic, 防止误用成半接管(Validate 是唯一允许的执行钩子)。

func DevAppCommandResultFromPayload added in v1.0.58

func DevAppCommandResultFromPayload(tool string, payload any, dryRun bool) output.CommandResult

DevAppCommandResultFromPayload is the shared dingtalk-dev outcome mapper for the native `dev ...` tree and the existing `devapp +...` shortcut tree. Both entry points must classify the same upstream payload into the same unified outcome; only command routing and projection differ.

func FromLeafSpec added in v1.0.57

func FromLeafSpec(spec LeafSpec) corecmd.Spec

FromLeafSpec 把 LeafSpec 归一为统一的 corecmd.Spec。契约字段 (Flags/Constraints/Safety)与编排钩子(Validate/PostMount/RunE)直接透传; dispatch 收敛为一个闭包:Call 优先,其次显式 Server 路由,最后按 product 自动路由。RunE 逃生舱存在时不设 Dispatch(与旧行为一致)。

func GetCaller added in v1.0.48

func GetCaller() edition.ToolCaller

GetCaller returns the shared ToolCaller for use by sibling packages.

func GroupRunE added in v1.0.48

func GroupRunE(cmd *cobra.Command, args []string) error

GroupRunE is the exported version of groupRunE for use by extension packages.

func HasContractConfirmDeferred added in v1.0.57

func HasContractConfirmDeferred(cmd *cobra.Command) bool

HasContractConfirmDeferred reports whether ConfirmSafety is deferred to the first deps.Caller.CallTool (no Validate on the leaf).

func HasContractConfirmSafety added in v1.0.57

func HasContractConfirmSafety(cmd *cobra.Command) bool

HasContractConfirmSafety reports whether DeclareLeafMetadata installed the ConfirmSafety wrapper for a user_required SafetySpec.

func HasContractValidate added in v1.0.57

func HasContractValidate(cmd *cobra.Command) bool

HasContractValidate reports whether DeclareLeafMetadata installed a Validate hook (confirm-after-Validate mode on the RunE wrapper).

func HasSheetMutationConfirmationGuard added in v1.0.52

func HasSheetMutationConfirmationGuard(cmd *cobra.Command) bool

HasSheetMutationConfirmationGuard reports whether a Sheet command is protected by protectSheetMutationCommand. It is exported for the app-level final Schema-to-runtime delivery gate; callers must not set the annotation directly.

func InitDeps added in v1.0.48

func InitDeps(caller edition.ToolCaller)

InitDeps initializes shared dependencies for all product commands. Must be called before any product command's RunE executes (typically during command tree construction in newLegacyPublicCommands).

func InitDepsForTest added in v1.0.57

func InitDepsForTest(t *testing.T, caller edition.ToolCaller)

InitDepsForTest installs caller for the test duration and restores the prior deps pointer (including a prior nil) via testseam. Prefer this over InitDeps + InitDeps(previousCaller): restoring through InitDeps(nil) leaves a non-nil Deps with a nil Caller, which is not the original unset state.

func InsertDocMediaFile added in v1.0.62

func InsertDocMediaFile(cmd *cobra.Command, nodeID, filePath string, emit func(any) error) error

InsertDocMediaFile inserts one file into an explicitly selected document for a composite creation flow. It does not inherit the document's title as the attachment filename. The caller validates every local path before creation.

func IsAuthError added in v1.0.48

func IsAuthError(err error) bool

IsAuthError returns true if the error is a CLIError with an auth-related code.

func IsPublicTransferIP added in v1.0.62

func IsPublicTransferIP(ip netip.Addr) bool

IsPublicTransferIP reports whether an address is an ordinary public transfer destination. It excludes special-purpose and unallocated IPv6 space even when Go classifies it as global unicast. Callers must also validate URL hosts and pin the checked address for the actual connection.

func IsReadToolName added in v1.0.56

func IsReadToolName(toolName string) bool

IsReadToolName is the fail-closed naming contract for the dry-run read channel. Both the Shortcut runtime and the helper boundary enforce it so a future direct helper caller cannot accidentally route a write tool through ReadToolCaller.

func LoadRoleConfigs added in v1.0.42

func LoadRoleConfigs(dir string) (map[string]*RoleConfig, error)

LoadRoleConfigs loads every *.yaml / *.yml file directly under dir and indexes the roles by ClientID — the lookup a multi-bot, one-role-per-bot deployment needs. A duplicate ClientID is an error: two roles must not share one bot.

func MustGetStringFlag added in v1.0.48

func MustGetStringFlag(cmd *cobra.Command, name string) string

MustGetStringFlag retrieves a string flag, falling back to inherited flags.

func NewIncompleteResultError added in v1.0.62

func NewIncompleteResultError(message string, cause error, fallbackRetryable bool, opts ...apperrors.Option) error

NewIncompleteResultError adds retained business data to a stable outer failure subtype without flattening the downstream failure contract.

fallbackRetryable is used only when the cause does not publish an explicit retry decision. A caller cancellation always wins and remains non-retryable. The outer opts own the operation, stage, reason and partialResult; retry timing and server diagnostics are copied from the cause.

func NewLeafCommand added in v1.0.55

func NewLeafCommand(spec LeafSpec) *cobra.Command

NewLeafCommand 是命令框架的「完全托管模式」:经 FromLeafSpec 归一为 corecmd.Spec 后交由统一构建器 corecmd.New 编排(flag 注册、 约束声明检查、Schema 投影、帮助渲染、required/约束校验、Safety 确认、 toolArgs 装配)。本函数只保留 LeafSpec→CommandSpec 的映射与 MCP dispatch 闭包(callMCPTool/OnServer/Call)。所有 LeafSpec 命令(含 devapp 全部叶子) 由此统一流经 command 单一 spec 路径。

func NewPublicCommands

func NewPublicCommands(runner executor.Runner) []*cobra.Command

func NonResumableCursorResponseError added in v1.0.63

func NonResumableCursorResponseError(guardCursor string, executionStarted bool) error

NonResumableCursorResponseError 处理成功响应体中夹带的 error-v1: 保护游标。 服务端可能返回成功却把不可恢复游标放进 nextCursor/cursor,表示本轮分页结果不可续读, 语义与服务端 NON_RESUMABLE_ERROR_CURSOR 错误码一致:必须丢弃全部累计结果、立即停止分页、 禁止回传该游标。executionStarted 供调用方区分只读分页(true)与写前唯一键预检(false)—— 预检失败必须声明未开始写入,避免调用方误判可能已产生副作用。

func NormalizeAITableViewConfig added in v1.0.62

func NormalizeAITableViewConfig(ctx context.Context, baseID, tableID string, config map[string]any) error

NormalizeAITableViewConfig is shared by the atomic and Shortcut entrypoints. It normalizes the caller-owned map, resolves typed entity filters and rejects config blocks owned by dedicated endpoints before any write.

func NormalizeBlockIDs added in v1.0.62

func NormalizeBlockIDs(raw string) ([]string, error)

NormalizeBlockIDs parses a --block-id value that accepts either a single block ID or several ASCII-comma-separated IDs ("a,b,c").

It splits, trims, drops empty entries, and dedupes while preserving first-seen order. Deletion is keyed by block ID, so order carries no semantics — dedupe simply avoids asking the server to delete the same block twice.

func NormalizeMessageMentions added in v1.0.56

func NormalizeMessageMentions(text string, ids []string, atAll, wrapAngle bool) string

NormalizeMessageMentions applies the placeholder convention required by the selected sender identity and ensures a declared @all is present in the body. Current-user messages use <@id>/<@all>; bot and webhook messages use @id/@mobile/@all.

func NormalizeSearchConversationScopeError added in v1.0.58

func NormalizeSearchConversationScopeError(conversationID string, err error) error

NormalizeSearchConversationScopeError maps only errors that prove the requested conversation does not exist or that openConversationId itself is invalid. Unknown MCP tool failures must remain unchanged: the legacy CodeMCPToolError bucket also carries permission, throttling, and transient backend failures, none of which proves that the caller supplied a bad CID.

func NormalizeSkillName

func NormalizeSkillName(input string) string

NormalizeSkillName converts free-form skill names to a stable dash-case key.

func ParseChatA2UIMessages added in v1.0.62

func ParseChatA2UIMessages(raw string) ([]string, error)

ParseChatA2UIMessages uses the same payload parser as the native card leaf.

func ParseConversationFileDownloadURL added in v1.0.62

func ParseConversationFileDownloadURL(text string) (string, error)

ParseConversationFileDownloadURL reuses the native robot file-message link parser.

func ParseConversationFileSendIDs added in v1.0.56

func ParseConversationFileSendIDs(text string) (int64, int64, error)

ParseConversationFileSendIDs extracts the committed dentry and space IDs.

func PrepareChatReplyMentions added in v1.0.62

func PrepareChatReplyMentions(text string, ids []string, atAll, user bool) string

PrepareChatReplyMentions reuses the native reply's normalization and missing placeholder insertion before adapting the resulting body to the sender.

func PrepareDocJSONMLBody added in v1.0.60

func PrepareDocJSONMLBody(cmd *cobra.Command, raw string) (string, error)

PrepareDocJSONMLBody exposes the shared strict JSONML write pipeline to higher-level Doc commands. It validates a complete document body and requires a root node; optional repair remains controlled by the caller's --fix-jsonml flag when that flag exists.

func PrepareDocJSONMLNode added in v1.0.60

func PrepareDocJSONMLNode(cmd *cobra.Command, raw string) (string, error)

PrepareDocJSONMLNode exposes the shared strict JSONML write pipeline for a single block node. Unlike PrepareDocJSONMLBody, it does not require a root document node.

func RecordQueryRecoveryError added in v1.0.63

func RecordQueryRecoveryError(err error) error

RecordQueryRecoveryError 仅为记录查询的已知游标错误补充恢复策略,不重试请求或重放写流程。 网络、权限与未知错误保持原样;判断依据为结构化错误码,不能匹配报错文案猜测原因。

func RegisterCamelCaseAliases added in v1.0.48

func RegisterCamelCaseAliases(cmd *cobra.Command)

RegisterCamelCaseAliases recursively walks the command tree and registers hidden camelCase aliases for every kebab-case flag. This prevents flag-value prefix matching from misinterpreting AI-generated camelCase flags (e.g. --baseId) as a short flag + glued value (--base + "Id").

func RegisterCrossProductAliases added in v1.0.48

func RegisterCrossProductAliases(cmd *cobra.Command)

RegisterCrossProductAliases automatically registers hidden alias flags for cross-product compatibility. Call this once after all primary flags are registered.

For each alias group, it finds the first flag already registered on cmd (the "primary"), then registers all other names in the group as hidden String flags. Existing flags are never overwritten.

func RegisterPublicNamed added in v1.0.63

func RegisterPublicNamed(name string, factory Factory)

func RegisterRuntimeDefault added in v1.0.48

func RegisterRuntimeDefault(id string, fn edition.RuntimeDefaultFn)

RegisterRuntimeDefault records a runtime default resolver. Panics on empty id, nil fn, or duplicate registration so conflicts surface at init.

func RenderLegacyMCPText added in v1.0.58

func RenderLegacyMCPText(toolName, text string) error

RenderLegacyMCPText renders an already-fetched MCP text response through the exact legacy formatter. It lets dual validation execute the business request once, validate a shadow unified result, and still preserve legacy bytes.

func ReturnIncompleteResult added in v1.0.62

func ReturnIncompleteResult(
	cmd *cobra.Command,
	shadow output.CommandResult,
	terminalErr error,
	legacyErr error,
	writeLegacy func() error,
) error

ReturnIncompleteResult closes an incomplete-result invocation according to the command's output rollout without issuing another business request.

Unified commands return the structured terminal error and publish no success-shaped payload. Dual-validation commands validate the once-built shadow result, preserve the established legacy bytes, and then return the structured terminal error. Legacy commands preserve both their output and their historical terminal error (which may be nil).

func RunDocImportShortcut added in v1.0.57

func RunDocImportShortcut(cmd *cobra.Command) error

RunDocImportShortcut exposes the existing, fully-tested Doc import pipeline to the Shortcut application layer. The Cobra leaf still owns its own flags and Contract; this bridge only shares the raw/API execution primitive.

func RunDocMediaInsertShortcut added in v1.0.57

func RunDocMediaInsertShortcut(cmd *cobra.Command) error

RunDocMediaInsertShortcut shares the existing prepare + OSS PUT + block insertion implementation with the canonical Doc Shortcut.

func RunDocMediaUploadWithResult added in v1.0.62

func RunDocMediaUploadWithResult(cmd *cobra.Command, emit func(map[string]any) error) error

RunDocMediaUploadWithResult shares the existing upload without coupling the Shortcut to the legacy renderer. emit receives only a completed upload.

func RunDocResourceUpdateShortcut added in v1.0.57

func RunDocResourceUpdateShortcut(cmd *cobra.Command) error

RunDocResourceUpdateShortcut shares the cover upload/transfer pipeline.

func RunPagedMCPCommand added in v1.0.58

func RunPagedMCPCommand(cmd *cobra.Command, cfg PagedMCPCommandConfig) error

func RuntimeDefaultsSnapshot added in v1.0.48

func RuntimeDefaultsSnapshot() map[string]edition.RuntimeDefaultFn

RuntimeDefaultsSnapshot returns a copy of the resolver map for the edition.Hooks.RuntimeDefaults hook. Always returns a new map so callers can't mutate the registry after boot.

func SetChatCryptoClient added in v1.0.62

func SetChatCryptoClient(client *messagecrypto.Client)

SetChatCryptoClient injects the app-owned SafeChat/Ding crypto client.

func SetCmdClassOverride added in v1.0.42

func SetCmdClassOverride(key string, class CmdClass)

SetCmdClassOverride registers a process-wide classification override for the given key. The key may be a single verb or a space-joined command path; it is normalised to lowercase. Passing CmdClassUnknown removes the override.

func SetHTTPGetFile added in v1.0.48

func SetHTTPGetFile(fn func(ctx context.Context, url string, headers map[string]string, destPath string) error)

SetHTTPGetFile overrides the HTTP GET function (for testing). Pass nil to restore default.

func SetHTTPPutFile added in v1.0.48

func SetHTTPPutFile(fn func(ctx context.Context, url string, headers map[string]string, filePath string, fileSize int64) error)

SetHTTPPutFile overrides the HTTP PUT function (for testing). Pass nil to restore default.

func ShellQuoteArg added in v1.0.59

func ShellQuoteArg(s string) string

ShellQuoteArg 按 POSIX sh 规则把 s 引用成可安全放进可复制命令的单个 argv 元素。

为什么需要它:错误提示里的恢复命令是给用户直接复制到 shell 执行的,其中的查询域取自用户 输入(--workspace 的常见形态就是带查询串的 URL)。裸拼接下,合法 URL 里的 `&` 就会把命令 拆成后台任务,空格会拆参,`;` 与 `$()` 还能执行额外内容。

为什么不用 strconv.Quote(internal/auth 侧展示 profile 标识的既有做法):那是 Go 语法引号, 产出双引号串,而 shell 双引号内 `$()`、反引号、`$VAR` 仍会展开——正是要防的场景。auth 那处 成立是因为它显式声明「仅作数据展示,不是可执行命令」,本函数的产物恰恰要能执行。

策略是「必要时才引用」:全由安全字符组成时原样返回,命令保持可读、在 PowerShell/cmd 下同样 可复制;只要含一个非安全字符就整体单引号包裹——单引号内 POSIX sh 不做任何展开($ ` \ ! 全部 字面化),是唯一无需逐字符转义的形式。单引号自身无法出现在单引号串内,按 POSIX 标准写法 先闭合、拼一个反斜杠转义的单引号、再重开——即把每个单引号替换成下面这四个字符:

'\''

空串必须显式引用成一对空单引号,否则该参数会从 argv 里整个消失,后面的 token 会被前一个 flag 吞掉。

func SwapHTTPPutFileForTest added in v1.0.62

func SwapHTTPPutFileForTest(t *testing.T, fn func(context.Context, string, map[string]string, string, int64) error)

SwapHTTPPutFileForTest injects upload outcomes without contacting a live OSS URL.

func UnifiedDiff added in v1.0.57

func UnifiedDiff(oldName string, old []byte, newName string, new []byte, contextLines int) []byte

UnifiedDiff returns an anchored diff of the two texts old and new in the "unified diff" format. If old and new are identical, UnifiedDiff returns a nil slice (no output).

Unix diff implementations typically look for a diff with the smallest number of lines inserted and removed, which can in the worst case take time quadratic in the number of lines in the texts. As a result, many implementations either can be made to run for a long time or cut off the search after a predetermined amount of work.

In contrast, this implementation looks for a diff with the smallest number of "unique" lines inserted and removed, where unique means a line that appears just once in both old and new. We call this an "anchored diff" because the unique lines anchor the chosen matching regions. An anchored diff is usually clearer than a standard diff, because the algorithm does not try to reuse unrelated blank lines or closing braces. The algorithm also guarantees to run in O(n log n) time instead of the standard O(n²) time.

Some systems call this approach a "patience diff," named for the "patience sorting" algorithm, itself named for a solitaire card game. We avoid that name for two reasons. First, the name has been used for a few different variants of the algorithm, so it is imprecise. Second, the name is frequently interpreted as meaning that you have to wait longer (to be patient) for the diff, meaning that it is a slower algorithm, when in fact the algorithm is faster than the standard one.

func UploadConversationLocalFile added in v1.0.56

func UploadConversationLocalFile(
	ctx context.Context,
	targetArgs map[string]any,
	meta ConversationLocalFileMeta,
	uuid string,
) (string, error)

UploadConversationLocalFile executes the existing init -> HTTP upload -> commit flow and returns the commit response for message-content assembly.

func UploadDocSpaceFileData added in v1.0.61

func UploadDocSpaceFileData(ctx context.Context, request DocSpaceUploadRequest) (map[string]any, error)

UploadDocSpaceFileData runs credentials -> OSS PUT -> commit exactly once on the doc MCP server and returns the parsed commit response without rendering it. It is intentionally separate from UploadDriveFileData so the two target domains cannot silently exchange similarly named identifiers.

func UploadDriveFileData added in v1.0.58

func UploadDriveFileData(ctx context.Context, request DriveUploadRequest) (map[string]any, error)

UploadDriveFileData runs credentials -> OSS PUT -> commit exactly once and returns the parsed commit response without rendering it. Unlike the legacy leaf helper, this path fails when the commit has no non-empty JSON response; the Shortcut can then require terminal success evidence and read back the created node before reporting success.

func ValidateChatQuoteReply added in v1.0.62

func ValidateChatQuoteReply(cmd *cobra.Command, conversationID, messageID string) error

ValidateChatQuoteReply keeps shortcut Bot quote replies behind the same topic-container checks as the original native send-by-bot command.

func ValidateNaming

func ValidateNaming(vendor, name string) error

func WrapError added in v1.0.48

func WrapError(err error) error

WrapError analyzes a raw error and wraps it with a friendly message. It classifies errors by pattern (network, auth, permission, resource, JSON parse, server error, file lock) and returns an appropriate CLIError.

func WrapErrorWithOperation added in v1.0.48

func WrapErrorWithOperation(err error, operation string) error

WrapErrorWithOperation wraps an error with operation context for traceability.

Types

type ApprovalRequest added in v1.0.42

type ApprovalRequest struct {
	ID        string        `json:"id"`
	Requester string        `json:"requester"`      // staffId of who asked
	ConvID    string        `json:"conv_id"`        // conversation to reply into
	Summary   string        `json:"summary"`        // human-readable "what will happen"
	Verb      string        `json:"verb,omitempty"` // action verb, e.g. "todo.create" (remember key)
	Action    plannedAction `json:"action"`         // structured command to run on approve
	State     approvalState `json:"state"`
	// OutTrackID is the delivered card's instance id, recorded so a button
	// callback that only carries the card id (not the approval id in its action
	// params) can still be mapped back to this request.
	OutTrackID string `json:"out_track_id,omitempty"`
	DecidedBy  string `json:"decided_by,omitempty"` // staffId who approved/rejected
	ExecErr    string `json:"exec_err,omitempty"`   // failure detail when State=failed
	// AutoApproved marks a request the owner made of THEMSELVES: no second
	// confirmation is asked (the owner asking IS the authorization), but the
	// full record is still persisted for audit, with DecidedBy=owner. Lets the
	// audit trail distinguish an auto-run from an explicitly-confirmed one.
	AutoApproved bool      `json:"auto_approved,omitempty"`
	CreatedAt    time.Time `json:"created_at"`
	DecidedAt    time.Time `json:"decided_at,omitempty"`
}

ApprovalRequest is one pending/decided confirmation. It is the on-disk record too (marshalled as-is), so every field is JSON-tagged and self-describing.

type CLIError added in v1.0.48

type CLIError struct {
	Code       string
	Message    string
	Suggestion string
	Operation  string // the operation that failed (for traceability)
	ServerCode string
	Details    map[string]any
	Cause      error
}

CLIError is a user-friendly error with code, suggestion, and exit code. Supports traceability via the Operation field and error chain via Cause.

func (*CLIError) Error added in v1.0.48

func (e *CLIError) Error() string

func (*CLIError) ExitCode added in v1.0.48

func (e *CLIError) ExitCode() int

func (*CLIError) ToJSON added in v1.0.48

func (e *CLIError) ToJSON() map[string]any

ToJSON returns a structured JSON representation for machine consumption.

func (*CLIError) Unwrap added in v1.0.48

func (e *CLIError) Unwrap() error

type CmdClass added in v1.0.42

type CmdClass int

CmdClass describes whether a dws command is read-only or mutating. It is the signal a connector confirmation gate consumes to decide whether a robot may run a command directly (read-only) or must first ask the principal to approve it (write / mutating).

SAFETY CONTRACT: callers MUST treat CmdClassUnknown conservatively, i.e. as if it were CmdClassWrite (require confirmation). The classifier deliberately returns Unknown rather than silently coercing it to Write so that the confirmation gate keeps full information and can, for example, log/telemeter "unclassified" commands separately. Never auto-allow an Unknown command.

const (
	// CmdClassUnknown means the leaf verb was not recognised by the
	// heuristics or any override. Callers must default to requiring
	// confirmation (treat as write) for safety.
	CmdClassUnknown CmdClass = iota
	// CmdClassRead is a read-only / non-mutating command that may be run
	// without principal confirmation.
	CmdClassRead
	// CmdClassWrite is a mutating / state-changing command that must be
	// confirmed by the principal before it runs.
	CmdClassWrite
)

func ClassifyDwsCommand added in v1.0.42

func ClassifyDwsCommand(parts ...string) CmdClass

ClassifyDwsCommand classifies a dws command given its path segments (e.g. "todo", "task", "create"). It consults the package-level override table and then the read/write verb heuristics, scanning segments right-to-left so the leaf action verb dominates a container/noun segment.

Remember the SAFETY CONTRACT on CmdClass: a CmdClassUnknown result MUST be treated as write (require confirmation) by the caller.

func ClassifyDwsCommandWith added in v1.0.42

func ClassifyDwsCommandWith(overrides map[string]CmdClass, parts ...string) CmdClass

ClassifyDwsCommandWith is like ClassifyDwsCommand but lets the caller supply an explicit override table (e.g. a per-tenant or per-request map) instead of the package-level one. A nil overrides map is allowed and means "no overrides". Override lookups always win over the heuristics.

func (CmdClass) String added in v1.0.42

func (c CmdClass) String() string

String renders the class as a stable lowercase token, handy for logs and telemetry.

type ConfirmPolicy added in v1.0.42

type ConfirmPolicy string

ConfirmPolicy controls how a role asks its owner before taking an action.

const (
	// ConfirmManual asks the owner to confirm every action.
	ConfirmManual ConfirmPolicy = "manual"
	// ConfirmAuto lets the bot judge for itself whether confirmation is needed.
	ConfirmAuto ConfirmPolicy = "auto"
	// ConfirmRemember reuses the owner's previous choice for the same kind of
	// operation.
	ConfirmRemember ConfirmPolicy = "remember"
)

type ConversationLocalFileMeta added in v1.0.56

type ConversationLocalFileMeta = conversationLocalFileMeta

ConversationLocalFileMeta exposes the already-reviewed native chat upload metadata to built-in semantic Shortcuts. It remains an alias so the native Cobra leaf and Shortcut use exactly the same upload implementation.

func BuildConversationLocalFileMeta added in v1.0.56

func BuildConversationLocalFileMeta(filePath, fileName, md5Value string) (ConversationLocalFileMeta, error)

BuildConversationLocalFileMeta validates a local file and computes the metadata required by DingTalk's conversation-file upload flow.

type Deps added in v1.0.48

type Deps struct {
	Caller edition.ToolCaller
	Out    *Formatter
}

Deps holds shared dependencies injected from the host application.

type DocSpaceUploadRequest added in v1.0.61

type DocSpaceUploadRequest struct {
	FilePath      string
	FileName      string
	FileSize      int64
	WorkspaceID   string
	FolderID      string
	OverwriteNode string
	Convert       bool
}

DocSpaceUploadRequest describes the document-space upload transaction used by curated shortcuts. The document-space API deliberately uses workspaceId, folderId and overwriteNodeId rather than the similarly named Drive fields.

type DocWriteResult added in v1.0.48

type DocWriteResult struct {
	Success       bool   `json:"success"`
	NodeID        string `json:"nodeId"`
	ChunksWritten int    `json:"chunksWritten"`
	// Degradations lists the chunk boundaries that changed the rendered
	// structure. Empty means the document reads exactly as the input did.
	Degradations   []MarkdownDegradation `json:"degradations,omitempty"`
	ServerResponse json.RawMessage       `json:"serverResponse,omitempty"`
}

DocWriteResult is the structured output of the write pipeline.

type DriveUploadRequest added in v1.0.58

type DriveUploadRequest struct {
	FilePath      string
	FileName      string
	FileSize      int64
	SpaceID       string
	ParentID      string
	OverwriteFile string
	MIMEType      string
}

DriveUploadRequest describes the reusable Drive upload transaction used by the native leaf and the curated +upload shortcut. FilePath must already be resolved and validated by the caller.

type Factory

type Factory func() Handler

type Formatter added in v1.0.48

type Formatter struct {
	// contains filtered or unexported fields
}

Formatter provides output formatting compatible with the old Wukong CLI.

func GetFormatter added in v1.0.48

func GetFormatter() *Formatter

GetFormatter returns the shared output formatter for use by sibling packages.

func NewFormatter added in v1.0.48

func NewFormatter() *Formatter

func NewFormatterWithWriters added in v1.0.58

func NewFormatterWithWriters(w, errW io.Writer) *Formatter

NewFormatterWithWriters 是注入式构造函数(B45,WS1 改动点3):数据流 w 与 诊断流 errW 均由调用方注入。nil 按默认进程流处理(w→os.Stdout、 errW→os.Stderr),因此 NewFormatter 的既有行为不变,只是收口到本构造器。

func (*Formatter) PrintDim added in v1.0.48

func (f *Formatter) PrintDim(msg string)

func (*Formatter) PrintError added in v1.0.48

func (f *Formatter) PrintError(msg string)

func (*Formatter) PrintInfo added in v1.0.48

func (f *Formatter) PrintInfo(msg string)

func (*Formatter) PrintJSON added in v1.0.48

func (f *Formatter) PrintJSON(data any) error

PrintJSON serializes data as pretty-printed JSON and writes it to the output stream. Go 的 json.Encoder 默认开启 HTML 转义(SetEscapeHTML(true)),会将 &、<、> 分别 转义为 \u0026、\u003c、\u003e。对于大多数 CLI 输出场景这是安全的默认行为。 如果返回值中包含 URL 等不应被转义的内容,请使用 PrintJSONUnescaped。

func (*Formatter) PrintJSONUnescaped added in v1.0.48

func (f *Formatter) PrintJSONUnescaped(data any) error

PrintJSONUnescaped 与 PrintJSON 功能相同,但禁用了 HTML 转义。 适用于返回值中包含带查询参数的 URL(如预签名上传 URL)的场景, 避免 & 被转义为 \u0026 导致 URL 无法直接使用。

使用场景示例:

  • minutes upload create 返回的 presignedUrl 包含多个 & 分隔的查询参数
  • 其他返回值中包含需要原样输出的 URL 的接口

影响范围:仅在调用方显式选择时生效,不影响全局 PrintJSON 的行为。

func (*Formatter) PrintKeyValue added in v1.0.48

func (f *Formatter) PrintKeyValue(key, value string)

func (*Formatter) PrintProgress added in v1.0.55

func (f *Formatter) PrintProgress(msg string)

func (*Formatter) PrintRaw added in v1.0.48

func (f *Formatter) PrintRaw(text string)

func (*Formatter) PrintSuccess added in v1.0.48

func (f *Formatter) PrintSuccess(msg string)

func (*Formatter) PrintTable added in v1.0.48

func (f *Formatter) PrintTable(headers []string, rows [][]string)

PrintTable preserves the legacy formatter contract. Unified-result commands bypass this formatter and use internal/output, so rollout does not silently move bytes for commands that have not migrated yet.

func (*Formatter) PrintWarning added in v1.0.48

func (f *Formatter) PrintWarning(msg string)

func (*Formatter) SetWriters added in v1.0.58

func (f *Formatter) SetWriters(w, errW io.Writer)

SetWriters 运行期替换两个写入目标(B46,WS1 改动点3):deps.Out 的 writer 不再是构造期一次性硬编码,而是可注入接缝。nil 侧保留当前值(支持单侧替换)。 既有的 deps.Out.w / deps.Out.errW 直接替换习惯不受影响。

type Handler

type Handler interface {
	Name() string
	Command(runner executor.Runner) *cobra.Command
}

type LeafConstraint added in v1.0.57

type LeafConstraint = corecmd.Constraint

LeafConstraint 声明一组 flag 的关系约束(corecmd.Constraint 的别名)。框架 在 required 校验之后、Validate 钩子之前统一执行;「是否提供」的判定复用有效 值回退链(显式主 flag → 别名 → env),即只传兼容别名同样视为已提供。约束 同时投影到 Agent Runtime Schema 并渲染进 --help 的「参数约束」段。

type LeafConstraintKind added in v1.0.57

type LeafConstraintKind = corecmd.ConstraintKind

LeafConstraintKind 是跨 flag 关系约束的类型(corecmd.ConstraintKind 的 别名)。取值与 shortcut 框架的 ConstraintKind 逐字一致。

type LeafContract added in v1.0.57

type LeafContract = corecmd.ContractDecl

LeafContract 是叶子 Contract 声明(corecmd.ContractDecl 别名)。 嵌套字段直接使用 contract.*(InterfaceSpec / ParamDecl / SelectionSpec 等), 不再保留平行 Decl 类型。

type LeafFlag added in v1.0.55

type LeafFlag = corecmd.FlagSpec

LeafFlag 声明一个 flag 的注册方式与到 MCP toolArgs 的绑定 (corecmd.FlagSpec 的别名,字段含义见 command 定义)。

type LeafFlagKind added in v1.0.55

type LeafFlagKind = corecmd.FlagKind

LeafFlagKind 是 flag 的值类型(corecmd.FlagKind 的别名)。

type LeafSpec added in v1.0.55

type LeafSpec struct {
	Use           string
	Short         string
	Long          string
	Example       string
	OutputRollout output.RolloutState

	// Server 非空时走 callMCPToolOnServer(显式 server 路由),否则走
	// callMCPTool(按 product 路由)。Call 非空时两者都被忽略。不是 CLI 声明。
	Server string
	Tool   string
	Flags  []LeafFlag
	// Constraints 是跨 flag 的关系约束(至少一个 / 恰好一个 / 互斥),由
	// command 统一校验并投影到 Runtime Schema 与 --help。复杂的条件式校验
	// 仍放 Validate 钩子(钩子本身不是约束声明)。
	Constraints []LeafConstraint

	// Safety 直接使用 Agent Runtime Schema 的安全模型。Confirmation 驱动
	// 运行时确认,其余字段原样进入 Schema;字段之间不做机械推导。
	Safety contract.SafetySpec

	// ConfirmFirst 为 true 时确认门先于 required/约束/Validate 校验执行
	//(devapp 旧版写守卫语义:写命令未带 --yes 时快速失败
	// confirmation_required,与参数完整性无关)。默认 false 保持 shortcut
	// 顺序(先校验,后端调用前再确认)。
	ConfirmFirst bool

	// ConstParams 是与 flag 无关的固定载荷(如 precheckOnly),在 flag 装配
	// 之后并入 toolArgs。载荷声明,不上用户 flag 表;从不满足 Required。
	ConstParams map[string]any

	// Contract 是叶子 ContractFinal 声明(identity/selection/interface/dry_run/…)。
	Contract LeafContract

	// Call 是执行体:非空时替代默认 MCP 派发。toolArgs 已由 Flags/ConstParams
	// 装配完成;Call 不应再写业务参数。分页等横切由领域工具处理,不进声明。
	Call       func(cmd *cobra.Command, tool string, args map[string]any) error
	ResultCall func(cmd *cobra.Command, tool string, args map[string]any) (output.CommandResult, error)

	// Validate 是编排钩子(条件式校验),不是声明面。单 flag 转换用
	// LeafFlag.Transform;可声明的互斥/至少一个应写 Constraints。
	Validate func(cmd *cobra.Command, args []string) error

	// RunE 非空时完全自定义执行体(逃生舱);表面事实仍须 Flags/Contract 声明。
	RunE func(cmd *cobra.Command, args []string) error

	// PostMount 是挂载收尾钩子(领域工具等),不是声明面。
	// 业务 flag 必须写在 Flags;分页由领域工具注入。
	PostMount func(cmd *cobra.Command)
}

LeafSpec 是命令框架的 Leaf 声明门面(映射为 corecmd.Spec)。

声明面 = Contract 最终数据源:Flags(含 parameter 字段)、Constraints、 Safety、ConstParams、Use/Short/Long/Example、Contract(Selection/Interface/…)。 Catalog 组装透传 ContractFinal;声明路径不再引入评审并行字段。

执行面(不算声明):Validate、Call、RunE、PostMount;Server/Tool 仅路由。

type Manifest

type Manifest struct {
	Vendor      string
	Name        string
	Description string
}

func (Manifest) FullName

func (m Manifest) FullName() string

type MarkdownChunkPlan added in v1.0.60

type MarkdownChunkPlan struct {
	Chunks       []string              `json:"-"`
	Limit        int                   `json:"limit"`
	Degradations []MarkdownDegradation `json:"degradations,omitempty"`
}

MarkdownChunkPlan is the result of splitting markdown for append-mode writes.

The contract is deliberately NOT strings.Join(Chunks, "") == content: the server's mode=append inserts a brand new structure per call, so keeping a table or a fenced code block intact across a boundary requires re-emitting its header or its fence. Instead:

  • len(Chunks) >= 1 always, so Chunks[0] is safe to index.
  • every chunk is at most Limit runes when Limit > 0.
  • every chunk is a complete, self-contained top-level block sequence: no half table, no unclosed fence, and no partial line unless a hard-split degradation is recorded for that boundary.
  • every boundary that changes the rendered structure appears in Degradations. An empty Degradations means ExpectedDocument() renders identically to the input.

func SplitMarkdownForAppend added in v1.0.60

func SplitMarkdownForAppend(content string, limitRunes int) MarkdownChunkPlan

SplitMarkdownForAppend splits content into chunks that are each safe to send as an independent update_document mode=append call. See MarkdownChunkPlan for the exact contract.

limitRunes <= 0 disables splitting and returns the content as a single chunk, which callers use as an explicit "send it in one call whatever the size" escape hatch.

func (MarkdownChunkPlan) Degraded added in v1.0.60

func (p MarkdownChunkPlan) Degraded() bool

Degraded reports whether any boundary changed the rendered structure.

func (MarkdownChunkPlan) ExpectedDocument added in v1.0.60

func (p MarkdownChunkPlan) ExpectedDocument() string

ExpectedDocument is the document the server is expected to hold once every chunk has been appended. Readback verification must compare against this rather than the original content, because repaired boundaries legitimately differ from the input.

It is a method rather than a field so a large document is not duplicated in memory unless a caller actually verifies.

func (MarkdownChunkPlan) Summary added in v1.0.60

func (p MarkdownChunkPlan) Summary() map[string]any

Summary is the structured projection for command envelopes.

func (MarkdownChunkPlan) Warnings added in v1.0.60

func (p MarkdownChunkPlan) Warnings() []string

Warnings renders one human-readable line per distinct degradation kind, aggregated with a count and the affected line numbers.

type MarkdownDegradation added in v1.0.60

type MarkdownDegradation struct {
	Kind string `json:"kind"`
	Tier string `json:"tier"`
	// ChunkIndex is the chunk *before* the boundary this describes.
	ChunkIndex int    `json:"chunkIndex"`
	Line       int    `json:"line"`
	Detail     string `json:"detail"`
	// InjectedSuffix was appended to Chunks[ChunkIndex] and InjectedPrefix was
	// prepended to Chunks[ChunkIndex+1] — the two halves of one repair, which
	// live in different chunks and are therefore reported separately. They exist
	// so a caller can strip them and recover the original content exactly.
	InjectedSuffix string `json:"injectedSuffix,omitempty"`
	InjectedPrefix string `json:"injectedPrefix,omitempty"`
}

MarkdownDegradation records one boundary that could not be made invisible.

type PATError added in v1.0.48

type PATError struct {
	RawJSON string
}

PATError represents a PAT authorization failure that should be passed through to stderr as raw JSON without any CLI-layer wrapping.

func (*PATError) Error added in v1.0.48

func (e *PATError) Error() string

func (*PATError) ExitCode added in v1.0.48

func (e *PATError) ExitCode() int

func (*PATError) RawStderr added in v1.0.48

func (e *PATError) RawStderr() string

type PagedAggregationMode added in v1.0.58

type PagedAggregationMode int
const (
	PagedAggregationArray PagedAggregationMode = iota
	PagedAggregationConversationMessages
)

type PagedCursorKind added in v1.0.58

type PagedCursorKind int
const (
	PagedCursorString PagedCursorKind = iota
	PagedCursorInt64
)

type PagedMCPCommandConfig added in v1.0.58

type PagedMCPCommandConfig struct {
	ServerID         string
	ToolName         string
	ItemPath         string
	ItemIdentityPath string
	CursorPath       string
	HasMorePath      string
	CursorArg        string
	PageSizeArg      string
	CursorKind       PagedCursorKind
	AggregationMode  PagedAggregationMode
	BuildArgs        func(*cobra.Command) (map[string]any, error)
	Fallback         func(map[string]any) error
	ProjectResult    func(map[string]any) map[string]any
	// ResultProjection enriches the framework-only Result after the established
	// legacy projection. dual_validate shadows it without changing public bytes.
	ResultProjection func(map[string]any) map[string]any
}

type RoleConfig added in v1.0.42

type RoleConfig struct {
	// Name is the human-facing role name, e.g. "人事助理".
	Name string `yaml:"name"`
	// ClientID is the DingTalk bot clientId this role is bound to. One role owns
	// exactly one bot, so this is also the unique key across a role set.
	ClientID string `yaml:"client_id"`
	// Persona is a professional prompt fragment merged into the agent's system
	// prompt to shape tone and expertise.
	Persona string `yaml:"persona"`
	// KnowledgeSources lists knowledge sources using the existing
	// --knowledge-source syntax: a bare path is a local directory, "wiki:<spaceId>"
	// a whole knowledge space, "doc:<docId>" a single document.
	KnowledgeSources []string `yaml:"knowledge_sources"`
	// AllowedScopes names the dws capabilities/products this role may use, e.g.
	// ["todo", "approval", "attendance"]. Consumed by later permission checks.
	AllowedScopes []string `yaml:"allowed_scopes"`
	// OwnerUserID is the userId of the role's owner; confirmation requests go here.
	OwnerUserID string `yaml:"owner_user_id"`
	// ConfirmPolicy selects the confirmation strategy; empty defaults to manual.
	ConfirmPolicy ConfirmPolicy `yaml:"confirm_policy"`
	// Extra is an open-ended bag for forward-compatible keys, so the schema can
	// grow without a breaking change. Intentionally minimal — not a config DSL.
	Extra map[string]string `yaml:"extra"`
}

RoleConfig is the on-disk (YAML) definition of one digital-employee role. It maps 1:1 to a single bot via ClientID.

func LoadRoleConfig added in v1.0.42

func LoadRoleConfig(path string) (*RoleConfig, error)

LoadRoleConfig reads, parses and validates a single role YAML file.

type TaskResult added in v1.0.60

type TaskResult struct {
	ID         string     `json:"id"`
	Type       string     `json:"type"`
	Status     TaskStatus `json:"status"`
	ResultURL  string     `json:"resultUrl,omitempty"`
	ResultName string     `json:"resultName,omitempty"`
	Message    string     `json:"message,omitempty"`
	CreateTime string     `json:"createTime,omitempty"`
}

TaskResult is the unified, flattened representation of an async task query response. JSON field names follow camelCase convention per the DWS CLI output specification.

func QueryTask added in v1.0.60

func QueryTask(ctx context.Context, taskID, taskType string) (*TaskResult, error)

QueryTask queries the status of an async task by task ID and type via the unified "query_task" MCP tool and normalizes the response into a TaskResult. taskType must be one of: export, import, copy, move (lowercase).

type TaskStatus added in v1.0.60

type TaskStatus string

TaskStatus represents the normalized lifecycle status of an async task.

const (
	TaskStatusPending       TaskStatus = "PENDING"
	TaskStatusProcessing    TaskStatus = "PROCESSING"
	TaskStatusSuccess       TaskStatus = "SUCCESS"
	TaskStatusFailed        TaskStatus = "FAILED"
	TaskStatusPartialFailed TaskStatus = "PARTIAL_FAILED"
	TaskStatusTimeout       TaskStatus = "TIMEOUT"
)

func NormalizeStatus added in v1.0.60

func NormalizeStatus(raw string) TaskStatus

NormalizeStatus maps a raw status string from an MCP response to a canonical TaskStatus value.

Mapping rules:

  • PENDING, QUEUED → PENDING
  • PROCESSING, RUNNING, IN_PROGRESS → PROCESSING
  • SUCCESS, SUCCEED, SUCCEEDED, DONE, FINISHED, COMPLETE, COMPLETED → SUCCESS
  • FAILED, FAILURE, ERROR → FAILED
  • PARTIAL_FAILED, PARTIALLY_FAILED → PARTIAL_FAILED
  • TIMEOUT → TIMEOUT
  • empty or unknown → PROCESSING (conservative)

Source Files

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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