helpers

package
v1.0.56-beta.1 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2026 License: Apache-2.0 Imports: 52 Imported by: 0

Documentation

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"
	CodeContentTruncated   = "CONTENT_TRUNCATED"
	CodeMCPServerError     = "MCP_SERVER_ERROR"
	CodeMCPToolError       = "MCP_TOOL_ERROR"
	CodeUnclassified       = "UNCLASSIFIED"
)
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.

Variables

This section is empty.

Functions

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 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 BuildDeleteDimensionArgs added in v1.0.48

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

BuildDeleteDimensionArgs converts CLI flags to MCP params for delete_dimension.

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 BuildMoveDimensionArgs added in v1.0.48

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

BuildMoveDimensionArgs converts CLI flags to MCP params for move_dimension.

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

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 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 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 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 NewLeafCommand added in v1.0.55

func NewLeafCommand(spec LeafSpec) *cobra.Command

NewLeafCommand 按 LeafSpec 构建叶子命令。

func NewPublicCommands

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

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 NormalizeSkillName

func NormalizeSkillName(input string) string

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

func ParseConversationFileSendIDs added in v1.0.56

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

ParseConversationFileSendIDs extracts the committed dentry and space IDs.

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 RegisterPublic

func RegisterPublic(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 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 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 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 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)
	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 DocWriteResult added in v1.0.48

type DocWriteResult struct {
	Success        bool            `json:"success"`
	NodeID         string          `json:"nodeId"`
	ChunksWritten  int             `json:"chunksWritten"`
	ServerResponse json.RawMessage `json:"serverResponse,omitempty"`
}

DocWriteResult is the structured output of the write pipeline.

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 (*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)

func (*Formatter) PrintWarning added in v1.0.48

func (f *Formatter) PrintWarning(msg string)

type Handler

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

type LeafFlag added in v1.0.55

type LeafFlag struct {
	Name    string       // flag 名(kebab-case)
	Usage   string       // 注册 usage 文案
	Kind    LeafFlagKind // 值类型,默认 LeafString
	Default string       // 注册默认值(cobra 注册仅 LeafString 使用;回退链链尾对所有 Kind 生效,不遮蔽别名/env)

	// Required 为 true 时在 RunE 期校验有效值非空。普通 Required 汇聚为
	// cmdutil.ValidateRequiredFlags 兼容的统一报错;配置 EnvVar 时回退读
	// 环境变量,仍为空则报 RequiredHint(或默认文案)。
	Required     bool
	RequiredHint string
	// MarkRequired 为 true 时调用 cobra MarkFlagRequired(catalog required
	// 投影的硬下限),cobra 会在 RunE 之前先行报错。
	MarkRequired bool

	Aliases []string // 隐藏别名,按主 flag 的 Kind 注册;主 flag 未显式提供时按序回退
	EnvVar  string   // 有效值为空时回退读取的环境变量(整型 flag 的 env 值必须可解析)
	// ArgDefault:注册默认值为空、但 toolArgs 需要兜底的场景(如 list type
	// 注册默认 "ALL" 之外的旧命令);有效值为空时以 ArgDefault 入参。
	ArgDefault string
	// Bind 是 toolArgs 的键;为空时使用 Name。
	Bind string
	// Transform 把字符串有效值转为入参值;nil 时原样入参。返回
	// (nil, nil) 表示跳过该键(用于「可空数值:为空或解析失败都不入参」
	// 的手写语义)。
	Transform func(raw string) (any, error)
	// OmitEmpty 为 true 时有效值为空则不进入 toolArgs(LeafInt 恒为
	// 「非零才入参」,忽略此字段)。
	OmitEmpty bool
	// Trim 为 true 时对有效值做 strings.TrimSpace(主 flag/别名/env 统一),
	// 对应手写 devAppStringFlag 恒 trim 的语义;亦使「纯空白」值在 required
	// 校验中视为空。
	Trim bool
}

LeafFlag 声明一个 flag 的注册方式与到 MCP toolArgs 的绑定。

type LeafFlagKind added in v1.0.55

type LeafFlagKind int

LeafFlagKind 是 flag 的值类型。

const (
	// LeafString 字符串 flag(默认)。
	LeafString LeafFlagKind = iota
	// LeafInt 整型 flag(注册为 cobra Int);仅在值 != 0 时进入 toolArgs,
	// 对应手写「putInt 仅在非零才入参」语义(如 devapp app-group-id)。
	LeafInt
)

type LeafSpec added in v1.0.55

type LeafSpec struct {
	Use     string
	Short   string
	Long    string
	Example string

	// Server 非空时走 callMCPToolOnServer(显式 server 路由),否则走
	// callMCPTool(按 product 路由)。Call 非空时两者都被忽略。
	Server string
	Tool   string
	Flags  []LeafFlag

	// Call 是可插拔派发函数,非空时替代默认的 callMCPTool/callMCPToolOnServer。
	// 供非 MCP 直连命令(如 devapp 走 executor.Runner)复用本框架:调用方用
	// 闭包捕获自己的 runner/派发器即可。签名与默认路径一致——收到框架装配好
	// 的 toolArgs,自行派发。
	Call func(cmd *cobra.Command, tool string, args map[string]any) error

	// Validate 是跨 flag 校验钩子(如时间区间、互斥关系),在 required
	// 校验之后、toolArgs 装配之前执行;nil 时跳过。单 flag 的格式转换
	// 应放在 LeafFlag.Transform,不要放进 Validate。
	Validate func(cmd *cobra.Command, args []string) error

	// RunE 非空时完全自定义执行体(逃生舱),框架只负责注册 flag。
	RunE func(cmd *cobra.Command, args []string) error

	// PostMount 在 flag 注册完成之后、RunE 设定之前对构建好的 cmd 做最终
	// 调整(设置 Args/DisableAutoGenTag、调用 annotate/preferLegacy 等)。
	// 无论是否使用 RunE 逃生舱都会执行。对标 lark shortcut 的 PostMount。
	PostMount func(cmd *cobra.Command)
}

LeafSpec 声明一个 MCP 直连叶子命令。

type Manifest

type Manifest struct {
	Vendor      string
	Name        string
	Description string
}

func (Manifest) FullName

func (m Manifest) FullName() string

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

Source Files

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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