Files
Enterprise-Knowledge-Base/cli/cmd/kb/create.go
T
nullkey bdc589e1c0 refactor(cli): --limit/--all-pages, Go 1.26, internal/agent → aiclient
Cross-cutting cleanup that lands alongside the new feature surface:

- `--limit / -L` and `--all-pages` on every list command. Default
  --limit 30 (gh-parity); --all-pages drains every server page
  client-side, capped by --limit. Closes the audit finding that the
  old "1000 max per call" implicit cap was undiscoverable.
- `auth token` emits a TTY-only stderr advisory when stdout is a
  terminal (the credential just got displayed in scrollback) plus an
  api-key-mode rotation hint.
- Comment + doc discipline pass: drop external project name
  references from in-code comments (we reference them in design notes,
  not inline).
- Bump `go` directive to 1.26.0 and CI matrix to 1.26.x to align with
  the main module's go.mod.
- Rename `cli/internal/agent` → `cli/internal/aiclient` to
  disambiguate from the new `cli/cmd/agent` resource subtree. The
  package handles AI coding-agent env detection + per-command --help
  annotations; the new name reflects that more precisely.
2026-05-15 12:03:56 +08:00

106 lines
3.6 KiB
Go

package kb
import (
"context"
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// kbCreateFields enumerates the fields surfaced for `--json` discovery on
// `kb create`. The result is the full KnowledgeBase struct; these mirror its
// top-level json tags. Nested config objects are intentionally omitted —
// users wanting them can drop --json (no filter) or use --jq.
var kbCreateFields = []string{
"id", "name", "type", "description",
"is_temporary", "is_pinned",
"embedding_model_id", "summary_model_id",
"knowledge_count", "chunk_count",
"is_processing", "processing_count",
"created_at", "updated_at",
}
type CreateOptions struct {
Name string
Description string
EmbeddingModel string
DryRun bool
}
// CreateService is the narrow SDK surface this command depends on.
// *sdk.Client satisfies it via duck typing (ADR-4).
type CreateService interface {
CreateKnowledgeBase(ctx context.Context, kb *sdk.KnowledgeBase) (*sdk.KnowledgeBase, error)
}
// NewCmdCreate builds `weknora kb create`.
func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
opts := &CreateOptions{}
cmd := &cobra.Command{
Use: "create --name <name>",
Short: "Create a new knowledge base",
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
opts.DryRun = cmdutil.IsDryRun(c)
if opts.DryRun {
return runCreate(c.Context(), opts, jopts, nil) // service unused on dry-run
}
cli, err := f.Client()
if err != nil {
return err
}
return runCreate(c.Context(), opts, jopts, cli)
},
}
cmd.Flags().StringVar(&opts.Name, "name", "", "Knowledge base name (required)")
cmd.Flags().StringVar(&opts.Description, "description", "", "Knowledge base description (optional)")
cmd.Flags().StringVar(&opts.EmbeddingModel, "embedding-model", "", "Embedding model ID (optional; server picks default when unset)")
cmdutil.AddJSONFlags(cmd, kbCreateFields)
aiclient.SetAgentHelp(cmd, "Creates a knowledge base under the active context. --name is required; --description and --embedding-model are optional. Returns data: full KnowledgeBase object including the new id.")
return cmd
}
func runCreate(ctx context.Context, opts *CreateOptions, jopts *cmdutil.JSONOptions, svc CreateService) error {
// Validate locally before any HTTP — keeps `input.invalid_argument`
// distinct from a server-side 400.
if strings.TrimSpace(opts.Name) == "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--name is required")
}
req := &sdk.KnowledgeBase{
Name: opts.Name,
Description: opts.Description,
}
if opts.EmbeddingModel != "" {
req.EmbeddingModelID = opts.EmbeddingModel
}
if opts.DryRun {
return cmdutil.EmitDryRun(jopts.Enabled(), req, nil,
&format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("create knowledge base %q", opts.Name)})
}
created, err := svc.CreateKnowledgeBase(ctx, req)
if err != nil {
return cmdutil.WrapHTTP(err, "create knowledge base")
}
if jopts.Enabled() {
risk := &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("created knowledge base %s", created.ID)}
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.SuccessWithRisk(created, &format.Meta{KBID: created.ID}, risk), jopts.Fields, jopts.JQ)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Created knowledge base %q (id: %s)\n", created.Name, created.ID)
return nil
}