Files
Enterprise-Knowledge-Base/cli/cmd/link/link.go
T
nullkey d3c03b2f34 feat(cli)!: v0.10 reliability, agent-UX, and command-surface hardening
A hardening + finalization pass over the agent-first CLI: correctness fixes,
richer machine-readable signals, flag/naming consistency, and a symmetric
config surface. Pre-1.0, so it includes breaking renames.

Correctness:
- agent update: resolve/validate --model/--rerank-model (was storing a bogus
  name verbatim, corrupting config.model_id).
- doctor: honor WEKNORA_HOST / WEKNORA_API_KEY (headless path no longer reports
  "no host configured").
- session ask / MCP session_ask: text answer was empty on non-TTY — the agent
  stream sets Done=true on an intermediate agent_query frame before the answer,
  and AgentAccumulator treated the first Done as terminal. Terminate on the
  `complete` event (new sdk.AgentResponseTypeComplete), not a per-frame Done.
- batch exit codes: any per-item failure collapses to operation.failed (exit 1),
  including `doc upload --recursive` partial failures — a permanent per-file
  failure (e.g. a duplicate) no longer surfaces as a retryable exit 7 an agent
  would loop on; per-item typed errors stay in the envelope.

Agent-first signals & discovery:
- error.exit_code in the envelope (type + exit_code disambiguate the
  input.invalid_argument exit-2-vs-5 split in one JSON read).
- meta.hint on empty content search and on draft doc create; doc wait fails fast
  on a never-parsing draft instead of hanging to --timeout.
- retrieval-readiness is visible in the natural flow: kb status / kb check emit
  retrieval_ready, and kb create hints the fix when no embedding model is bound
  — an unconfigured KB no longer looks silently healthy.
- schema contract completeness: every leaf declares output + >=1 example
  (drift-guarded); output strings match the meta actually emitted; chunk list
  and search docs now emit meta.total_count (both previously dropped it).
- schema tolerates a quoted multi-word command label; zero-state auth — and
  `link` with no profile — point at profile setup / the headless WEKNORA_KB_ID
  path instead of looping on `auth login`.
- id-addressed reads tolerate a redundant --kb (doc view/wait, chunk list/view
  accept and ignore it, declared in schema) so a carried-over --kb doesn't
  exit 2; streaming commands warn that --jq does not apply to an NDJSON stream.
- keep JSON-always as the default; --jq hints spell out the .data path.

Consistency & gating:
- doc create: drop the deprecated --name alias (--title only; pre-1.0 break).
- chunk list --limit aligned to 1..10000; model list --limit/-L with
  has_more/total_count; api write-gates -X PUT/PATCH (exit 10); skills install
  expands a leading ~.
- docs corrected: search docs / doc list --keyword help is case-insensitive
  (server does LOWER LIKE); AGENTS.md risk-action list (no phantom kb.init; add
  model.update / kb.config.set) and batch example (failed item carries `error`);
  session resume --message id comes from `message list`, not the stream.
- auth/profile ergonomics: env credentials are now first-class — `auth token`
  prints the active WEKNORA_API_KEY / WEKNORA_TOKEN, and auth login/logout/refresh
  give an env-aware message instead of looping on "run auth login". `auth logout`
  clears credentials but keeps the profile registered (host preserved for
  re-login); deleting a profile is `profile remove`'s job (clean logout/remove
  separation, matching gh / lark).

Config surface (symmetric read/write, in-place model edits):
- kb config now returns a secret-free KBModelConfigView (was {}); `kb config`
  reads, new `kb config set` writes; `kb init` removed (misnomer).
- kb create --chat-model: retrieval-ready in one step.
- model update: edit a model in place (id preserved, references survive) —
  rotate --api-key-stdin, change base-url / display-name / etc.
- session continue-stream renamed to session resume.

Docs: AGENTS.md is the single wire-contract source; CHANGELOG slimmed; stale
kb-init / continue-stream references removed; skill wire-vocab guard extended.
AGENTS.md / weknora-shared SKILL document retrieval_ready (a KB needs an
embedding model to be searchable), that --jq does not apply to NDJSON
streams, and the env-credential-first auth path; the KB quickstart example
now creates a retrieval-ready KB.
2026-07-06 22:53:01 +08:00

