helpers

package
v1.0.54 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 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 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 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 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 NewPublicCommands

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

func NormalizeSkillName

func NormalizeSkillName(input string) string

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

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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