app

package
v1.0.21 Latest Latest
Warning

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

Go to latest
Published: May 5, 2026 License: Apache-2.0 Imports: 57 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// PatAuthRetryTimeout is the maximum time to wait for user authorization
	// when a PAT scope error is detected.
	PatAuthRetryTimeout = 10 * time.Minute

	// PatAuthPollInterval is how often we poll to check if the user has
	// completed authorization.
	PatAuthPollInterval = 5 * time.Second
)
View Source
const (
	// PerfDebugEnv is the environment variable to enable performance timing output.
	PerfDebugEnv = "DWS_PERF_DEBUG"

	// PerfReportEnv is the environment variable to enable JSON perf report output.
	// Set to "auto" to write to ~/.dws/perf/latest.json, or a custom file path.
	PerfReportEnv = "DWS_PERF_REPORT"
)

Variables

This section is empty.

Functions

func AppendDynamicServer added in v1.0.9

func AppendDynamicServer(server market.ServerDescriptor)

AppendDynamicServer adds a single server descriptor to the existing dynamic server registry without replacing the current entries. This is used by the plugin loader to inject plugin servers alongside Market-discovered servers.

func BuildTime added in v1.0.7

func BuildTime() string

BuildTime returns the build timestamp injected via ldflags.

func CloseFileLogger

func CloseFileLogger()

CloseFileLogger flushes and closes the file logger.

func DirectRuntimeProductIDs

func DirectRuntimeProductIDs() map[string]bool

DirectRuntimeProductIDs returns the set of product IDs that have direct runtime endpoints configured, sourced from dynamic server discovery.

func DiscoveryBaseURL

func DiscoveryBaseURL() string

DiscoveryBaseURL returns the effective base URL for discovery — discoveryBaseURLOverride if set, otherwise DefaultMarketBaseURL.

func Execute

func Execute() (exitCode int)

Execute runs the root command and returns the process exit code.

func FileLoggerInstance

func FileLoggerInstance() *slog.Logger

FileLoggerInstance returns the package-level file logger, or nil if not initialized.

func ForceRefreshAccessToken added in v1.0.16

func ForceRefreshAccessToken(ctx context.Context, configDir string) (string, error)

ForceRefreshAccessToken forces a single refresh_token exchange and returns the new access_token. It is intended for callers that have observed a server-side rejection (HTTP 401 or business code such as TOKEN_VERIFIED_FAILED) on what locally appeared to be a still-valid token.

Steps:

  1. MarkAccessTokenStale rewrites ExpiresAt to a past instant so OAuthProvider.GetAccessToken's fast-path will miss.
  2. NewOAuthProvider + GetAccessToken triggers lockedRefresh, which uses the existing dual-layer lock (process + file) to serialize concurrent refresh attempts across goroutines and processes.
  3. ResetRuntimeTokenCache clears the per-process sync.Once cache so the next resolveAuthToken call re-reads from disk.

Existing OAuthProvider.GetAccessToken behaviour is unchanged; this helper is the only entry point that orchestrates "force refresh" semantics.

func GitCommit added in v1.0.7

func GitCommit() string

GitCommit returns the git commit hash injected via ldflags.

func IsAuthRetrying added in v1.0.16

func IsAuthRetrying(ctx context.Context) bool

IsAuthRetrying reports whether the current context is already inside an AuthRefreshRequired retry. Mirrors IsPatRetrying.

func IsPatRetrying added in v1.0.11

func IsPatRetrying(ctx context.Context) bool

IsPatRetrying returns true if the current context is already in a PAT retry.

func IsPerfDebugEnabled added in v1.0.8

func IsPerfDebugEnabled() bool

IsPerfDebugEnabled returns true if performance debug output is enabled.

func IsStdioEndpoint added in v1.0.9

func IsStdioEndpoint(endpoint string) bool

IsStdioEndpoint returns true if the endpoint uses the stdio:// scheme.

func LookupStdioClient added in v1.0.9

func LookupStdioClient(productID string) (*transport.StdioClient, bool)

LookupStdioClient returns the StdioClient registered for the given product ID. The productID can be either the full key (pluginName/serverKey) or just the serverKey. This supports backward compatibility with existing CanonicalProduct values.

func MCPIdentityHeaders added in v1.0.9

func MCPIdentityHeaders() map[string]string

MCPIdentityHeaders returns the same header map used for MCP HTTP requests (agent identity, env trace headers, edition MergeHeaders). Intended for non-MCP transports such as the A2A gateway client.

func NewRootCommand

func NewRootCommand(ctx ...context.Context) *cobra.Command

NewRootCommand constructs the root CLI command. The provided context is propagated to background goroutines and the Cobra command tree so that SIGINT/SIGTERM can cancel in-flight work.

func NewRootCommandWithEngine

func NewRootCommandWithEngine(rootCtx context.Context, engine *pipeline.Engine) *cobra.Command

