refactor(cli): drop aiclient package; align AGENTS.md with mainstream
Survey of 10 mainstream CLIs (gh, lark, stripe, vercel, supabase, aws, azure, gcloud, openai/codex, github-copilot-cli) showed env-gated per-command --help blurbs are a Stripe-only pattern; gh uses env detect for telemetry only, and lark relies on installed agent Skills + MCP. Our cmd/mcp/serve already covers the dominant 2025/26 path, so internal/aiclient/ (136 LOC + 38 callsites) is net maintenance burden without precedent. - Drop internal/aiclient/ entirely (annotations + detect + tests) - Remove 38 SetAgentHelp callsites + agentAwareHelpFunc / SetHelpFunc wiring in cmd/root.go - Migrate 4 command-level rules to standard Long help (visible to all, not env-gated): doc upload mode mutex, kb edit at-least-one, kb pin idempotent, search chunks channel mutex - Rewrite AGENTS.md as a developer guide (gh-style 6 H2 / 167 lines): audience preamble + Build / Architecture / Command Structure / Testing / Code Style / Error Handling. Drops sections absent in surveyed projects (Commit & PR Conventions, Who Uses This CLI) - Clean 14 internal doc refs (ADR-N, spec §X, v0.X) in source comments and docs that pointed at docs/superpowers/ — that directory is local-only / uncommitted, so refs are dead for outside readers - Drop forward-looking "once v0.2 ships" from README
This commit is contained in:
+7
-17
@@ -1,18 +1,13 @@
|
||||
// Package agentcmd holds the `weknora agent` command tree:
|
||||
// list / view / invoke. The directory is named `agent/` (matches cobra
|
||||
// noun-verb convention) but the Go package is `agentcmd` to avoid
|
||||
// shadowing cli/internal/agent (which owns SetAgentHelp + agent-aware
|
||||
// help rendering for AI coding agents — a distinct concept from
|
||||
// WeKnora's first-class custom-agent resources).
|
||||
// colliding with cobra's *cobra.Command identifier.
|
||||
//
|
||||
// Disambiguation in cli/AGENTS.md: "agent" in this subtree refers to
|
||||
// WeKnora's user-defined Custom Agents (server resource: GET/POST
|
||||
// /agents/...). The CLI's `agent invoke` calls /agent-chat/:session_id
|
||||
// which dispatches the agent's configured workflow (system prompt,
|
||||
// allowed tools, KB scope, retrieval thresholds, etc.). This is
|
||||
// orthogonal to AGENTS.md / SetAgentHelp, which exists so AI coding
|
||||
// agents (Claude Code, Cursor) consuming the CLI can read structured
|
||||
// hints from --help.
|
||||
// "agent" in this subtree refers to WeKnora's user-defined Custom
|
||||
// Agents (server resource: GET/POST /agents/...). The CLI's
|
||||
// `agent invoke` calls /agent-chat/:session_id which dispatches the
|
||||
// agent's configured workflow (system prompt, allowed tools, KB scope,
|
||||
// retrieval thresholds).
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
@@ -29,12 +24,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
Short: "Manage and invoke custom agents",
|
||||
Long: `Custom Agents bundle a system prompt, model, tool allow-list, and KB
|
||||
scope into an addressable resource. List visible agents, view a single
|
||||
agent's configuration, or invoke an agent against a query.
|
||||
|
||||
Distinct from the per-CLI ` + "`AGENTS.md`" + ` reference: that file documents the
|
||||
contract for AI coding agents (Claude Code / Cursor) running ` + "`weknora`" + `
|
||||
on a user's behalf. This subtree manages WeKnora's first-class custom-agent
|
||||
resources stored on the server.`,
|
||||
agent's configuration, or invoke an agent against a query.`,
|
||||
Args: cobra.NoArgs,
|
||||
Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
@@ -18,7 +17,7 @@ import (
|
||||
)
|
||||
|
||||
// agentInvokeFields enumerates fields surfaced for `--json` discovery on
|
||||
// `agent invoke`. Matches invokeData below — the single-shot result
|
||||
// `agent invoke`. Matches invokeData below - the single-shot result
|
||||
// object with the agent's final answer plus the trace (references,
|
||||
// tool events).
|
||||
var agentInvokeFields = []string{
|
||||
@@ -36,7 +35,7 @@ type InvokeOptions struct {
|
||||
|
||||
// InvokeService is the narrow SDK surface this command depends on.
|
||||
//
|
||||
// CreateSession is called when --session is omitted — sessions are
|
||||
// CreateSession is called when --session is omitted - sessions are
|
||||
// agent-agnostic at creation (verified against
|
||||
// internal/handler/session/handler.go CreateSession, which only persists
|
||||
// {title, description}). The agent ID is supplied per-request via
|
||||
@@ -68,7 +67,7 @@ func NewCmdInvoke(f *cmdutil.Factory) *cobra.Command {
|
||||
tools, KB scope, retrieval thresholds) over SSE. By default a fresh session
|
||||
is auto-created; pass --session to continue an existing conversation. The
|
||||
agent picks the model, retrieval params, and tool surface from its own
|
||||
config — agent invoke is the thin shim that streams the result.
|
||||
config - agent invoke is the thin shim that streams the result.
|
||||
|
||||
Modes:
|
||||
TTY (default): live answer streaming + tool-trace footer
|
||||
@@ -94,7 +93,6 @@ Modes:
|
||||
cmd.Flags().StringVar(&opts.SessionID, "session", "", "Continue an existing chat session (skip auto-create)")
|
||||
cmd.Flags().BoolVar(&opts.NoStream, "no-stream", false, "Buffer the full answer before printing (forces accumulate mode)")
|
||||
cmdutil.AddJSONFlags(cmd, agentInvokeFields)
|
||||
aiclient.SetAgentHelp(cmd, "Streams an agent's answer over SSE. Pass --json (or run non-TTY) to receive a single completed {answer, references, tool_events, …} JSON object instead of partial chunks. Errors: resource.not_found (unknown agent_id) / server.session_create_failed (auto-create) / local.sse_stream_aborted (mid-stream).")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -167,7 +165,7 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
|
||||
return cmdutil.WrapHTTP(streamErr, "agent-chat stream")
|
||||
}
|
||||
|
||||
// Server closed cleanly but never sent a Done event — treat as aborted
|
||||
// Server closed cleanly but never sent a Done event - treat as aborted
|
||||
// so agents don't silently emit a truncated answer as ok=true.
|
||||
if !acc.Done() {
|
||||
return cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")
|
||||
@@ -204,7 +202,7 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
|
||||
}
|
||||
|
||||
// renderToolTrace prints a compact tool-event footer in human mode.
|
||||
// Skipped when the agent emitted no tool events — silent beats an empty
|
||||
// Skipped when the agent emitted no tool events - silent beats an empty
|
||||
// banner.
|
||||
func renderToolTrace(w io.Writer, events []sse.AgentToolEvent) {
|
||||
if len(events) == 0 {
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/text"
|
||||
@@ -17,7 +16,7 @@ import (
|
||||
)
|
||||
|
||||
// agentListFields enumerates the fields surfaced for `--json` discovery
|
||||
// on `agent list`. Mirrors the json tags on sdk.Agent — nested Config is
|
||||
// on `agent list`. Mirrors the json tags on sdk.Agent - nested Config is
|
||||
// omitted because its sub-fields make filtering noisy (use `--jq` instead).
|
||||
var agentListFields = []string{
|
||||
"id", "name", "description", "avatar",
|
||||
@@ -59,7 +58,6 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
}
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (0 = no cap, 1..10000 = explicit)")
|
||||
cmdutil.AddJSONFlags(cmd, agentListFields)
|
||||
aiclient.SetAgentHelp(cmd, "Lists tenant-visible agents (built-in + custom) as a bare JSON array of Agent objects (empty `[]` when none). --limit caps the returned slice. Use `--json=id,name` to project fields, `--jq` for arbitrary reshape.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -80,7 +78,7 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
|
||||
if items == nil {
|
||||
items = []sdk.Agent{} // ensure JSON [] not null
|
||||
}
|
||||
// Default sort: updated_at desc — most recently-edited agents surface
|
||||
// Default sort: updated_at desc - most recently-edited agents surface
|
||||
// first. Mirrors kb list / doc list behavior.
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
return items[i].UpdatedAt.After(items[j].UpdatedAt)
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
@@ -15,7 +14,7 @@ import (
|
||||
|
||||
// agentViewFields enumerates fields surfaced for `--json` discovery on
|
||||
// `agent view`. Filter applies to the bare Agent object. Config sub-fields
|
||||
// are intentionally omitted — too granular for naked projection; use
|
||||
// are intentionally omitted - too granular for naked projection; use
|
||||
// `--jq '.config'` to reach them.
|
||||
var agentViewFields = []string{
|
||||
"id", "name", "description", "avatar",
|
||||
@@ -36,7 +35,7 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
|
||||
Long: `Renders the agent's metadata (id / name / description / created-by /
|
||||
timestamps) plus a compact config summary (mode, model, allowed tools, KB
|
||||
scope). Pass --json for the full Agent object including the nested config
|
||||
struct — or --jq '.config' to extract just the config.`,
|
||||
struct - or --jq '.config' to extract just the config.`,
|
||||
Example: ` weknora agent view ag_abc
|
||||
weknora agent view ag_abc --json | jq '.config.allowed_tools'`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
@@ -53,7 +52,6 @@ struct — or --jq '.config' to extract just the config.`,
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, agentViewFields)
|
||||
aiclient.SetAgentHelp(cmd, "Fetches an agent by ID. Returns the full sdk.Agent (with nested config) as a bare JSON object. Errors: resource.not_found when the agent ID does not exist or is not visible to the active tenant.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
+2
-4
@@ -18,14 +18,13 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// apiFields is intentionally a marker — api wraps arbitrary HTTP responses
|
||||
// apiFields is intentionally a marker - api wraps arbitrary HTTP responses
|
||||
// whose schema the CLI doesn't know, so the `--json=id,name` field-filter
|
||||
// is a no-op here. The marker shows up in --help so users can tell.
|
||||
var apiFields = []string{"<response-shape-varies>"}
|
||||
@@ -74,7 +73,7 @@ Examples:
|
||||
}
|
||||
method := resolveMethod(opts)
|
||||
// Escape-hatch DELETE through `weknora api` is just as destructive
|
||||
// as `weknora kb delete` — exit-10 protocol must apply (AGENTS.md).
|
||||
// as `weknora kb delete` - exit-10 protocol must apply (cli/README.md).
|
||||
if method == http.MethodDelete {
|
||||
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, jopts.Enabled(), "endpoint", args[0]); err != nil {
|
||||
return err
|
||||
@@ -92,7 +91,6 @@ Examples:
|
||||
cmd.Flags().StringVar(&opts.Input, "input", "", "Read request body from file (use `-` for stdin)")
|
||||
cmdutil.AddJSONFlags(cmd, apiFields)
|
||||
cmd.MarkFlagsMutuallyExclusive("data", "input")
|
||||
aiclient.SetAgentHelp(cmd, "Raw HTTP passthrough. Auth / tenant / request-id headers injected from the active context. --json wraps as {status, headers, body}; --json field filtering is ignored here (response shape unknown to CLI) — use --jq for reshape. DELETE triggers exit-10 confirm. Non-2xx maps to typed errors via ClassifyHTTPStatus (4xx → input.invalid_argument / auth.* / resource.not_found; 5xx → server.error). --data and --input are mutually exclusive.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -201,7 +201,7 @@ func TestAPI_PathWithoutSlash(t *testing.T) {
|
||||
// withRootHarness wraps `weknora api ...` under a synthetic root cmd that
|
||||
// registers the global `-y/--yes` persistent flag (mirrors addGlobalFlags in
|
||||
// cmd/root.go). Required because api's NewCmd doesn't register --yes itself
|
||||
// — it inherits from root in production.
|
||||
// - it inherits from root in production.
|
||||
func withRootHarness(api *cobra.Command, args ...string) *cobra.Command {
|
||||
root := &cobra.Command{Use: "weknora"}
|
||||
root.PersistentFlags().BoolP("yes", "y", false, "")
|
||||
@@ -260,7 +260,7 @@ func TestAPI_DELETE_WithYes_Proceeds(t *testing.T) {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
if !called {
|
||||
t.Error("DELETE handler not called — confirmation may have blocked")
|
||||
t.Error("DELETE handler not called - confirmation may have blocked")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ const (
|
||||
)
|
||||
|
||||
// modeFromRefs maps the per-context TokenRef / APIKeyRef presence to a
|
||||
// canonical credential-mode token. Bearer wins when both are present —
|
||||
// canonical credential-mode token. Bearer wins when both are present -
|
||||
// matches the precedence in cmdutil.buildClient.
|
||||
func modeFromRefs(apiKeyRef, tokenRef string) string {
|
||||
switch {
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
@@ -31,11 +30,12 @@ type listEntry struct {
|
||||
|
||||
// NewCmdList builds `weknora auth list`. Per-host enumeration: render one
|
||||
// row per registered context, marking the active one. Reads only
|
||||
// ~/.config/weknora/config.yaml — no network, no keyring touch.
|
||||
// ~/.config/weknora/config.yaml - no network, no keyring touch.
|
||||
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List configured authentication contexts",
|
||||
Long: `Show every configured context (name, host, user, mode, current). Read-only; no network or keyring access.`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
@@ -46,7 +46,6 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, authListFields)
|
||||
aiclient.SetAgentHelp(cmd, "Lists configured auth contexts (name/host/user/mode/current). Read-only, no network, no keyring access. Use to confirm context names before --context or `auth login --name`.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ func TestList_HumanRender(t *testing.T) {
|
||||
// Mode column.
|
||||
assert.Contains(t, got, ModeBearer)
|
||||
assert.Contains(t, got, ModeAPIKey)
|
||||
// Sorted alphabetically — prod after staging? No: "prod" < "staging".
|
||||
// Sorted alphabetically - prod after staging? No: "prod" < "staging".
|
||||
assert.Less(t, strings.Index(got, "prod"), strings.Index(got, "staging"),
|
||||
"contexts should render sorted by name")
|
||||
}
|
||||
@@ -72,7 +72,7 @@ func TestList_JSON_BareArray(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestModeFromRefs(t *testing.T) {
|
||||
// Hand-edited config with neither ref set — surface "unknown" rather
|
||||
// Hand-edited config with neither ref set - surface "unknown" rather
|
||||
// than pretending the context is a valid login.
|
||||
assert.Equal(t, ModeUnknown, modeFromRefs("", ""))
|
||||
assert.Equal(t, ModeBearer, modeFromRefs("", "tok"))
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
@@ -17,7 +16,7 @@ import (
|
||||
)
|
||||
|
||||
// authLoginFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `auth login`. The post-login summary has no token values — they stay in the
|
||||
// `auth login`. The post-login summary has no token values - they stay in the
|
||||
// keyring; agents who need to verify the credential should re-run
|
||||
// `auth status`.
|
||||
var authLoginFields = []string{
|
||||
@@ -97,7 +96,6 @@ the current_context in ~/.config/weknora/config.yaml.`,
|
||||
cmd.Flags().BoolVar(&opts.WithToken, "with-token", false, "Read an API key from stdin instead of prompting for password")
|
||||
cmdutil.AddJSONFlags(cmd, authLoginFields)
|
||||
_ = cmd.MarkFlagRequired("host")
|
||||
aiclient.SetAgentHelp(cmd, "Authenticates and stores credentials. --with-token reads an API key from stdin (no password prompt, agent-safe). Otherwise email/password prompts fire — non-TTY callers must pipe `--with-token` or pre-set --name. Errors: auth.bad_credential on wrong password; input.invalid_argument on bad --host; input.missing_flag when --with-token has empty stdin.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -126,7 +124,7 @@ func runLogin(ctx context.Context, opts *LoginOptions, jopts *cmdutil.JSONOption
|
||||
opts.APIKey = key
|
||||
// Validate against the server before persisting so a typo'd /
|
||||
// expired / wrong-host key fails fast (gh CLI parity). The probe
|
||||
// is /auth/me — read-only, side-effect-free.
|
||||
// is /auth/me - read-only, side-effect-free.
|
||||
user, err := defaultAPIKeyValidator(ctx, opts.Host, key)
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeAuthBadCredential, err, "validate API key")
|
||||
@@ -268,7 +266,7 @@ func validateHost(host string) error {
|
||||
|
||||
// warnOnFileFallback prints a one-shot stderr advisory when the secrets
|
||||
// store fell back to the plaintext 0600 file backend (keychain unavailable
|
||||
// — typical on headless CI, WSL without DBus, agent containers). Helps
|
||||
// - typical on headless CI, WSL without DBus, agent containers). Helps
|
||||
// users notice that credentials are NOT in the OS keychain before they're
|
||||
// surprised by it later. doctor's credential_storage check carries the
|
||||
// same info but agents that bypass doctor would otherwise miss it.
|
||||
@@ -276,7 +274,7 @@ func warnOnFileFallback(store secrets.Store) {
|
||||
if _, isFile := store.(*secrets.FileStore); !isFile {
|
||||
return
|
||||
}
|
||||
fmt.Fprintln(iostreams.IO.Err, "warning: OS keychain unavailable — credentials will be saved to a 0600 file under $XDG_CONFIG_HOME/weknora/secrets/.")
|
||||
fmt.Fprintln(iostreams.IO.Err, "warning: OS keychain unavailable - credentials will be saved to a 0600 file under $XDG_CONFIG_HOME/weknora/secrets/.")
|
||||
fmt.Fprintln(iostreams.IO.Err, " install / unlock the keyring (or use `weknora doctor` to inspect) for OS-backed storage.")
|
||||
}
|
||||
|
||||
|
||||
@@ -124,7 +124,7 @@ func stubAPIKeyValidator(fn apiKeyValidator) func() {
|
||||
func TestRunLogin_WithToken_Empty(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
|
||||
// Validator must NOT be called when stdin is empty — verify by setting
|
||||
// Validator must NOT be called when stdin is empty - verify by setting
|
||||
// a panic-on-call sentinel.
|
||||
restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) {
|
||||
t.Fatal("validator should not be called on empty stdin")
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
@@ -30,7 +29,7 @@ type logoutResult struct {
|
||||
|
||||
// NewCmdLogout builds `weknora auth logout`. Clears stored credentials
|
||||
// (keyring + file fallback) and removes the context entry from config.yaml.
|
||||
// No server-side revocation — local-only credential clear.
|
||||
// No server-side revocation - local-only credential clear.
|
||||
func NewCmdLogout(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &LogoutOptions{}
|
||||
cmd := &cobra.Command{
|
||||
@@ -39,7 +38,7 @@ func NewCmdLogout(f *cmdutil.Factory) *cobra.Command {
|
||||
Long: `Clear keyring + file-fallback secrets for one context (or all of
|
||||
them with --all) and drop the context entry from ~/.config/weknora/config.yaml.
|
||||
|
||||
Note: this does NOT revoke the credential server-side — for API keys, you
|
||||
Note: this does NOT revoke the credential server-side - for API keys, you
|
||||
must rotate them in the server UI; for JWT, the token will continue to be
|
||||
accepted until it expires.`,
|
||||
Example: ` weknora auth logout # current context
|
||||
@@ -58,7 +57,6 @@ accepted until it expires.`,
|
||||
cmd.Flags().BoolVar(&opts.All, "all", false, "Log out of every configured context")
|
||||
cmdutil.AddJSONFlags(cmd, authLogoutFields)
|
||||
cmd.MarkFlagsMutuallyExclusive("name", "all")
|
||||
aiclient.SetAgentHelp(cmd, "Clears local credentials only; the server-side token / api-key continues to be valid until expired or rotated. Returns data.removed: [...names]. Errors: auth.unauthenticated when no contexts configured.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -85,7 +83,7 @@ func runLogout(opts *LogoutOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Facto
|
||||
delete(cfg.Contexts, name)
|
||||
}
|
||||
// If we removed the active context, pick a remaining one (deterministic by
|
||||
// map order would be flaky — leave CurrentContext empty so the next
|
||||
// map order would be flaky - leave CurrentContext empty so the next
|
||||
// invocation surfaces a clear "no current context" error rather than
|
||||
// silently switching).
|
||||
if _, stillExists := cfg.Contexts[cfg.CurrentContext]; !stillExists {
|
||||
@@ -128,7 +126,7 @@ func pickLogoutTargets(opts *LogoutOptions, cfg *config.Config) ([]string, error
|
||||
|
||||
// clearContextSecrets best-effort deletes every secret slot the context
|
||||
// references. Errors are swallowed because a missing secret is a no-op
|
||||
// (tested in keyring_test.go) — we don't want a stale ref to block logout.
|
||||
// (tested in keyring_test.go) - we don't want a stale ref to block logout.
|
||||
func clearContextSecrets(store secrets.Store, c config.Context, name string) {
|
||||
if c.TokenRef != "" {
|
||||
_ = store.Delete(name, "access")
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
)
|
||||
|
||||
// newLogoutFactory builds a Factory whose Config closure mutates the supplied
|
||||
// cfg in place — runLogout writes back via config.Save which touches disk, so
|
||||
// cfg in place - runLogout writes back via config.Save which touches disk, so
|
||||
// tests use t.Setenv("XDG_CONFIG_HOME", t.TempDir()) at the call site to
|
||||
// isolate the on-disk file.
|
||||
func newLogoutFactory(t *testing.T, cfg *config.Config, store secrets.Store) *cmdutil.Factory {
|
||||
|
||||
+8
-10
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
@@ -17,11 +16,11 @@ type RefreshOptions struct {
|
||||
}
|
||||
|
||||
// authRefreshFields enumerates the fields surfaced for `--json` discovery
|
||||
// on `auth refresh`. Token values are intentionally omitted — see refreshResult.
|
||||
// on `auth refresh`. Token values are intentionally omitted - see refreshResult.
|
||||
var authRefreshFields = []string{"context"}
|
||||
|
||||
// refreshResult is the typed payload emitted under data on success. Token
|
||||
// values are intentionally NOT included — emitting them would leak secrets
|
||||
// values are intentionally NOT included - emitting them would leak secrets
|
||||
// into stdout / agent transcripts. Agents needing to verify the new token
|
||||
// can re-run `weknora auth status` (live API check).
|
||||
type refreshResult struct {
|
||||
@@ -29,10 +28,10 @@ type refreshResult struct {
|
||||
}
|
||||
|
||||
// NewCmdRefresh builds `weknora auth refresh`. Renews the JWT access
|
||||
// token by spending the stored refresh_token via POST /auth/refresh —
|
||||
// token by spending the stored refresh_token via POST /auth/refresh -
|
||||
// the standard OAuth refresh-token grant.
|
||||
//
|
||||
// API-key contexts are rejected — they have no refresh semantic;
|
||||
// API-key contexts are rejected - they have no refresh semantic;
|
||||
// rotate the key via the server UI instead.
|
||||
func NewCmdRefresh(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &RefreshOptions{}
|
||||
@@ -43,7 +42,7 @@ func NewCmdRefresh(f *cmdutil.Factory) *cobra.Command {
|
||||
exchanges it for a new access + refresh token pair via POST /api/v1/auth/refresh.
|
||||
Both new tokens replace the existing entries in the OS keyring.
|
||||
|
||||
API-key contexts are rejected with input.invalid_argument — they have no
|
||||
API-key contexts are rejected with input.invalid_argument - they have no
|
||||
refresh semantic. Rotate the key in the server UI instead.`,
|
||||
Example: ` weknora auth refresh # refresh the current context
|
||||
weknora auth refresh --name staging # refresh a specific context`,
|
||||
@@ -58,12 +57,11 @@ refresh semantic. Rotate the key in the server UI instead.`,
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.Name, "name", "", "Context to refresh (defaults to the current context)")
|
||||
cmdutil.AddJSONFlags(cmd, authRefreshFields)
|
||||
aiclient.SetAgentHelp(cmd, "Renews the access token using the stored refresh token. Errors with auth.token_expired when refresh itself is rejected — surface the hint to re-run auth login.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// defaultRefresher constructs a fresh, unauthenticated SDK client targeting
|
||||
// host — the /auth/refresh endpoint reads the refresh token from the body,
|
||||
// host - the /auth/refresh endpoint reads the refresh token from the body,
|
||||
// so no bearer / api-key header is needed.
|
||||
func defaultRefresher(host string) cmdutil.Refresher {
|
||||
return sdk.NewClient(host)
|
||||
@@ -92,9 +90,9 @@ func runRefresh(ctx context.Context, opts *RefreshOptions, jopts *cmdutil.JSONOp
|
||||
fmt.Sprintf("context %q has no host", name))
|
||||
}
|
||||
if c.RefreshRef == "" {
|
||||
hint := "api-key contexts can't be refreshed — rotate the key in the server UI and run `weknora auth login --with-token`"
|
||||
hint := "api-key contexts can't be refreshed - rotate the key in the server UI and run `weknora auth login --with-token`"
|
||||
if c.APIKeyRef == "" {
|
||||
hint = "no refresh token stored — run `weknora auth login` to authenticate"
|
||||
hint = "no refresh token stored - run `weknora auth login` to authenticate"
|
||||
}
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
|
||||
@@ -140,7 +140,7 @@ func TestRefresh_NoRefreshTokenStored(t *testing.T) {
|
||||
"prod": {Host: "https://kb", TokenRef: "mem://prod/access", RefreshRef: "mem://prod/refresh"},
|
||||
},
|
||||
}
|
||||
// MemStore is empty — RefreshRef points to a slot that doesn't exist.
|
||||
// MemStore is empty - RefreshRef points to a slot that doesn't exist.
|
||||
f := newRefreshFactory(t, cfg, secrets.NewMemStore())
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, nil, f, stubSvc(&fakeRefreshService{}))
|
||||
require.Error(t, err)
|
||||
@@ -168,7 +168,7 @@ func TestRefresh_ServerRefused(t *testing.T) {
|
||||
assert.Contains(t, typed.Hint, "auth login")
|
||||
// stored access must NOT have been overwritten with empty
|
||||
if v, _ := store.Get("prod", "access"); v == "" {
|
||||
// Was never set in this test, that's fine — main thing is no panic.
|
||||
// Was never set in this test, that's fine - main thing is no panic.
|
||||
_ = v
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
@@ -37,7 +36,14 @@ func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "status",
|
||||
Short: "Show the active context, principal, and token state",
|
||||
Args: cobra.NoArgs,
|
||||
Long: `Live-check the active credential by calling /auth/me. Reports the user
|
||||
and tenant the server resolves the credential to.
|
||||
|
||||
Exits with auth.unauthenticated when the token is invalid or missing - run
|
||||
` + "`weknora auth login`" + ` (or ` + "`auth refresh`" + ` for JWT contexts) to recover.
|
||||
For JWT contexts the SDK transparently refreshes on 401, so this command
|
||||
usually only surfaces a hard auth failure.`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
if err != nil {
|
||||
@@ -51,7 +57,6 @@ func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, authStatusFields)
|
||||
aiclient.SetAgentHelp(cmd, "Live-checks the active credential by calling /auth/me. Returns {context, user_id, email, tenant_id, tenant_name}. Errors: auth.unauthenticated when token is invalid or missing (run `auth login` / `auth refresh`).")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ func TestRunStatus_SDKError_Transport(t *testing.T) {
|
||||
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
|
||||
err := runStatus(context.Background(), nil, f, &fakeStatusService{err: assert.AnError})
|
||||
require.Error(t, err)
|
||||
// Non-HTTP errors (DNS / TCP) are transport problems, not auth problems —
|
||||
// Non-HTTP errors (DNS / TCP) are transport problems, not auth problems -
|
||||
// classify network.error so retry logic / exit code 7 / IsTransient apply.
|
||||
assert.True(t, cmdutil.IsTransient(err), "expected transient/network classification, got %v", err)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
@@ -27,7 +26,7 @@ type tokenResult struct {
|
||||
// curl -H "Authorization: Bearer $WEKNORA_TOKEN" ... # JWT mode
|
||||
// curl -H "X-API-Key: $WEKNORA_TOKEN" ... # api-key mode
|
||||
//
|
||||
// The user is responsible for constructing the appropriate header —
|
||||
// The user is responsible for constructing the appropriate header -
|
||||
// `auth list` shows which mode each context uses.
|
||||
//
|
||||
// Default output: raw token on stdout, no trailing newline (clean $(...)).
|
||||
@@ -60,7 +59,6 @@ to see which mode each context uses, and construct the matching HTTP header:
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, authTokenFields)
|
||||
aiclient.SetAgentHelp(cmd, "Prints the active context's credential to stdout for scripting. Default: raw secret, no trailing newline. With --json: bare {token, mode, context} object. Errors: auth.unauthenticated when no active context or no stored credential (run `auth login`); local.keychain_denied when the keyring rejects the read.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -89,7 +87,7 @@ func runToken(f *cmdutil.Factory, jopts *cmdutil.JSONOptions) error {
|
||||
}
|
||||
|
||||
// Resolve the stored credential. Prefer bearer (JWT) when both refs
|
||||
// are present — JWT is the more capable mode and what `buildClient`
|
||||
// are present - JWT is the more capable mode and what `buildClient`
|
||||
// uses for the Authorization header (see factory.go buildClient).
|
||||
var token, mode string
|
||||
switch {
|
||||
@@ -119,18 +117,18 @@ func runToken(f *cmdutil.Factory, jopts *cmdutil.JSONOptions) error {
|
||||
return jopts.Emit(iostreams.IO.Out, tokenResult{Token: token, Mode: mode, Context: ctxName})
|
||||
}
|
||||
|
||||
// No trailing newline — clean $(weknora auth token) substitution.
|
||||
// No trailing newline - clean $(weknora auth token) substitution.
|
||||
fmt.Fprint(iostreams.IO.Out, token)
|
||||
// Defensive hint to stderr when stdout is an interactive terminal:
|
||||
// the user likely didn't mean to display the secret on screen.
|
||||
// stderr-only so scripts (always non-TTY) are unaffected. Mode-specific
|
||||
// because api-key tokens are long-lived and rotation is the only
|
||||
// recourse on leak — bearer tokens self-expire via refresh.
|
||||
// recourse on leak - bearer tokens self-expire via refresh.
|
||||
if iostreams.IO.IsStdoutTTY() {
|
||||
fmt.Fprintln(iostreams.IO.Err)
|
||||
fmt.Fprintln(iostreams.IO.Err, "hint: pipe to $(weknora auth token) to capture; this terminal scrollback now contains the secret")
|
||||
if mode == ModeAPIKey {
|
||||
fmt.Fprintln(iostreams.IO.Err, "note: api-key credentials are long-lived — rotate via your auth provider if exposed (no `auth refresh` path)")
|
||||
fmt.Fprintln(iostreams.IO.Err, "note: api-key credentials are long-lived - rotate via your auth provider if exposed (no `auth refresh` path)")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -165,7 +165,7 @@ func TestAuthToken_NoStoredCredential(t *testing.T) {
|
||||
},
|
||||
}
|
||||
store := secrets.NewMemStore()
|
||||
// no Set — keyring is empty
|
||||
// no Set - keyring is empty
|
||||
iostreams.SetForTest(t)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), nil)
|
||||
if err == nil {
|
||||
@@ -200,7 +200,7 @@ func TestAuthToken_ContextWithNoCredentialRefs(t *testing.T) {
|
||||
// interactive terminal, it ALSO writes a stderr advisory ("you just put the
|
||||
// secret in your scrollback") + a mode-specific rotation note for api-key
|
||||
// credentials. The stdout half must stay clean under all modes so $(...)
|
||||
// substitution is unaffected — tests assert both axes.
|
||||
// substitution is unaffected - tests assert both axes.
|
||||
|
||||
func makeBearerCfg() (*config.Config, *secrets.MemStore) {
|
||||
cfg := &config.Config{
|
||||
@@ -278,7 +278,7 @@ func TestAuthToken_TTY_APIKeyMode_IncludesRotationNote(t *testing.T) {
|
||||
func TestAuthToken_TTY_JSONMode_NoStderrHint(t *testing.T) {
|
||||
// --json output mode targets script/agent consumers even when stdout
|
||||
// happens to be a TTY (e.g. an IDE running the CLI on the user's
|
||||
// behalf). Hint would pollute their parsing — suppress.
|
||||
// behalf). Hint would pollute their parsing - suppress.
|
||||
cfg, store := makeBearerCfg()
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.JSONOptions{}); err != nil {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Package chat implements `weknora chat <text>` — the streaming RAG answer
|
||||
// Package chat implements `weknora chat <text>` - the streaming RAG answer
|
||||
// entry point.
|
||||
//
|
||||
// Two output modes share a single SDK call:
|
||||
@@ -27,7 +27,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
@@ -116,7 +115,6 @@ Modes:
|
||||
cmd.Flags().StringVar(&opts.SessionID, "session", "", "Continue an existing chat session (skip auto-create)")
|
||||
cmd.Flags().BoolVar(&opts.NoStream, "no-stream", false, "Buffer the full answer before printing (forces accumulate mode)")
|
||||
cmdutil.AddJSONFlags(cmd, chatFields)
|
||||
aiclient.SetAgentHelp(cmd, "Streams an LLM answer over SSE. Agent / non-TTY callers should pass --json so the full {answer, references, session_id, assistant_message_id} object is emitted once at completion (no partial chunks). Pass --session to thread follow-ups. Errors: server.session_create_failed when auto-create fails; local.sse_stream_aborted on mid-stream disconnect.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -161,7 +159,7 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
|
||||
streamMode := iostreams.IO.IsStdoutTTY() && !opts.NoStream && !jsonOut
|
||||
|
||||
// Surface the auto-created session ID up-front so a user who hits ^C
|
||||
// mid-stream still has the pointer to resume — no need to scroll back
|
||||
// mid-stream still has the pointer to resume - no need to scroll back
|
||||
// past tokens. Skipped in JSON mode (it ends up in the data object) and
|
||||
// when the caller already supplied --session.
|
||||
if autoCreated && !jsonOut {
|
||||
@@ -193,7 +191,7 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
|
||||
// Re-surface the auto-created session id on failure so a user who
|
||||
// missed the start-of-stream notice (it scrolls past mid-stream
|
||||
// tokens, especially on ^C) can still recover with --session.
|
||||
// Skipped in JSON mode — the data object carries it in .session_id.
|
||||
// Skipped in JSON mode - the data object carries it in .session_id.
|
||||
if autoCreated && !jsonOut {
|
||||
fmt.Fprintf(iostreams.IO.Err, "session: %s (resume with --session %s)\n", sessionID, sessionID)
|
||||
}
|
||||
@@ -212,11 +210,11 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
|
||||
return cmdutil.WrapHTTP(streamErr, "knowledge qa stream")
|
||||
}
|
||||
|
||||
// SDK returned nil but we never saw a Done event — server closed the
|
||||
// SDK returned nil but we never saw a Done event - server closed the
|
||||
// connection cleanly mid-stream. Treat as aborted so the user sees the
|
||||
// truncation rather than a silent partial answer. Includes the empty-body
|
||||
// case (Done frame never arrived AND no content): better to surface the
|
||||
// abort than emit ok=true with answer="" — agents can't distinguish the
|
||||
// abort than emit ok=true with answer="" - agents can't distinguish the
|
||||
// model genuinely had nothing to say from the stream getting cut.
|
||||
if !acc.Done() {
|
||||
return cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")
|
||||
@@ -227,7 +225,7 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
|
||||
|
||||
if jsonOut {
|
||||
// Prefer the SDK-echoed session id (acc.SessionID) but fall back to
|
||||
// our local sessionID — agents must always see a usable pointer.
|
||||
// our local sessionID - agents must always see a usable pointer.
|
||||
sid := acc.SessionID
|
||||
if sid == "" {
|
||||
sid = sessionID
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
@@ -32,7 +31,7 @@ type addResult struct {
|
||||
}
|
||||
|
||||
// NewCmdAdd builds `weknora context add`. Registers a *credentialless*
|
||||
// connection target — host + optional user only. Credentials for the new
|
||||
// connection target - host + optional user only. Credentials for the new
|
||||
// context are attached separately with `weknora auth login --name <n>`,
|
||||
// separating "where" the CLI talks to (the host) and "how" it authenticates
|
||||
// (the credential). If you want one command for both, run
|
||||
@@ -64,7 +63,6 @@ adds leave the current context untouched.`,
|
||||
cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in 'context list' (optional, cosmetic only)")
|
||||
cmdutil.AddJSONFlags(cmd, contextAddFields)
|
||||
_ = cmd.MarkFlagRequired("host")
|
||||
aiclient.SetAgentHelp(cmd, "Adds a context. First context added auto-becomes current. Errors with resource.already_exists if name collides; input.invalid_argument if --host is not an absolute http(s) URL.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// consistent with the rest of this CLI.
|
||||
//
|
||||
// Package name `contextcmd` (not `context`) to avoid shadowing stdlib context.
|
||||
// The cobra Use: string is "context" — this is what users type.
|
||||
// The cobra Use: string is "context" - this is what users type.
|
||||
package contextcmd
|
||||
|
||||
import (
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
@@ -30,7 +29,7 @@ type listEntry struct {
|
||||
}
|
||||
|
||||
// NewCmdList builds `weknora context list`. Per-host enumeration with an
|
||||
// active marker. Reads only config.yaml — no network, no keyring touch.
|
||||
// active marker. Reads only config.yaml - no network, no keyring touch.
|
||||
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "list",
|
||||
@@ -39,7 +38,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
active context (used by subsequent commands when --context is unset) is
|
||||
marked with a leading "*". No network requests are issued.
|
||||
|
||||
The credential mode (api-key vs password) is intentionally not shown here —
|
||||
The credential mode (api-key vs password) is intentionally not shown here -
|
||||
run "weknora auth list" for that. "context list" is the catalog of *where*
|
||||
the CLI can talk to; "auth list" is the catalog of *how*.`,
|
||||
Args: cobra.NoArgs,
|
||||
@@ -52,7 +51,6 @@ the CLI can talk to; "auth list" is the catalog of *how*.`,
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, contextListFields)
|
||||
aiclient.SetAgentHelp(cmd, "Lists CLI contexts (name/host/user/current). Read-only, no network. Use this before context use to verify the target name exists.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
@@ -43,11 +42,11 @@ func NewCmdRemove(f *cmdutil.Factory) *cobra.Command {
|
||||
Long: `Deletes the named context from config.yaml and best-effort clears any
|
||||
keyring references it owned (matches ` + "`weknora auth logout`" + `).
|
||||
|
||||
Removing the current context also clears CurrentContext — subsequent commands
|
||||
Removing the current context also clears CurrentContext - subsequent commands
|
||||
will error until you select another with ` + "`weknora context use <name>`" + ` or pick
|
||||
one up via the global ` + "`--context`" + ` flag. Because that change is observable in
|
||||
every later command, removing the current context requires explicit -y/--yes
|
||||
in scripted / --json invocations (exit code 10; see cli/AGENTS.md).`,
|
||||
in scripted / --json invocations (exit code 10; see cli/README.md).`,
|
||||
Example: ` weknora context remove staging # remove non-current → no prompt
|
||||
weknora context remove production -y # remove current → confirm`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
@@ -65,7 +64,6 @@ in scripted / --json invocations (exit code 10; see cli/AGENTS.md).`,
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, contextRemoveFields)
|
||||
aiclient.SetAgentHelp(cmd, "Removes a context entry. Removing the current context requires -y in non-TTY/--json (exit-10). Always best-effort clears keyring refs.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -81,7 +79,7 @@ func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, sto
|
||||
wasCurrent := name == cfg.CurrentContext
|
||||
|
||||
jsonOut := jopts.Enabled()
|
||||
// Confirmation only fires for removing the current context — non-current
|
||||
// Confirmation only fires for removing the current context - non-current
|
||||
// remove uses the same low-friction policy as `auth logout`.
|
||||
if wasCurrent {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jsonOut, "current context", name); err != nil {
|
||||
@@ -105,7 +103,7 @@ func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, sto
|
||||
return jopts.Emit(iostreams.IO.Out, result)
|
||||
}
|
||||
if wasCurrent {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s (current context cleared — run `weknora context use <name>` to pick another)\n", name)
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s (current context cleared - run `weknora context use <name>` to pick another)\n", name)
|
||||
} else {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s\n", name)
|
||||
}
|
||||
@@ -114,7 +112,7 @@ func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, sto
|
||||
|
||||
// clearContextSecrets mirrors auth/logout.go: best-effort delete every secret
|
||||
// slot the context references. Errors are swallowed so a missing keyring
|
||||
// entry doesn't block remove (logout has had the same policy since v0.2).
|
||||
// entry doesn't block remove (same policy as `auth logout`).
|
||||
func clearContextSecrets(store secrets.Store, c config.Context, name string) {
|
||||
if c.TokenRef != "" {
|
||||
_ = store.Delete(name, "access")
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
@@ -43,7 +42,6 @@ the global --context flag instead, which writes nothing to disk.`,
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, contextUseFields)
|
||||
aiclient.SetAgentHelp(cmd, "Switches default CLI context. With --json: returns {current_context, previous_context}. Errors with local.context_not_found and a did-you-mean hint when name unknown.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -82,7 +80,7 @@ func notFoundError(name string, cfg *config.Config) error {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeLocalContextNotFound,
|
||||
Message: fmt.Sprintf("context not found: %s", name),
|
||||
Hint: "no contexts registered — run `weknora auth login` first",
|
||||
Hint: "no contexts registered - run `weknora auth login` first",
|
||||
}
|
||||
}
|
||||
keys := contextKeys(cfg.Contexts)
|
||||
|
||||
@@ -118,12 +118,12 @@ func TestUse_CaseSensitive(t *testing.T) {
|
||||
}}
|
||||
_ = config.Save(cfg)
|
||||
|
||||
err := runUse("production", nil) // lowercase — must NOT match "Production"
|
||||
err := runUse("production", nil) // lowercase - must NOT match "Production"
|
||||
if err == nil {
|
||||
t.Fatal("expected case-sensitive miss")
|
||||
}
|
||||
cm := err.(*cmdutil.Error)
|
||||
// did-you-mean kicks in (distance 1 — "P"→"p")
|
||||
// did-you-mean kicks in (distance 1 - "P"→"p")
|
||||
if !strings.Contains(cm.Hint, "Production") {
|
||||
t.Errorf("hint should suggest 'Production' (case-different), got %q", cm.Hint)
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
@@ -64,7 +63,6 @@ without the user's explicit go-ahead.`,
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, docDeleteFields)
|
||||
aiclient.SetAgentHelp(cmd, "Destructively deletes one document by id. ALWAYS pass -y/--yes in agent mode (no TTY ⇒ confirm prompt fails). Returns data: {id, deleted:true}.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -115,7 +115,7 @@ func TestDelete_AgentPrompterErrors(t *testing.T) {
|
||||
// TestDelete_NoYes_NonTTY_RequiresConfirmation: when stdout isn't a TTY
|
||||
// (typical agent pipe / CI), the destructive-write protocol requires
|
||||
// explicit -y/--yes. The CLI exits 10 with input.confirmation_required,
|
||||
// never silently proceeds. See cli/AGENTS.md "Exit codes".
|
||||
// never silently proceeds. See cli/README.md "Exit codes".
|
||||
func TestDelete_NoYes_NonTTY_RequiresConfirmation(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
// "Doc" is the CLI noun; the underlying SDK type is `Knowledge`. The renaming
|
||||
// is deliberate: end-users think of a knowledge entry as the document they
|
||||
// uploaded, not as an abstract knowledge unit. Mapping happens in this package
|
||||
// only — the SDK surface and server API keep the original spelling.
|
||||
// only - the SDK surface and server API keep the original spelling.
|
||||
package doc
|
||||
|
||||
import (
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
@@ -57,7 +56,6 @@ Existing files are NOT overwritten unless --clobber is passed.`,
|
||||
}
|
||||
cmd.Flags().StringVarP(&opts.Output, "output", "O", "", `Output path; "-" for stdout. Defaults to the server-suggested filename.`)
|
||||
cmd.Flags().BoolVar(&opts.Clobber, "clobber", false, "Overwrite the output file if it already exists")
|
||||
aiclient.SetAgentHelp(cmd, "Downloads a document. Agents that pipe the bytes should pass --output - (stdout). The exit code is 0 on success, 1 on resource.not_found, 5 on missing --output when the server didn't supply a filename.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -85,7 +83,7 @@ func runDownload(ctx context.Context, opts *DownloadOptions, svc DownloadService
|
||||
// resolveDownloadDest returns the final destination ("-" for stdout, an
|
||||
// absolute or relative path otherwise) after applying the --output flag
|
||||
// and sanitizing the server-suggested name. A server that returns a path-
|
||||
// like filename (..\, /etc/foo) is rejected — only the basename is
|
||||
// like filename (..\, /etc/foo) is rejected - only the basename is
|
||||
// accepted.
|
||||
func resolveDownloadDest(opts *DownloadOptions, suggested string) (string, error) {
|
||||
if opts.Output == "-" {
|
||||
|
||||
@@ -113,7 +113,7 @@ func TestDownload_RejectsServerPathTraversal(t *testing.T) {
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
defer os.Chdir(prevWD)
|
||||
|
||||
// The server sends "../../etc/shadow" — we accept only "shadow" and
|
||||
// The server sends "../../etc/shadow" - we accept only "shadow" and
|
||||
// write to cwd.
|
||||
svc := &fakeDownloadSvc{content: "exfil", filename: "../../etc/shadow"}
|
||||
require.NoError(t, runDownload(context.Background(), &DownloadOptions{}, svc, "doc_abc"))
|
||||
|
||||
+3
-5
@@ -11,7 +11,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/text"
|
||||
@@ -41,7 +40,7 @@ type ListOptions struct {
|
||||
}
|
||||
|
||||
// docListStatusValues mirrors internal/types/knowledge.go ParseStatus*
|
||||
// constants — these are the values the server accepts on the
|
||||
// constants - these are the values the server accepts on the
|
||||
// ?parse_status= query. Kept in sync manually since the SDK doesn't
|
||||
// re-export the enum.
|
||||
var docListStatusValues = []string{"pending", "processing", "completed", "failed"}
|
||||
@@ -94,7 +93,6 @@ backend storage order is not guaranteed and varies between deployments.`,
|
||||
cmd.Flags().BoolVar(&opts.AllPages, "all-pages", false, "Walk all server pages until exhausted (or --limit hit)")
|
||||
cmd.Flags().StringVar(&opts.Status, "status", "", "Filter by parse status: pending | processing | completed | failed")
|
||||
cmdutil.AddJSONFlags(cmd, docListFields)
|
||||
aiclient.SetAgentHelp(cmd, "Lists docs in the resolved KB as a bare JSON array of Knowledge objects (empty `[]` when none). --status filters server-side; `failed` surfaces ingestion errors. --all-pages walks every server page until exhausted (capped by --limit), useful for one-shot exports.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -114,7 +112,7 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
|
||||
if opts.Status != "" && !validDocListStatus(opts.Status) {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
Message: fmt.Sprintf("--status must be one of: %s — got %q",
|
||||
Message: fmt.Sprintf("--status must be one of: %s - got %q",
|
||||
strings.Join(docListStatusValues, " | "), opts.Status),
|
||||
}
|
||||
}
|
||||
@@ -189,7 +187,7 @@ func validDocListStatus(s string) bool {
|
||||
}
|
||||
|
||||
// formatSize renders a byte count as a short human string (KB / MB).
|
||||
// Kept tiny on purpose — go-humanize would pull a transitive dep just for one
|
||||
// Kept tiny on purpose - go-humanize would pull a transitive dep just for one
|
||||
// column. A "-" placeholder hides zero-size entries (URL / text).
|
||||
func formatSize(bytes int64) string {
|
||||
if bytes <= 0 {
|
||||
|
||||
@@ -161,7 +161,7 @@ func TestList_KBFlagWiredToResolveKB(t *testing.T) {
|
||||
}
|
||||
// With --kb=kb_<id> supplied, ResolveKB short-circuits on the prefix
|
||||
// match without consulting the client. The RunE then asks for the client
|
||||
// to run the actual list — that call triggers the forced error.
|
||||
// to run the actual list - that call triggers the forced error.
|
||||
// Surfacing "forced-after-resolvekb" (rather than CodeKBIDRequired) is
|
||||
// the proof point that --kb was honored.
|
||||
cmd := NewCmdList(f)
|
||||
@@ -292,7 +292,7 @@ func TestList_Limit_LessThanPageSize_SlicesToLimit(t *testing.T) {
|
||||
opts := &ListOptions{PageSize: 20, Limit: 5}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.JSONOptions{}, svc, "kb_xxx"))
|
||||
body := out.String()
|
||||
// Count occurrences of "id":"doc_" — should be exactly 5.
|
||||
// Count occurrences of "id":"doc_" - should be exactly 5.
|
||||
got := strings.Count(body, `"id":"doc_`)
|
||||
assert.Equal(t, 5, got, "--limit 5 must slice 20 returned items to 5; body=\n%s", body)
|
||||
}
|
||||
@@ -338,6 +338,3 @@ func TestList_AllPages_WithLimit_StopsAtLimit(t *testing.T) {
|
||||
assert.LessOrEqual(t, len(svc.calls), 3, "should not walk past the page that fills --limit")
|
||||
}
|
||||
|
||||
// (test removed: --page flag was dropped in v0.4 mainstream-alignment;
|
||||
// --all-pages now walks unconditionally, no mutex case to test.)
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
@@ -69,6 +68,8 @@ Pass --name to override the recorded file name (useful when the local file
|
||||
has a generic name like "report.pdf" but you want to surface it as e.g.
|
||||
"Q3 Marketing Report.pdf" in the UI).
|
||||
|
||||
The three input modes (positional file / --recursive directory walk /
|
||||
--from-url remote ingest) are mutually exclusive - pass exactly one.
|
||||
Use --recursive --glob to upload a directory tree (see Examples).`,
|
||||
Example: ` weknora doc upload report.pdf
|
||||
weknora doc upload notes.md --kb a32a63ff-fb36-4874-bcaa-30f48570a694
|
||||
@@ -114,7 +115,6 @@ Use --recursive --glob to upload a directory tree (see Examples).`,
|
||||
cmd.Flags().StringVar(&opts.Glob, "glob", "*", "Filename pattern to filter when --recursive (e.g. '*.pdf')")
|
||||
cmd.Flags().StringVar(&opts.FromURL, "from-url", "", "Ingest a remote `URL` (HTTP/HTTPS) instead of a local file")
|
||||
cmdutil.AddJSONFlags(cmd, docUploadFields)
|
||||
aiclient.SetAgentHelp(cmd, "Three modes (mutually exclusive): local file (positional), --recursive directory walk + --glob, or --from-url remote ingest. Returns data: Knowledge object (file/URL) or aggregate report (recursive). Errors: resource.already_exists (URL previously ingested) / local.upload_file_not_found.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -156,7 +156,7 @@ func runUploadFromURL(ctx context.Context, opts *UploadOptions, jopts *cmdutil.J
|
||||
if errors.Is(err, sdk.ErrDuplicateURL) {
|
||||
// Server returns 409 with the existing knowledge entry's data.
|
||||
// Surface as resource.already_exists; the data payload (if any)
|
||||
// is observable via err's wrap chain — but the typed code is
|
||||
// is observable via err's wrap chain - but the typed code is
|
||||
// what agents branch on.
|
||||
return cmdutil.Wrapf(cmdutil.CodeResourceAlreadyExists, err,
|
||||
"URL already ingested into this knowledge base")
|
||||
@@ -190,7 +190,7 @@ func renderUploadSuccess(k *sdk.Knowledge, jopts *cmdutil.JSONOptions, humanVerb
|
||||
// validateUploadPath checks that path exists and refers to a regular file.
|
||||
// Symlinks and directories are rejected up-front so users get a typed error
|
||||
// instead of an opaque SDK failure mid-upload. os.Stat (not Lstat) is used
|
||||
// here so a symlink to a regular file is accepted — that matches what
|
||||
// here so a symlink to a regular file is accepted - that matches what
|
||||
// `cp` / `git add` do, and the SDK opens the file via os.Open which follows
|
||||
// symlinks anyway.
|
||||
func validateUploadPath(path string) error {
|
||||
|
||||
@@ -19,7 +19,7 @@ type uploadOutcome struct {
|
||||
}
|
||||
|
||||
// runUploadRecursive walks dir, filters by Glob, and uploads each match
|
||||
// sequentially. Per-file errors do NOT abort the walk — they accumulate
|
||||
// sequentially. Per-file errors do NOT abort the walk - they accumulate
|
||||
// and the final return aggregates them so the user sees the full picture
|
||||
// in one run. Exit semantics: nil error on full success, a typed *cmdutil.Error
|
||||
// when ≥1 file failed (the typed code mirrors the first failure's
|
||||
@@ -48,7 +48,7 @@ func runUploadRecursive(ctx context.Context, opts *UploadOptions, jopts *cmdutil
|
||||
|
||||
// Sanity-check the pattern up front so a typo doesn't show up as "no
|
||||
// files matched" per-file. Cobra populates --glob; tests pass it
|
||||
// explicitly — no in-function default needed.
|
||||
// explicitly - no in-function default needed.
|
||||
if _, err := filepath.Match(opts.Glob, ""); err != nil {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
|
||||
@@ -109,7 +109,7 @@ func TestUploadRecursive_PartialFailure_Exits1(t *testing.T) {
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
// CodeServerError preserves the 500 classification of the underlying
|
||||
// SDK error — the recursive wrapper just aggregates.
|
||||
// SDK error - the recursive wrapper just aggregates.
|
||||
assert.Equal(t, cmdutil.CodeServerError, typed.Code)
|
||||
|
||||
got := out.String()
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/text"
|
||||
@@ -52,7 +51,6 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, docViewFields)
|
||||
aiclient.SetAgentHelp(cmd, "Returns the full Knowledge object for one document: id, kb_id, file metadata, parse_status, processed_at, error_message. Use this instead of paging through `doc list` when you have the doc id.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ func TestView_Human_RendersExpectedFields(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A doc with no FileName falls back to Title for the NAME line — same
|
||||
// A doc with no FileName falls back to Title for the NAME line - same
|
||||
// ordering as `doc list` (KnowledgeDisplayName precedence).
|
||||
func TestView_Human_TitleFallback(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
@@ -69,7 +69,7 @@ func TestView_Human_TitleFallback(t *testing.T) {
|
||||
}
|
||||
|
||||
// Optional fields (ProcessedAt nil, ErrorMessage empty, EmbeddingModelID
|
||||
// empty) must not produce empty KEY: lines — the formatter omits them
|
||||
// empty) must not produce empty KEY: lines - the formatter omits them
|
||||
// rather than printing "PROCESSED: -".
|
||||
func TestView_Human_OmitsEmptyFields(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
+18
-20
@@ -1,12 +1,12 @@
|
||||
// Package doctor implements `weknora doctor` — 4-item self-check (spec §1.2).
|
||||
// Package doctor implements `weknora doctor` - 4-item self-check.
|
||||
//
|
||||
// Status semantics (4-tier):
|
||||
//
|
||||
// ok — passed
|
||||
// warn — soft problem; non-blocking (e.g. server minor older than CLI,
|
||||
// ok - passed
|
||||
// warn - soft problem; non-blocking (e.g. server minor older than CLI,
|
||||
// keychain unavailable so falling back to file store)
|
||||
// fail — failed; "hint" actionable
|
||||
// skip — cascade-skipped (prereq failed) or --offline mode
|
||||
// fail - failed; "hint" actionable
|
||||
// skip - cascade-skipped (prereq failed) or --offline mode
|
||||
//
|
||||
// JSON output emits the Result object directly (bare data). Exit-code
|
||||
// signal:
|
||||
@@ -28,7 +28,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/build"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/compat"
|
||||
@@ -66,7 +65,7 @@ type Check struct {
|
||||
Hint string `json:"hint,omitempty"`
|
||||
}
|
||||
|
||||
// Summary is the agent-friendly short-circuit payload (spec §1.2).
|
||||
// Summary is the agent-friendly short-circuit payload.
|
||||
//
|
||||
// AllPassed is true only when there are zero warn/fail/skip rows; warn does
|
||||
// not block exit-0 but it does flip AllPassed so agents reading just the
|
||||
@@ -125,7 +124,6 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd.Flags().BoolVar(&opts.NoCache, "no-cache", false, "Bypass server-info cache (located at $XDG_CACHE_HOME/weknora/server-info.yaml); force re-probe")
|
||||
cmd.Flags().BoolVar(&opts.Offline, "offline", false, "Skip network checks; only verify local keyring/file storage (credential_storage check still runs)")
|
||||
cmdutil.AddJSONFlags(cmd, doctorFields)
|
||||
aiclient.SetAgentHelp(cmd, "Returns 4 health checks as a bare JSON object {summary, checks}. AGENT short-circuit: read summary.all_passed; if false, inspect checks[].status (ok/warn/fail/skip). exit 1 only when any status=fail; warn does not affect exit.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -133,7 +131,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
// offline-mode skip and prereq-failed skip. Returns true when the check has
|
||||
// been completed (Status set on c) and the caller should NOT run its body.
|
||||
//
|
||||
// A prereq is considered "passing" if its Status is OK or Warn — warn signals
|
||||
// A prereq is considered "passing" if its Status is OK or Warn - warn signals
|
||||
// a soft problem that does not block downstream functionality. Only fail/skip
|
||||
// cascades into a downstream skip.
|
||||
func cascade(c *Check, offline bool, prereqs ...*Check) bool {
|
||||
@@ -160,7 +158,7 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string)
|
||||
{Name: "credential_storage"},
|
||||
}
|
||||
|
||||
// 1. base_url_reachable — gated by offline only.
|
||||
// 1. base_url_reachable - gated by offline only.
|
||||
if !cascade(&checks[0], opts.Offline) {
|
||||
t0 := time.Now()
|
||||
if err := svc.PingBaseURL(ctx); err != nil {
|
||||
@@ -173,7 +171,7 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. auth_credential — needs base_url.
|
||||
// 2. auth_credential - needs base_url.
|
||||
if !cascade(&checks[1], opts.Offline, &checks[0]) {
|
||||
if _, err := svc.GetCurrentUser(ctx); err != nil {
|
||||
checks[1].Status = StatusFail
|
||||
@@ -184,7 +182,7 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string)
|
||||
}
|
||||
}
|
||||
|
||||
// 3. server_version — needs auth_credential.
|
||||
// 3. server_version - needs auth_credential.
|
||||
if !cascade(&checks[2], opts.Offline, &checks[1]) {
|
||||
info, fromCache, err := loadOrProbeServerInfo(ctx, opts, svc)
|
||||
if err != nil {
|
||||
@@ -195,14 +193,14 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string)
|
||||
}
|
||||
}
|
||||
|
||||
// 4. credential_storage — independent of network; never gated by offline.
|
||||
// 4. credential_storage - independent of network; never gated by offline.
|
||||
fillCredentialStorageCheck(&checks[3])
|
||||
|
||||
return Result{Summary: summarize(checks), Checks: checks}
|
||||
}
|
||||
|
||||
// fillVersionCheck applies compat.Compat to (server, cli) version pair and
|
||||
// sets Status/Details/Hint on c. fromCache toggles the "cached" suffix —
|
||||
// sets Status/Details/Hint on c. fromCache toggles the "cached" suffix -
|
||||
// the loader knows authoritatively which branch it took, time-based
|
||||
// derivation from ProbedAt is unreliable since SaveCache uses time.Now().
|
||||
//
|
||||
@@ -239,8 +237,8 @@ func fillVersionCheck(c *Check, info *compat.Info, cliVer string, fromCache bool
|
||||
}
|
||||
}
|
||||
|
||||
// credStoreFactory is the seam tests use to inject a fake-store outcome —
|
||||
// keyring success, file-store fallback, or hard failure — without touching
|
||||
// credStoreFactory is the seam tests use to inject a fake-store outcome -
|
||||
// keyring success, file-store fallback, or hard failure - without touching
|
||||
// the lazy-resolve buildServices contract (round-4 fix). Production stays
|
||||
// at secrets.NewBestEffortStore.
|
||||
var credStoreFactory = func() (secrets.Store, error) { return secrets.NewBestEffortStore() }
|
||||
@@ -248,7 +246,7 @@ var credStoreFactory = func() (secrets.Store, error) { return secrets.NewBestEff
|
||||
// SetCredStoreFactoryForTest overrides the credential-storage factory used by
|
||||
// runChecks and returns a cleanup function that restores the previous value.
|
||||
// Exported so out-of-package tests (notably cli/acceptance/contract) can
|
||||
// pin the credential_storage outcome — otherwise the check probes the real
|
||||
// pin the credential_storage outcome - otherwise the check probes the real
|
||||
// OS keyring, which is present on macOS dev machines but not on Linux CI
|
||||
// runners without libsecret, producing host-dependent test flakes.
|
||||
//
|
||||
@@ -269,7 +267,7 @@ func SetCredStoreFactoryForTest(fn func() (secrets.Store, error)) (restore func(
|
||||
//
|
||||
// keyring usable → StatusOK (preferred path)
|
||||
// file fallback → StatusWarn (keyring unavailable, secrets still persist
|
||||
// with 0600 file perms — agent containers / WSL hit this)
|
||||
// with 0600 file perms - agent containers / WSL hit this)
|
||||
// construction fails → StatusFail
|
||||
//
|
||||
// Detection of "fallback to file store" relies on the type returned by
|
||||
@@ -378,7 +376,7 @@ func marker(s Status) string {
|
||||
// server, not localhost.
|
||||
//
|
||||
// Critically: this does NOT pre-resolve f.Client(). doctor's package promise
|
||||
// (top comment) is that credential_storage runs even when no auth is set up —
|
||||
// (top comment) is that credential_storage runs even when no auth is set up -
|
||||
// e.g. first-time `weknora doctor` to diagnose setup. Pre-resolving Client
|
||||
// here would early-exit with auth.unauthenticated before any check runs,
|
||||
// contradicting the docs. Instead, GetCurrentUser / GetSystemInfo lazily
|
||||
@@ -443,7 +441,7 @@ func (s *realServices) GetCurrentUser(ctx context.Context) (*sdk.CurrentUserResp
|
||||
|
||||
// GetSystemInfo lazily resolves the SDK client (same rationale as GetCurrentUser).
|
||||
// In the cascade ordering, auth_credential gates server_version, so this only
|
||||
// runs when auth_credential succeeded — but the lazy resolution keeps doctor
|
||||
// runs when auth_credential succeeded - but the lazy resolution keeps doctor
|
||||
// useful when only credential_storage is checkable (e.g., user not yet logged in).
|
||||
func (s *realServices) GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, error) {
|
||||
cli, err := s.f.Client()
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
// and would make CI flake on macOS vs Linux vs WSL). Restored in t.Cleanup.
|
||||
//
|
||||
// The hook intentionally lives at package scope (rather than as a runChecks
|
||||
// parameter) so the production call site stays a zero-arg function — keeping
|
||||
// parameter) so the production call site stays a zero-arg function - keeping
|
||||
// the lazy-resolve buildServices contract unchanged (round-4 fix).
|
||||
func withCredStoreFactory(t *testing.T, fn func() (secrets.Store, error)) {
|
||||
t.Helper()
|
||||
@@ -58,7 +58,7 @@ func TestDoctor_AllOK(t *testing.T) {
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
// Pin credential_storage to ok so this test doesn't probe the host OS
|
||||
// keyring — macOS dev machines have Keychain, Linux CI without libsecret
|
||||
// keyring - macOS dev machines have Keychain, Linux CI without libsecret
|
||||
// would otherwise warn and break the AllPassed assertion.
|
||||
withCredStoreFactory(t, func() (secrets.Store, error) {
|
||||
return secrets.NewMemStore(), nil
|
||||
@@ -107,7 +107,7 @@ func TestDoctor_BaseURLFails_DownstreamSkip(t *testing.T) {
|
||||
if r.Checks[2].Status != StatusSkip {
|
||||
t.Errorf("server_version status = %q, want skip", r.Checks[2].Status)
|
||||
}
|
||||
// credential_storage 与网络无关,应该独立运行(不受 base_url fail 影响)
|
||||
// credential_storage is network-independent and runs regardless of base_url failures.
|
||||
if r.Checks[3].Name != "credential_storage" {
|
||||
t.Errorf("Checks[3] = %q, want credential_storage", r.Checks[3].Name)
|
||||
}
|
||||
@@ -245,7 +245,7 @@ func TestDoctor_NoCache_BypassesCache(t *testing.T) {
|
||||
func TestDoctor_VersionSkewWarns(t *testing.T) {
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
// Force keyring path to ok so credential_storage doesn't itself warn —
|
||||
// Force keyring path to ok so credential_storage doesn't itself warn -
|
||||
// we want this test to assert ONLY on server_version.
|
||||
withCredStoreFactory(t, func() (secrets.Store, error) { return secrets.NewMemStore(), nil })
|
||||
|
||||
@@ -262,7 +262,7 @@ func TestDoctor_VersionSkewWarns(t *testing.T) {
|
||||
if v.Status != StatusWarn {
|
||||
t.Errorf("server_version status = %q, want warn (server older than CLI)", v.Status)
|
||||
}
|
||||
// compat.Compat hint contains "server is older" — that's the load-bearing
|
||||
// compat.Compat hint contains "server is older" - that's the load-bearing
|
||||
// substring agents may pattern-match. Not asserting full message text
|
||||
// since compat.Compat owns the wording.
|
||||
if !strings.Contains(v.Details, "older") {
|
||||
@@ -318,7 +318,7 @@ func TestDoctor_HardErrorStillFails(t *testing.T) {
|
||||
|
||||
// TestDoctor_KeychainFallbackWarns covers credential_storage's third
|
||||
// state: keyring unavailable, fell back to FileStore (agent containers,
|
||||
// headless CI, WSL without DBus). The check should warn — secrets still
|
||||
// headless CI, WSL without DBus). The check should warn - secrets still
|
||||
// persist (0600 file perms) but the OS-backed path was unreachable.
|
||||
func TestDoctor_KeychainFallbackWarns(t *testing.T) {
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
@@ -355,7 +355,7 @@ func TestDoctor_KeychainFallbackWarns(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestDoctor_CredStoreFactoryError surfaces the constructor failure path as
|
||||
// fail (not warn) — distinguishes "cannot persist credentials at all" from
|
||||
// fail (not warn) - distinguishes "cannot persist credentials at all" from
|
||||
// "downgraded to file store".
|
||||
func TestDoctor_CredStoreFactoryError(t *testing.T) {
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
@@ -487,7 +487,7 @@ func TestDoctor_RunE_FailReturnsSilentError(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoctor_RunE_WarnReturnsNil — soft skew path stays exit-0. Pairs with
|
||||
// TestDoctor_RunE_WarnReturnsNil - soft skew path stays exit-0. Pairs with
|
||||
// TestDoctor_RunE_FailReturnsSilentError: warn does NOT trigger SilentError.
|
||||
func TestDoctor_RunE_WarnReturnsNil(t *testing.T) {
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
@@ -15,7 +14,7 @@ import (
|
||||
|
||||
// kbCreateFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `kb create`. The result is the full KnowledgeBase struct; these mirror its
|
||||
// top-level json tags. Nested config objects are intentionally omitted —
|
||||
// top-level json tags. Nested config objects are intentionally omitted -
|
||||
// users wanting them can drop --json (no filter) or use --jq.
|
||||
var kbCreateFields = []string{
|
||||
"id", "name", "type", "description",
|
||||
@@ -33,7 +32,7 @@ type CreateOptions struct {
|
||||
}
|
||||
|
||||
// CreateService is the narrow SDK surface this command depends on.
|
||||
// *sdk.Client satisfies it via duck typing (ADR-4).
|
||||
// *sdk.Client satisfies it via duck typing.
|
||||
type CreateService interface {
|
||||
CreateKnowledgeBase(ctx context.Context, kb *sdk.KnowledgeBase) (*sdk.KnowledgeBase, error)
|
||||
}
|
||||
@@ -62,7 +61,6 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd.Flags().StringVar(&opts.EmbeddingModel, "embedding-model", "", "Embedding model ID (optional; server picks default when unset)")
|
||||
cmdutil.AddJSONFlags(cmd, kbCreateFields)
|
||||
_ = cmd.MarkFlagRequired("name")
|
||||
aiclient.SetAgentHelp(cmd, "Creates a knowledge base under the active context. --name is required; --description and --embedding-model are optional. Returns the full KnowledgeBase object including the new id.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
@@ -47,7 +46,7 @@ Pass -y/--yes (global flag) to skip the prompt (required in agent / CI / piped c
|
||||
|
||||
AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10
|
||||
and writes input.confirmation_required to stderr. NEVER auto-pass -y
|
||||
without the user's explicit go-ahead — the exit-10 protocol exists
|
||||
without the user's explicit go-ahead - the exit-10 protocol exists
|
||||
exactly to guard against unintended deletes.`,
|
||||
Example: ` weknora kb delete kb_abc # interactive confirm
|
||||
weknora kb delete kb_abc -y # no prompt
|
||||
@@ -67,7 +66,6 @@ exactly to guard against unintended deletes.`,
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, kbDeleteFields)
|
||||
aiclient.SetAgentHelp(cmd, "Destructively deletes a knowledge base by id. ALWAYS pass -y/--yes in agent mode (no TTY ⇒ confirm prompt fails). Returns data: {id, deleted:true}.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -55,8 +55,8 @@ func TestDelete_NotFound(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
// SetForTest uses bytes.Buffer for Out — IsStdoutTTY() = false. Without
|
||||
// -y/--yes, exit-10 protocol fires (see AGENTS.md): the CLI must NOT
|
||||
// SetForTest uses bytes.Buffer for Out - IsStdoutTTY() = false. Without
|
||||
// -y/--yes, exit-10 protocol fires (see cli/README.md): the CLI must NOT
|
||||
// silently proceed in scripted contexts.
|
||||
iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
@@ -86,7 +86,7 @@ func TestDelete_JSONOutput(t *testing.T) {
|
||||
}
|
||||
|
||||
// The remaining tests cover the interactive confirm path which only fires
|
||||
// under IsStdoutTTY() && !JSONOut — exercised via SetForTestWithTTY.
|
||||
// under IsStdoutTTY() && !JSONOut - exercised via SetForTestWithTTY.
|
||||
|
||||
func TestDelete_ConfirmYes(t *testing.T) {
|
||||
_, _ = iostreams.SetForTestWithTTY(t)
|
||||
|
||||
+5
-4
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
@@ -26,7 +25,7 @@ var kbEditFields = []string{
|
||||
|
||||
type EditOptions struct {
|
||||
// Name/Description are *string so we can distinguish "unset" from "set to
|
||||
// empty". An unset field is omitted from the SDK request — only fields the
|
||||
// empty". An unset field is omitted from the SDK request - only fields the
|
||||
// user passed are sent. Server PUT semantics are "replace everything in the
|
||||
// request"; if we always sent both, an `--name` invocation would silently
|
||||
// clear the description.
|
||||
@@ -52,7 +51,10 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "edit <id>",
|
||||
Short: "Edit a knowledge base's name or description",
|
||||
Args: cobra.ExactArgs(1),
|
||||
Long: `Update a knowledge base's name and/or description. At least one of
|
||||
--name / --description must be supplied; fields you omit are preserved
|
||||
server-side.`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
if err != nil {
|
||||
@@ -74,7 +76,6 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd.Flags().StringVar(&name, "name", "", "New name (omit to leave unchanged)")
|
||||
cmd.Flags().StringVar(&desc, "description", "", "New description (omit to leave unchanged)")
|
||||
cmdutil.AddJSONFlags(cmd, kbEditFields)
|
||||
aiclient.SetAgentHelp(cmd, "Edits a knowledge base. At least one of --name/--description is required. Fields not passed are preserved server-side. Returns the updated KnowledgeBase.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -104,7 +104,7 @@ func TestEdit_BothFlags(t *testing.T) {
|
||||
func TestEdit_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
// 404 must come from the GetKnowledgeBase pre-fetch in the fetch-then-
|
||||
// update flow — that's the first server roundtrip when the id is bad.
|
||||
// update flow - that's the first server roundtrip when the id is bad.
|
||||
svc := &fakeEditSvc{currentErr: errors.New("HTTP error 404: not found")}
|
||||
opts := &EditOptions{}
|
||||
opts.Name = stringPtr("x")
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
@@ -63,7 +62,6 @@ piped contexts. Without -y the CLI exits 10 in non-interactive mode.`,
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, kbEmptyFields)
|
||||
aiclient.SetAgentHelp(cmd, "Destructively empties a knowledge base (deletes all documents, preserves the KB record + config). ALWAYS pass -y/--yes in agent mode (non-TTY ⇒ confirm fails). Returns data: {id, deleted_count}. Async — items may still be processing server-side after the call returns.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
+3
-4
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/text"
|
||||
@@ -18,7 +17,7 @@ import (
|
||||
|
||||
// kbListFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `kb list`. Nested config structs (chunking / image / FAQ / VLM / storage
|
||||
// / extract) are intentionally omitted — users wanting those can use `--jq`
|
||||
// / extract) are intentionally omitted - users wanting those can use `--jq`
|
||||
// against the full object.
|
||||
var kbListFields = []string{
|
||||
"id", "name", "type", "description",
|
||||
@@ -49,6 +48,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List knowledge bases visible to the active context",
|
||||
Long: `List knowledge bases visible to the active context, sorted by most recently updated. Pass --pinned to restrict to pinned KBs.`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
@@ -65,7 +65,6 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd.Flags().BoolVar(&opts.Pinned, "pinned", false, "Only show pinned knowledge bases")
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (0 = no cap, 1..10000 = explicit)")
|
||||
cmdutil.AddJSONFlags(cmd, kbListFields)
|
||||
aiclient.SetAgentHelp(cmd, "Lists all knowledge bases as a bare JSON array of {id, name, ...} objects (empty `[]` when none). --pinned restricts to pinned KBs (client-side filter). --limit caps the returned slice. Use `--json` (bare) for full objects, `--json=id,name` to project fields, or `--jq` for arbitrary reshape.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -92,7 +91,7 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
|
||||
}
|
||||
items = filtered
|
||||
}
|
||||
// Spec §1.2: default sort by updated_at desc. Server return order is not
|
||||
// Default sort by updated_at desc. Server return order is not
|
||||
// guaranteed, so client-side sort makes output deterministic regardless
|
||||
// of backend storage choices.
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
|
||||
+2
-3
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
@@ -20,7 +19,7 @@ var kbPinFields = []string{"id", "is_pinned"}
|
||||
type PinOptions struct{}
|
||||
|
||||
// PinService is the narrow SDK surface this command depends on. The CLI
|
||||
// reads current state before toggling so `pin`/`unpin` are idempotent —
|
||||
// reads current state before toggling so `pin`/`unpin` are idempotent -
|
||||
// the server endpoint is only a non-idempotent toggle.
|
||||
type PinService interface {
|
||||
GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error)
|
||||
@@ -42,6 +41,7 @@ func newPinCmd(f *cmdutil.Factory, use string, want bool, short string) *cobra.C
|
||||
cmd := &cobra.Command{
|
||||
Use: use + " <id>",
|
||||
Short: short,
|
||||
Long: short + ". Idempotent: reads the current pin state and toggles only if different, so re-running on a KB already in the target state is a no-op.",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
@@ -56,7 +56,6 @@ func newPinCmd(f *cmdutil.Factory, use string, want bool, short string) *cobra.C
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, kbPinFields)
|
||||
aiclient.SetAgentHelp(cmd, fmt.Sprintf("Idempotent %s: reads current pin state, toggles only if different. No-op when already in the requested state.", use))
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
+1
-2
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/text"
|
||||
@@ -38,6 +37,7 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "view <id>",
|
||||
Short: "Show a knowledge base by ID",
|
||||
Long: `Fetch a knowledge base's full configuration: chunking settings, embedding / summary model IDs, knowledge_count, chunk_count.`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
@@ -52,7 +52,6 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, kbViewFields)
|
||||
aiclient.SetAgentHelp(cmd, "Returns details of one knowledge base by ID (config + counts).")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Package linkcmd implements `weknora link` — binds the current working
|
||||
// Package linkcmd implements `weknora link` - binds the current working
|
||||
// directory to a knowledge base by writing .weknora/project.yaml. Always
|
||||
// overwrites an existing link silently rather than refusing when one is
|
||||
// already present. The cobra Long: text covers the user-facing modes
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/projectlink"
|
||||
@@ -49,7 +48,7 @@ overridden by the --kb flag or WEKNORA_KB_ID env var.
|
||||
|
||||
Pass --kb <id-or-name> for non-interactive use (scripts, CI). Run on a TTY
|
||||
without --kb to be prompted from the list of available KBs. Always overwrites
|
||||
any existing link — re-run to switch.
|
||||
any existing link - re-run to switch.
|
||||
|
||||
AI agents: link writes to the user's working directory. Only run it when the
|
||||
user explicitly asked to bind this directory; don't run it as a side effect.`,
|
||||
@@ -67,7 +66,6 @@ user explicitly asked to bind this directory; don't run it as a side effect.`,
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name; omit on a TTY for interactive prompt")
|
||||
cmdutil.AddJSONFlags(cmd, linkFields)
|
||||
aiclient.SetAgentHelp(cmd, "Writes .weknora/project.yaml binding cwd to a KB. Pass --kb (id or name) for non-interactive use. Always overwrites.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -115,7 +113,7 @@ func runLink(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, f *
|
||||
}
|
||||
|
||||
// resolveContext picks the auth context to record in the link. There is no
|
||||
// per-invocation override flag on `weknora link` itself — to record under a
|
||||
// per-invocation override flag on `weknora link` itself - to record under a
|
||||
// different context, use the global persistent flag (`weknora --context
|
||||
// staging link --kb my-kb`); the active context at link time is what gets
|
||||
// written.
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/projectlink"
|
||||
@@ -49,7 +48,6 @@ is present anywhere in the parent chain.`,
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, unlinkFields)
|
||||
aiclient.SetAgentHelp(cmd, "Removes .weknora/project.yaml (the cwd → KB binding). Walks up from cwd. Errors with input.invalid_argument when no link is present in the parent chain.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -29,7 +29,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
Initial tool surface is read-only and curated: kb_list / kb_view /
|
||||
doc_list / doc_view / doc_download / search_chunks / chat / agent_list /
|
||||
agent_invoke. Destructive verbs (create / delete / upload) are deliberately
|
||||
excluded — the agent should ask the user before mutating; the CLI's
|
||||
excluded - the agent should ask the user before mutating; the CLI's
|
||||
exit-10 protocol covers that path.`,
|
||||
Args: cobra.NoArgs,
|
||||
Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
|
||||
|
||||
+12
-9
@@ -3,13 +3,12 @@ package mcpcmd
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
mcpserver "github.com/Tencent/WeKnora/cli/internal/mcp"
|
||||
)
|
||||
|
||||
// NewCmdServe builds `weknora mcp serve`. Currently stdio-only; HTTP
|
||||
// (streamable / SSE) is roadmap 5-7.
|
||||
// (streamable / SSE) transports may be added later.
|
||||
func NewCmdServe(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "serve",
|
||||
@@ -18,19 +17,24 @@ func NewCmdServe(f *cmdutil.Factory) *cobra.Command {
|
||||
stderr; the data channel is reserved for protocol traffic.
|
||||
|
||||
Authentication is inherited from the active context (or --context). The
|
||||
server eagerly resolves the SDK client at startup — if no context is
|
||||
server eagerly resolves the SDK client at startup - if no context is
|
||||
configured, the process exits with auth.unauthenticated before any MCP
|
||||
handshake. This way an IDE-side agent sees a clear failure mode rather
|
||||
than a server that handshakes successfully then errors on every tool.
|
||||
|
||||
To use with Claude Code, add to ~/.claude/mcp_servers.json:
|
||||
To register with your MCP client (Claude Desktop / Code / Cursor / etc.),
|
||||
add an entry pointing at this binary under "mcpServers":
|
||||
|
||||
{
|
||||
"weknora": {
|
||||
"command": "weknora",
|
||||
"args": ["mcp", "serve"]
|
||||
"mcpServers": {
|
||||
"weknora": {
|
||||
"command": "weknora",
|
||||
"args": ["mcp", "serve"]
|
||||
}
|
||||
}
|
||||
}`,
|
||||
}
|
||||
|
||||
Consult your MCP client's documentation for the exact config-file location.`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
// Eagerly construct the SDK client. Surfaces auth /
|
||||
@@ -42,6 +46,5 @@ To use with Claude Code, add to ~/.claude/mcp_servers.json:
|
||||
return mcpserver.RunStdio(c.Context(), cli)
|
||||
},
|
||||
}
|
||||
aiclient.SetAgentHelp(cmd, "Long-lived stdio MCP server. stdin/stdout for JSON-RPC, stderr for logs. Exposes 9 read-only tools; destructive verbs intentionally excluded. Auth inherited from active context — exit and relaunch with --context to switch. chat / agent_invoke accumulate server-side and return a single result (MCP spec has no streaming-content extension).")
|
||||
return cmd
|
||||
}
|
||||
|
||||
+7
-29
@@ -19,7 +19,6 @@ import (
|
||||
mcpcmd "github.com/Tencent/WeKnora/cli/cmd/mcp"
|
||||
"github.com/Tencent/WeKnora/cli/cmd/search"
|
||||
sessioncmd "github.com/Tencent/WeKnora/cli/cmd/session"
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/build"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
@@ -35,8 +34,9 @@ func Execute() int {
|
||||
// downstream `--json | jq` pipelines never filter error shapes
|
||||
// out of the success stream. The typed exit code (3/4/5/6/7/10)
|
||||
// carries the error class.
|
||||
cmdutil.PrintError(iostreams.IO.Err, MapCobraError(err))
|
||||
return cmdutil.ExitCode(MapCobraError(err))
|
||||
mapped := MapCobraError(err)
|
||||
cmdutil.PrintError(iostreams.IO.Err, mapped)
|
||||
return cmdutil.ExitCode(mapped)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -70,7 +70,7 @@ func MapCobraError(err error) error {
|
||||
var cobraFlagErrorPrefixes = []string{
|
||||
"unknown command ",
|
||||
"required flag(s)",
|
||||
"accepts ", // ExactArgs / RangeArgs / etc. — `accepts N arg(s), received M`
|
||||
"accepts ", // ExactArgs / RangeArgs / etc. - `accepts N arg(s), received M`
|
||||
"requires at least", // MinimumNArgs
|
||||
"requires at most", // MaximumNArgs
|
||||
"unknown flag",
|
||||
@@ -84,7 +84,7 @@ func NewRootCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
v, commit, date := build.Info()
|
||||
cmd := &cobra.Command{
|
||||
Use: "weknora",
|
||||
Short: "WeKnora CLI — RAG knowledge base from your terminal",
|
||||
Short: "WeKnora CLI - RAG knowledge base from your terminal",
|
||||
Long: `WeKnora CLI lets you authenticate, browse knowledge bases, and run
|
||||
hybrid searches against a WeKnora server from your shell or an AI agent.`,
|
||||
Example: ` weknora auth login --host=https://kb.example.com # one-time setup
|
||||
@@ -101,7 +101,7 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`,
|
||||
Version: fmt.Sprintf("%s (commit %s, built %s)", v, commit, date),
|
||||
PersistentPreRun: func(c *cobra.Command, args []string) {
|
||||
// Propagate the global --context flag into the Factory for this
|
||||
// invocation only. Spec §1.2: single-shot override, no disk write.
|
||||
// invocation only - single-shot override, no disk write.
|
||||
if v, _ := c.Flags().GetString("context"); v != "" {
|
||||
f.ContextOverride = v
|
||||
}
|
||||
@@ -110,7 +110,6 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`,
|
||||
// Match `weknora version` line format so both forms output the same.
|
||||
cmd.SetVersionTemplate("weknora {{.Version}}\n")
|
||||
addGlobalFlags(cmd)
|
||||
cmd.SetHelpFunc(agentAwareHelpFunc(cmd.HelpFunc()))
|
||||
// Wrap cobra's flag-parsing errors as FlagError so cmdutil.ExitCode maps
|
||||
// them to exit 2. "unknown command" errors are detected by message prefix
|
||||
// in Execute() since cobra emits them as plain errors.
|
||||
@@ -136,7 +135,7 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`,
|
||||
}
|
||||
|
||||
// addGlobalFlags registers persistent flags available on every subcommand.
|
||||
// Only flags whose behavior is actually wired are listed — a flag that
|
||||
// Only flags whose behavior is actually wired are listed - a flag that
|
||||
// accepts values but does nothing is a worse contract than no flag.
|
||||
func addGlobalFlags(cmd *cobra.Command) {
|
||||
pf := cmd.PersistentFlags()
|
||||
@@ -144,27 +143,6 @@ func addGlobalFlags(cmd *cobra.Command) {
|
||||
pf.String("context", "", "Override the active context for this invocation (no disk write)")
|
||||
}
|
||||
|
||||
// agentAwareHelpFunc wraps cobra's default help to append the AI agent
|
||||
// guidance (Annotations[aiclient.AIAgentHelpKey]) only when an AI coding
|
||||
// agent env var is detected (CLAUDECODE / CURSOR_AGENT). Help-only
|
||||
// render — no behavior switch.
|
||||
func agentAwareHelpFunc(orig func(*cobra.Command, []string)) func(*cobra.Command, []string) {
|
||||
return func(c *cobra.Command, args []string) {
|
||||
orig(c, args)
|
||||
if aiclient.DetectAIAgent() == "" {
|
||||
return
|
||||
}
|
||||
extra := aiclient.FormatAgentGuidance(c)
|
||||
if extra == "" {
|
||||
return
|
||||
}
|
||||
w := c.OutOrStdout()
|
||||
fmt.Fprintln(w)
|
||||
fmt.Fprintln(w, "AI Agent guidance:")
|
||||
fmt.Fprintln(w, " "+extra)
|
||||
}
|
||||
}
|
||||
|
||||
// versionFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `version`. Mirrors the version object payload.
|
||||
var versionFields = []string{"version", "commit", "date"}
|
||||
|
||||
@@ -63,7 +63,7 @@ func TestMapCobraError_PinnedPrefixes(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("required flag(s)", func(t *testing.T) {
|
||||
// Self-contained probe — the pin must hold even before resource commands
|
||||
// Self-contained probe - the pin must hold even before resource commands
|
||||
// register their own required flags. RunE is required: without it cobra
|
||||
// treats the command as a parent and skips ValidateRequiredFlags.
|
||||
probe := &cobra.Command{Use: "probe", RunE: func(*cobra.Command, []string) error { return nil }}
|
||||
@@ -77,7 +77,7 @@ func TestMapCobraError_PinnedPrefixes(t *testing.T) {
|
||||
"cobra required-flag prefix changed; update cobraFlagErrorPrefixes. got: %q", err.Error())
|
||||
})
|
||||
|
||||
t.Run("accepts N arg(s) — ExactArgs", func(t *testing.T) {
|
||||
t.Run("accepts N arg(s) - ExactArgs", func(t *testing.T) {
|
||||
probe := &cobra.Command{
|
||||
Use: "probe",
|
||||
Args: cobra.ExactArgs(1),
|
||||
@@ -115,7 +115,7 @@ func TestMapCobraError(t *testing.T) {
|
||||
|
||||
// TestRoot_ContextFlagPropagation guards the cobra → Factory wiring of the
|
||||
// global --context flag. Without this, a future refactor that disconnects
|
||||
// PersistentPreRun from f.ContextOverride would only fail e2e — the
|
||||
// PersistentPreRun from f.ContextOverride would only fail e2e - the
|
||||
// per-package TestFactory_ContextOverride only proves the Factory side.
|
||||
func TestRoot_ContextFlagPropagation(t *testing.T) {
|
||||
cases := []struct {
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
@@ -44,7 +43,7 @@ type ChunksService interface {
|
||||
// Uses a positional query argument with the KB selected via flag.
|
||||
//
|
||||
// The `--kb` flag accepts either a KB UUID (passed through unchanged) or a
|
||||
// name (resolved via ListKnowledgeBases — see cmdutil.ResolveKBFlag).
|
||||
// name (resolved via ListKnowledgeBases - see cmdutil.ResolveKBFlag).
|
||||
func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &ChunksOptions{}
|
||||
cmd := &cobra.Command{
|
||||
@@ -53,6 +52,9 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
|
||||
Example: ` weknora search chunks "what is RAG?" --kb engineering
|
||||
weknora search chunks "embedding model" --kb kb_abc --limit 20
|
||||
weknora search chunks "k8s" --kb engineering --no-keyword # vector-only`,
|
||||
Long: `Hybrid (vector + keyword) retrieval against the knowledge base. Pass
|
||||
--no-vector or --no-keyword to disable one channel; you cannot disable both.
|
||||
--limit caps the returned slice client-side.`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
opts.Query = strings.TrimSpace(args[0])
|
||||
@@ -80,7 +82,6 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
|
||||
}
|
||||
bindChunksFlags(cmd, opts)
|
||||
_ = cmd.MarkFlagRequired("kb")
|
||||
aiclient.SetAgentHelp(cmd, "Hybrid retrieval; returns ranked chunk list. The server may include parent/nearby/relation chunks beyond match_count; --limit caps the returned slice client-side. Pass --no-vector or --no-keyword to disable a channel (mutually exclusive both-off).")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -88,7 +89,7 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
|
||||
// the constructor readable; --kb is marked required by the caller.
|
||||
func bindChunksFlags(cmd *cobra.Command, opts *ChunksOptions) {
|
||||
cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name")
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 8, "Maximum results to return (default 8 — tuned for RAG context window; list commands default to 30)")
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 8, "Maximum results to return (default 8 - tuned for RAG context window; list commands default to 30)")
|
||||
cmd.Flags().Float64Var(&opts.VectorThreshold, "vector-threshold", 0, "Vector retrieval similarity floor (per-channel, pre-fusion); 0 = no filter")
|
||||
cmd.Flags().Float64Var(&opts.KeywordThreshold, "keyword-threshold", 0, "Keyword retrieval score floor (per-channel, pre-fusion); 0 = no filter")
|
||||
cmd.Flags().BoolVar(&opts.NoVector, "no-vector", false, "Disable the vector channel")
|
||||
@@ -129,7 +130,7 @@ func runChunks(ctx context.Context, opts *ChunksOptions, jopts *cmdutil.JSONOpti
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "hybrid search")
|
||||
}
|
||||
// match_count is the server's *primary-match* cap — after that, the
|
||||
// match_count is the server's *primary-match* cap - after that, the
|
||||
// service appends parent / nearby / relation chunks as context
|
||||
// enrichment, so the wire response can exceed Limit. Treat --limit as
|
||||
// a hard return-count cap by trimming on the client. Recall isn't
|
||||
@@ -148,7 +149,7 @@ func runChunks(ctx context.Context, opts *ChunksOptions, jopts *cmdutil.JSONOpti
|
||||
return renderChunkResults(results, opts.KBID)
|
||||
}
|
||||
|
||||
// renderChunkResults prints a compact pretty list. Minimal stopgap — a
|
||||
// renderChunkResults prints a compact pretty list. Minimal stopgap - a
|
||||
// richer tabular renderer can replace this later without breaking the
|
||||
// JSON contract.
|
||||
func renderChunkResults(results []*sdk.SearchResult, kbID string) error {
|
||||
|
||||
@@ -46,7 +46,7 @@ func TestRunSearch_HumanOutput(t *testing.T) {
|
||||
|
||||
// JSON output must surface match_type so machine consumers / agents can
|
||||
// reason about retrieval channels without re-implementing the wire format.
|
||||
// (Human renderer keeps default minimal — diagnostic info opt-in via --json.)
|
||||
// (Human renderer keeps default minimal - diagnostic info opt-in via --json.)
|
||||
func TestRunSearch_JSONIncludesMatchType(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/text"
|
||||
@@ -54,6 +53,9 @@ func NewCmdDocs(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: `docs "<query>"`,
|
||||
Short: "Find documents in a knowledge base by name (client-side substring match)",
|
||||
Long: `Pages through the KB's documents and surfaces every entry whose title or
|
||||
filename contains the query (case-insensitive). Useful for finding a
|
||||
specific upload to download or delete by id.`,
|
||||
Example: ` weknora search docs "Q3 forecast" --kb finance
|
||||
weknora search docs "spec" --kb engineering --limit 5`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
@@ -85,7 +87,6 @@ func NewCmdDocs(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return")
|
||||
cmdutil.AddJSONFlags(cmd, docsFields)
|
||||
_ = cmd.MarkFlagRequired("kb")
|
||||
aiclient.SetAgentHelp(cmd, "Lists documents in --kb whose title or file_name contains the query. Pages through the KB sequentially; stops once limit hits found. Returns the full Knowledge object so agents can derive id / file_size / processed_at without a second call.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/text"
|
||||
@@ -39,7 +38,7 @@ type KBSearchService interface {
|
||||
ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBase, error)
|
||||
}
|
||||
|
||||
// NewCmdKB builds `weknora search kb "<query>"` — substring + case-insensitive
|
||||
// NewCmdKB builds `weknora search kb "<query>"` - substring + case-insensitive
|
||||
// match across KB names and descriptions visible to the active context.
|
||||
// Results are sorted by name length (shortest first; usually the closest
|
||||
// hit) for deterministic output.
|
||||
@@ -48,6 +47,12 @@ func NewCmdKB(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: `kb "<query>"`,
|
||||
Short: "Find knowledge bases by name or description (client-side substring match)",
|
||||
Long: `Substring + case-insensitive match across KB names and descriptions visible
|
||||
to the active context. Results are sorted by name length (shortest first;
|
||||
usually the closest hit) for deterministic output.
|
||||
|
||||
This is name-discovery only - for searching *inside* a knowledge base's
|
||||
content, use ` + "`weknora search chunks`" + `.`,
|
||||
Example: ` weknora search kb "marketing"
|
||||
weknora search kb "team" --limit 5 --json`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
@@ -72,7 +77,6 @@ func NewCmdKB(f *cmdutil.Factory) *cobra.Command {
|
||||
}
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return")
|
||||
cmdutil.AddJSONFlags(cmd, kbSearchFields)
|
||||
aiclient.SetAgentHelp(cmd, "Lists KBs whose name or description contains the query (case-insensitive). Useful to discover --kb identifiers before running search chunks / doc list.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -5,12 +5,11 @@ package search
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
)
|
||||
|
||||
// NewCmdSearch builds the `weknora search` parent. Pure dispatcher to the
|
||||
// four subcommands — users must pick a verb (chunks / kb / docs / sessions).
|
||||
// four subcommands - users must pick a verb (chunks / kb / docs / sessions).
|
||||
func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "search",
|
||||
@@ -28,7 +27,6 @@ func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
|
||||
Args: cobra.NoArgs,
|
||||
Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
|
||||
}
|
||||
aiclient.SetAgentHelp(cmd, "Search parent. Use `search chunks/kb/docs/sessions <q>` — there is no bare-positional form.")
|
||||
|
||||
cmd.AddCommand(NewCmdChunks(f))
|
||||
cmd.AddCommand(NewCmdKB(f))
|
||||
|
||||
@@ -20,9 +20,8 @@ func TestSearch_NoArgs_ShowsHelp(t *testing.T) {
|
||||
require.NoError(t, cmd.Execute())
|
||||
}
|
||||
|
||||
// TestSearch_RejectsPositional: bare positional (e.g. the v0.0-style
|
||||
// `weknora search "<q>" --kb X`) must error — the legacy alias was
|
||||
// dropped, search is now pure dispatcher.
|
||||
// TestSearch_RejectsPositional: bare positional `weknora search "<q>" --kb X`
|
||||
// must error - search is a pure dispatcher with no shortcut form.
|
||||
func TestSearch_RejectsPositional(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
cmd := NewCmdSearch(&cmdutil.Factory{})
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/text"
|
||||
@@ -67,7 +66,6 @@ func NewCmdSessions(f *cmdutil.Factory) *cobra.Command {
|
||||
}
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return")
|
||||
cmdutil.AddJSONFlags(cmd, sessionsSearchFields)
|
||||
aiclient.SetAgentHelp(cmd, "Lists chat sessions whose title or description contains the query. Pages through the tenant sequentially; stops once limit matches found. Returns full Session objects so agents can pivot to session view/delete by id.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -124,7 +122,7 @@ func matchSession(s sdk.Session, needle string) bool {
|
||||
}
|
||||
|
||||
// sortSessionsByRecency sorts in place by UpdatedAt desc. Server returns
|
||||
// strings; we compare lexically — RFC3339 timestamps sort correctly that
|
||||
// strings; we compare lexically - RFC3339 timestamps sort correctly that
|
||||
// way, and a stable order is enough for output determinism even if a
|
||||
// non-conforming string slips through.
|
||||
func sortSessionsByRecency(items []sdk.Session) {
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
@@ -64,7 +63,6 @@ without the user's explicit go-ahead.`,
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, sessionDeleteFields)
|
||||
aiclient.SetAgentHelp(cmd, "Destructively deletes a chat session by id. ALWAYS pass -y/--yes in agent mode (no TTY ⇒ confirm prompt fails). Returns data: {id, deleted:true}.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/text"
|
||||
@@ -68,7 +67,6 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd.Flags().BoolVar(&opts.AllPages, "all-pages", false, "Walk all server pages until exhausted (or --limit hit)")
|
||||
cmd.Flags().StringVar(&opts.Since, "since", "", "Only show sessions updated within `duration` (e.g. 7d, 24h, 30m)")
|
||||
cmdutil.AddJSONFlags(cmd, sessionListFields)
|
||||
aiclient.SetAgentHelp(cmd, "Lists chat sessions as a bare JSON array of Session objects (empty `[]` when none). --all-pages drains every server page in one call (capped by --limit). --since filters client-side after fetch.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -196,7 +194,7 @@ func parseSinceDuration(s string) (time.Duration, error) {
|
||||
}
|
||||
|
||||
// fuzzyTime renders a server-provided timestamp string in "2d ago" form.
|
||||
// Returns the raw input if parsing fails — better to surface the unknown
|
||||
// Returns the raw input if parsing fails - better to surface the unknown
|
||||
// format than to silently render "-".
|
||||
func fuzzyTime(now time.Time, ts string) string {
|
||||
if ts == "" {
|
||||
|
||||
@@ -262,5 +262,3 @@ func TestList_AllPages_WithLimit_StopsAtLimit(t *testing.T) {
|
||||
assert.LessOrEqual(t, len(svc.calls), 3, "must not fetch beyond what fills --limit")
|
||||
}
|
||||
|
||||
// (test removed: --page flag was dropped in v0.4 mainstream-alignment;
|
||||
// --all-pages now walks unconditionally, no mutex case to test.)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//
|
||||
// Package name `sessioncmd` (not `session`) so callers can `import sdk
|
||||
// "github.com/Tencent/WeKnora/client"` and use `sdk.Session` without
|
||||
// shadowing — same hygiene as `contextcmd`.
|
||||
// shadowing - same hygiene as `contextcmd`.
|
||||
package sessioncmd
|
||||
|
||||
import (
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
@@ -49,7 +48,6 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, sessionViewFields)
|
||||
aiclient.SetAgentHelp(cmd, "Shows a chat session's metadata (title, description, timestamps). Errors with resource.not_found if id is unknown.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user