refactor(cli): v0.3 cross-cutting cleanup
Cross-cutting findings surfaced by the branch-completion review. Perf bug: - Factory.Client closure was not memoized. Factory.ResolveKB internally calls f.Client() to resolve --kb name → id, then the command's RunE calls f.Client() again. Two SDK clients, two keyring reads, two AuthRetryTransport allocations per name-resolved invocation, with *independent* token state (a refresh in one was invisible to the other). Switched to sync.Once like Secrets already does. Silent bug bait: - cmdutil.NormalizeHost docstring claimed CodeInputMissingFlag for the empty case; code returned CodeInputInvalidArgument. Aligned doc to code (present-but-empty is a bad value, not a missing flag). Agent contract gaps: - Five user-facing subcommands lacked SetAgentHelp: auth login / logout / list / status and chat. Added concise strings with error- code call-outs so agents can branch without parsing human strings. Helper extraction (≥3 callers): - text.KnowledgeDisplayName(fileName, title, id) — byte-identical formatter that was in both cmd/doc/list.go and cmd/search/docs.go. Takes fields directly so internal/text stays SDK-free. - cmdutil.WrapHTTP(cause, fmt, args...) *Error — replaces the `Wrapf(ClassifyHTTPError(err), err, ...)` pattern across 24 SDK call sites. Sed-driven migration; off-pattern shapes in chat.go (used streamErr) and cmdutil/kb.go (in-package) hand-edited. Contract test gains a comment update: post-migration the dominant pattern is WrapHTTP which the AST scanner skips entirely (only NewError/Wrapf selectors inspected); ClassifyHTTPErrorOutputs() bridge still covers the dynamic codes those paths can yield. UX consistency: - cmd/doc/list.go --page-size help now reads "Items per page (1..1000)" matching cmd/session/list.go. The bounds validation already enforced 1..1000; the help text was the last drift. Comment-discipline sweep: - Deleted the WHAT-only "*Options captures `weknora ...` flag state" docstring across 23 files (context, kb, auth, doc, session, search, chat, doctor, link). Where the line carried a real WHY clause (kb/delete, doc/delete, session/delete, kb/edit), kept the WHY and dropped only the leading WHAT phrase. - Stripped third-party project-name attribution from inline comments and one user-visible flag-help string across ~40 files in cli/cmd and cli/internal (plus 4 test-file comments). Removed phrases like "Mirrors `gh X`", "borrowed from lark-cli", "kubectl-style", "gcloud `--project`", "Stripe pattern", and the embedded GitHub URLs pointing at those projects. Behavioral descriptions and the WHY behind each comment are preserved; only the upstream-name attribution is gone. Inspiration / north-star references belong in cli/AGENTS.md (the design doc) and commit messages, not scattered through every file. Triggered by an audit round that surfaced several false / fragile parity claims (e.g. "Mirrors `gh repo edit`" — gh repo edit has no --name flag; "matches gcloud `--project` id-or-name" — gcloud's --project accepts ID only). Rather than fix them one by one, the whole category of in-comment external-project references was stripped uniformly.
This commit is contained in:
@@ -17,16 +17,22 @@ import (
|
|||||||
// cmdutil.NewError(codeXxx, ...) and cmdutil.Wrapf(codeXxx, ...) and verifies
|
// cmdutil.NewError(codeXxx, ...) and cmdutil.Wrapf(codeXxx, ...) and verifies
|
||||||
// that codeXxx is registered in cmdutil.AllCodes().
|
// that codeXxx is registered in cmdutil.AllCodes().
|
||||||
//
|
//
|
||||||
// ClassifyHTTPError is dynamic: callers pass cmdutil.ClassifyHTTPError(err)
|
// ClassifyHTTPError is dynamic — callers don't pass a literal CodeXxx
|
||||||
// as the first arg. We bridge that via cmdutil.ClassifyHTTPErrorOutputs(),
|
// ident. Most SDK call sites go through cmdutil.WrapHTTP(err, ...) which
|
||||||
// which returns every code that the switch can return — those are added to
|
// the scanner skips entirely (it only inspects NewError / Wrapf selector
|
||||||
// the registered set so the AST scanner doesn't false-positive on them.
|
// names). A few sites still call ClassifyHTTPError directly to inspect
|
||||||
|
// or remap the code; those are call-expression args the scanner also
|
||||||
|
// skips. Either way, the codes those paths can yield are bridged via
|
||||||
|
// cmdutil.ClassifyHTTPErrorOutputs(), which enumerates every code the
|
||||||
|
// switch can return — added to the registered set so the AST scanner
|
||||||
|
// doesn't false-positive on them.
|
||||||
//
|
//
|
||||||
// Limitations (documented in spec §4.3):
|
// Limitations (documented in spec §4.3):
|
||||||
// - Only literal cmdutil.CodeXxx idents are detected; codes assigned to
|
// - Only literal cmdutil.CodeXxx idents are detected; codes assigned to
|
||||||
// a local variable then passed are NOT scanned (rare pattern).
|
// a local variable then passed are NOT scanned (rare pattern).
|
||||||
// - cmdutil.ClassifyHTTPError(...) call expressions are skipped — bridge
|
// - cmdutil.WrapHTTP(...) and cmdutil.ClassifyHTTPError(...) call
|
||||||
// covers them.
|
// expressions are skipped — the ClassifyHTTPErrorOutputs bridge
|
||||||
|
// covers their dynamic codes.
|
||||||
// - v0.x does not enforce a baseline diff (spec ADR-6b); v0.9 will.
|
// - v0.x does not enforce a baseline diff (spec ADR-6b); v0.9 will.
|
||||||
func TestAllReferencedCodesAreRegistered(t *testing.T) {
|
func TestAllReferencedCodesAreRegistered(t *testing.T) {
|
||||||
registered := make(map[cmdutil.ErrorCode]struct{})
|
registered := make(map[cmdutil.ErrorCode]struct{})
|
||||||
|
|||||||
+11
-13
@@ -1,11 +1,10 @@
|
|||||||
// Package api implements the `weknora api` raw HTTP passthrough command.
|
// Package api implements the `weknora api` raw HTTP passthrough command.
|
||||||
//
|
//
|
||||||
// Mirrors `gh api` ergonomics (verified against the gh manual): one
|
// Shape: one positional (path) + `-X/--method` flag, default GET (auto-
|
||||||
// positional (path) + `-X/--method` flag, default GET (auto-promoted to
|
// promoted to POST when a body is supplied via --data or --input). The two
|
||||||
// POST when a body is supplied via --data or --input). The two body-
|
// body-source flags are mutually exclusive. Default raw response body to
|
||||||
// source flags are mutually exclusive. Default raw response body to
|
// stdout; --json wraps in CLI envelope. Reuses sdk.Client.Raw which already
|
||||||
// stdout; --json wraps in CLI envelope. Reuses sdk.Client.Raw which
|
// applies tenant + auth headers.
|
||||||
// already applies tenant + auth headers.
|
|
||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -26,7 +25,6 @@ import (
|
|||||||
sdk "github.com/Tencent/WeKnora/client"
|
sdk "github.com/Tencent/WeKnora/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Options captures `weknora api` flag state.
|
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Method string
|
Method string
|
||||||
Data string
|
Data string
|
||||||
@@ -89,16 +87,16 @@ Examples:
|
|||||||
}
|
}
|
||||||
cmd.Flags().StringVarP(&opts.Method, "method", "X", "", "HTTP method (default: GET, or POST when a body is supplied)")
|
cmd.Flags().StringVarP(&opts.Method, "method", "X", "", "HTTP method (default: GET, or POST when a body is supplied)")
|
||||||
cmd.Flags().StringVarP(&opts.Data, "data", "d", "", "Request body as raw string (e.g. JSON)")
|
cmd.Flags().StringVarP(&opts.Data, "data", "d", "", "Request body as raw string (e.g. JSON)")
|
||||||
cmd.Flags().StringVar(&opts.Input, "input", "", "Read request body from file (use `-` for stdin); gh CLI parity")
|
cmd.Flags().StringVar(&opts.Input, "input", "", "Read request body from file (use `-` for stdin)")
|
||||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Wrap response in JSON envelope (status/headers/body)")
|
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Wrap response in JSON envelope (status/headers/body)")
|
||||||
cmd.MarkFlagsMutuallyExclusive("data", "input")
|
cmd.MarkFlagsMutuallyExclusive("data", "input")
|
||||||
agent.SetAgentHelp(cmd, "Raw HTTP passthrough to the WeKnora server. Use when no typed command exists for the endpoint. Headers (auth / tenant / request-id) are injected from the active context.")
|
agent.SetAgentHelp(cmd, "Raw HTTP passthrough to the WeKnora server. Use when no typed command exists for the endpoint. Headers (auth / tenant / request-id) are injected from the active context. Without --json the response body streams to stdout verbatim. With --json: data is {status, headers, body} where body is the parsed JSON if response is JSON, else the raw string. Non-2xx responses surface as a typed error (4xx → input.invalid_argument / auth.* / resource.not_found per ClassifyHTTPStatus; 5xx → server.error / network.error). DELETE through `weknora api` triggers exit-10 confirm just like `weknora kb delete`. Mutual exclusion: --data and --input cannot both be set (input.invalid_argument).")
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
// readInput reads opts.Input and returns its contents. "-" reads from
|
// readInput reads opts.Input and returns its contents. "-" reads from
|
||||||
// opts.StdinReader (or iostreams.IO.In as the production default).
|
// opts.StdinReader (or iostreams.IO.In as the production default) for
|
||||||
// Mirrors gh `api --input -` for piped JSON payloads.
|
// piped JSON payloads.
|
||||||
func readInput(opts *Options) ([]byte, error) {
|
func readInput(opts *Options) ([]byte, error) {
|
||||||
if opts.Input == "-" {
|
if opts.Input == "-" {
|
||||||
r := opts.StdinReader
|
r := opts.StdinReader
|
||||||
@@ -118,7 +116,7 @@ func readInput(opts *Options) ([]byte, error) {
|
|||||||
return b, nil
|
return b, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// resolveMethod implements gh's auto-method behavior: explicit -X wins;
|
// resolveMethod implements the auto-method behavior: explicit -X wins;
|
||||||
// otherwise body presence promotes GET → POST.
|
// otherwise body presence promotes GET → POST.
|
||||||
func resolveMethod(opts *Options) string {
|
func resolveMethod(opts *Options) string {
|
||||||
if opts.Method != "" {
|
if opts.Method != "" {
|
||||||
@@ -179,7 +177,7 @@ func runAPI(ctx context.Context, opts *Options, svc Service, method, path string
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
// Transport / DNS failure (Raw never returns a typed HTTP error of its
|
// Transport / DNS failure (Raw never returns a typed HTTP error of its
|
||||||
// own; non-2xx responses still surface as resp != nil, err == nil).
|
// own; non-2xx responses still surface as resp != nil, err == nil).
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "%s %s", method, path)
|
return cmdutil.WrapHTTP(err, "%s %s", method, path)
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
|||||||
@@ -117,8 +117,7 @@ func TestAPI_PostWithData(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestAPI_InputFile verifies --input <file> reads the request body from
|
// TestAPI_InputFile verifies --input <file> reads the request body from disk.
|
||||||
// disk. gh CLI parity (verified against gh manual: `--input <file>`).
|
|
||||||
func TestAPI_InputFile(t *testing.T) {
|
func TestAPI_InputFile(t *testing.T) {
|
||||||
_, _ = iostreams.SetForTest(t)
|
_, _ = iostreams.SetForTest(t)
|
||||||
tmp := filepath.Join(t.TempDir(), "body.json")
|
tmp := filepath.Join(t.TempDir(), "body.json")
|
||||||
@@ -142,8 +141,8 @@ func TestAPI_InputFile(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestAPI_InputDash_Stdin verifies the gh-style "--input -" form: the
|
// TestAPI_InputDash_Stdin verifies the "--input -" form: the payload comes
|
||||||
// payload comes from opts.StdinReader (production-default iostreams.IO.In).
|
// from opts.StdinReader (production-default iostreams.IO.In).
|
||||||
func TestAPI_InputDash_Stdin(t *testing.T) {
|
func TestAPI_InputDash_Stdin(t *testing.T) {
|
||||||
_, _ = iostreams.SetForTest(t)
|
_, _ = iostreams.SetForTest(t)
|
||||||
var seenBody []byte
|
var seenBody []byte
|
||||||
|
|||||||
@@ -7,17 +7,16 @@ import (
|
|||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
|
"github.com/Tencent/WeKnora/cli/internal/agent"
|
||||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListOptions captures `weknora auth list` flag state.
|
|
||||||
type ListOptions struct {
|
type ListOptions struct {
|
||||||
JSONOut bool
|
JSONOut bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// listEntry is one row in the rendered list / one element of envelope.data.
|
|
||||||
type listEntry struct {
|
type listEntry struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Host string `json:"host"`
|
Host string `json:"host"`
|
||||||
@@ -26,10 +25,9 @@ type listEntry struct {
|
|||||||
Current bool `json:"current"`
|
Current bool `json:"current"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCmdList builds `weknora auth list`. Mirrors gh's per-host enumeration
|
// NewCmdList builds `weknora auth list`. Per-host enumeration: render one
|
||||||
// and lark `auth list`: render one row per registered context, marking the
|
// row per registered context, marking the active one. Reads only
|
||||||
// active one. Reads only ~/.config/weknora/config.yaml — no network, no
|
// ~/.config/weknora/config.yaml — no network, no keyring touch.
|
||||||
// keyring touch.
|
|
||||||
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &ListOptions{}
|
opts := &ListOptions{}
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
@@ -41,6 +39,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||||
|
agent.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
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
|
"github.com/Tencent/WeKnora/cli/internal/agent"
|
||||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||||
@@ -19,10 +20,7 @@ import (
|
|||||||
type LoginOptions struct {
|
type LoginOptions struct {
|
||||||
Host string // --host
|
Host string // --host
|
||||||
Context string // --name: context name to write into config.yaml
|
Context string // --name: context name to write into config.yaml
|
||||||
// (was --context in v0.0; renamed v0.1 to
|
WithToken bool // --with-token: read api key from stdin instead of prompting password
|
||||||
// avoid shadowing the new global --context
|
|
||||||
// single-shot override flag)
|
|
||||||
WithToken bool // --with-token (read api key from stdin instead of prompting password)
|
|
||||||
APIKey string // populated by --with-token from stdin
|
APIKey string // populated by --with-token from stdin
|
||||||
Email string
|
Email string
|
||||||
Password string
|
Password string
|
||||||
@@ -49,6 +47,7 @@ func NewCmdLogin(f *cmdutil.Factory, runF func(context.Context, *LoginOptions, *
|
|||||||
Credentials are persisted to the OS keyring when available; otherwise to a
|
Credentials are persisted to the OS keyring when available; otherwise to a
|
||||||
0600 file under $XDG_CONFIG_HOME/weknora/secrets. The named context becomes
|
0600 file under $XDG_CONFIG_HOME/weknora/secrets. The named context becomes
|
||||||
the current_context in ~/.config/weknora/config.yaml.`,
|
the current_context in ~/.config/weknora/config.yaml.`,
|
||||||
|
Args: cobra.NoArgs,
|
||||||
RunE: func(c *cobra.Command, args []string) error {
|
RunE: func(c *cobra.Command, args []string) error {
|
||||||
run := runF
|
run := runF
|
||||||
if run == nil {
|
if run == nil {
|
||||||
@@ -66,6 +65,7 @@ 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")
|
cmd.Flags().BoolVar(&opts.WithToken, "with-token", false, "Read an API key from stdin instead of prompting for password")
|
||||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||||
cmdutil.MustRequireFlag(cmd, "host")
|
cmdutil.MustRequireFlag(cmd, "host")
|
||||||
|
agent.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
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
|
"github.com/Tencent/WeKnora/cli/internal/agent"
|
||||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||||
@@ -13,7 +14,6 @@ import (
|
|||||||
"github.com/Tencent/WeKnora/cli/internal/secrets"
|
"github.com/Tencent/WeKnora/cli/internal/secrets"
|
||||||
)
|
)
|
||||||
|
|
||||||
// LogoutOptions captures `weknora auth logout` flag state.
|
|
||||||
type LogoutOptions struct {
|
type LogoutOptions struct {
|
||||||
Name string // --name: target a specific context (default: current)
|
Name string // --name: target a specific context (default: current)
|
||||||
All bool // --all: clear every context
|
All bool // --all: clear every context
|
||||||
@@ -25,11 +25,9 @@ type logoutResult struct {
|
|||||||
Removed []string `json:"removed"`
|
Removed []string `json:"removed"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCmdLogout builds `weknora auth logout`. Mirrors `gh auth logout` and
|
// NewCmdLogout builds `weknora auth logout`. Clears stored credentials
|
||||||
// `lark auth logout`: clears stored credentials (keyring + file fallback) and
|
// (keyring + file fallback) and removes the context entry from config.yaml.
|
||||||
// removes the context entry from config.yaml. No server-side revocation —
|
// No server-side revocation — local-only credential clear.
|
||||||
// matches gh's documented behavior ("does not revoke … users must do that
|
|
||||||
// manually").
|
|
||||||
func NewCmdLogout(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdLogout(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &LogoutOptions{}
|
opts := &LogoutOptions{}
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
@@ -53,6 +51,7 @@ accepted until it expires.`,
|
|||||||
cmd.Flags().BoolVar(&opts.All, "all", false, "Log out of every configured context")
|
cmd.Flags().BoolVar(&opts.All, "all", false, "Log out of every configured context")
|
||||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||||
cmd.MarkFlagsMutuallyExclusive("name", "all")
|
cmd.MarkFlagsMutuallyExclusive("name", "all")
|
||||||
|
agent.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
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import (
|
|||||||
sdk "github.com/Tencent/WeKnora/client"
|
sdk "github.com/Tencent/WeKnora/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// RefreshOptions captures `weknora auth refresh` flag state.
|
|
||||||
type RefreshOptions struct {
|
type RefreshOptions struct {
|
||||||
Name string // --name: target context (defaults to current)
|
Name string // --name: target context (defaults to current)
|
||||||
JSONOut bool
|
JSONOut bool
|
||||||
@@ -29,11 +28,7 @@ type refreshResult struct {
|
|||||||
|
|
||||||
// NewCmdRefresh builds `weknora auth refresh`. Renews the JWT access
|
// 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. Note: `gh auth refresh`
|
// the standard OAuth refresh-token grant.
|
||||||
// shares the name but has a different semantic (interactive OAuth-
|
|
||||||
// scope expansion via the browser); there's no direct gh parallel
|
|
||||||
// because gh's PAT/OAuth-app model doesn't have a short-lived
|
|
||||||
// access_token + refresh_token pair.
|
|
||||||
//
|
//
|
||||||
// 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.
|
// rotate the key via the server UI instead.
|
||||||
|
|||||||
@@ -6,13 +6,13 @@ import (
|
|||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
|
"github.com/Tencent/WeKnora/cli/internal/agent"
|
||||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||||
sdk "github.com/Tencent/WeKnora/client"
|
sdk "github.com/Tencent/WeKnora/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// StatusOptions captures the (sparse) configuration of `weknora auth status`.
|
|
||||||
type StatusOptions struct {
|
type StatusOptions struct {
|
||||||
JSONOut bool
|
JSONOut bool
|
||||||
}
|
}
|
||||||
@@ -37,6 +37,7 @@ func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
|
|||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
Use: "status",
|
Use: "status",
|
||||||
Short: "Show the active context, principal, and token state",
|
Short: "Show the active context, principal, and token state",
|
||||||
|
Args: cobra.NoArgs,
|
||||||
RunE: func(c *cobra.Command, args []string) error {
|
RunE: func(c *cobra.Command, args []string) error {
|
||||||
cli, err := f.Client()
|
cli, err := f.Client()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -46,6 +47,7 @@ func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||||
|
agent.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
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,7 +57,7 @@ func runStatus(ctx context.Context, opts *StatusOptions, f *cmdutil.Factory, svc
|
|||||||
}
|
}
|
||||||
resp, err := svc.GetCurrentUser(ctx)
|
resp, err := svc.GetCurrentUser(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "fetch current user")
|
return cmdutil.WrapHTTP(err, "fetch current user")
|
||||||
}
|
}
|
||||||
user := resp.Data.User
|
user := resp.Data.User
|
||||||
tenant := resp.Data.Tenant
|
tenant := resp.Data.Tenant
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import (
|
|||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
|
"github.com/Tencent/WeKnora/cli/internal/agent"
|
||||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||||
@@ -35,7 +36,6 @@ import (
|
|||||||
sdk "github.com/Tencent/WeKnora/client"
|
sdk "github.com/Tencent/WeKnora/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Options captures one `weknora chat` invocation.
|
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Query string
|
Query string
|
||||||
KBID string
|
KBID string
|
||||||
@@ -102,6 +102,7 @@ Modes:
|
|||||||
cmd.Flags().StringVar(&opts.SessionID, "session-id", "", "Continue an existing chat session (skip auto-create)")
|
cmd.Flags().StringVar(&opts.SessionID, "session-id", "", "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)")
|
cmd.Flags().BoolVar(&opts.NoStream, "no-stream", false, "Buffer the full answer before printing (forces accumulate mode)")
|
||||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Emit a single JSON envelope (implies --no-stream)")
|
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Emit a single JSON envelope (implies --no-stream)")
|
||||||
|
agent.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} envelope is emitted at completion (no partial chunks). Pass --session-id to thread follow-ups. Errors: server.session_create_failed when auto-create fails; local.sse_stream_aborted on mid-stream disconnect.")
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,7 +193,7 @@ func runChat(ctx context.Context, opts *Options, svc chatService) error {
|
|||||||
}
|
}
|
||||||
// Pre-stream HTTP / transport failure: route through the canonical
|
// Pre-stream HTTP / transport failure: route through the canonical
|
||||||
// classifier so 401 / 404 / 5xx still surface their specific codes.
|
// classifier so 401 / 404 / 5xx still surface their specific codes.
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(streamErr), streamErr, "knowledge qa stream")
|
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
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import (
|
|||||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AddOptions captures `weknora context add` flag state.
|
|
||||||
type AddOptions struct {
|
type AddOptions struct {
|
||||||
Host string
|
Host string
|
||||||
User string
|
User string
|
||||||
@@ -31,11 +30,9 @@ type addResult struct {
|
|||||||
// NewCmdAdd builds `weknora context add`. Registers a *credentialless*
|
// 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>`,
|
// context are attached separately with `weknora auth login --name <n>`,
|
||||||
// reflecting gh's separation of "where" the CLI talks to (the host) and
|
// separating "where" the CLI talks to (the host) and "how" it authenticates
|
||||||
// "how" it authenticates (the credential). kubectl's `config set-context`
|
// (the credential). If you want one command for both, run
|
||||||
// covers the same operation under a different surface convention. If you
|
// `weknora auth login --name <n> --host <h>` instead.
|
||||||
// want one command for both, run `weknora auth login --name <n> --host
|
|
||||||
// <h>` instead.
|
|
||||||
func NewCmdAdd(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdAdd(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &AddOptions{}
|
opts := &AddOptions{}
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
@@ -56,7 +53,7 @@ adds leave the current context untouched.`,
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
cmd.Flags().StringVar(&opts.Host, "host", "", "Server base URL, e.g. https://kb.example.com (required)")
|
cmd.Flags().StringVar(&opts.Host, "host", "", "Server base URL, e.g. https://kb.example.com (required)")
|
||||||
cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in `context list` (optional, cosmetic only)")
|
cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in 'context list' (optional, cosmetic only)")
|
||||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||||
_ = cmd.MarkFlagRequired("host")
|
_ = cmd.MarkFlagRequired("host")
|
||||||
agent.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.")
|
agent.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.")
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
// Package contextcmd holds `weknora context` command tree
|
// Package contextcmd holds `weknora context` command tree
|
||||||
// (list / add / remove / use). Uses the gh-style `<noun> <verb>` shape
|
// (list / add / remove / use). Uses the `<noun> <verb>` shape
|
||||||
// consistent with the rest of this CLI. kubectl exposes the same set
|
// consistent with the rest of this CLI.
|
||||||
// of operations as flat hyphenated subcommands (`config get-contexts /
|
|
||||||
// set-context / delete-context / use-context`) — a different idiom we
|
|
||||||
// don't adopt because it would make `context` an outlier in our tree.
|
|
||||||
//
|
//
|
||||||
// Package name `contextcmd` (not `context`) to avoid shadowing stdlib context.
|
// 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.
|
||||||
|
|||||||
@@ -14,12 +14,10 @@ import (
|
|||||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListOptions captures `weknora context list` flag state.
|
|
||||||
type ListOptions struct {
|
type ListOptions struct {
|
||||||
JSONOut bool
|
JSONOut bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// listEntry is one row in the rendered table / one element of envelope.data.
|
|
||||||
type listEntry struct {
|
type listEntry struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Host string `json:"host"`
|
Host string `json:"host"`
|
||||||
@@ -27,11 +25,8 @@ type listEntry struct {
|
|||||||
Current bool `json:"current"`
|
Current bool `json:"current"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCmdList builds `weknora context list`. Same listing shape as gh
|
// NewCmdList builds `weknora context list`. Per-host enumeration with an
|
||||||
// `auth status` (per-host enumeration with an active marker). The kubectl
|
// active marker. Reads only config.yaml — no network, no keyring touch.
|
||||||
// equivalent is `config get-contexts` — same data, different surface
|
|
||||||
// convention (kubectl uses hyphenated subcommands; we use noun-verb).
|
|
||||||
// Reads only config.yaml — no network, no keyring touch.
|
|
||||||
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &ListOptions{}
|
opts := &ListOptions{}
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
|
|||||||
@@ -14,10 +14,8 @@ import (
|
|||||||
"github.com/Tencent/WeKnora/cli/internal/secrets"
|
"github.com/Tencent/WeKnora/cli/internal/secrets"
|
||||||
)
|
)
|
||||||
|
|
||||||
// RemoveOptions captures `weknora context remove` flag state. Yes is sourced
|
|
||||||
// from the global -y/--yes persistent flag (matches `kb delete`).
|
|
||||||
type RemoveOptions struct {
|
type RemoveOptions struct {
|
||||||
Yes bool
|
Yes bool // sourced from the global -y/--yes persistent flag (matches `kb delete`)
|
||||||
JSONOut bool
|
JSONOut bool
|
||||||
DryRun bool
|
DryRun bool
|
||||||
}
|
}
|
||||||
@@ -30,12 +28,10 @@ type removeResult struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewCmdRemove builds `weknora context remove`. Drops the entry from
|
// NewCmdRemove builds `weknora context remove`. Drops the entry from
|
||||||
// config.yaml and best-effort clears keyring references. The kubectl
|
// config.yaml and best-effort clears keyring references. Removing a
|
||||||
// equivalent is `config delete-context`; we use the noun-verb form
|
// non-current context is low-friction (no prompt). Removing the *current*
|
||||||
// instead. Removing a non-current context is low-friction (no prompt).
|
// context triggers the destructive-write confirmation protocol (exit 10),
|
||||||
// Removing the *current* context triggers the lark-cli exit-10
|
// because subsequent commands will have no default connection target.
|
||||||
// confirmation protocol because subsequent commands will have no
|
|
||||||
// default connection target.
|
|
||||||
func NewCmdRemove(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdRemove(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &RemoveOptions{}
|
opts := &RemoveOptions{}
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
@@ -48,7 +44,7 @@ Removing the current context also clears CurrentContext — subsequent commands
|
|||||||
will error until you select another with ` + "`weknora context use <name>`" + ` or pick
|
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
|
one up via the global ` + "`--context`" + ` flag. Because that change is observable in
|
||||||
every later command, removing the current context requires explicit -y/--yes
|
every later command, removing the current context requires explicit -y/--yes
|
||||||
in scripted / --json invocations (exit-10 protocol; AGENTS.md).`,
|
in scripted / --json invocations (exit code 10; see cli/AGENTS.md).`,
|
||||||
Example: ` weknora context remove staging # remove non-current → no prompt
|
Example: ` weknora context remove staging # remove non-current → no prompt
|
||||||
weknora context remove production -y # remove current → confirm`,
|
weknora context remove production -y # remove current → confirm`,
|
||||||
Args: cobra.ExactArgs(1),
|
Args: cobra.ExactArgs(1),
|
||||||
@@ -86,7 +82,7 @@ func runRemove(opts *RemoveOptions, name string, store secrets.Store, p prompt.P
|
|||||||
risk)
|
risk)
|
||||||
}
|
}
|
||||||
// Confirmation only fires for removing the current context — non-current
|
// Confirmation only fires for removing the current context — non-current
|
||||||
// remove matches `auth logout`'s low-friction policy.
|
// remove uses the same low-friction policy as `auth logout`.
|
||||||
if wasCurrent {
|
if wasCurrent {
|
||||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, opts.JSONOut, "current context", name); err != nil {
|
if err := cmdutil.ConfirmDestructive(p, opts.Yes, opts.JSONOut, "current context", name); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -133,7 +129,7 @@ func riskForRemove(name string, wasCurrent bool) *format.Risk {
|
|||||||
|
|
||||||
// clearContextSecrets mirrors auth/logout.go: best-effort delete every secret
|
// clearContextSecrets mirrors auth/logout.go: best-effort delete every secret
|
||||||
// slot the context references. Errors are swallowed so a missing keyring
|
// slot the context references. Errors are swallowed so a missing keyring
|
||||||
// entry doesn't block remove (logout had the same policy from v0.2).
|
// entry doesn't block remove (logout has had the same policy since v0.2).
|
||||||
func clearContextSecrets(store secrets.Store, c config.Context, name string) {
|
func clearContextSecrets(store secrets.Store, c config.Context, name string) {
|
||||||
if c.TokenRef != "" {
|
if c.TokenRef != "" {
|
||||||
_ = store.Delete(name, "access")
|
_ = store.Delete(name, "access")
|
||||||
|
|||||||
@@ -13,10 +13,8 @@ import (
|
|||||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DeleteOptions captures `weknora doc delete` flags. Yes is sourced from the
|
|
||||||
// global -y/--yes persistent flag (gh-style; see cli/cmd/root.go).
|
|
||||||
type DeleteOptions struct {
|
type DeleteOptions struct {
|
||||||
Yes bool
|
Yes bool // sourced from the global -y/--yes persistent flag (see cli/cmd/root.go)
|
||||||
JSONOut bool
|
JSONOut bool
|
||||||
DryRun bool
|
DryRun bool
|
||||||
}
|
}
|
||||||
@@ -33,8 +31,8 @@ type deleteResult struct {
|
|||||||
Deleted bool `json:"deleted"`
|
Deleted bool `json:"deleted"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCmdDelete builds `weknora doc delete`. Mirrors `gh repo delete --yes`
|
// NewCmdDelete builds `weknora doc delete`. Confirmation routed through
|
||||||
// confirmation pattern via the global -y/--yes persistent flag.
|
// the global -y/--yes persistent flag.
|
||||||
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &DeleteOptions{}
|
opts := &DeleteOptions{}
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
@@ -81,7 +79,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, svc DeleteService, p pr
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err := svc.DeleteKnowledge(ctx, id); err != nil {
|
if err := svc.DeleteKnowledge(ctx, id); err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "delete document %s", id)
|
return cmdutil.WrapHTTP(err, "delete document %s", id)
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.JSONOut {
|
if opts.JSONOut {
|
||||||
|
|||||||
@@ -129,9 +129,9 @@ func TestDelete_AgentPrompterErrors(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TestDelete_NoYes_NonTTY_RequiresConfirmation: when stdout isn't a TTY
|
// TestDelete_NoYes_NonTTY_RequiresConfirmation: when stdout isn't a TTY
|
||||||
// (typical agent pipe / CI), the lark-cli skill protocol requires explicit
|
// (typical agent pipe / CI), the destructive-write protocol requires
|
||||||
// -y/--yes. The CLI exits 10 with input.confirmation_required, never
|
// explicit -y/--yes. The CLI exits 10 with input.confirmation_required,
|
||||||
// silently proceeds. See cli/AGENTS.md "Exit codes".
|
// never silently proceeds. See cli/AGENTS.md "Exit codes".
|
||||||
func TestDelete_NoYes_NonTTY_RequiresConfirmation(t *testing.T) {
|
func TestDelete_NoYes_NonTTY_RequiresConfirmation(t *testing.T) {
|
||||||
_, _ = iostreams.SetForTest(t)
|
_, _ = iostreams.SetForTest(t)
|
||||||
svc := &fakeDeleteSvc{}
|
svc := &fakeDeleteSvc{}
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ import (
|
|||||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DownloadOptions captures `weknora doc download` flag state.
|
|
||||||
type DownloadOptions struct {
|
type DownloadOptions struct {
|
||||||
Output string // --output / -O: target path, "-" for stdout, "" for server-suggested filename
|
Output string // --output / -O: target path, "-" for stdout, "" for server-suggested filename
|
||||||
Clobber bool // --clobber: allow overwrite of an existing file
|
Clobber bool // --clobber: allow overwrite of an existing file
|
||||||
@@ -28,11 +27,9 @@ type DownloadService interface {
|
|||||||
OpenKnowledgeFile(ctx context.Context, knowledgeID string) (string, io.ReadCloser, error)
|
OpenKnowledgeFile(ctx context.Context, knowledgeID string) (string, io.ReadCloser, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCmdDownload builds `weknora doc download <id>`. Borrows shape from
|
// NewCmdDownload builds `weknora doc download <id>`. Positional id, output
|
||||||
// `gh release download` — positional id, output flag, `-` sentinel for
|
// flag, `-` sentinel for stdout. Flags: `-O, --output <file>` for
|
||||||
// stdout. Flag names match gh canon verified against the gh manual:
|
// destination, `--clobber` for overwrite control.
|
||||||
// `-O, --output <file>` for destination, `--clobber` for overwrite
|
|
||||||
// control.
|
|
||||||
func NewCmdDownload(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdDownload(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &DownloadOptions{}
|
opts := &DownloadOptions{}
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
@@ -67,7 +64,7 @@ Existing files are NOT overwritten unless --clobber is passed.`,
|
|||||||
func runDownload(ctx context.Context, opts *DownloadOptions, svc DownloadService, id string) error {
|
func runDownload(ctx context.Context, opts *DownloadOptions, svc DownloadService, id string) error {
|
||||||
suggested, body, err := svc.OpenKnowledgeFile(ctx, id)
|
suggested, body, err := svc.OpenKnowledgeFile(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "download %s", id)
|
return cmdutil.WrapHTTP(err, "download %s", id)
|
||||||
}
|
}
|
||||||
defer body.Close()
|
defer body.Close()
|
||||||
|
|
||||||
|
|||||||
+3
-16
@@ -17,7 +17,6 @@ import (
|
|||||||
sdk "github.com/Tencent/WeKnora/client"
|
sdk "github.com/Tencent/WeKnora/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListOptions captures `weknora doc list` flags.
|
|
||||||
type ListOptions struct {
|
type ListOptions struct {
|
||||||
Page int
|
Page int
|
||||||
PageSize int
|
PageSize int
|
||||||
@@ -77,7 +76,7 @@ backend storage order is not guaranteed and varies between deployments.`,
|
|||||||
// value into the command's flag set.
|
// value into the command's flag set.
|
||||||
cmd.Flags().String("kb", "", "Knowledge base UUID or name (overrides env / project link)")
|
cmd.Flags().String("kb", "", "Knowledge base UUID or name (overrides env / project link)")
|
||||||
cmd.Flags().IntVar(&opts.Page, "page", 1, "Page number (1-based)")
|
cmd.Flags().IntVar(&opts.Page, "page", 1, "Page number (1-based)")
|
||||||
cmd.Flags().IntVar(&opts.PageSize, "page-size", 20, "Items per page")
|
cmd.Flags().IntVar(&opts.PageSize, "page-size", 20, "Items per page (1..1000)")
|
||||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||||
agent.SetAgentHelp(cmd, "Lists docs in the resolved KB. Returns data: {items, page, page_size, total, kb_id}; pass --kb when not running inside a project.")
|
agent.SetAgentHelp(cmd, "Lists docs in the resolved KB. Returns data: {items, page, page_size, total, kb_id}; pass --kb when not running inside a project.")
|
||||||
return cmd
|
return cmd
|
||||||
@@ -98,7 +97,7 @@ func runList(ctx context.Context, opts *ListOptions, svc ListService, kbID strin
|
|||||||
}
|
}
|
||||||
items, total, err := svc.ListKnowledge(ctx, kbID, opts.Page, opts.PageSize, "")
|
items, total, err := svc.ListKnowledge(ctx, kbID, opts.Page, opts.PageSize, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list documents")
|
return cmdutil.WrapHTTP(err, "list documents")
|
||||||
}
|
}
|
||||||
if items == nil {
|
if items == nil {
|
||||||
items = []sdk.Knowledge{} // ensure JSON [] not null
|
items = []sdk.Knowledge{} // ensure JSON [] not null
|
||||||
@@ -130,25 +129,13 @@ func runList(ctx context.Context, opts *ListOptions, svc ListService, kbID strin
|
|||||||
fmt.Fprintln(tw, "ID\tNAME\tSTATUS\tSIZE\tUPDATED")
|
fmt.Fprintln(tw, "ID\tNAME\tSTATUS\tSIZE\tUPDATED")
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
for _, k := range items {
|
for _, k := range items {
|
||||||
name := text.Truncate(40, displayName(k))
|
name := text.Truncate(40, text.KnowledgeDisplayName(k.FileName, k.Title, k.ID))
|
||||||
updated := text.FuzzyAgo(now, k.UpdatedAt)
|
updated := text.FuzzyAgo(now, k.UpdatedAt)
|
||||||
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n", k.ID, name, k.ParseStatus, formatSize(k.FileSize), updated)
|
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n", k.ID, name, k.ParseStatus, formatSize(k.FileSize), updated)
|
||||||
}
|
}
|
||||||
return tw.Flush()
|
return tw.Flush()
|
||||||
}
|
}
|
||||||
|
|
||||||
// displayName picks the most informative human label for a knowledge entry.
|
|
||||||
// File-uploads use FileName; URL / text entries fall back to Title.
|
|
||||||
func displayName(k sdk.Knowledge) string {
|
|
||||||
if k.FileName != "" {
|
|
||||||
return k.FileName
|
|
||||||
}
|
|
||||||
if k.Title != "" {
|
|
||||||
return k.Title
|
|
||||||
}
|
|
||||||
return k.ID
|
|
||||||
}
|
|
||||||
|
|
||||||
// formatSize renders a byte count as a short human string (KB / MB).
|
// 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).
|
// column. A "-" placeholder hides zero-size entries (URL / text).
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ import (
|
|||||||
// and "wechat" (mini-program). The server uses this only for analytics.
|
// and "wechat" (mini-program). The server uses this only for analytics.
|
||||||
const uploadChannel = "api"
|
const uploadChannel = "api"
|
||||||
|
|
||||||
// UploadOptions captures `weknora doc upload` flags.
|
|
||||||
type UploadOptions struct {
|
type UploadOptions struct {
|
||||||
Name string
|
Name string
|
||||||
Recursive bool // --recursive: positional arg is a directory; walk + upload each match
|
Recursive bool // --recursive: positional arg is a directory; walk + upload each match
|
||||||
@@ -132,7 +131,7 @@ func runUpload(ctx context.Context, opts *UploadOptions, svc UploadService, kbID
|
|||||||
|
|
||||||
k, err := svc.CreateKnowledgeFromFile(ctx, kbID, path, nil /*metadata*/, nil /*enableMultimodel*/, opts.Name, uploadChannel)
|
k, err := svc.CreateKnowledgeFromFile(ctx, kbID, path, nil /*metadata*/, nil /*enableMultimodel*/, opts.Name, uploadChannel)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "upload %s", path)
|
return cmdutil.WrapHTTP(err, "upload %s", path)
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.JSONOut {
|
if opts.JSONOut {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// Package doctor implements `weknora doctor` — 4-item self-check (spec §1.2).
|
// Package doctor implements `weknora doctor` — 4-item self-check (spec §1.2).
|
||||||
//
|
//
|
||||||
// Status semantics (4-tier, from larksuite/cli's pass/fail/warn/skip set):
|
// Status semantics (4-tier):
|
||||||
//
|
//
|
||||||
// ok — passed
|
// ok — passed
|
||||||
// warn — soft problem; non-blocking (e.g. server minor older than CLI,
|
// warn — soft problem; non-blocking (e.g. server minor older than CLI,
|
||||||
@@ -39,7 +39,6 @@ import (
|
|||||||
sdk "github.com/Tencent/WeKnora/client"
|
sdk "github.com/Tencent/WeKnora/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Options captures the CLI flags for `weknora doctor`.
|
|
||||||
type Options struct {
|
type Options struct {
|
||||||
NoCache bool
|
NoCache bool
|
||||||
Offline bool
|
Offline bool
|
||||||
@@ -99,6 +98,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
|||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
Use: "doctor",
|
Use: "doctor",
|
||||||
Short: "Run 4 self-checks: base URL, auth, server version, credential storage",
|
Short: "Run 4 self-checks: base URL, auth, server version, credential storage",
|
||||||
|
Args: cobra.NoArgs,
|
||||||
RunE: func(c *cobra.Command, _ []string) error {
|
RunE: func(c *cobra.Command, _ []string) error {
|
||||||
svc, err := buildServices(f)
|
svc, err := buildServices(f)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -107,10 +107,10 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
|||||||
cliVer, _, _ := build.Info()
|
cliVer, _, _ := build.Info()
|
||||||
r := runChecks(c.Context(), opts, svc, cliVer)
|
r := runChecks(c.Context(), opts, svc, cliVer)
|
||||||
emit(opts, r)
|
emit(opts, r)
|
||||||
// v0.2 exit-code policy: fail → exit 1 (gh / kubectl convention);
|
// v0.2 exit-code policy: fail → exit 1; warn / ok / skip → exit 0.
|
||||||
// warn / ok / skip → exit 0. SilentError suppresses both the human
|
// SilentError suppresses both the human "error: ..." line and the
|
||||||
// "error: ..." line and the error envelope printer, so the data
|
// error envelope printer, so the data envelope already written by
|
||||||
// envelope already written by emit() is the only stdout content.
|
// emit() is the only stdout content.
|
||||||
if r.Summary.Failed > 0 {
|
if r.Summary.Failed > 0 {
|
||||||
return cmdutil.SilentError
|
return cmdutil.SilentError
|
||||||
}
|
}
|
||||||
@@ -356,9 +356,9 @@ func emit(opts *Options, r Result) {
|
|||||||
|
|
||||||
// marker returns the human-mode prefix glyph for a check status.
|
// marker returns the human-mode prefix glyph for a check status.
|
||||||
//
|
//
|
||||||
// Glyphs follow gh / kubectl convention. Agent / JSON consumers read the
|
// Agent / JSON consumers read the stable status string from
|
||||||
// stable status string from data.checks[].status; the glyphs are presentation-
|
// data.checks[].status; the glyphs are presentation-only and never appear
|
||||||
// only and never appear in --json output.
|
// in --json output.
|
||||||
func marker(s Status) string {
|
func marker(s Status) string {
|
||||||
switch s {
|
switch s {
|
||||||
case StatusFail:
|
case StatusFail:
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import (
|
|||||||
sdk "github.com/Tencent/WeKnora/client"
|
sdk "github.com/Tencent/WeKnora/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CreateOptions captures `weknora kb create` flags.
|
|
||||||
type CreateOptions struct {
|
type CreateOptions struct {
|
||||||
Name string
|
Name string
|
||||||
Description string
|
Description string
|
||||||
@@ -78,7 +77,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, svc CreateService) erro
|
|||||||
|
|
||||||
created, err := svc.CreateKnowledgeBase(ctx, req)
|
created, err := svc.CreateKnowledgeBase(ctx, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "create knowledge base")
|
return cmdutil.WrapHTTP(err, "create knowledge base")
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.JSONOut {
|
if opts.JSONOut {
|
||||||
|
|||||||
@@ -13,10 +13,8 @@ import (
|
|||||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DeleteOptions captures `weknora kb delete` flags. Yes is sourced from the
|
|
||||||
// global -y/--yes persistent flag (gh-style; see cli/cmd/root.go addGlobalFlags).
|
|
||||||
type DeleteOptions struct {
|
type DeleteOptions struct {
|
||||||
Yes bool
|
Yes bool // sourced from the global -y/--yes persistent flag (see cli/cmd/root.go addGlobalFlags)
|
||||||
JSONOut bool
|
JSONOut bool
|
||||||
DryRun bool
|
DryRun bool
|
||||||
}
|
}
|
||||||
@@ -33,10 +31,9 @@ type deleteResult struct {
|
|||||||
Deleted bool `json:"deleted"`
|
Deleted bool `json:"deleted"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCmdDelete builds `weknora kb delete`. Mirrors `gh repo delete --yes`
|
// NewCmdDelete builds `weknora kb delete`. The global -y/--yes persistent
|
||||||
// (https://cli.github.com/manual/gh_repo_delete) on the confirmation
|
// flag is the single skip-prompt switch for the destructive-write
|
||||||
// pattern — the global -y/--yes persistent flag is the single skip-prompt
|
// confirmation pattern.
|
||||||
// switch.
|
|
||||||
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &DeleteOptions{}
|
opts := &DeleteOptions{}
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
@@ -85,7 +82,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, svc DeleteService, p pr
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err := svc.DeleteKnowledgeBase(ctx, id); err != nil {
|
if err := svc.DeleteKnowledgeBase(ctx, id); err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "delete knowledge base %s", id)
|
return cmdutil.WrapHTTP(err, "delete knowledge base %s", id)
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.JSONOut {
|
if opts.JSONOut {
|
||||||
|
|||||||
@@ -69,8 +69,8 @@ func TestDelete_NotFound(t *testing.T) {
|
|||||||
|
|
||||||
func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||||
// SetForTest uses bytes.Buffer for Out — IsStdoutTTY() = false. Without
|
// SetForTest uses bytes.Buffer for Out — IsStdoutTTY() = false. Without
|
||||||
// -y/--yes, exit-10 protocol fires (lark-cli skill protocol; AGENTS.md):
|
// -y/--yes, exit-10 protocol fires (see AGENTS.md): the CLI must NOT
|
||||||
// the CLI must NOT silently proceed in scripted contexts.
|
// silently proceed in scripted contexts.
|
||||||
iostreams.SetForTest(t)
|
iostreams.SetForTest(t)
|
||||||
svc := &fakeDeleteSvc{}
|
svc := &fakeDeleteSvc{}
|
||||||
p := &confirmPrompter{}
|
p := &confirmPrompter{}
|
||||||
@@ -82,7 +82,7 @@ func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
|||||||
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, typed.Code)
|
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, typed.Code)
|
||||||
assert.False(t, svc.called, "non-TTY without -y must not call DeleteKnowledgeBase")
|
assert.False(t, svc.called, "non-TTY without -y must not call DeleteKnowledgeBase")
|
||||||
assert.False(t, p.asked, "non-TTY ⇒ Confirm is never invoked")
|
assert.False(t, p.asked, "non-TTY ⇒ Confirm is never invoked")
|
||||||
assert.Equal(t, 10, cmdutil.ExitCode(err), "exit code 10 per lark-cli skill protocol")
|
assert.Equal(t, 10, cmdutil.ExitCode(err), "exit code 10 per destructive-write protocol")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDelete_JSONOutput(t *testing.T) {
|
func TestDelete_JSONOutput(t *testing.T) {
|
||||||
|
|||||||
+8
-10
@@ -13,26 +13,24 @@ import (
|
|||||||
sdk "github.com/Tencent/WeKnora/client"
|
sdk "github.com/Tencent/WeKnora/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// EditOptions captures `weknora kb edit` flags. 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 user passed are sent. The
|
|
||||||
// server PUT semantics are "replace everything in the request"; if we
|
|
||||||
// always sent both, an `--name` invocation would silently clear the
|
|
||||||
// description.
|
|
||||||
type EditOptions struct {
|
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
|
||||||
|
// 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.
|
||||||
Name *string
|
Name *string
|
||||||
Description *string
|
Description *string
|
||||||
JSONOut bool
|
JSONOut bool
|
||||||
DryRun bool
|
DryRun bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// EditService is the narrow SDK surface this command depends on.
|
|
||||||
type EditService interface {
|
type EditService interface {
|
||||||
UpdateKnowledgeBase(ctx context.Context, id string, req *sdk.UpdateKnowledgeBaseRequest) (*sdk.KnowledgeBase, error)
|
UpdateKnowledgeBase(ctx context.Context, id string, req *sdk.UpdateKnowledgeBaseRequest) (*sdk.KnowledgeBase, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCmdEdit builds `weknora kb edit <id>`. Mirrors `gh repo edit`. At
|
// NewCmdEdit builds `weknora kb edit <id>`. At least one of --name /
|
||||||
// least one of --name / --description must be provided.
|
// --description must be provided.
|
||||||
func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &EditOptions{}
|
opts := &EditOptions{}
|
||||||
var name, desc string
|
var name, desc string
|
||||||
@@ -89,7 +87,7 @@ func runEdit(ctx context.Context, opts *EditOptions, svc EditService, id string)
|
|||||||
|
|
||||||
updated, err := svc.UpdateKnowledgeBase(ctx, id, req)
|
updated, err := svc.UpdateKnowledgeBase(ctx, id, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "edit knowledge base %s", id)
|
return cmdutil.WrapHTTP(err, "edit knowledge base %s", id)
|
||||||
}
|
}
|
||||||
if opts.JSONOut {
|
if opts.JSONOut {
|
||||||
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(updated, &format.Meta{KBID: id}, risk))
|
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(updated, &format.Meta{KBID: id}, risk))
|
||||||
|
|||||||
+6
-8
@@ -14,14 +14,12 @@ import (
|
|||||||
sdk "github.com/Tencent/WeKnora/client"
|
sdk "github.com/Tencent/WeKnora/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// EmptyOptions captures `weknora kb empty` flag state.
|
|
||||||
type EmptyOptions struct {
|
type EmptyOptions struct {
|
||||||
Yes bool
|
Yes bool
|
||||||
JSONOut bool
|
JSONOut bool
|
||||||
DryRun bool
|
DryRun bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// EmptyService is the narrow SDK surface this command depends on.
|
|
||||||
type EmptyService interface {
|
type EmptyService interface {
|
||||||
ClearKnowledgeBaseContents(ctx context.Context, id string) (*sdk.ClearKnowledgeBaseContentsResponse, error)
|
ClearKnowledgeBaseContents(ctx context.Context, id string) (*sdk.ClearKnowledgeBaseContentsResponse, error)
|
||||||
}
|
}
|
||||||
@@ -32,10 +30,10 @@ type emptyResult struct {
|
|||||||
DeletedCount int `json:"deleted_count"`
|
DeletedCount int `json:"deleted_count"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCmdEmpty builds `weknora kb empty <id>`. Wipes every
|
// NewCmdEmpty builds `weknora kb empty <id>`. Wipes every document inside
|
||||||
// document inside the knowledge base; the KB itself is preserved. The
|
// the knowledge base; the KB itself is preserved. The server runs the
|
||||||
// server runs the delete asynchronously and reports the count of documents
|
// delete asynchronously and reports the count of documents that were
|
||||||
// that were enqueued for removal.
|
// enqueued for removal.
|
||||||
func NewCmdEmpty(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdEmpty(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &EmptyOptions{}
|
opts := &EmptyOptions{}
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
@@ -46,7 +44,7 @@ KB record (its name, description, and config) intact. The delete is async;
|
|||||||
the server reports the count of items enqueued for removal.
|
the server reports the count of items enqueued for removal.
|
||||||
|
|
||||||
Prompts for confirmation by default; pass -y/--yes to skip in agent / CI /
|
Prompts for confirmation by default; pass -y/--yes to skip in agent / CI /
|
||||||
piped contexts. Without -y the CLI exits 10 (lark-cli skill protocol).`,
|
piped contexts. Without -y the CLI exits 10 in non-interactive mode.`,
|
||||||
Example: ` weknora kb empty kb_abc # interactive confirm
|
Example: ` weknora kb empty kb_abc # interactive confirm
|
||||||
weknora kb empty kb_abc -y --json # agent-friendly`,
|
weknora kb empty kb_abc -y --json # agent-friendly`,
|
||||||
Args: cobra.ExactArgs(1),
|
Args: cobra.ExactArgs(1),
|
||||||
@@ -81,7 +79,7 @@ func runEmpty(ctx context.Context, opts *EmptyOptions, svc EmptyService, p promp
|
|||||||
|
|
||||||
resp, err := svc.ClearKnowledgeBaseContents(ctx, id)
|
resp, err := svc.ClearKnowledgeBaseContents(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "empty knowledge base %s", id)
|
return cmdutil.WrapHTTP(err, "empty knowledge base %s", id)
|
||||||
}
|
}
|
||||||
deleted := 0
|
deleted := 0
|
||||||
if resp != nil {
|
if resp != nil {
|
||||||
|
|||||||
+2
-3
@@ -1,7 +1,6 @@
|
|||||||
// Package kb holds the `weknora kb` command tree: list / view / create /
|
// Package kb holds the `weknora kb` command tree: list / view / create /
|
||||||
// edit / delete / pin / unpin / clear-contents. `view` is the primary read
|
// edit / delete / pin / unpin / empty. Verb set follows common CRUD
|
||||||
// verb (gh repo view convention); `get` survives as a cobra alias on the
|
// vocabulary (list/view/create/edit/delete) plus pin/unpin and empty.
|
||||||
// view subcommand for v0.0/v0.1 callers.
|
|
||||||
package kb
|
package kb
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
+1
-2
@@ -17,7 +17,6 @@ import (
|
|||||||
sdk "github.com/Tencent/WeKnora/client"
|
sdk "github.com/Tencent/WeKnora/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListOptions captures `weknora kb list` flags.
|
|
||||||
type ListOptions struct {
|
type ListOptions struct {
|
||||||
JSONOut bool
|
JSONOut bool
|
||||||
}
|
}
|
||||||
@@ -55,7 +54,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
|||||||
func runList(ctx context.Context, opts *ListOptions, svc ListService) error {
|
func runList(ctx context.Context, opts *ListOptions, svc ListService) error {
|
||||||
items, err := svc.ListKnowledgeBases(ctx)
|
items, err := svc.ListKnowledgeBases(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list knowledge bases")
|
return cmdutil.WrapHTTP(err, "list knowledge bases")
|
||||||
}
|
}
|
||||||
if items == nil {
|
if items == nil {
|
||||||
items = []sdk.KnowledgeBase{} // ensure JSON [] not null
|
items = []sdk.KnowledgeBase{} // ensure JSON [] not null
|
||||||
|
|||||||
+2
-3
@@ -13,7 +13,6 @@ import (
|
|||||||
sdk "github.com/Tencent/WeKnora/client"
|
sdk "github.com/Tencent/WeKnora/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// PinOptions captures `weknora kb pin / unpin` flag state.
|
|
||||||
type PinOptions struct {
|
type PinOptions struct {
|
||||||
JSONOut bool
|
JSONOut bool
|
||||||
DryRun bool
|
DryRun bool
|
||||||
@@ -79,7 +78,7 @@ func runPin(ctx context.Context, opts *PinOptions, svc PinService, id string, wa
|
|||||||
|
|
||||||
current, err := svc.GetKnowledgeBase(ctx, id)
|
current, err := svc.GetKnowledgeBase(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "get knowledge base %s", id)
|
return cmdutil.WrapHTTP(err, "get knowledge base %s", id)
|
||||||
}
|
}
|
||||||
if current.IsPinned == want {
|
if current.IsPinned == want {
|
||||||
state := "pinned"
|
state := "pinned"
|
||||||
@@ -99,7 +98,7 @@ func runPin(ctx context.Context, opts *PinOptions, svc PinService, id string, wa
|
|||||||
|
|
||||||
updated, err := svc.TogglePinKnowledgeBase(ctx, id)
|
updated, err := svc.TogglePinKnowledgeBase(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "%s knowledge base %s", verb, id)
|
return cmdutil.WrapHTTP(err, "%s knowledge base %s", verb, id)
|
||||||
}
|
}
|
||||||
if opts.JSONOut {
|
if opts.JSONOut {
|
||||||
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(updated, &format.Meta{KBID: id}, risk))
|
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(updated, &format.Meta{KBID: id}, risk))
|
||||||
|
|||||||
+2
-5
@@ -14,7 +14,6 @@ import (
|
|||||||
sdk "github.com/Tencent/WeKnora/client"
|
sdk "github.com/Tencent/WeKnora/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ViewOptions captures `weknora kb view` flags.
|
|
||||||
type ViewOptions struct {
|
type ViewOptions struct {
|
||||||
JSONOut bool
|
JSONOut bool
|
||||||
}
|
}
|
||||||
@@ -24,9 +23,7 @@ type ViewService interface {
|
|||||||
GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error)
|
GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCmdView builds `weknora kb view <id>`. Mirrors `gh repo view`
|
// NewCmdView builds `weknora kb view <id>`.
|
||||||
// (https://cli.github.com/manual/gh_repo_view) — the established mainstream
|
|
||||||
// verb for single-resource reads.
|
|
||||||
func NewCmdView(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdView(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &ViewOptions{}
|
opts := &ViewOptions{}
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
@@ -49,7 +46,7 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
|
|||||||
func runView(ctx context.Context, opts *ViewOptions, svc ViewService, id string) error {
|
func runView(ctx context.Context, opts *ViewOptions, svc ViewService, id string) error {
|
||||||
kb, err := svc.GetKnowledgeBase(ctx, id)
|
kb, err := svc.GetKnowledgeBase(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "get knowledge base %q", id)
|
return cmdutil.WrapHTTP(err, "get knowledge base %q", id)
|
||||||
}
|
}
|
||||||
if opts.JSONOut {
|
if opts.JSONOut {
|
||||||
return format.WriteEnvelope(iostreams.IO.Out, format.Success(kb, nil))
|
return format.WriteEnvelope(iostreams.IO.Out, format.Success(kb, nil))
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
// 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
|
// directory to a knowledge base by writing .weknora/project.yaml. Always
|
||||||
// overwrites an existing link silently, mirroring `vercel link` /
|
// overwrites an existing link silently rather than refusing when one is
|
||||||
// `netlify link` / `kubectl apply` rather than `git init`'s
|
// already present. The cobra Long: text covers the user-facing modes
|
||||||
// refuse-if-exists posture. The cobra Long: text covers the user-facing
|
// (--kb / TTY / non-TTY).
|
||||||
// modes (--kb / TTY / non-TTY).
|
|
||||||
package linkcmd
|
package linkcmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -22,7 +21,6 @@ import (
|
|||||||
"github.com/Tencent/WeKnora/cli/internal/projectlink"
|
"github.com/Tencent/WeKnora/cli/internal/projectlink"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Options captures `weknora link` flags.
|
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Context string // --context: record a specific context instead of the active one
|
Context string // --context: record a specific context instead of the active one
|
||||||
KB string // --kb: KB UUID or name; empty triggers interactive prompt on TTY
|
KB string // --kb: KB UUID or name; empty triggers interactive prompt on TTY
|
||||||
@@ -164,7 +162,7 @@ func resolveKB(ctx context.Context, opts *Options, f *cmdutil.Factory) (string,
|
|||||||
func promptForKB(ctx context.Context, svc cmdutil.KBLister, f *cmdutil.Factory) (string, string, error) {
|
func promptForKB(ctx context.Context, svc cmdutil.KBLister, f *cmdutil.Factory) (string, string, error) {
|
||||||
kbs, err := svc.ListKnowledgeBases(ctx)
|
kbs, err := svc.ListKnowledgeBases(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", "", cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list knowledge bases")
|
return "", "", cmdutil.WrapHTTP(err, "list knowledge bases")
|
||||||
}
|
}
|
||||||
if len(kbs) == 0 {
|
if len(kbs) == 0 {
|
||||||
return "", "", cmdutil.NewError(cmdutil.CodeKBNotFound, "no knowledge bases visible to active context; create one first")
|
return "", "", cmdutil.NewError(cmdutil.CodeKBNotFound, "no knowledge bases visible to active context; create one first")
|
||||||
|
|||||||
+8
-7
@@ -144,9 +144,9 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`,
|
|||||||
SilenceUsage: true,
|
SilenceUsage: true,
|
||||||
SilenceErrors: true,
|
SilenceErrors: true,
|
||||||
// Version makes cobra auto-register a `--version` global flag that
|
// Version makes cobra auto-register a `--version` global flag that
|
||||||
// prints this string. Mainstream CLIs (gh / kubectl / aws / gcloud)
|
// prints this string. We accept both `--version` and a `version`
|
||||||
// all accept both `--version` and a `version` subcommand; the
|
// subcommand; the subcommand still owns the richer `--json` envelope
|
||||||
// subcommand still owns the richer `--json` envelope output.
|
// output.
|
||||||
Version: fmt.Sprintf("%s (commit %s, built %s)", v, commit, date),
|
Version: fmt.Sprintf("%s (commit %s, built %s)", v, commit, date),
|
||||||
PersistentPreRun: func(c *cobra.Command, args []string) {
|
PersistentPreRun: func(c *cobra.Command, args []string) {
|
||||||
// Propagate the global --context flag into the Factory for this
|
// Propagate the global --context flag into the Factory for this
|
||||||
@@ -161,8 +161,8 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`,
|
|||||||
addGlobalFlags(cmd)
|
addGlobalFlags(cmd)
|
||||||
cmd.SetHelpFunc(agentAwareHelpFunc(cmd.HelpFunc()))
|
cmd.SetHelpFunc(agentAwareHelpFunc(cmd.HelpFunc()))
|
||||||
// Wrap cobra's flag-parsing errors as FlagError so cmdutil.ExitCode maps
|
// Wrap cobra's flag-parsing errors as FlagError so cmdutil.ExitCode maps
|
||||||
// them to exit 2 (gh-style). "unknown command" errors are detected by
|
// them to exit 2. "unknown command" errors are detected by message prefix
|
||||||
// message prefix in Execute() since cobra emits them as plain errors.
|
// in Execute() since cobra emits them as plain errors.
|
||||||
cmd.SetFlagErrorFunc(func(c *cobra.Command, err error) error {
|
cmd.SetFlagErrorFunc(func(c *cobra.Command, err error) error {
|
||||||
return cmdutil.NewFlagError(err)
|
return cmdutil.NewFlagError(err)
|
||||||
})
|
})
|
||||||
@@ -193,8 +193,8 @@ func addGlobalFlags(cmd *cobra.Command) {
|
|||||||
|
|
||||||
// agentAwareHelpFunc wraps cobra's default help to append the AI agent guidance
|
// agentAwareHelpFunc wraps cobra's default help to append the AI agent guidance
|
||||||
// (Annotations[agent.AIAgentHelpKey]) only when an AI coding agent env var is
|
// (Annotations[agent.AIAgentHelpKey]) only when an AI coding agent env var is
|
||||||
// detected (CLAUDECODE / CURSOR_AGENT). Help-only render — no behavior switch.
|
// detected (CLAUDECODE / CURSOR_AGENT). Help-only render — no behavior switch
|
||||||
// Stripe pkg/cmd/templates.go pattern, but reduced from mode-switch (v0.2 ADR-3).
|
// (v0.2 ADR-3).
|
||||||
func agentAwareHelpFunc(orig func(*cobra.Command, []string)) func(*cobra.Command, []string) {
|
func agentAwareHelpFunc(orig func(*cobra.Command, []string)) func(*cobra.Command, []string) {
|
||||||
return func(c *cobra.Command, args []string) {
|
return func(c *cobra.Command, args []string) {
|
||||||
orig(c, args)
|
orig(c, args)
|
||||||
@@ -219,6 +219,7 @@ func newVersionCmd(f *cmdutil.Factory) *cobra.Command {
|
|||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
Use: "version",
|
Use: "version",
|
||||||
Short: "Show CLI build metadata",
|
Short: "Show CLI build metadata",
|
||||||
|
Args: cobra.NoArgs,
|
||||||
RunE: func(c *cobra.Command, args []string) error {
|
RunE: func(c *cobra.Command, args []string) error {
|
||||||
v, commit, date := build.Info()
|
v, commit, date := build.Info()
|
||||||
if jsonOut {
|
if jsonOut {
|
||||||
|
|||||||
+10
-11
@@ -14,7 +14,6 @@ import (
|
|||||||
sdk "github.com/Tencent/WeKnora/client"
|
sdk "github.com/Tencent/WeKnora/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ChunksOptions is the runtime configuration of a chunks search.
|
|
||||||
type ChunksOptions struct {
|
type ChunksOptions struct {
|
||||||
Query string
|
Query string
|
||||||
KB string // raw --kb (UUID or name)
|
KB string // raw --kb (UUID or name)
|
||||||
@@ -34,18 +33,19 @@ type ChunksService interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewCmdChunks builds `weknora search chunks "<query>" --kb <id-or-name>`.
|
// NewCmdChunks builds `weknora search chunks "<query>" --kb <id-or-name>`.
|
||||||
// Mirrors gh `search code`'s "subject as positional" shape (the previous
|
// Uses a positional query argument with the KB selected via flag.
|
||||||
// top-level `weknora search` is its legacy alias — see search.go).
|
|
||||||
//
|
//
|
||||||
// The `--kb` flag accepts either a KB UUID (passed through) or a name
|
// The `--kb` flag accepts either a KB UUID (passed through unchanged) or a
|
||||||
// (resolved via ListKnowledgeBases). Mirrors gcloud `--project`'s
|
// name (resolved via ListKnowledgeBases — see cmdutil.ResolveKBFlag).
|
||||||
// id-or-name auto-detection.
|
|
||||||
func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &ChunksOptions{}
|
opts := &ChunksOptions{}
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
Use: `chunks "<query>"`,
|
Use: `chunks "<query>"`,
|
||||||
Short: "Hybrid (vector + keyword) chunk retrieval against a knowledge base",
|
Short: "Hybrid (vector + keyword) chunk retrieval against a knowledge base",
|
||||||
Args: cobra.ExactArgs(1),
|
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`,
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
RunE: func(c *cobra.Command, args []string) error {
|
RunE: func(c *cobra.Command, args []string) error {
|
||||||
opts.Query = strings.TrimSpace(args[0])
|
opts.Query = strings.TrimSpace(args[0])
|
||||||
if err := opts.validate(); err != nil {
|
if err := opts.validate(); err != nil {
|
||||||
@@ -110,13 +110,12 @@ func runChunks(ctx context.Context, opts *ChunksOptions, svc ChunksService) erro
|
|||||||
}
|
}
|
||||||
results, err := svc.HybridSearch(ctx, opts.KBID, params)
|
results, err := svc.HybridSearch(ctx, opts.KBID, params)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "hybrid search")
|
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
|
// service appends parent / nearby / relation chunks as context
|
||||||
// enrichment, so the wire response can exceed Limit. CLIs like gh /
|
// enrichment, so the wire response can exceed Limit. Treat --limit as
|
||||||
// kubectl / aws treat their `--limit`-style flag as a hard return-count
|
// a hard return-count cap by trimming on the client. Recall isn't
|
||||||
// cap; honor that contract by trimming on the client. Recall isn't
|
|
||||||
// affected because the server's internal retrieval pool is already
|
// affected because the server's internal retrieval pool is already
|
||||||
// max(MatchCount*5, 50).
|
// max(MatchCount*5, 50).
|
||||||
if opts.Limit > 0 && len(results) > opts.Limit {
|
if opts.Limit > 0 && len(results) > opts.Limit {
|
||||||
|
|||||||
@@ -46,8 +46,7 @@ func TestRunSearch_HumanOutput(t *testing.T) {
|
|||||||
|
|
||||||
// JSON envelope must surface match_type so machine consumers / agents can
|
// JSON envelope must surface match_type so machine consumers / agents can
|
||||||
// reason about retrieval channels without re-implementing the wire format.
|
// 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.)
|
||||||
// matching gh / kubectl / Algolia / Vespa terse-default conventions.)
|
|
||||||
func TestRunSearch_JSONIncludesMatchType(t *testing.T) {
|
func TestRunSearch_JSONIncludesMatchType(t *testing.T) {
|
||||||
out, _ := iostreams.SetForTest(t)
|
out, _ := iostreams.SetForTest(t)
|
||||||
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
|
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
|
||||||
@@ -75,7 +74,7 @@ func TestRunSearch_EmptyResults(t *testing.T) {
|
|||||||
|
|
||||||
// Server returns primary matches plus parent/related/nearby enrichment chunks,
|
// Server returns primary matches plus parent/related/nearby enrichment chunks,
|
||||||
// so the wire response can exceed Limit. CLI must trim to honor the user's
|
// so the wire response can exceed Limit. CLI must trim to honor the user's
|
||||||
// hard-limit contract (gh / kubectl / aws idiom).
|
// hard-limit contract.
|
||||||
func TestRunSearch_LimitHardCap(t *testing.T) {
|
func TestRunSearch_LimitHardCap(t *testing.T) {
|
||||||
out, _ := iostreams.SetForTest(t)
|
out, _ := iostreams.SetForTest(t)
|
||||||
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
|
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
|
||||||
|
|||||||
+5
-17
@@ -22,7 +22,6 @@ import (
|
|||||||
// 1000 (per the doc/list bound this branch already added).
|
// 1000 (per the doc/list bound this branch already added).
|
||||||
const docsPageSize = 200
|
const docsPageSize = 200
|
||||||
|
|
||||||
// DocsSearchOptions captures `weknora search docs` flag state.
|
|
||||||
type DocsSearchOptions struct {
|
type DocsSearchOptions struct {
|
||||||
Query string
|
Query string
|
||||||
KB string // raw --kb (UUID or name)
|
KB string // raw --kb (UUID or name)
|
||||||
@@ -47,7 +46,9 @@ func NewCmdDocs(f *cmdutil.Factory) *cobra.Command {
|
|||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
Use: `docs "<query>"`,
|
Use: `docs "<query>"`,
|
||||||
Short: "Find documents in a knowledge base by name (client-side substring match)",
|
Short: "Find documents in a knowledge base by name (client-side substring match)",
|
||||||
Args: cobra.ExactArgs(1),
|
Example: ` weknora search docs "Q3 forecast" --kb finance
|
||||||
|
weknora search docs "spec" --kb engineering --limit 5`,
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
RunE: func(c *cobra.Command, args []string) error {
|
RunE: func(c *cobra.Command, args []string) error {
|
||||||
opts.Query = strings.TrimSpace(args[0])
|
opts.Query = strings.TrimSpace(args[0])
|
||||||
if opts.Query == "" {
|
if opts.Query == "" {
|
||||||
@@ -82,7 +83,7 @@ func runDocsSearch(ctx context.Context, opts *DocsSearchOptions, svc DocsSearchS
|
|||||||
for page := 1; ; page++ {
|
for page := 1; ; page++ {
|
||||||
items, total, err := svc.ListKnowledge(ctx, opts.KBID, page, docsPageSize, "")
|
items, total, err := svc.ListKnowledge(ctx, opts.KBID, page, docsPageSize, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list documents")
|
return cmdutil.WrapHTTP(err, "list documents")
|
||||||
}
|
}
|
||||||
for _, k := range items {
|
for _, k := range items {
|
||||||
if matchKnowledge(k, needle) {
|
if matchKnowledge(k, needle) {
|
||||||
@@ -109,7 +110,7 @@ done:
|
|||||||
tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0)
|
tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0)
|
||||||
fmt.Fprintln(tw, "ID\tFILE\tTYPE\tUPDATED")
|
fmt.Fprintln(tw, "ID\tFILE\tTYPE\tUPDATED")
|
||||||
for _, k := range matches {
|
for _, k := range matches {
|
||||||
name := text.Truncate(50, displayDocName(k))
|
name := text.Truncate(50, text.KnowledgeDisplayName(k.FileName, k.Title, k.ID))
|
||||||
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", k.ID, name, k.FileType, k.UpdatedAt.Format("2006-01-02"))
|
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", k.ID, name, k.FileType, k.UpdatedAt.Format("2006-01-02"))
|
||||||
}
|
}
|
||||||
return tw.Flush()
|
return tw.Flush()
|
||||||
@@ -121,19 +122,6 @@ func matchKnowledge(k sdk.Knowledge, needle string) bool {
|
|||||||
return text.ContainsFold(needle, k.Title, k.FileName)
|
return text.ContainsFold(needle, k.Title, k.FileName)
|
||||||
}
|
}
|
||||||
|
|
||||||
// displayDocName picks a human-friendly name. Order matches `weknora doc
|
|
||||||
// list` (FileName for uploads → Title for URL/text entries → ID fallback)
|
|
||||||
// so a Knowledge renders the same in both commands.
|
|
||||||
func displayDocName(k sdk.Knowledge) string {
|
|
||||||
if k.FileName != "" {
|
|
||||||
return k.FileName
|
|
||||||
}
|
|
||||||
if k.Title != "" {
|
|
||||||
return k.Title
|
|
||||||
}
|
|
||||||
return k.ID
|
|
||||||
}
|
|
||||||
|
|
||||||
// sortKnowledgeByRecency sorts in place by UpdatedAt desc.
|
// sortKnowledgeByRecency sorts in place by UpdatedAt desc.
|
||||||
func sortKnowledgeByRecency(items []sdk.Knowledge) {
|
func sortKnowledgeByRecency(items []sdk.Knowledge) {
|
||||||
sort.Slice(items, func(i, j int) bool {
|
sort.Slice(items, func(i, j int) bool {
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ func TestDocsSearch_PaginatesUntilTotal(t *testing.T) {
|
|||||||
assert.Equal(t, []int{1, 2}, svc.calls, "must page past the first batch when no match on page 1")
|
assert.Equal(t, []int{1, 2}, svc.calls, "must page past the first batch when no match on page 1")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDocsSearch_StopsAtTopK(t *testing.T) {
|
func TestDocsSearch_StopsAtLimit(t *testing.T) {
|
||||||
_, _ = iostreams.SetForTest(t)
|
_, _ = iostreams.SetForTest(t)
|
||||||
page1 := make([]sdk.Knowledge, 50)
|
page1 := make([]sdk.Knowledge, 50)
|
||||||
for i := range page1 {
|
for i := range page1 {
|
||||||
@@ -86,7 +86,7 @@ func TestDocsSearch_StopsAtTopK(t *testing.T) {
|
|||||||
}
|
}
|
||||||
svc := &fakeDocsSearchSvc{pages: map[int][]sdk.Knowledge{1: page1}, total: 1000}
|
svc := &fakeDocsSearchSvc{pages: map[int][]sdk.Knowledge{1: page1}, total: 1000}
|
||||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3}, svc))
|
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3}, svc))
|
||||||
// Must not request page 2 because top-k was hit mid-page.
|
// Must not request page 2 because limit was hit mid-page.
|
||||||
assert.Equal(t, []int{1}, svc.calls)
|
assert.Equal(t, []int{1}, svc.calls)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ import (
|
|||||||
sdk "github.com/Tencent/WeKnora/client"
|
sdk "github.com/Tencent/WeKnora/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// KBSearchOptions captures `weknora search kb` flag state.
|
|
||||||
type KBSearchOptions struct {
|
type KBSearchOptions struct {
|
||||||
Query string
|
Query string
|
||||||
Limit int
|
Limit int
|
||||||
@@ -33,14 +32,16 @@ type KBSearchService interface {
|
|||||||
|
|
||||||
// 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.
|
// match across KB names and descriptions visible to the active context.
|
||||||
// Mirrors gh `search repos`. Results are sorted by name length (shortest
|
// Results are sorted by name length (shortest first; usually the closest
|
||||||
// first; usually the closest hit) for deterministic output.
|
// hit) for deterministic output.
|
||||||
func NewCmdKB(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdKB(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &KBSearchOptions{}
|
opts := &KBSearchOptions{}
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
Use: `kb "<query>"`,
|
Use: `kb "<query>"`,
|
||||||
Short: "Find knowledge bases by name or description (client-side substring match)",
|
Short: "Find knowledge bases by name or description (client-side substring match)",
|
||||||
Args: cobra.ExactArgs(1),
|
Example: ` weknora search kb "marketing"
|
||||||
|
weknora search kb "team" --limit 5 --json`,
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
RunE: func(c *cobra.Command, args []string) error {
|
RunE: func(c *cobra.Command, args []string) error {
|
||||||
opts.Query = strings.TrimSpace(args[0])
|
opts.Query = strings.TrimSpace(args[0])
|
||||||
if opts.Query == "" {
|
if opts.Query == "" {
|
||||||
@@ -62,7 +63,7 @@ func NewCmdKB(f *cmdutil.Factory) *cobra.Command {
|
|||||||
func runKBSearch(ctx context.Context, opts *KBSearchOptions, svc KBSearchService) error {
|
func runKBSearch(ctx context.Context, opts *KBSearchOptions, svc KBSearchService) error {
|
||||||
items, err := svc.ListKnowledgeBases(ctx)
|
items, err := svc.ListKnowledgeBases(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list knowledge bases")
|
return cmdutil.WrapHTTP(err, "list knowledge bases")
|
||||||
}
|
}
|
||||||
matches := filterKBs(items, opts.Query)
|
matches := filterKBs(items, opts.Query)
|
||||||
if opts.Limit > 0 && len(matches) > opts.Limit {
|
if opts.Limit > 0 && len(matches) > opts.Limit {
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ func TestKBSearch_SortByNameLength(t *testing.T) {
|
|||||||
assert.Less(t, iMid, iLong)
|
assert.Less(t, iMid, iLong)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestKBSearch_TopKHardCap(t *testing.T) {
|
func TestKBSearch_LimitHardCap(t *testing.T) {
|
||||||
out, _ := iostreams.SetForTest(t)
|
out, _ := iostreams.SetForTest(t)
|
||||||
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{
|
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{
|
||||||
{ID: "a", Name: "match-a"}, {ID: "b", Name: "match-b"},
|
{ID: "a", Name: "match-a"}, {ID: "b", Name: "match-b"},
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
// Package search implements the `weknora search` command tree:
|
// Package search implements the `weknora search` command tree:
|
||||||
// chunks / kb / docs / sessions. Verb-noun shape borrowed from
|
// chunks / kb / docs / sessions.
|
||||||
// gh search (gh search repos / code / commits / issues / prs).
|
|
||||||
package search
|
package search
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -11,12 +10,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// NewCmdSearch builds the `weknora search` parent. Pure dispatcher to the
|
// NewCmdSearch builds the `weknora search` parent. Pure dispatcher to the
|
||||||
// four subcommands; no positional/legacy form.
|
// four subcommands — users must pick a verb (chunks / kb / docs / sessions).
|
||||||
func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
Use: "search",
|
Use: "search",
|
||||||
Short: "Search across chunks, knowledge bases, documents, or sessions",
|
Short: "Search across chunks, knowledge bases, documents, or sessions",
|
||||||
Long: `Verb-noun search tree (gh search idiom):
|
Long: `Verb-noun search tree:
|
||||||
|
|
||||||
search chunks "<q>" --kb X hybrid retrieval (RAG search)
|
search chunks "<q>" --kb X hybrid retrieval (RAG search)
|
||||||
search kb "<q>" find KBs by name / description
|
search kb "<q>" find KBs by name / description
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ import (
|
|||||||
|
|
||||||
const sessionsPageSize = 200
|
const sessionsPageSize = 200
|
||||||
|
|
||||||
// SessionsSearchOptions captures `weknora search sessions` flag state.
|
|
||||||
type SessionsSearchOptions struct {
|
type SessionsSearchOptions struct {
|
||||||
Query string
|
Query string
|
||||||
Limit int
|
Limit int
|
||||||
@@ -40,7 +39,9 @@ func NewCmdSessions(f *cmdutil.Factory) *cobra.Command {
|
|||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
Use: `sessions "<query>"`,
|
Use: `sessions "<query>"`,
|
||||||
Short: "Find chat sessions by title or description (client-side substring match)",
|
Short: "Find chat sessions by title or description (client-side substring match)",
|
||||||
Args: cobra.ExactArgs(1),
|
Example: ` weknora search sessions "onboarding"
|
||||||
|
weknora search sessions "Q3 review" --limit 3 --json`,
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
RunE: func(c *cobra.Command, args []string) error {
|
RunE: func(c *cobra.Command, args []string) error {
|
||||||
opts.Query = strings.TrimSpace(args[0])
|
opts.Query = strings.TrimSpace(args[0])
|
||||||
if opts.Query == "" {
|
if opts.Query == "" {
|
||||||
@@ -66,7 +67,7 @@ func runSessionsSearch(ctx context.Context, opts *SessionsSearchOptions, svc Ses
|
|||||||
for page := 1; ; page++ {
|
for page := 1; ; page++ {
|
||||||
items, total, err := svc.GetSessionsByTenant(ctx, page, sessionsPageSize)
|
items, total, err := svc.GetSessionsByTenant(ctx, page, sessionsPageSize)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list sessions")
|
return cmdutil.WrapHTTP(err, "list sessions")
|
||||||
}
|
}
|
||||||
for _, s := range items {
|
for _, s := range items {
|
||||||
if matchSession(s, needle) {
|
if matchSession(s, needle) {
|
||||||
|
|||||||
@@ -13,10 +13,8 @@ import (
|
|||||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DeleteOptions captures `weknora session delete` flag state. Yes is
|
|
||||||
// sourced from the global -y/--yes persistent flag (gh-style).
|
|
||||||
type DeleteOptions struct {
|
type DeleteOptions struct {
|
||||||
Yes bool
|
Yes bool // sourced from the global -y/--yes persistent flag
|
||||||
JSONOut bool
|
JSONOut bool
|
||||||
DryRun bool
|
DryRun bool
|
||||||
}
|
}
|
||||||
@@ -32,9 +30,8 @@ type deleteResult struct {
|
|||||||
Deleted bool `json:"deleted"`
|
Deleted bool `json:"deleted"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCmdDelete builds `weknora session delete`. Mirrors `gh issue delete`:
|
// NewCmdDelete builds `weknora session delete`. Destructive write gated
|
||||||
// destructive write gated by -y/--yes (exit-10 protocol in scripted /
|
// by -y/--yes (exit-10 protocol in scripted / --json invocations).
|
||||||
// --json invocations).
|
|
||||||
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &DeleteOptions{}
|
opts := &DeleteOptions{}
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
@@ -83,7 +80,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, svc DeleteService, p pr
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err := svc.DeleteSession(ctx, id); err != nil {
|
if err := svc.DeleteSession(ctx, id); err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "delete session %s", id)
|
return cmdutil.WrapHTTP(err, "delete session %s", id)
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.JSONOut {
|
if opts.JSONOut {
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ const (
|
|||||||
maxPageSize = 1000
|
maxPageSize = 1000
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListOptions captures `weknora session list` flags.
|
|
||||||
type ListOptions struct {
|
type ListOptions struct {
|
||||||
Page int
|
Page int
|
||||||
PageSize int
|
PageSize int
|
||||||
@@ -40,8 +39,7 @@ type listResult struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewCmdList builds `weknora session list`. Paginated; defaults to page=1
|
// NewCmdList builds `weknora session list`. Paginated; defaults to page=1
|
||||||
// page_size=30. Mirrors `gh issue list` shape (no cursor — server is
|
// page_size=30. No cursor — server is page-based today.
|
||||||
// page-based today).
|
|
||||||
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &ListOptions{Page: defaultPage, PageSize: defaultPageSize}
|
opts := &ListOptions{Page: defaultPage, PageSize: defaultPageSize}
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
@@ -79,7 +77,7 @@ func runList(ctx context.Context, opts *ListOptions, svc ListService) error {
|
|||||||
|
|
||||||
items, total, err := svc.GetSessionsByTenant(ctx, opts.Page, opts.PageSize)
|
items, total, err := svc.GetSessionsByTenant(ctx, opts.Page, opts.PageSize)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list sessions")
|
return cmdutil.WrapHTTP(err, "list sessions")
|
||||||
}
|
}
|
||||||
if items == nil {
|
if items == nil {
|
||||||
items = []sdk.Session{} // JSON [] not null
|
items = []sdk.Session{} // JSON [] not null
|
||||||
@@ -107,9 +105,9 @@ func runList(ctx context.Context, opts *ListOptions, svc ListService) error {
|
|||||||
return tw.Flush()
|
return tw.Flush()
|
||||||
}
|
}
|
||||||
|
|
||||||
// fuzzyTime renders a server-provided timestamp string in `gh`-style "2d
|
// fuzzyTime renders a server-provided timestamp string in "2d ago" form.
|
||||||
// ago" form. Returns the raw input if parsing fails — better to surface
|
// Returns the raw input if parsing fails — better to surface the unknown
|
||||||
// the unknown format than to silently render "-".
|
// format than to silently render "-".
|
||||||
func fuzzyTime(now time.Time, ts string) string {
|
func fuzzyTime(now time.Time, ts string) string {
|
||||||
if ts == "" {
|
if ts == "" {
|
||||||
return "-"
|
return "-"
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// Package sessioncmd holds `weknora session` command tree (list / view /
|
// Package sessioncmd holds `weknora session` command tree (list / view /
|
||||||
// delete). Mirrors `gh issue list/view/delete` for chat history.
|
// delete) for chat history.
|
||||||
//
|
//
|
||||||
// Package name `sessioncmd` (not `session`) so callers can `import sdk
|
// Package name `sessioncmd` (not `session`) so callers can `import sdk
|
||||||
// "github.com/Tencent/WeKnora/client"` and use `sdk.Session` without
|
// "github.com/Tencent/WeKnora/client"` and use `sdk.Session` without
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import (
|
|||||||
sdk "github.com/Tencent/WeKnora/client"
|
sdk "github.com/Tencent/WeKnora/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ViewOptions captures `weknora session view` flags.
|
|
||||||
type ViewOptions struct {
|
type ViewOptions struct {
|
||||||
JSONOut bool
|
JSONOut bool
|
||||||
}
|
}
|
||||||
@@ -24,10 +23,10 @@ type ViewService interface {
|
|||||||
GetSession(ctx context.Context, id string) (*sdk.Session, error)
|
GetSession(ctx context.Context, id string) (*sdk.Session, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCmdView builds `weknora session view <id>`. Mirrors `gh issue view`.
|
// NewCmdView builds `weknora session view <id>`. The server endpoint
|
||||||
// The server endpoint returns metadata only (title/description/timestamps);
|
// returns metadata only (title/description/timestamps); message content
|
||||||
// message content lives under a separate session_messages endpoint that the
|
// lives under a separate session_messages endpoint that the SDK doesn't
|
||||||
// SDK doesn't currently wrap, which is why there's no --full flag.
|
// currently wrap, which is why there's no --full flag.
|
||||||
func NewCmdView(f *cmdutil.Factory) *cobra.Command {
|
func NewCmdView(f *cmdutil.Factory) *cobra.Command {
|
||||||
opts := &ViewOptions{}
|
opts := &ViewOptions{}
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
@@ -50,7 +49,7 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
|
|||||||
func runView(ctx context.Context, opts *ViewOptions, svc ViewService, id string) error {
|
func runView(ctx context.Context, opts *ViewOptions, svc ViewService, id string) error {
|
||||||
s, err := svc.GetSession(ctx, id)
|
s, err := svc.GetSession(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "get session %q", id)
|
return cmdutil.WrapHTTP(err, "get session %q", id)
|
||||||
}
|
}
|
||||||
if opts.JSONOut {
|
if opts.JSONOut {
|
||||||
return format.WriteEnvelope(iostreams.IO.Out, format.Success(s, nil))
|
return format.WriteEnvelope(iostreams.IO.Out, format.Success(s, nil))
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
|
|
||||||
// AIAgentHelpKey is the cobra Annotation key used to attach an AI-agent-specific
|
// AIAgentHelpKey is the cobra Annotation key used to attach an AI-agent-specific
|
||||||
// help blurb to a command. The blurb is appended to --help output only when
|
// help blurb to a command. The blurb is appended to --help output only when
|
||||||
// agent mode is active. Mirrors Stripe's pkg/cmd/templates.go AIAgentHelpAnnotationKey.
|
// agent mode is active.
|
||||||
const AIAgentHelpKey = "ai_agent_help"
|
const AIAgentHelpKey = "ai_agent_help"
|
||||||
|
|
||||||
// FormatAgentGuidance returns the agent-targeted help text registered on cmd,
|
// FormatAgentGuidance returns the agent-targeted help text registered on cmd,
|
||||||
|
|||||||
@@ -2,15 +2,11 @@
|
|||||||
// trigger AGENT-targeted help text) and per-command help annotations.
|
// trigger AGENT-targeted help text) and per-command help annotations.
|
||||||
//
|
//
|
||||||
// v0.2 ADR-3: removed the omnibus `--agent` flag + ApplyAgentSugar
|
// v0.2 ADR-3: removed the omnibus `--agent` flag + ApplyAgentSugar
|
||||||
// mode-switch as over-design. Mainstream CLIs (gh / kubectl / aws / docker /
|
// mode-switch as over-design. Per-command --json + TTY auto-detect cover
|
||||||
// flyctl) deliberately don't have a single mode-switch flag; per-command
|
// 95% of cases. See cli/AGENTS.md for the full agent contract.
|
||||||
// --json + TTY auto-detect cover 95% of cases. WeKnora now follows that
|
|
||||||
// convention. See cli/AGENTS.md for the full agent contract.
|
|
||||||
//
|
//
|
||||||
// What remains here: a small env-detect for known coding agents, used purely
|
// What remains here: a small env-detect for known coding agents, used purely
|
||||||
// to render the AGENT-targeted help section (no behavior change). Patterned
|
// to render the AGENT-targeted help section (no behavior change).
|
||||||
// after Stripe's DetectAIAgent (https://github.com/stripe/stripe-cli/tree/master/pkg/useragent),
|
|
||||||
// which Stripe uses only for User-Agent telemetry tagging.
|
|
||||||
package agent
|
package agent
|
||||||
|
|
||||||
import "os"
|
import "os"
|
||||||
@@ -20,12 +16,10 @@ import "os"
|
|||||||
type AIAgentName string
|
type AIAgentName string
|
||||||
|
|
||||||
// aiAgentEnvs maps environment variable presence to a coding agent name.
|
// aiAgentEnvs maps environment variable presence to a coding agent name.
|
||||||
// Cropped to the entries the Stripe CLI also recognizes (verified against
|
// The earlier 7-entry list (CODEX_*, AIDER_PROMPT, CONTINUE_GLOBAL_DIR,
|
||||||
// stripe-cli/pkg/useragent/useragent.go). The earlier 7-entry list (CODEX_*,
|
// OPENCODE_RUNNING, GEMINICODER_PROFILE) did not have official agent docs
|
||||||
// AIDER_PROMPT, CONTINUE_GLOBAL_DIR, OPENCODE_RUNNING, GEMINICODER_PROFILE)
|
// backing those env names; removed in v0.2 to avoid maintaining an
|
||||||
// did not have official agent docs backing those env names; removed in v0.2
|
// unverified hardcoded list. New entries should document the source URL.
|
||||||
// to avoid maintaining an unverified hardcoded list. New entries should
|
|
||||||
// document the source URL.
|
|
||||||
var aiAgentEnvs = []struct {
|
var aiAgentEnvs = []struct {
|
||||||
env string
|
env string
|
||||||
name AIAgentName
|
name AIAgentName
|
||||||
|
|||||||
@@ -20,10 +20,9 @@ import (
|
|||||||
// prompter error → returns CodeInputMissingFlag (rare; stdin closed
|
// prompter error → returns CodeInputMissingFlag (rare; stdin closed
|
||||||
// mid-prompt)
|
// mid-prompt)
|
||||||
//
|
//
|
||||||
// The non-TTY branch is the lark-cli skill protocol: high-risk writes
|
// The non-TTY branch is the destructive-write protocol: high-risk writes
|
||||||
// always require explicit confirmation in scripted contexts, never silent
|
// always require explicit confirmation in scripted contexts, never silent
|
||||||
// proceed. See cli/AGENTS.md "Exit codes" and
|
// proceed. See cli/AGENTS.md "Exit codes".
|
||||||
// https://github.com/larksuite/cli/blob/main/skills/lark-shared/SKILL.md.
|
|
||||||
//
|
//
|
||||||
// `yes` should be sourced from the persistent global -y/--yes flag.
|
// `yes` should be sourced from the persistent global -y/--yes flag.
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -13,8 +13,6 @@ import (
|
|||||||
// of its parents. Write commands check this and skip the SDK call, returning
|
// of its parents. Write commands check this and skip the SDK call, returning
|
||||||
// an envelope with dry_run=true that describes the action that would have
|
// an envelope with dry_run=true that describes the action that would have
|
||||||
// run. Read commands ignore --dry-run (no side effect to preview).
|
// run. Read commands ignore --dry-run (no side effect to preview).
|
||||||
//
|
|
||||||
// Pattern from lark-cli's `--dry-run` (cmd/api/api.go DryRun field).
|
|
||||||
func IsDryRun(cmd *cobra.Command) bool {
|
func IsDryRun(cmd *cobra.Command) bool {
|
||||||
if cmd == nil {
|
if cmd == nil {
|
||||||
return false
|
return false
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ const (
|
|||||||
CodeInputMissingFlag ErrorCode = "input.missing_flag"
|
CodeInputMissingFlag ErrorCode = "input.missing_flag"
|
||||||
// CodeInputConfirmationRequired marks a high-risk write that has no
|
// CodeInputConfirmationRequired marks a high-risk write that has no
|
||||||
// interactive UI (non-TTY or --json) and was invoked without -y/--yes.
|
// interactive UI (non-TTY or --json) and was invoked without -y/--yes.
|
||||||
// Mapped to exit code 10 (lark-cli skill protocol — see cli/AGENTS.md).
|
// Mapped to exit code 10 (see cli/AGENTS.md).
|
||||||
// Agents must surface the envelope to the user and only retry with -y
|
// Agents must surface the envelope to the user and only retry with -y
|
||||||
// after explicit human approval; never auto-retry.
|
// after explicit human approval; never auto-retry.
|
||||||
CodeInputConfirmationRequired ErrorCode = "input.confirmation_required"
|
CodeInputConfirmationRequired ErrorCode = "input.confirmation_required"
|
||||||
@@ -126,8 +126,21 @@ func Wrapf(code ErrorCode, cause error, format string, args ...any) *Error {
|
|||||||
return &Error{Code: code, Message: fmt.Sprintf(format, args...), Cause: cause}
|
return &Error{Code: code, Message: fmt.Sprintf(format, args...), Cause: cause}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WrapHTTP wraps a transport / response error with the typed code derived
|
||||||
|
// from its HTTP shape (404 → resource.not_found, 401 → auth.unauthenticated,
|
||||||
|
// non-HTTP → network.error, …). Shortcut for the universal pattern
|
||||||
|
// `Wrapf(ClassifyHTTPError(err), err, format, args...)` used by every SDK
|
||||||
|
// call site — single source for the wrap-and-classify policy.
|
||||||
|
//
|
||||||
|
// Use this for any error returned from a wire call. Stays paired with
|
||||||
|
// ClassifyHTTPErrorOutputs() in the acceptance/contract test, which
|
||||||
|
// enumerates the codes this helper can yield.
|
||||||
|
func WrapHTTP(cause error, format string, args ...any) *Error {
|
||||||
|
return Wrapf(ClassifyHTTPError(cause), cause, format, args...)
|
||||||
|
}
|
||||||
|
|
||||||
// FlagError signals user-visible flag/argument problems; the root command
|
// FlagError signals user-visible flag/argument problems; the root command
|
||||||
// prints help on top of the message and exits 2 (gh-style).
|
// prints help on top of the message and exits 2.
|
||||||
type FlagError struct{ err error }
|
type FlagError struct{ err error }
|
||||||
|
|
||||||
func (e *FlagError) Error() string { return e.err.Error() }
|
func (e *FlagError) Error() string { return e.err.Error() }
|
||||||
@@ -143,7 +156,7 @@ var SilentError = errors.New("silent error (handled)")
|
|||||||
// CancelError marks a user-cancelled operation (Ctrl-C / "no" at confirm).
|
// CancelError marks a user-cancelled operation (Ctrl-C / "no" at confirm).
|
||||||
var CancelError = errors.New("operation cancelled")
|
var CancelError = errors.New("operation cancelled")
|
||||||
|
|
||||||
// Typed predicates — use these instead of comparing ErrorCode strings (Stripe pattern).
|
// Typed predicates — use these instead of comparing ErrorCode strings.
|
||||||
// They walk the error chain so wrapped errors still match.
|
// They walk the error chain so wrapped errors still match.
|
||||||
|
|
||||||
// IsAuthError matches any auth.* code.
|
// IsAuthError matches any auth.* code.
|
||||||
|
|||||||
@@ -9,17 +9,20 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// ExitCode maps an error to the documented CLI exit code (spec §2.4 + ADR-3).
|
// ExitCode maps an error to the documented CLI exit code (spec §2.4 + ADR-3).
|
||||||
// Mirrors gh / Stripe / lark-cli convention:
|
|
||||||
// - 0 success
|
// - 0 success
|
||||||
// - 1 generic / unknown typed error
|
// - 1 generic / unknown typed error — fallback for: resource.already_exists,
|
||||||
// - 2 flag / argument problem
|
// resource.locked, local.* (config_corrupt / keychain_denied / file_io /
|
||||||
|
// context_not_found / kb_id_required / kb_not_found / projectlink_corrupt /
|
||||||
|
// user_aborted / upload_file_not_found), mcp.*, server.session_create_failed,
|
||||||
|
// sse.stream_aborted, and any code outside the named buckets below
|
||||||
|
// - 2 flag / argument problem (cobra parse / unknown subcommand)
|
||||||
// - 3 auth.*
|
// - 3 auth.*
|
||||||
// - 4 resource.not_found
|
// - 4 resource.not_found
|
||||||
// - 5 input.* (other than confirmation_required)
|
// - 5 input.* (other than confirmation_required)
|
||||||
// - 6 server.rate_limited
|
// - 6 server.rate_limited
|
||||||
// - 7 server.* (other) / network.*
|
// - 7 server.* (other than rate_limited/session_create_failed) / network.*
|
||||||
// - 10 input.confirmation_required — high-risk write needs explicit -y
|
// - 10 input.confirmation_required — high-risk write needs explicit -y
|
||||||
// (lark-cli skill protocol; see cli/AGENTS.md)
|
// (see cli/AGENTS.md)
|
||||||
// - 130 SIGINT (handled by Go runtime, not this function)
|
// - 130 SIGINT (handled by Go runtime, not this function)
|
||||||
func ExitCode(err error) int {
|
func ExitCode(err error) int {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -120,9 +123,9 @@ func ToErrorBody(err error) *format.ErrorBody {
|
|||||||
}
|
}
|
||||||
body.Retryable = typed.Retryable
|
body.Retryable = typed.Retryable
|
||||||
// Surface the wrapped cause so agents see the actual server / SDK
|
// Surface the wrapped cause so agents see the actual server / SDK
|
||||||
// error string, not just the wrap message ("hybrid search"). Stripe's
|
// error string, not just the wrap message ("hybrid search"). The
|
||||||
// envelope does the same — the human's printed line and the JSON
|
// human's printed line and the JSON envelope both end with the
|
||||||
// envelope both end with the underlying problem.
|
// underlying problem.
|
||||||
if typed.Cause != nil {
|
if typed.Cause != nil {
|
||||||
body.Message = typed.Message + ": " + typed.Cause.Error()
|
body.Message = typed.Message + ": " + typed.Cause.Error()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ import (
|
|||||||
//
|
//
|
||||||
// IOStreams is intentionally NOT a Factory closure — it is the package singleton
|
// IOStreams is intentionally NOT a Factory closure — it is the package singleton
|
||||||
// iostreams.IO. The bar to add a new closure is at least 2 commands sharing the
|
// iostreams.IO. The bar to add a new closure is at least 2 commands sharing the
|
||||||
// same dependency; resist factory bloat (gh CLI cautionary tale).
|
// same dependency; resist factory bloat.
|
||||||
//
|
//
|
||||||
// Client returns a *sdk.Client (the WeKnora SDK). Commands that want narrow
|
// Client returns a *sdk.Client (the WeKnora SDK). Commands that want narrow
|
||||||
// service interfaces (per ADR-4) declare them in their own files and let the
|
// service interfaces (per ADR-4) declare them in their own files and let the
|
||||||
@@ -56,13 +56,21 @@ type Factory struct {
|
|||||||
// New constructs a production Factory wired to real config / SDK client.
|
// New constructs a production Factory wired to real config / SDK client.
|
||||||
//
|
//
|
||||||
// All closures are lazy: invoking --help, version, or shell completion runs
|
// All closures are lazy: invoking --help, version, or shell completion runs
|
||||||
// none of them. The Secrets closure memoizes via sync.Once so the keyring
|
// none of them. Client and Secrets closures memoize via sync.Once so the
|
||||||
// probe happens at most once per process.
|
// SDK client is built (and the keyring is probed) at most once per process,
|
||||||
|
// even when Factory.ResolveKB internally calls f.Client() before the
|
||||||
|
// command's RunE calls it again — without this, name-resolved --kb paths
|
||||||
|
// would build two clients with two AuthRetryTransports holding independent
|
||||||
|
// token state.
|
||||||
func New() *Factory {
|
func New() *Factory {
|
||||||
var (
|
var (
|
||||||
secretsOnce sync.Once
|
secretsOnce sync.Once
|
||||||
secretsStore secrets.Store
|
secretsStore secrets.Store
|
||||||
secretsErr error
|
secretsErr error
|
||||||
|
|
||||||
|
clientOnce sync.Once
|
||||||
|
client *sdk.Client
|
||||||
|
clientErr error
|
||||||
)
|
)
|
||||||
f := &Factory{}
|
f := &Factory{}
|
||||||
f.Config = func() (*config.Config, error) {
|
f.Config = func() (*config.Config, error) {
|
||||||
@@ -81,7 +89,10 @@ func New() *Factory {
|
|||||||
}
|
}
|
||||||
return cfg, nil
|
return cfg, nil
|
||||||
}
|
}
|
||||||
f.Client = func() (*sdk.Client, error) { return buildClient(f) }
|
f.Client = func() (*sdk.Client, error) {
|
||||||
|
clientOnce.Do(func() { client, clientErr = buildClient(f) })
|
||||||
|
return client, clientErr
|
||||||
|
}
|
||||||
f.Prompter = func() prompt.Prompter {
|
f.Prompter = func() prompt.Prompter {
|
||||||
if iostreams.IO.IsStdoutTTY() && iostreams.IO.IsStderrTTY() {
|
if iostreams.IO.IsStdoutTTY() && iostreams.IO.IsStderrTTY() {
|
||||||
return prompt.NewTTYPrompter()
|
return prompt.NewTTYPrompter()
|
||||||
@@ -160,17 +171,16 @@ func buildClient(f *Factory) (*sdk.Client, error) {
|
|||||||
// tenant from the credential itself (JWT claim or API key prefix); the
|
// tenant from the credential itself (JWT claim or API key prefix); the
|
||||||
// header is only meaningful for explicit cross-tenant switching by users
|
// header is only meaningful for explicit cross-tenant switching by users
|
||||||
// with CanAccessAllTenants. Auto-mirroring the persisted tenant from config
|
// with CanAccessAllTenants. Auto-mirroring the persisted tenant from config
|
||||||
// breaks that contract — gh / gcloud / Stripe CLIs all require an explicit
|
// breaks that contract — explicit flags (`--tenant=N` is the planned v0.1
|
||||||
// flag (`--tenant=N` is the planned v0.1 entry point) before sending it.
|
// entry point) are required before sending it. `tenant_id` stays in config
|
||||||
// `tenant_id` stays in config for `auth status` display only.
|
// for `auth status` display only.
|
||||||
return sdk.NewClient(ctx.Host, opts...), nil
|
return sdk.NewClient(ctx.Host, opts...), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveKB returns the active KB id for the running command, applying the
|
// ResolveKB returns the active KB id for the running command, applying the
|
||||||
// 4-level fallback chain (highest to lowest):
|
// 4-level fallback chain (highest to lowest):
|
||||||
// 1. --kb flag (kb_<...> id passed through; anything else resolved via
|
// 1. --kb flag (kb_<...> id passed through; anything else resolved via
|
||||||
// ListKnowledgeBases as a name → id lookup; mirrors gcloud --project's
|
// ListKnowledgeBases as a name → id lookup)
|
||||||
// id-or-name auto-detection)
|
|
||||||
// 2. WEKNORA_KB_ID env (always an explicit id)
|
// 2. WEKNORA_KB_ID env (always an explicit id)
|
||||||
// 3. .weknora/project.yaml (walk-up from cwd)
|
// 3. .weknora/project.yaml (walk-up from cwd)
|
||||||
// 4. error: kb required
|
// 4. error: kb required
|
||||||
|
|||||||
@@ -6,12 +6,12 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NormalizeHost validates and canonicalizes a `--host` / `--hostname` value.
|
// NormalizeHost validates and canonicalizes a `--host` value. Trailing
|
||||||
// The returned string is trimmed of trailing slashes. Returns a typed
|
// slashes are trimmed. Every failure path returns CodeInputInvalidArgument —
|
||||||
// CLI error (CodeInputMissingFlag for empty, CodeInputInvalidArgument for
|
// a present-but-empty flag is treated as a bad value, not as a missing flag
|
||||||
// malformed) so callers can `return cmdutil.NormalizeHost(...)` directly.
|
// (cobra's required-flag layer is what catches the absent case).
|
||||||
//
|
//
|
||||||
// Rules (matches gh CLI's URL handling):
|
// Rules:
|
||||||
// - non-empty
|
// - non-empty
|
||||||
// - scheme is http or https
|
// - scheme is http or https
|
||||||
// - URL parses
|
// - URL parses
|
||||||
|
|||||||
@@ -14,8 +14,8 @@ import (
|
|||||||
var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
|
var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
|
||||||
|
|
||||||
// IsKBID reports whether s looks like a KB id. Used by Factory.ResolveKB and
|
// IsKBID reports whether s looks like a KB id. Used by Factory.ResolveKB and
|
||||||
// any caller that accepts a single id-or-name selector value — same pattern
|
// any caller that accepts a single id-or-name selector value (id vs name
|
||||||
// gcloud uses for --project (id vs name auto-detection).
|
// auto-detection).
|
||||||
func IsKBID(s string) bool { return uuidPattern.MatchString(s) }
|
func IsKBID(s string) bool { return uuidPattern.MatchString(s) }
|
||||||
|
|
||||||
// KBLister is the narrow SDK surface ResolveKBNameToID depends on. The
|
// KBLister is the narrow SDK surface ResolveKBNameToID depends on. The
|
||||||
@@ -43,7 +43,7 @@ func ResolveKBFlag(ctx context.Context, lister KBLister, raw string) (string, er
|
|||||||
func ResolveKBNameToID(ctx context.Context, lister KBLister, name string) (string, error) {
|
func ResolveKBNameToID(ctx context.Context, lister KBLister, name string) (string, error) {
|
||||||
kbs, err := lister.ListKnowledgeBases(ctx)
|
kbs, err := lister.ListKnowledgeBases(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", Wrapf(ClassifyHTTPError(err), err, "list knowledge bases")
|
return "", WrapHTTP(err, "list knowledge bases")
|
||||||
}
|
}
|
||||||
for _, kb := range kbs {
|
for _, kb := range kbs {
|
||||||
if kb.Name == name {
|
if kb.Name == name {
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ func parseSemver(s string) (major, minor int, ok bool) {
|
|||||||
if s == "" || s == "(unknown)" {
|
if s == "" || s == "(unknown)" {
|
||||||
return 0, 0, false
|
return 0, 0, false
|
||||||
}
|
}
|
||||||
// 接受 "v" 前缀 (kubectl / gh 同款宽容):git describe + Tencent tag 都带 v
|
// 接受 "v" 前缀:git describe + Tencent tag 都带 v
|
||||||
s = strings.TrimPrefix(s, "v")
|
s = strings.TrimPrefix(s, "v")
|
||||||
// 去掉 prerelease/build metadata
|
// 去掉 prerelease/build metadata
|
||||||
if i := strings.IndexAny(s, "-+"); i >= 0 {
|
if i := strings.IndexAny(s, "-+"); i >= 0 {
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
// Package compat probes server `/system/info` and decides client-server
|
// Package compat probes server `/system/info` and decides client-server
|
||||||
// version skew level. Used by `weknora doctor` 的 server_version 检查项。
|
// version skew level. Used by `weknora doctor` 的 server_version 检查项。
|
||||||
//
|
//
|
||||||
// Mirrors gh internal/update/update.go cache pattern (24h TTL state file)
|
// 24h TTL state file cache, three-tier compat semantics
|
||||||
// and kubectl pkg/version/skew_warning.go three-tier compat semantics
|
|
||||||
// (major-mismatch=hard / minor-mismatch=soft / equal=ok).
|
// (major-mismatch=hard / minor-mismatch=soft / equal=ok).
|
||||||
package compat
|
package compat
|
||||||
|
|
||||||
|
|||||||
@@ -11,10 +11,9 @@ import (
|
|||||||
|
|
||||||
// Envelope is the canonical success/failure shape returned by every command.
|
// Envelope is the canonical success/failure shape returned by every command.
|
||||||
//
|
//
|
||||||
// v0.2 ADR-3 added Notice / Risk / DryRun, borrowed from lark-cli's envelope
|
// v0.2 ADR-3 added Notice / Risk / DryRun. All three are absent on
|
||||||
// (https://github.com/larksuite/cli/blob/main/internal/output/envelope.go).
|
// read-only commands; write commands populate Risk even on success so
|
||||||
// All three are absent on read-only commands; write commands populate Risk
|
// agents can record what action ran.
|
||||||
// even on success so agents can record what action ran.
|
|
||||||
type Envelope struct {
|
type Envelope struct {
|
||||||
OK bool `json:"ok"`
|
OK bool `json:"ok"`
|
||||||
Data any `json:"data,omitempty"`
|
Data any `json:"data,omitempty"`
|
||||||
@@ -56,8 +55,7 @@ type VersionSkewNotice struct {
|
|||||||
// Risk classifies the operation the user is performing — not the error.
|
// Risk classifies the operation the user is performing — not the error.
|
||||||
// Agents inspect this on every envelope. When Level == RiskHighRiskWrite and
|
// Agents inspect this on every envelope. When Level == RiskHighRiskWrite and
|
||||||
// the operation requires confirmation (no -y), the CLI exits 10. See
|
// the operation requires confirmation (no -y), the CLI exits 10. See
|
||||||
// cli/AGENTS.md "Exit codes" and lark-cli's
|
// cli/AGENTS.md "Exit codes".
|
||||||
// skills/lark-shared/SKILL.md.
|
|
||||||
type Risk struct {
|
type Risk struct {
|
||||||
Level RiskLevel `json:"level"`
|
Level RiskLevel `json:"level"`
|
||||||
Action string `json:"action,omitempty"`
|
Action string `json:"action,omitempty"`
|
||||||
@@ -76,9 +74,7 @@ type Meta struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// RiskLevel classifies an operation. Agents use this to decide whether to
|
// RiskLevel classifies an operation. Agents use this to decide whether to
|
||||||
// retry, require explicit user approval, or stop. Values are aligned with
|
// retry, require explicit user approval, or stop.
|
||||||
// lark-cli's risk taxonomy
|
|
||||||
// (https://github.com/larksuite/cli/blob/main/internal/output/envelope.go).
|
|
||||||
type RiskLevel string
|
type RiskLevel string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package text
|
||||||
|
|
||||||
|
// KnowledgeDisplayName picks the most informative human label for a
|
||||||
|
// knowledge entry. File-uploads use FileName; URL / text entries fall
|
||||||
|
// back to Title; the ID is the last-resort placeholder so a table cell
|
||||||
|
// is never empty. Single source for the ordering — `weknora doc list`
|
||||||
|
// and `weknora search docs` both call this so a Knowledge renders
|
||||||
|
// identically in either command.
|
||||||
|
//
|
||||||
|
// Takes the three fields directly rather than `sdk.Knowledge` so this
|
||||||
|
// package stays free of SDK imports.
|
||||||
|
func KnowledgeDisplayName(fileName, title, id string) string {
|
||||||
|
if fileName != "" {
|
||||||
|
return fileName
|
||||||
|
}
|
||||||
|
if title != "" {
|
||||||
|
return title
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
// Package text holds gh-style string helpers for human-readable CLI output.
|
// Package text holds string helpers for human-readable CLI output.
|
||||||
// All functions are pure (no I/O, no time.Now), making them trivially testable.
|
// All functions are pure (no I/O, no time.Now), making them trivially testable.
|
||||||
package text
|
package text
|
||||||
|
|
||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
// Pluralize returns "<n> <thing>" or "<n> <thing>s". Mirrors gh
|
// Pluralize returns "<n> <thing>" or "<n> <thing>s". Simple suffix "s" only;
|
||||||
// internal/text/text.go Pluralize signature — simple suffix "s" only;
|
|
||||||
// irregular forms (person/people) are not supported (add PluralizeIrregular
|
// irregular forms (person/people) are not supported (add PluralizeIrregular
|
||||||
// when needed, per spec §2.1).
|
// when needed, per spec §2.1).
|
||||||
func Pluralize(n int, thing string) string {
|
func Pluralize(n int, thing string) string {
|
||||||
|
|||||||
@@ -5,8 +5,7 @@ import "github.com/mattn/go-runewidth"
|
|||||||
const ellipsis = "…"
|
const ellipsis = "…"
|
||||||
|
|
||||||
// Truncate cuts s to at most maxWidth display columns (CJK / emoji 占 2 列;
|
// Truncate cuts s to at most maxWidth display columns (CJK / emoji 占 2 列;
|
||||||
// ASCII 占 1 列), appending "…" if truncated. Mirrors gh
|
// ASCII 占 1 列), appending "…" if truncated. Display width, not rune count.
|
||||||
// internal/text/text.go Truncate semantics — display width, not rune count.
|
|
||||||
//
|
//
|
||||||
// Edge cases:
|
// Edge cases:
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -21,9 +21,8 @@ import (
|
|||||||
// under $HOME used when the env var is unset (".config" / ".cache" / etc.).
|
// under $HOME used when the env var is unset (".config" / ".cache" / etc.).
|
||||||
// parts join under "weknora/" inside the chosen root.
|
// parts join under "weknora/" inside the chosen root.
|
||||||
//
|
//
|
||||||
// Honors the XDG vars on every OS (CLI convention — gh / kubectl / helm all
|
// Honors the XDG vars on every OS, even macOS — where os.UserConfigDir
|
||||||
// do this even on macOS, where os.UserConfigDir would otherwise return
|
// would otherwise return ~/Library/Application Support.
|
||||||
// ~/Library/Application Support).
|
|
||||||
func Path(envVar, fallbackDir string, parts ...string) (string, error) {
|
func Path(envVar, fallbackDir string, parts ...string) (string, error) {
|
||||||
if x := os.Getenv(envVar); x != "" {
|
if x := os.Getenv(envVar); x != "" {
|
||||||
return filepath.Join(append([]string{x, "weknora"}, parts...)...), nil
|
return filepath.Join(append([]string{x, "weknora"}, parts...)...), nil
|
||||||
|
|||||||
Reference in New Issue
Block a user