NewRootCommandWithEngine constructs the root CLI command with an optional pipeline engine for input correction. When engine is nil, no pipeline processing is applied.

func PrintPatAuthError added in v1.0.11

func PrintPatAuthError(w io.Writer, scopeErr *PatScopeError)

PrintPatAuthError prints a human-readable PAT authorization error.

func PrintPatAuthJSON added in v1.0.11

func PrintPatAuthJSON(w io.Writer, scopeErr *PatScopeError)

PrintPatAuthJSON prints a machine-readable PAT authorization error.

func RawVersion added in v1.0.7

func RawVersion() string

RawVersion returns the bare version string without build metadata.

func RecordTiming added in v1.0.6

func RecordTiming(ctx context.Context, name string, d time.Duration)

RecordTiming is a convenience function to record timing to the collector in context.

func RegisterPluginAuth added in v1.0.9

func RegisterPluginAuth(productID string, auth *PluginAuth)

RegisterPluginAuth stores authentication credentials for a plugin server keyed by its canonical product ID. The runner looks up these credentials at execution time to inject the correct Bearer token instead of the default DingTalk OAuth token.

func RegisterStdioClient added in v1.0.9

func RegisterStdioClient(productID string, client *transport.StdioClient)

RegisterStdioClient stores a StdioClient keyed by its canonical product ID (the CLI.ID used in the server descriptor). The runner looks up this client when a stdio:// endpoint is resolved at execution time.

func ResetRuntimeTokenCache added in v1.0.5

func ResetRuntimeTokenCache()

ResetRuntimeTokenCache clears the cached token, forcing a reload on next access. This should be called after login/logout operations.

func ResolveAuxiliaryAccessToken added in v1.0.9

func ResolveAuxiliaryAccessToken(ctx context.Context, configDir, explicitToken string) (string, error)

ResolveAuxiliaryAccessToken resolves a bearer token for HTTP clients that should align with MCP tool calls. Non-empty explicitToken wins. When configDir matches the active edition config directory, the same process-cached path as MCP is used. Otherwise tokens are loaded from configDir with host compatibility hooks applied.

func SanitizeCommand added in v1.0.9

func SanitizeCommand(args []string) string

SanitizeCommand redacts sensitive flag values from a command arg slice.

func SetDiscoveryBaseURL

func SetDiscoveryBaseURL(url string)

SetDiscoveryBaseURL sets the base URL used for dynamic server discovery. Intended for test use only.

func SetDynamicServers

func SetDynamicServers(servers []market.ServerDescriptor)

SetDynamicServers injects server data discovered from servers.json. All product endpoints are resolved dynamically from this data.

func SetVersion added in v1.0.7

func SetVersion(v, bt, gc string)

SetVersion overrides the version, build time and git commit strings. Called by pkg/cli.SetVersion for overlay modules that inject their own version info via ldflags.

func StartTiming added in v1.0.6

func StartTiming(ctx context.Context, name string) func()

StartTiming is a convenience function that returns a stop function for defer usage. Example:

defer StartTiming(ctx, "operation")()

func StdioEndpoint added in v1.0.9

func StdioEndpoint(pluginName, serverKey string) string

StdioEndpoint returns a virtual endpoint URL for a stdio-based MCP server. Format: stdio://{pluginName}/{serverKey}

func StopAllStdioClients added in v1.0.10

func StopAllStdioClients()

StopAllStdioClients stops all registered stdio clients. This should be called on program exit to terminate child processes.

func StopStdioClient added in v1.0.10

func StopStdioClient(productID string) bool

StopStdioClient stops a specific stdio client by product ID. Returns true if the client was found and stopped, false otherwise.

func StopStdioClientsByPlugin added in v1.0.10

func StopStdioClientsByPlugin(pluginName string) int

StopStdioClientsByPlugin stops all stdio clients belonging to a plugin. The productID format is "pluginName/serverKey". This function stops all clients whose productID has the given pluginName prefix.

func Version

func Version() string

Version returns the current CLI version string, including build metadata when injected via ldflags (buildTime, gitCommit).

func WaitForPatAuthorization added in v1.0.11

func WaitForPatAuthorization(ctx context.Context, configDir string, output io.Writer) bool

WaitForPatAuthorization polls until the user completes authorization or timeout. It returns true if authorization was completed, false if timed out or cancelled.

func WithTimingCollector added in v1.0.6

func WithTimingCollector(ctx context.Context, tc *TimingCollector) context.Context

WithTimingCollector returns a new context with the TimingCollector attached.

Types

type CliSkillDTO added in v1.0.9

type CliSkillDTO struct {
	SkillID string `json:"skillId"`
	Name    string `json:"name"`
	Desc    string `json:"desc"`
	Icon    string `json:"icon"`
}

CliSkillDTO mirrors the old cli response payload for `skill search`.

type GlobalFlags