234 lines
8.8 KiB
Go

// Package linkcmd implements `weknora link` - binds the current working
// directory to a knowledge base by writing .weknora/project.yaml. Always
// overwrites an existing link silently rather than refusing when one is
// already present. The cobra Long: text covers the user-facing modes
// (--kb / TTY / non-TTY).
package linkcmd
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/projectlink"
)
// linkFields enumerates the fields surfaced for `--format json` discovery on
// `link`. Tracks the small linkResult struct.
var linkFields = []string{"profile", "kb_id", "kb_name", "project_link_path"}
type Options struct {
KB string // --kb: KB UUID or name; empty triggers interactive prompt on TTY
DryRun bool
}
// linkResult is the typed payload emitted under data.
type linkResult struct {
Profile string `json:"profile"`
KBID string `json:"kb_id"`
KBName string `json:"kb_name,omitempty"`
ProjectLinkPath string `json:"project_link_path"`
}
// NewCmd builds the `weknora link` command.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{}
cmd := &cobra.Command{
Use: "link [kb]",
Short: "Bind the current directory to a knowledge base",
Long: `Writes .weknora/project.yaml in the current working directory pointing
at the supplied knowledge base. Subsequent commands run from this directory
(or any subdirectory) automatically resolve --kb from the link unless
overridden by the --kb flag or WEKNORA_KB_ID env var.
Pass the knowledge base as a positional argument (weknora link <id-or-name>) or
via --kb — the two are equivalent — for non-interactive use (scripts, CI). Run
on a TTY without either to be prompted from the list of available KBs. Always
overwrites any existing link - re-run to switch.
AI agents: link writes to the user's working directory. Only run it when the
user explicitly asked to bind this directory; don't run it as a side effect.`,
Example: ` weknora link a32a63ff-fb36-4874-bcaa-30f48570a694 # positional UUID
weknora link engineering # positional name → id
weknora link --kb engineering # --kb form (equivalent)
weknora link # interactive (TTY)`,
// The knowledge base may be given as a positional arg (matching every
// other <id> command) or via --kb; the two are equivalent.
Args: cobra.MaximumNArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
// Accept the KB as a positional (consistent with `kb view <id>`,
// `doc view <id>`, …) in addition to --kb. Reject supplying both.
if len(args) == 1 {
if opts.KB != "" && opts.KB != args[0] {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"specify the knowledge base once: as a positional argument or --kb, not both")
}
opts.KB = args[0]
}
// Pure-local validation runs before the dry-run gate so --dry-run
// rejects identically to the live path. resolveProfile only reads
// config; the non-TTY-without-`--kb` check is a flag-shape error.
// Same typed errors as runLink (kept there for direct callers).
if _, err := resolveProfile(f); err != nil {
return err
}
if opts.KB == "" && !iostreams.IO.IsStdoutTTY() {
return cmdutil.NewError(cmdutil.CodeKBIDRequired, "--kb is required (no TTY for interactive prompt)")
}
if handled, err := cmdutil.HandleDryRun(c, opts.DryRun, cmdutil.DryRunPlan{
Action: "link",
Args: map[string]any{
"kb": opts.KB,
},
}); handled {
return err
}
return runLink(c.Context(), opts, fopts, f)
},
}
cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name; omit on a TTY for interactive prompt")
cmdutil.AddFormatFlag(cmd, linkFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Bind the current directory to a knowledge base by writing .weknora/project.yaml. Give the KB as a positional arg or --kb (non-interactive); only run when the user explicitly asks to link this directory.",
RequiredFlags: []string{"<kb> positional or --kb (required when no TTY)"},
Examples: []string{"weknora link engineering", "weknora link --kb a32a63ff-fb36-4874-bcaa-30f48570a694"},
Output: "envelope.data has profile, kb_id, kb_name, project_link_path",
})
return cmd
}
func runLink(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, f *cmdutil.Factory) error {
cwd, err := os.Getwd()
if err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "get cwd")
}
linkPath := filepath.Join(cwd, projectlink.DirName, projectlink.FileName)
profileName, err := resolveProfile(f)
if err != nil {
return err
}
kbID, kbName, err := resolveKB(ctx, opts, f)
if err != nil {
return err
}
link := &projectlink.Project{
Profile: profileName,
KBID: kbID,
CreatedAt: time.Now().UTC(),
}
if err := projectlink.Save(linkPath, link); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "write project link")
}
r := linkResult{
Profile: profileName,
KBID: kbID,
KBName: kbName,
ProjectLinkPath: linkPath,
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, r, nil)
}
if kbName != "" {
fmt.Fprintf(iostreams.IO.Out, "✓ Linked %s to %s (kb=%s, id=%s)\n", linkPath, profileName, kbName, kbID)
} else {
fmt.Fprintf(iostreams.IO.Out, "✓ Linked %s to %s (kb_id=%s)\n", linkPath, profileName, kbID)
}
return nil
}
// resolveProfile picks the active profile to record in the link. There is no
// per-invocation override flag on `weknora link` itself - to record under a
// different profile, use the global persistent flag (`weknora --profile
// staging link --kb my-kb`); the active profile at link time is what gets
// written.
func resolveProfile(f *cmdutil.Factory) (string, error) {
cfg, err := f.Config()
if err != nil {
return "", err
}
if cfg.CurrentProfile == "" {
// `link` binds a directory to a profile+KB, so it needs a configured
// profile — env credentials (WEKNORA_API_KEY) alone have no profile to
// record. Point at profile setup (not `auth login`, which loops with no
// profile) and name the headless alternative so an env-cred agent isn't
// stranded on a misleading hint.
return "", cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
"`link` records an active profile, but none is configured").
WithHint("register one with `weknora profile add <name> --host <url> --use`; for a headless (WEKNORA_API_KEY) workflow, skip `link` and pass --kb per command or set WEKNORA_KB_ID").
WithRetryArgv([]string{"weknora", "profile", "add", "--help"})
}
return cfg.CurrentProfile, nil
}
// resolveKB resolves --kb to (kbID, kbName). Name is empty when the user
// passed an id directly. Falls through to an interactive prompt on a TTY
// when --kb is empty; errors on non-TTY.
func resolveKB(ctx context.Context, opts *Options, f *cmdutil.Factory) (string, string, error) {
if opts.KB != "" {
if cmdutil.IsKBID(opts.KB) {
return opts.KB, "", nil
}
cli, err := f.Client()
if err != nil {
return "", "", err
}
id, err := cmdutil.ResolveKBNameToID(ctx, cli, opts.KB)
if err != nil {
return "", "", err
}
return id, opts.KB, nil
}
if !iostreams.IO.IsStdoutTTY() {
return "", "", cmdutil.NewError(cmdutil.CodeKBIDRequired, "--kb is required (no TTY for interactive prompt)")
}
cli, err := f.Client()
if err != nil {
return "", "", err
}
return promptForKB(ctx, cli, f)
}
// promptForKB lists available knowledge bases on stderr, then asks the user
// for an id or name. Resolved against the listed set so a typed name is
// converted to the canonical id.
func promptForKB(ctx context.Context, svc cmdutil.KBLister, f *cmdutil.Factory) (string, string, error) {
kbs, err := svc.ListKnowledgeBases(ctx)
if err != nil {
return "", "", cmdutil.WrapHTTP(err, "list knowledge bases")
}
if len(kbs) == 0 {
return "", "", cmdutil.NewError(cmdutil.CodeKBNotFound, "no knowledge bases visible to active profile; create one first")
}
fmt.Fprintln(iostreams.IO.Err, "Available knowledge bases:")
for _, kb := range kbs {
fmt.Fprintf(iostreams.IO.Err, " %s %s\n", kb.ID, kb.Name)
}
p := f.Prompter()
answer, err := p.Input("Knowledge base id or name", "")
if err != nil {
return "", "", cmdutil.Wrapf(cmdutil.CodeInputMissingFlag, err, "kb prompt")
}
for _, kb := range kbs {
if kb.ID == answer || kb.Name == answer {
return kb.ID, kb.Name, nil
}
}
return "", "", cmdutil.NewError(cmdutil.CodeKBNotFound, fmt.Sprintf("knowledge base not found: %s", answer))
}