feat(cli): agent-first WeKnora CLI

The `weknora` command-line client for the WeKnora RAG server. Full command
surface: kb / doc / chunk / session / message / agent / model / search / chat /
auth / profile / link / api / mcp / skills / config / doctor / schema /
exit-codes.

Agent-first wire contract: JSON envelope by default, typed error codes mapped to
stable exit codes, error.retry_argv / retryable / partial-failure status,
global --dry-run preview, the exit-10 confirmation protocol for writes, and
control/ANSI/Bidi input hygiene. Stateless env-credential auth
(WEKNORA_API_KEY / WEKNORA_TOKEN + WEKNORA_HOST) for headless/CI/agent use.
A curated read-only MCP tool surface (`mcp serve`) and embedded Agent Skills
(`skills install`). Extensive unit + contract-golden tests and CI.
This commit is contained in:
nullkey
2026-06-26 20:40:59 +08:00
committed by lyingbug
parent 445a4330fa
commit 6f8b825f5f
151 changed files with 7305 additions and 733 deletions
+2 -2
View File
@@ -1,5 +1,5 @@
// Package agentcmd holds the `weknora agent` command tree:
// list / view / create / edit / delete / status / check. The directory is
// list / view / create / update / delete / status / check. The directory is
// named `agent/` to match the cobra subcommand; the Go package is `agentcmd`
// to avoid colliding with cobra's *cobra.Command identifier.
//
@@ -22,7 +22,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
Use: "agent",
Short: "Manage custom agents (CRUD + status/check)",
Long: `Custom Agents bundle a system prompt, model, tool allow-list, and KB
scope into an addressable resource. Create, edit, list, view, check,
scope into an addressable resource. Create, update, list, view, check,
or delete agents. To invoke an agent, use: weknora session ask --agent <id>`,
}
cmd.AddCommand(NewCmdList(f))
+72 -8
View File
@@ -66,7 +66,8 @@ const agentCreateExample = ` weknora agent create "Support Bot" --model <model-
const agentCreateLong = `Create a new custom agent.
--model is required (an agent without a model cannot invoke). The 7
--model is required (an agent without a model cannot invoke); discover a
valid model id with 'weknora model list'. The 7
optional hot-path flags cover the most frequently set AgentConfig fields;
for the remaining 27 use --config-file with a YAML or JSON document
matching the AgentConfig schema (run --generate-skeleton to get a
@@ -122,6 +123,12 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
fmt.Sprintf("--temperature must be in 0.0..2.0, got %g", opts.Temperature))
}
// Reject an unknown --agent-mode / --kb-selection-mode up front
// (typed exit 5) rather than letting the server fail the create.
if err := validateAgentModeFlags(&opts.AgentMode, &opts.KBSelectionMode); err != nil {
return err
}
if systemPromptFile != "" {
r, err := cmdutil.OpenInput(systemPromptFile)
if err != nil {
@@ -159,6 +166,31 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
if err != nil {
return err
}
// Resolve --model / --rerank-model (id or name) and validate they
// exist, matching the id-or-name policy of `kb init`. A bogus name
// fails fast here instead of creating an agent whose model never
// resolves at run time.
if opts.Model, err = cmdutil.ResolveModelRef(cmd.Context(), cli, opts.Model, "KnowledgeQA"); err != nil {
return err
}
if opts.RerankModel, err = cmdutil.ResolveModelRef(cmd.Context(), cli, opts.RerankModel, "Rerank"); err != nil {
return err
}
// Resolve --attach-kb values (id or name) to canonical ids,
// matching the --kb flag's id-or-name policy. Without this a raw
// name is stored verbatim as a kb_id, silently creating an agent
// whose KB reference never resolves at run time.
if len(opts.KBs) > 0 {
resolved := make([]string, 0, len(opts.KBs))
for _, raw := range opts.KBs {
id, rerr := cmdutil.ResolveKBFlag(cmd.Context(), cli, raw)
if rerr != nil {
return rerr
}
resolved = append(resolved, id)
}
opts.KBs = resolved
}
return runCreate(cmd.Context(), opts, fopts, cli)
},
}
@@ -166,17 +198,17 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
// Required (enforced in PreRunE rather than cmd.MarkFlagRequired so
// --generate-skeleton can bypass it — cobra's MarkFlagRequired runs
// before PreRunE and would otherwise block the skeleton path).
cmd.Flags().StringVar(&opts.Model, "model", "", "LLM model id (required, except with --generate-skeleton)")
cmd.Flags().StringVar(&opts.Model, "model", "", "LLM model id or name (required, except with --generate-skeleton)")
// Hot-path (8 flag names, 7 distinct config fields)
cmd.Flags().StringVar(&opts.Description, "description", "", "Agent description")
cmd.Flags().StringVar(&opts.SystemPrompt, "system-prompt", "", "System prompt text (mutex with --system-prompt-file)")
cmd.Flags().StringVar(&systemPromptFile, "system-prompt-file", "", "Read system prompt from FILE, or '-' for stdin")
cmd.MarkFlagsMutuallyExclusive("system-prompt", "system-prompt-file")
cmd.Flags().StringVar(&opts.AgentMode, "agent-mode", "", "Agent operating mode: quick-answer | smart-reasoning")
cmd.Flags().StringSliceVar(&opts.KBs, "attach-kb", nil, "Attach a knowledge base id (repeatable); aligns with 'agent edit --add-kb'")
cmd.Flags().StringVar(&opts.KBSelectionMode, "kb-selection-mode", "", "KB selection mode: all | selected | none")
cmd.Flags().StringVar(&opts.RerankModel, "rerank-model", "", "Rerank model id")
cmd.Flags().StringVar(&opts.AgentMode, "agent-mode", "", "Agent operating mode: "+strings.Join(agentModeValues, " | "))
cmd.Flags().StringSliceVar(&opts.KBs, "attach-kb", nil, "Attach a knowledge base id (repeatable); aligns with 'agent update --add-kb'")
cmd.Flags().StringVar(&opts.KBSelectionMode, "kb-selection-mode", "", "KB selection mode: "+strings.Join(kbSelectionModeValues, " | "))
cmd.Flags().StringVar(&opts.RerankModel, "rerank-model", "", "Rerank model id or name")
cmd.Flags().Float64Var(&opts.Temperature, "temperature", 0.0, "Generation temperature (0.0..2.0)")
// Power-user / utility
@@ -187,9 +219,14 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
cmdutil.AddFormatFlag(cmd, agentViewFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Create a new custom agent. --model is required; --attach-kb takes KB ids (repeatable, not names). Emits the created Agent object.",
UsedFor: "Create a new custom agent. --model is required and accepts a model id or name; --attach-kb (repeatable) accepts KB ids or names. Emits the created Agent object.",
RequiredFlags: []string{"<name> (positional)", "--model"},
Output: "envelope.data is the created Agent object with id, name, config",
Examples: []string{
`weknora agent create "Support Bot" --model gpt-4o`,
`weknora agent create "Support Bot" --model gpt-4o --attach-kb kb_eng --system-prompt "You are a support assistant."`,
`weknora agent create --generate-skeleton # print a blank config to fill in (no --model needed)`,
},
Output: "envelope.data is the created Agent object with id, name, config",
})
return cmd
}
@@ -270,6 +307,33 @@ func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOp
return emitAgent(fopts, created)
}
// agentModeValues / kbSelectionModeValues are the closed server enums for the
// --agent-mode / --kb-selection-mode flags, sourced from the SDK enumerators so
// the CLI can't drift from the server vocabulary.
var (
agentModeValues = cmdutil.EnumStrings(sdk.AllAgentModes())
kbSelectionModeValues = cmdutil.EnumStrings(sdk.AllKBSelectionModes())
)
// validateAgentModeFlags validates and canonicalises --agent-mode and
// --kb-selection-mode in place against the SDK enums. An empty value passes
// through (flag unset → no override). Rejecting a typo here gives a fast,
// typed input.invalid_argument instead of a confusing server-side failure.
// Shared by `agent create` and `agent update`.
func validateAgentModeFlags(agentMode, kbSelectionMode *string) error {
v, err := cmdutil.ValidateEnum("agent-mode", *agentMode, agentModeValues)
if err != nil {
return err
}
*agentMode = v
v, err = cmdutil.ValidateEnum("kb-selection-mode", *kbSelectionMode, kbSelectionModeValues)
if err != nil {
return err
}
*kbSelectionMode = v
return nil
}
// applyCreateOverrides merges hot-path flag overrides into the base config,
// then applies the "--attach-kb implies --kb-selection-mode=selected" fallback.
// Shared by the --from path (base=copied agent's config) and the plain
+38 -1
View File
@@ -218,6 +218,44 @@ func TestCreate_Temperature_Bounds(t *testing.T) {
}
}
// TestCreate_AgentModeValidation: an unknown --agent-mode / --kb-selection-mode
// is rejected up front (PreRunE) with a typed input.invalid_argument (exit 5),
// while a valid value passes the gate. The closed set is sourced from the SDK
// enumerators, so this also guards against CLI/SDK drift.
func TestCreate_AgentModeValidation(t *testing.T) {
cases := []struct {
name string
args []string
wantErr string // substring; "" means the mode gate must pass
}{
{"bad agent-mode", []string{"--agent-mode", "bogus"}, "agent-mode"},
{"bad kb-selection-mode", []string{"--kb-selection-mode", "every"}, "kb-selection-mode"},
{"valid agent-mode", []string{"--agent-mode", "smart-reasoning", "--dry-run"}, ""},
{"valid kb-selection-mode", []string{"--kb-selection-mode", "selected", "--dry-run"}, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, _ = iostreams.SetForTest(t)
cmd := NewCmdCreate(nil)
cmd.SetArgs(append([]string{"Test", "--model", "model-x"}, tc.args...))
cmd.SilenceUsage, cmd.SilenceErrors = true, true
err := cmd.Execute()
if tc.wantErr == "" {
// Valid mode + --dry-run: must clear the mode gate. (--dry-run
// short-circuits before any client call, so nil factory is fine.)
require.NoError(t, err)
return
}
require.Error(t, err)
var ce *cmdutil.Error
require.ErrorAs(t, err, &ce)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, ce.Code)
assert.Equal(t, 5, cmdutil.ExitCode(err))
assert.Contains(t, err.Error(), tc.wantErr)
})
}
}
func TestCreate_CopyAgent_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{copyErr: errBadHTTP404}
@@ -251,4 +289,3 @@ func TestCreate_AttachKBFlagExists(t *testing.T) {
old := cmd.Flags().Lookup("kb")
assert.Nil(t, old, "old --kb flag must not exist on 'agent create' (renamed to --attach-kb)")
}
+1 -1
View File
@@ -106,7 +106,7 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
}
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "agent", opts.AgentID, "agent.delete", "weknora agent delete "+opts.AgentID+" -y"); err != nil {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "agent", opts.AgentID, "agent.delete", []string{"weknora", "agent", "delete", opts.AgentID, "-y"}); err != nil {
return err
}
if err := svc.DeleteAgent(ctx, opts.AgentID); err != nil {
+49 -58
View File
@@ -8,7 +8,6 @@ import (
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
@@ -64,7 +63,7 @@ type editFlagSet struct {
configFileSet bool
}
const agentEditLong = `Edit a custom agent's fields surgically.
const agentEditLong = `Update a custom agent's fields surgically.
At least one update flag is required; flags you omit preserve the current
server-side value via fetch-then-update. Pass --description "" to clear
@@ -89,20 +88,20 @@ with input.confirmation_required. Surface the prompt to the user and only
retry with -y after explicit approval. Other failure codes: resource.not_found
(agent id or KB id), auth.forbidden, input.invalid_argument (no flags, bad file).`
const agentEditExample = ` weknora agent edit ag_abc --name "Renamed" -y
weknora agent edit ag_abc --description "" -y # clear description
weknora agent edit ag_abc --add-kb kb_new --remove-kb kb_old -y
weknora agent edit ag_abc --system-prompt-file ./prompt.md -y
weknora agent edit ag_abc --config-file ./tuned.yaml --temperature 0.9 -y`
const agentEditExample = ` weknora agent update ag_abc --name "Renamed" -y
weknora agent update ag_abc --description "" -y # clear description
weknora agent update ag_abc --add-kb kb_new --remove-kb kb_old -y
weknora agent update ag_abc --system-prompt-file ./prompt.md -y
weknora agent update ag_abc --config-file ./tuned.yaml --temperature 0.9 -y`
// NewCmdEdit builds `weknora agent edit <agent-id>`.
// NewCmdEdit builds `weknora agent update <agent-id>`.
func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
opts := &EditOptions{}
var systemPromptFile, configFile string
cmd := &cobra.Command{
Use: "edit <agent-id>",
Short: "Edit a custom agent's configuration",
Use: "update <agent-id>",
Short: "Update a custom agent's configuration",
Long: agentEditLong,
Example: agentEditExample,
Args: cobra.ExactArgs(1),
@@ -127,6 +126,12 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
fmt.Sprintf("--temperature must be in 0.0..2.0, got %g", opts.Temperature))
}
// Reject an unknown --agent-mode / --kb-selection-mode up front
// (typed exit 5) rather than letting the server fail the update.
if err := validateAgentModeFlags(&opts.AgentMode, &opts.KBSelectionMode); err != nil {
return err
}
if systemPromptFile != "" {
r, err := cmdutil.OpenInput(systemPromptFile)
if err != nil {
@@ -156,7 +161,7 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
if !editHasAnyFlag(opts) {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: "agent edit requires at least one flag",
Message: "agent update requires at least one flag",
Hint: "pass at least one update flag (e.g., --name, --add-kb, --description) or --config-file",
}
}
@@ -200,7 +205,7 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
}
}
if handled, err := cmdutil.HandleDryRun(cmd, true, cmdutil.DryRunPlan{
Action: "agent.edit",
Action: "agent.update",
Args: planArgs,
}); handled {
return err
@@ -208,14 +213,32 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
}
yes, _ := cmd.Flags().GetBool("yes")
// Build the retry command from the flags the user actually passed.
retryCmd := buildAgentEditRetryCmd(cmd, opts.AgentID)
if err := cmdutil.ConfirmDestructive(f.Prompter(), yes, fopts.WantsJSON(), "edit", "agent", opts.AgentID, "agent.edit", retryCmd); err != nil {
// --add-kb/--remove-kb/--system-prompt-file/--config-file are excluded
// (multi-value / file-based — a precise single argv is impractical).
retryCmd := cmdutil.BuildRetryArgv(cmd, []string{"weknora", "agent", "update", opts.AgentID},
"name", "description", "model", "system-prompt", "agent-mode",
"rerank-model", "temperature", "kb-selection-mode", "format")
if err := cmdutil.ConfirmWrite(f.Prompter(), yes, fopts.WantsJSON(), "update", "agent", opts.AgentID, "agent.update", retryCmd); err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
// Resolve --add-kb values (id or name) to canonical ids, matching
// the --kb id-or-name policy and agent create --attach-kb. Avoids
// silently attaching an unresolvable name as a kb_id.
if len(opts.AddKBs) > 0 {
resolved := make([]string, 0, len(opts.AddKBs))
for _, raw := range opts.AddKBs {
id, rerr := cmdutil.ResolveKBFlag(cmd.Context(), cli, raw)
if rerr != nil {
return rerr
}
resolved = append(resolved, id)
}
opts.AddKBs = resolved
}
return runEdit(cmd.Context(), opts, fopts, cli)
},
}
@@ -227,68 +250,36 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
cmd.Flags().StringVar(&opts.SystemPrompt, "system-prompt", "", "System prompt text (mutex with --system-prompt-file)")
cmd.Flags().StringVar(&systemPromptFile, "system-prompt-file", "", "Read system prompt from FILE, or '-' for stdin")
cmd.MarkFlagsMutuallyExclusive("system-prompt", "system-prompt-file")
cmd.Flags().StringVar(&opts.AgentMode, "agent-mode", "", "Agent operating mode: quick-answer | smart-reasoning")
cmd.Flags().StringVar(&opts.AgentMode, "agent-mode", "", "Agent operating mode: "+strings.Join(agentModeValues, " | "))
cmd.Flags().StringVar(&opts.RerankModel, "rerank-model", "", "Rerank model id")
cmd.Flags().Float64Var(&opts.Temperature, "temperature", 0.0, "Generation temperature (0.0..2.0)")
cmd.Flags().StringSliceVar(&opts.AddKBs, "add-kb", nil, "Attach knowledge base id (repeatable, idempotent)")
cmd.Flags().StringSliceVar(&opts.RemoveKBs, "remove-kb", nil, "Detach knowledge base id (repeatable, idempotent)")
cmd.Flags().StringVar(&opts.KBSelectionMode, "kb-selection-mode", "", "KB selection mode: all | selected | none")
cmd.Flags().StringVar(&opts.KBSelectionMode, "kb-selection-mode", "", "KB selection mode: "+strings.Join(kbSelectionModeValues, " | "))
// Full-replace
cmd.Flags().StringVar(&configFile, "config-file", "", "Full AgentConfig YAML or JSON (REPLACES current config baseline; surgical flags then apply on top)")
cmdutil.AddFormatFlag(cmd, agentViewFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetRisk(cmd, "agent.edit")
cmdutil.SetWriteRisk(cmd, "agent.update")
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "surgically edit a custom agent's configuration",
RequiredFlags: []string{"<agent-id> (positional)", "at least one edit flag (--name, --add-kb, etc.)"},
UsedFor: "surgically update a custom agent's configuration",
RequiredFlags: []string{"<agent-id> (positional)", "at least one update flag (--name, --add-kb, etc.)"},
Examples: []string{
"weknora agent edit ag_abc --name \"Renamed\"",
"weknora agent edit ag_abc --add-kb kb_new --remove-kb kb_old",
"weknora agent edit ag_abc --config-file ./tuned.yaml",
"weknora agent update ag_abc --name \"Renamed\"",
"weknora agent update ag_abc --add-kb kb_new --remove-kb kb_old",
"weknora agent update ag_abc --config-file ./tuned.yaml",
},
Output: "envelope.data is the updated Agent object (id, name, config) after the update is applied",
Warnings: []string{
"Requires explicit user approval (exit 10 / input.confirmation_required); never auto-add -y.",
"agent edit overwrites config; fetch-then-update protects unmentioned fields, but bad input still saved.",
"agent update overwrites config; fetch-then-update protects unmentioned fields, but bad input still saved.",
},
})
return cmd
}
// buildAgentEditRetryCmd constructs a directly-executable retry argv from the
// flags the user actually set so agents can surface a precise re-run command.
func buildAgentEditRetryCmd(cmd *cobra.Command, id string) string {
var parts []string
parts = append(parts, "weknora", "agent", "edit", id)
cmd.Flags().Visit(func(f *pflag.Flag) {
switch f.Name {
case "name":
parts = append(parts, "--name", f.Value.String())
case "description":
parts = append(parts, "--description", f.Value.String())
case "model":
parts = append(parts, "--model", f.Value.String())
case "system-prompt":
parts = append(parts, "--system-prompt", f.Value.String())
case "agent-mode":
parts = append(parts, "--agent-mode", f.Value.String())
case "rerank-model":
parts = append(parts, "--rerank-model", f.Value.String())
case "temperature":
parts = append(parts, "--temperature", f.Value.String())
case "kb-selection-mode":
parts = append(parts, "--kb-selection-mode", f.Value.String())
case "format":
parts = append(parts, "--format", f.Value.String())
// --add-kb, --remove-kb, --system-prompt-file, --config-file are excluded
// because they are multi-value or file-based; a precise argv is impractical.
// The user must reconstruct those manually.
}
})
parts = append(parts, "-y")
return strings.Join(parts, " ")
}
// editHasAnyFlag reports whether opts carries at least one surgical update
// signal. Required-flag validation lives in runEdit (not PreRunE) so unit
@@ -304,7 +295,7 @@ func runEdit(ctx context.Context, opts *EditOptions, fopts *cmdutil.FormatOption
if !editHasAnyFlag(opts) {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: "agent edit requires at least one flag",
Message: "agent update requires at least one flag",
Hint: "pass at least one update flag (e.g., --name, --add-kb, --description) or --config-file",
}
}
@@ -373,7 +364,7 @@ func runEdit(ctx context.Context, opts *EditOptions, fopts *cmdutil.FormatOption
updated, err := svc.UpdateAgent(ctx, opts.AgentID, req)
if err != nil {
return cmdutil.WrapHTTP(err, "edit agent %s", opts.AgentID)
return cmdutil.WrapHTTP(err, "update agent %s", opts.AgentID)
}
return emitAgent(fopts, updated)
}
+6 -6
View File
@@ -250,7 +250,7 @@ func TestEdit_SystemPromptFile(t *testing.T) {
assert.Equal(t, "new prompt", svc.updateReq.Config.SystemPrompt)
}
// withRootHarnessAgent wraps `weknora agent edit ...` under a synthetic root
// withRootHarnessAgent wraps `weknora agent update ...` under a synthetic root
// cmd that registers the global persistent flags (mirrors addGlobalFlags in
// cmd/root.go).
func withRootHarnessAgent(edit *cobra.Command, args ...string) *cobra.Command {
@@ -262,7 +262,7 @@ func withRootHarnessAgent(edit *cobra.Command, args ...string) *cobra.Command {
ag := &cobra.Command{Use: "agent"}
ag.AddCommand(edit)
root.AddCommand(ag)
root.SetArgs(append([]string{"agent", "edit"}, args...))
root.SetArgs(append([]string{"agent", "update"}, args...))
root.SetContext(context.Background())
root.SilenceErrors = true
root.SilenceUsage = true
@@ -270,7 +270,7 @@ func withRootHarnessAgent(edit *cobra.Command, args ...string) *cobra.Command {
}
// TestAgentEdit_RequiresConfirmation asserts that without -y (non-TTY / JSON
// mode), agent edit returns input.confirmation_required (exit 10).
// mode), agent update returns input.confirmation_required (exit 10).
func TestAgentEdit_RequiresConfirmation(t *testing.T) {
iostreams.SetForTest(t) // non-TTY
f := &cmdutil.Factory{
@@ -284,7 +284,7 @@ func TestAgentEdit_RequiresConfirmation(t *testing.T) {
require.ErrorAs(t, err, &ce)
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, ce.Code)
assert.Equal(t, 10, cmdutil.ExitCode(err), "exit code 10 per destructive-write protocol")
// retry command must include -y and the agent id
assert.Contains(t, ce.RetryCommand, "-y")
assert.Contains(t, ce.RetryCommand, "ag_abc")
// retry argv must include -y and the agent id
assert.Contains(t, ce.RetryArgv, "-y")
assert.Contains(t, ce.RetryArgv, "ag_abc")
}
+31 -9
View File
@@ -51,6 +51,11 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
// Validate static input before building the client so a bad --limit
// returns input.invalid_argument (exit 5), not an auth error (exit 3).
if err := validateListOpts(opts); err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
@@ -58,19 +63,22 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
return runList(c.Context(), opts, fopts, cli)
},
}
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (1..10000)")
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return — client-side cap; meta.has_more/total_count report the full size (1..10000)")
cmdutil.AddFormatFlag(cmd, agentListFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "List custom agents visible to the active tenant. The SDK returns all agents in one call (no server-side pagination); meta.count reflects the full tenant set, --limit caps client-side.",
Examples: []string{"weknora agent list --format json", "weknora agent list --limit 10 --format json"},
Output: "envelope.data is an array of Agent objects with id, name, is_builtin; meta.count is the total returned",
Output: "envelope.data is an array of Agent objects with id, name, is_builtin; meta.total_count is the full tenant set and meta.has_more=true means --limit truncated it (raise --limit to get the rest)",
})
return cmd
}
func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOptions, svc ListService) error {
// validateListOpts checks --limit. Called from RunE before the client is built
// (so a bad value surfaces as exit 5, not an auth error) and at runList's top
// for direct callers; idempotent and nil-safe.
func validateListOpts(opts *ListOptions) error {
if opts == nil {
opts = &ListOptions{}
return nil
}
if opts.Limit < 1 || opts.Limit > 10000 {
return &cmdutil.Error{
@@ -78,6 +86,16 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
Message: fmt.Sprintf("--limit must be in 1..10000, got %d", opts.Limit),
}
}
return nil
}
func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOptions, svc ListService) error {
if opts == nil {
opts = &ListOptions{}
}
if err := validateListOpts(opts); err != nil {
return err
}
items, err := svc.ListAgents(ctx)
if err != nil {
return cmdutil.WrapHTTP(err, "list agents")
@@ -90,16 +108,20 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
sort.Slice(items, func(i, j int) bool {
return items[i].UpdatedAt.After(items[j].UpdatedAt)
})
// --limit applies after sort so the cap returns the top-N most-recent.
// The agent list SDK is unpaginated, so client-side truncation does not
// imply server-side has_more — there is no cursor to continue with.
// has_more is omitted; callers needing all agents should raise --limit.
// The agent list SDK is unpaginated — it returns every agent in one
// call — so the CLI holds the true total and can tell the caller
// whether the client-side --limit dropped any. total_count is the full
// count; has_more flags that --limit truncated it (raise --limit to get
// the rest — there is no server cursor to continue with).
total := len(items)
truncated := false
if opts.Limit > 0 && len(items) > opts.Limit {
items = items[:opts.Limit]
truncated = true
}
if fopts.WantsJSON() {
meta := &output.Meta{Count: len(items)}
meta := &output.Meta{Count: output.IntPtr(len(items)), HasMore: truncated, TotalCount: output.IntPtr(total)}
return fopts.Emit(iostreams.IO.Out, items, meta)
}
+29
View File
@@ -145,6 +145,35 @@ func TestList_Limit_CapsResults(t *testing.T) {
}
}
// TestList_Truncation_SignalsHasMoreAndTotal pins that --limit truncation
// tells the agent it did not get everything (has_more + total_count).
// Regression: agent list silently dropped agents past --limit with no signal.
func TestList_Truncation_SignalsHasMoreAndTotal(t *testing.T) {
out, _ := iostreams.SetForTest(t)
if err := runList(context.Background(), &ListOptions{Limit: 5}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: makeAgents(20)}); err != nil {
t.Fatalf("runList: %v", err)
}
if !strings.Contains(out.String(), `"has_more":true`) {
t.Errorf("truncated list must set has_more:true; got:\n%s", out.String())
}
if !strings.Contains(out.String(), `"total_count":20`) {
t.Errorf("truncated list must report total_count:20; got:\n%s", out.String())
}
}
func TestList_NoTruncation_OmitsHasMore(t *testing.T) {
out, _ := iostreams.SetForTest(t)
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: makeAgents(3)}); err != nil {
t.Fatalf("runList: %v", err)
}
if strings.Contains(out.String(), `"has_more"`) {
t.Errorf("non-truncated list must omit has_more; got:\n%s", out.String())
}
if !strings.Contains(out.String(), `"total_count":3`) {
t.Errorf("list must report total_count:3; got:\n%s", out.String())
}
}
func TestList_Limit_Zero_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runList(context.Background(), &ListOptions{Limit: 0}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: makeAgents(7)})