type GlobalFlags struct {
	ClientID     string
	ClientSecret string
	Debug        bool
	DryRun       bool
	Fields       string
	Format       string
	JQ           string
	Mock         bool
	Output       string
	Timeout      int
	Token        string
	Verbose      bool
	Yes          bool
}

GlobalFlags contains the root-level persistent flags shared across the CLI.

type PatScopeError added in v1.0.11

type PatScopeError struct {
	OriginalError string
	Identity      string
	ErrorType     string
	Message       string
	Hint          string
	MissingScope  string
}

PatScopeError holds information about a missing PAT scope.

func (*PatScopeError) Error added in v1.0.11

func (e *PatScopeError) Error() string

type PerfPhase added in v1.0.9

type PerfPhase struct {
	Name       string `json:"name"`
	DurationMs int64  `json:"duration_ms"`
	Seq        int    `json:"seq"`
}

PerfPhase is a single phase in the performance report.

type PerfReport added in v1.0.9

type PerfReport struct {
	Kind       string      `json:"kind"`
	Version    string      `json:"version"`
	CLIVersion string      `json:"cli_version"`
	Command    string      `json:"command"`
	Timestamp  time.Time   `json:"timestamp"`
	TotalMs    int64       `json:"total_ms"`
	Phases     []PerfPhase `json:"phases"`
	Slowest    string      `json:"slowest"`
	OverheadMs int64       `json:"overhead_ms"`
}

PerfReport is the JSON-serialisable performance report.

func LoadLatestReport added in v1.0.9

func LoadLatestReport() (*PerfReport, error)

LoadLatestReport reads the default perf report file (~/.dws/perf/latest.json).

type PluginAuth added in v1.0.9

type PluginAuth struct {
	// Token is the Bearer token extracted from the plugin's
	// "Authorization" header (e.g. a third-party API key).
	Token string

	// ExtraHeaders contains any additional custom HTTP headers
	// declared by the plugin (excluding Authorization).
	ExtraHeaders map[string]string

	// TrustedDomains lists the hostnames that the token is allowed
	// to be sent to. Typically derived from the server endpoint.
	TrustedDomains []string
}

PluginAuth holds authentication credentials for a plugin-owned streamable-http MCP server. Each server is keyed by its canonical product ID (CLI.ID) so that different servers can use independent tokens without interfering with each other or with the default DingTalk OAuth token.

func LookupPluginAuth added in v1.0.9

func LookupPluginAuth(productID string) (*PluginAuth, bool)

LookupPluginAuth returns the authentication credentials registered for the given product ID, or nil if none exists.

type TimingCollector added in v1.0.6

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

TimingCollector collects timing measurements for a single command execution. It is safe for concurrent use.

func NewTimingCollector added in v1.0.6

func NewTimingCollector() *TimingCollector

NewTimingCollector creates a new collector with the start time set to now.

func TimingCollectorFromContext added in v1.0.6

func TimingCollectorFromContext(ctx context.Context) *TimingCollector

TimingCollectorFromContext extracts the TimingCollector from context, or nil.

func (*TimingCollector) BuildReport added in v1.0.9

func (tc *TimingCollector) BuildReport(cliVersion, command string) PerfReport

BuildReport constructs a PerfReport from the collected timing entries.

func (*TimingCollector) Entries added in v1.0.6

func (tc *TimingCollector) Entries() []TimingEntry

Entries returns a copy of all recorded entries in insertion order.

func (*TimingCollector) Print added in v1.0.6

func (tc *TimingCollector) Print(w io.Writer)

Print writes a summary of all timing entries to the given writer.

func (*TimingCollector) PrintIfEnabled added in v1.0.6

func (tc *TimingCollector) PrintIfEnabled()

PrintIfEnabled prints timing info to stderr if DWS_PERF_DEBUG is set.

func (*TimingCollector) Record added in v1.0.6

func (tc *TimingCollector) Record(name string, d time.Duration)

Record adds a timing entry with the given name and duration.

func (*TimingCollector) StartTimer added in v1.0.6

func (tc *TimingCollector) StartTimer(name string) func()

StartTimer returns a function that, when called, records the elapsed time since StartTimer was called. This is convenient for defer usage:

defer tc.StartTimer("operation")()

func (*TimingCollector) Total added in v1.0.6

func (tc *TimingCollector) Total() time.Duration

Total returns the total elapsed time since the collector was created.

func (*TimingCollector) WriteReportIfEnabled added in v1.0.9

func (tc *TimingCollector) WriteReportIfEnabled(cliVersion, command string)

WriteReportIfEnabled checks DWS_PERF_REPORT and writes a JSON report if set.

type TimingEntry added in v1.0.6

type TimingEntry struct {
	Name      string
	Duration  time.Duration
	Timestamp time.Time
	Seq       int // insertion order
}

TimingEntry represents a single timing measurement.

Jump to

Keyboard shortcuts

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