feat(cli): --log-level + kb/agent status & check + cross-cutting refactor
Operability surface and the bulk of the jopts→fopts migration: * --log-level error|warn|info|debug + WEKNORA_LOG_LEVEL env, wired to the SDK via client.SetDebugLevel. Invalid --log-level returns FlagError (exit 2). * kb status <kb-id> / kb check <kb-id> verb split (1 HTTP vs 1+N for failed_count aggregation). * agent status <agent-id> / agent check <agent-id> verb split (probes kb_scope_all_reachable via 1+N HTTP). * kb create <name> positional (matches agent create). * Positional id help strings namespaced (<kb-id> / <agent-id>). * All auth / context / link / doctor / kb / agent CRUD commands migrated to the FormatOptions API. * root.go Execute(ctx) takes a context so signal-cancellation propagates via cmd.Context() into long-running commands. * Pagination termination uses len(accum) >= total (not page*pageSize) so server-capped page sizes do not truncate aggregations.
This commit is contained in:
@@ -34,5 +34,7 @@ or delete agents.`,
|
||||
cmd.AddCommand(NewCmdCreate(f))
|
||||
cmd.AddCommand(NewCmdEdit(f))
|
||||
cmd.AddCommand(NewCmdDelete(f))
|
||||
cmd.AddCommand(NewCmdStatus(f))
|
||||
cmd.AddCommand(NewCmdCheck(f))
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// AgentCheckResult is the deep-verification response for `agent check <id>`.
|
||||
// Superset of AgentStatusResult: status fields + KBScopeAllReachable from
|
||||
// probing each KB in agent.Config.KnowledgeBases. Verb split with
|
||||
// `agent status`: status reads existing state cheaply, check actively
|
||||
// verifies dependencies.
|
||||
type AgentCheckResult struct {
|
||||
ID string `json:"id"`
|
||||
Reachable bool `json:"reachable"`
|
||||
ModelID string `json:"model_id,omitempty"`
|
||||
KBScopeAllReachable *bool `json:"kb_scope_all_reachable,omitempty"` // pointer so we can distinguish "not applicable" (e.g. agent unreachable) from "false"
|
||||
}
|
||||
|
||||
// AgentCheckService is the narrow SDK surface needed for agent check.
|
||||
type AgentCheckService interface {
|
||||
GetAgent(ctx context.Context, id string) (*sdk.Agent, error)
|
||||
GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error)
|
||||
}
|
||||
|
||||
var agentCheckFields = []string{"id", "reachable", "model_id", "kb_scope_all_reachable"}
|
||||
|
||||
// NewCmdCheck builds `weknora agent check <id>`.
|
||||
func NewCmdCheck(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "check <agent-id>",
|
||||
Short: "Verify a custom agent end-to-end (status + kb_scope reachability)",
|
||||
Long: `Active verification of a custom agent.
|
||||
|
||||
Performs 1 + N HTTP calls:
|
||||
1 GET /agents/{id} — reachable + model_id
|
||||
N GET /kb/{kb_id} for each id in agent.config.knowledge_bases
|
||||
— sets kb_scope_all_reachable = true iff every probe succeeds
|
||||
|
||||
Use 'weknora agent status <id>' for a fast read-only health snapshot
|
||||
(1 HTTP call, no KB probing). Use 'agent check' when you need to verify
|
||||
the agent's downstream dependencies are all reachable.`,
|
||||
Example: ` weknora agent check ag_abc
|
||||
weknora agent check ag_abc --format json`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := runAgentCheck(c.Context(), cli, args[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return emitAgentCheck(res, fopts, iostreams.IO.Out)
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, agentCheckFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
// runAgentCheck is the testable core. Never errors for "agent not
|
||||
// reachable" — Reachable=false carries that signal.
|
||||
func runAgentCheck(ctx context.Context, svc AgentCheckService, id string) (*AgentCheckResult, error) {
|
||||
a, err := svc.GetAgent(ctx, id)
|
||||
if err != nil {
|
||||
return &AgentCheckResult{ID: id, Reachable: false}, nil
|
||||
}
|
||||
res := &AgentCheckResult{ID: a.ID, Reachable: true}
|
||||
if a.Config != nil {
|
||||
res.ModelID = a.Config.ModelID
|
||||
}
|
||||
// Probe each KB in scope. Vacuously true when scope is empty or
|
||||
// config is nil.
|
||||
allOK := true
|
||||
if a.Config != nil {
|
||||
for _, kbID := range a.Config.KnowledgeBases {
|
||||
if _, err := svc.GetKnowledgeBase(ctx, kbID); err != nil {
|
||||
allOK = false
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
res.KBScopeAllReachable = &allOK
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// emitAgentCheck renders res. Same dispatch as emitAgentStatus.
|
||||
func emitAgentCheck(res *AgentCheckResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, res)
|
||||
case cmdutil.FormatText, "":
|
||||
return writeAgentCheckText(w, res)
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for agent check", fopts.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
func writeAgentCheckText(w io.Writer, res *AgentCheckResult) error {
|
||||
fmt.Fprintf(w, "ID: %s\n", res.ID)
|
||||
fmt.Fprintf(w, "Reachable: %v\n", res.Reachable)
|
||||
if !res.Reachable {
|
||||
return nil
|
||||
}
|
||||
if res.ModelID != "" {
|
||||
fmt.Fprintf(w, "Model: %s\n", res.ModelID)
|
||||
}
|
||||
if res.KBScopeAllReachable != nil {
|
||||
fmt.Fprintf(w, "KB scope OK: %v\n", *res.KBScopeAllReachable)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// compile-time check: SDK client satisfies AgentCheckService.
|
||||
var _ AgentCheckService = (*sdk.Client)(nil)
|
||||
@@ -0,0 +1,150 @@
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
type fakeAgentCheckSvc struct {
|
||||
agent *sdk.Agent
|
||||
agentErr error
|
||||
kbProbeOK map[string]bool // kb_id → reachable
|
||||
kbErr error // applied for any KB id not in the map
|
||||
}
|
||||
|
||||
func (f *fakeAgentCheckSvc) GetAgent(_ context.Context, id string) (*sdk.Agent, error) {
|
||||
if f.agentErr != nil {
|
||||
return nil, f.agentErr
|
||||
}
|
||||
return f.agent, nil
|
||||
}
|
||||
|
||||
func (f *fakeAgentCheckSvc) GetKnowledgeBase(_ context.Context, id string) (*sdk.KnowledgeBase, error) {
|
||||
if ok, found := f.kbProbeOK[id]; found {
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("kb %s unreachable", id)
|
||||
}
|
||||
return &sdk.KnowledgeBase{ID: id}, nil
|
||||
}
|
||||
if f.kbErr != nil {
|
||||
return nil, f.kbErr
|
||||
}
|
||||
return &sdk.KnowledgeBase{ID: id}, nil
|
||||
}
|
||||
|
||||
func TestRunAgentCheck_AllReachable(t *testing.T) {
|
||||
svc := &fakeAgentCheckSvc{
|
||||
agent: &sdk.Agent{ID: "ag_x", Config: &sdk.AgentConfig{
|
||||
ModelID: "m_x",
|
||||
KnowledgeBases: []string{"kb_a", "kb_b"},
|
||||
}},
|
||||
kbProbeOK: map[string]bool{"kb_a": true, "kb_b": true},
|
||||
}
|
||||
res, err := runAgentCheck(context.Background(), svc, "ag_x")
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
if !res.Reachable {
|
||||
t.Error("Reachable=false, want true")
|
||||
}
|
||||
if res.ModelID != "m_x" {
|
||||
t.Errorf("ModelID=%q, want m_x", res.ModelID)
|
||||
}
|
||||
if res.KBScopeAllReachable == nil || !*res.KBScopeAllReachable {
|
||||
t.Errorf("KBScopeAllReachable should be true (pointer set), got %v", res.KBScopeAllReachable)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunAgentCheck_OneKBFails(t *testing.T) {
|
||||
svc := &fakeAgentCheckSvc{
|
||||
agent: &sdk.Agent{ID: "ag_x", Config: &sdk.AgentConfig{
|
||||
ModelID: "m_x",
|
||||
KnowledgeBases: []string{"kb_a", "kb_b"},
|
||||
}},
|
||||
kbProbeOK: map[string]bool{"kb_a": true, "kb_b": false},
|
||||
}
|
||||
res, _ := runAgentCheck(context.Background(), svc, "ag_x")
|
||||
if res.KBScopeAllReachable == nil || *res.KBScopeAllReachable {
|
||||
t.Errorf("KBScopeAllReachable should be false; got %v", res.KBScopeAllReachable)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunAgentCheck_Unreachable(t *testing.T) {
|
||||
svc := &fakeAgentCheckSvc{agentErr: fmt.Errorf("404")}
|
||||
res, err := runAgentCheck(context.Background(), svc, "ag_x")
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
if res.Reachable {
|
||||
t.Error("Reachable=true on 404; want false")
|
||||
}
|
||||
if res.ID != "ag_x" {
|
||||
t.Errorf("ID=%q, want ag_x (echoed even on unreachable)", res.ID)
|
||||
}
|
||||
// KBScopeAllReachable should be nil when agent is unreachable
|
||||
if res.KBScopeAllReachable != nil {
|
||||
t.Errorf("KBScopeAllReachable should be nil when agent unreachable; got %v", res.KBScopeAllReachable)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunAgentCheck_NilConfig(t *testing.T) {
|
||||
// Defensive: Agent.Config is a pointer; nil should not panic and
|
||||
// KBScopeAllReachable should be vacuously true (no KBs to probe).
|
||||
svc := &fakeAgentCheckSvc{agent: &sdk.Agent{ID: "ag_x", Config: nil}}
|
||||
res, err := runAgentCheck(context.Background(), svc, "ag_x")
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
if !res.Reachable {
|
||||
t.Error("Reachable=false, want true on nil config")
|
||||
}
|
||||
if res.ModelID != "" {
|
||||
t.Errorf("ModelID=%q, want empty (no config)", res.ModelID)
|
||||
}
|
||||
// Vacuously true: no KBs to probe
|
||||
if res.KBScopeAllReachable == nil || !*res.KBScopeAllReachable {
|
||||
t.Errorf("KBScopeAllReachable should be vacuously true for nil config; got %v", res.KBScopeAllReachable)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitAgentCheck_JSON(t *testing.T) {
|
||||
trueP := true
|
||||
var buf bytes.Buffer
|
||||
res := &AgentCheckResult{ID: "ag_x", Reachable: true, ModelID: "m_x", KBScopeAllReachable: &trueP}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
|
||||
if err := emitAgentCheck(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
var got AgentCheckResult
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
if got.ModelID != "m_x" {
|
||||
t.Errorf("ModelID=%q, want m_x", got.ModelID)
|
||||
}
|
||||
if got.KBScopeAllReachable == nil || !*got.KBScopeAllReachable {
|
||||
t.Errorf("KBScopeAllReachable should be true in JSON output; got %v", got.KBScopeAllReachable)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitAgentCheck_TextHuman(t *testing.T) {
|
||||
trueP := true
|
||||
var buf bytes.Buffer
|
||||
res := &AgentCheckResult{ID: "ag_x", Reachable: true, ModelID: "m_x", KBScopeAllReachable: &trueP}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
if err := emitAgentCheck(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
for _, want := range []string{"ag_x", "m_x", "true"} {
|
||||
if !strings.Contains(buf.String(), want) {
|
||||
t.Errorf("output missing %q:\n%s", want, buf.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-10
@@ -139,15 +139,16 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
|
||||
return nil
|
||||
},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(cmd)
|
||||
fopts, err := cmdutil.CheckFormatFlag(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runCreate(cmd.Context(), opts, jopts, cli)
|
||||
return runCreate(cmd.Context(), opts, fopts, cli)
|
||||
},
|
||||
}
|
||||
|
||||
@@ -172,11 +173,11 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd.Flags().StringVar(&configFile, "config-file", "", "Full AgentConfig YAML or JSON (use '-' for stdin)")
|
||||
cmd.Flags().BoolVar(&opts.GenerateSkeleton, "generate-skeleton", false, "Emit blank AgentConfig YAML to stdout and exit")
|
||||
|
||||
cmdutil.AddJSONFlags(cmd, agentViewFields)
|
||||
cmdutil.AddFormatFlag(cmd, agentViewFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runCreate(ctx context.Context, opts *CreateOptions, jopts *cmdutil.JSONOptions, svc CreateService) error {
|
||||
func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOptions, svc CreateService) error {
|
||||
if opts.GenerateSkeleton {
|
||||
return cmdutil.GenerateAgentSkeleton(iostreams.IO.Out)
|
||||
}
|
||||
@@ -233,7 +234,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, jopts *cmdutil.JSONOpti
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "update copied agent %s", copied.ID)
|
||||
}
|
||||
return emitAgent(jopts, updated)
|
||||
return emitAgent(fopts, updated)
|
||||
}
|
||||
|
||||
// 4. Plain create path: apply hot-path flag overrides onto base
|
||||
@@ -249,7 +250,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, jopts *cmdutil.JSONOpti
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "create agent")
|
||||
}
|
||||
return emitAgent(jopts, created)
|
||||
return emitAgent(fopts, created)
|
||||
}
|
||||
|
||||
// applyCreateOverrides merges hot-path flag overrides into the base config,
|
||||
@@ -291,11 +292,11 @@ func openConfigFile(path string) (io.Reader, string, error) {
|
||||
}
|
||||
|
||||
// emitAgent writes the Agent to stdout per the v0.4 wire contract (bare
|
||||
// SDK shape for --json, human KV otherwise). Shared by create and edit;
|
||||
// SDK shape for --format json, human KV otherwise). Shared by create and edit;
|
||||
// defined here for proximity to the create flow.
|
||||
func emitAgent(jopts *cmdutil.JSONOptions, ag *sdk.Agent) error {
|
||||
if jopts.Enabled() {
|
||||
return jopts.Emit(iostreams.IO.Out, ag)
|
||||
func emitAgent(fopts *cmdutil.FormatOptions, ag *sdk.Agent) error {
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, ag)
|
||||
}
|
||||
renderAgent(iostreams.IO.Out, ag)
|
||||
return nil
|
||||
|
||||
@@ -49,7 +49,7 @@ func TestCreate_HappyPath_MinimalRequired(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{createResp: &sdk.Agent{ID: "ag_new", Name: "Test"}}
|
||||
opts := &CreateOptions{Name: "Test", Model: "model-x"}
|
||||
err := runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc)
|
||||
err := runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, svc.createReq)
|
||||
assert.Equal(t, "Test", svc.createReq.Name)
|
||||
@@ -88,7 +88,7 @@ func TestCreate_ConfigFile_FlagsOverrideFile(t *testing.T) {
|
||||
ConfigFileBody: bytes.NewBufferString(`{"agent_mode":"smart-reasoning","model_id":"model-y","temperature":0.5}`),
|
||||
ConfigFileKind: "json",
|
||||
}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
require.NotNil(t, svc.createReq.Config)
|
||||
assert.Equal(t, "smart-reasoning", svc.createReq.Config.AgentMode, "file value preserved when no flag override")
|
||||
assert.Equal(t, "model-x", svc.createReq.Config.ModelID, "flag overrides file")
|
||||
@@ -102,7 +102,7 @@ func TestCreate_From_CopiesThenUpdates(t *testing.T) {
|
||||
updateResp: &sdk.Agent{ID: "ag_clone", Name: "Renamed"},
|
||||
}
|
||||
opts := &CreateOptions{Name: "Renamed", Model: "model-x", From: "ag_source"}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, "ag_source", svc.copySrcID)
|
||||
require.True(t, svc.updateCalled, "must Update after Copy when overrides present")
|
||||
assert.Equal(t, "ag_clone", svc.updateID)
|
||||
@@ -115,7 +115,7 @@ func TestCreate_GenerateSkeleton_NoAPICall(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{}
|
||||
opts := &CreateOptions{GenerateSkeleton: true}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Nil(t, svc.createReq, "must not call CreateAgent")
|
||||
assert.Equal(t, "", svc.copySrcID, "must not call CopyAgent")
|
||||
assert.Contains(t, out.String(), "agent_mode:", "skeleton emitted to stdout")
|
||||
@@ -130,7 +130,7 @@ func TestCreate_RepeatedKB_ImpliesSelectedMode(t *testing.T) {
|
||||
KBs: []string{"kb_a", "kb_b"},
|
||||
flags: createFlagSet{kbsSet: true},
|
||||
}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, []string{"kb_a", "kb_b"}, svc.createReq.Config.KnowledgeBases)
|
||||
assert.Equal(t, "selected", svc.createReq.Config.KBSelectionMode, "passing --kb implies selected mode")
|
||||
}
|
||||
@@ -144,7 +144,7 @@ func TestCreate_SystemPromptFile_ReaderRead(t *testing.T) {
|
||||
SystemPromptReader: strings.NewReader("You are a helpful assistant.\n"),
|
||||
flags: createFlagSet{systemPromptSet: true},
|
||||
}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, "You are a helpful assistant.", svc.createReq.Config.SystemPrompt, "TrimSpace removes trailing newline")
|
||||
}
|
||||
|
||||
@@ -171,7 +171,7 @@ func TestCreate_From_PreservesSourceFieldsNotOverridden(t *testing.T) {
|
||||
Temperature: 0.9,
|
||||
flags: createFlagSet{temperatureSet: true},
|
||||
}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
require.NotNil(t, svc.updateReq)
|
||||
require.NotNil(t, svc.updateReq.Config)
|
||||
assert.Equal(t, "Source prompt", svc.updateReq.Config.SystemPrompt, "source SystemPrompt must round-trip")
|
||||
@@ -198,7 +198,7 @@ func TestCreate_From_KBReplacesSourceList(t *testing.T) {
|
||||
KBs: []string{"kb_new"},
|
||||
flags: createFlagSet{kbsSet: true},
|
||||
}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
require.NotNil(t, svc.updateReq.Config)
|
||||
assert.Equal(t, []string{"kb_new"}, svc.updateReq.Config.KnowledgeBases, "--kb replaces source KB list")
|
||||
assert.Equal(t, "selected", svc.updateReq.Config.KBSelectionMode, "--kb on --from implies selected mode")
|
||||
@@ -222,7 +222,7 @@ func TestCreate_CopyAgent_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{copyErr: errBadHTTP404}
|
||||
opts := &CreateOptions{Name: "X", Model: "model-x", From: "ag_missing"}
|
||||
err := runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc)
|
||||
err := runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "resource.not_found")
|
||||
}
|
||||
|
||||
+10
-9
@@ -36,7 +36,7 @@ type deleteResult struct {
|
||||
// reserved for unlink-style local cleanups, not server-side resource removal.
|
||||
const agentDeleteLong = `Permanently delete a custom agent.
|
||||
|
||||
Prompts for confirmation by default when stdout is a TTY and --json is
|
||||
Prompts for confirmation by default when stdout is a TTY and --format json is
|
||||
not set. Pass -y/--yes (the global flag) to skip the prompt (required in
|
||||
agent / CI / piped contexts).
|
||||
|
||||
@@ -52,7 +52,7 @@ exactly to guard against unintended deletes.`
|
||||
|
||||
const agentDeleteExample = ` weknora agent delete ag_abc # interactive confirm
|
||||
weknora agent delete ag_abc -y # no prompt
|
||||
weknora agent delete ag_abc -y --json # bare {id, deleted:true} JSON`
|
||||
weknora agent delete ag_abc -y --format json # bare {id, deleted:true} JSON`
|
||||
|
||||
// NewCmdDelete builds `weknora agent delete <agent-id>`.
|
||||
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
||||
@@ -64,32 +64,33 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
||||
Example: agentDeleteExample,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(cmd)
|
||||
fopts, err := cmdutil.CheckFormatFlag(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
opts.AgentID = args[0]
|
||||
opts.Yes, _ = cmd.Flags().GetBool("yes")
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runDelete(cmd.Context(), opts, jopts, cli, f.Prompter())
|
||||
return runDelete(cmd.Context(), opts, fopts, cli, f.Prompter())
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, agentDeleteFields)
|
||||
cmdutil.AddFormatFlag(cmd, agentDeleteFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runDelete(ctx context.Context, opts *DeleteOptions, jopts *cmdutil.JSONOptions, svc DeleteService, p prompt.Prompter) error {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jopts.Enabled(), "agent", opts.AgentID); err != nil {
|
||||
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(), "agent", opts.AgentID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := svc.DeleteAgent(ctx, opts.AgentID); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete agent %s", opts.AgentID)
|
||||
}
|
||||
if jopts.Enabled() {
|
||||
return jopts.Emit(iostreams.IO.Out, deleteResult{ID: opts.AgentID, Deleted: true})
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: opts.AgentID, Deleted: true})
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted agent %s\n", opts.AgentID)
|
||||
return nil
|
||||
|
||||
@@ -28,7 +28,7 @@ func TestDelete_NonTTY_NoYes_ExitTen(t *testing.T) {
|
||||
err := runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_abc", Yes: false},
|
||||
&cmdutil.JSONOptions{}, svc, &testutil.ConfirmPrompter{},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, &testutil.ConfirmPrompter{},
|
||||
)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
@@ -44,7 +44,7 @@ func TestDelete_NonTTY_WithYes_Direct(t *testing.T) {
|
||||
require.NoError(t, runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_abc", Yes: true},
|
||||
nil, svc, &testutil.ConfirmPrompter{},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
))
|
||||
assert.Equal(t, "ag_abc", svc.gotID)
|
||||
assert.Contains(t, out.String(), "ag_abc")
|
||||
@@ -56,7 +56,7 @@ func TestDelete_404_PropagatesNotFound(t *testing.T) {
|
||||
err := runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_missing", Yes: true},
|
||||
nil, svc, &testutil.ConfirmPrompter{},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
@@ -71,7 +71,7 @@ func TestDelete_TTY_ConfirmYes(t *testing.T) {
|
||||
require.NoError(t, runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_abc"},
|
||||
nil, svc, p,
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p,
|
||||
))
|
||||
assert.True(t, p.Asked)
|
||||
assert.Equal(t, "ag_abc", svc.gotID)
|
||||
@@ -84,7 +84,7 @@ func TestDelete_TTY_ConfirmNo(t *testing.T) {
|
||||
err := runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_abc"},
|
||||
nil, svc, p,
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p,
|
||||
)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
@@ -100,7 +100,7 @@ func TestDelete_JSON_BareObject(t *testing.T) {
|
||||
require.NoError(t, runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_abc", Yes: true},
|
||||
&cmdutil.JSONOptions{}, svc, &testutil.ConfirmPrompter{},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, &testutil.ConfirmPrompter{},
|
||||
))
|
||||
assert.Contains(t, out.String(), `"id":"ag_abc"`)
|
||||
assert.Contains(t, out.String(), `"deleted":true`)
|
||||
|
||||
@@ -142,15 +142,16 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
||||
return nil
|
||||
},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(cmd)
|
||||
fopts, err := cmdutil.CheckFormatFlag(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runEdit(cmd.Context(), opts, jopts, cli)
|
||||
return runEdit(cmd.Context(), opts, fopts, cli)
|
||||
},
|
||||
}
|
||||
|
||||
@@ -171,7 +172,7 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
||||
// Full-replace
|
||||
cmd.Flags().StringVar(&configFile, "config-file", "", "Full AgentConfig YAML or JSON (REPLACES current config baseline; surgical flags then apply on top)")
|
||||
|
||||
cmdutil.AddJSONFlags(cmd, agentViewFields)
|
||||
cmdutil.AddFormatFlag(cmd, agentViewFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -185,7 +186,7 @@ func editHasAnyFlag(opts *EditOptions) bool {
|
||||
fl.addKBsSet || fl.removeKBsSet || fl.kbSelectionModeSet || fl.configFileSet
|
||||
}
|
||||
|
||||
func runEdit(ctx context.Context, opts *EditOptions, jopts *cmdutil.JSONOptions, svc EditService) error {
|
||||
func runEdit(ctx context.Context, opts *EditOptions, fopts *cmdutil.FormatOptions, svc EditService) error {
|
||||
if !editHasAnyFlag(opts) {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
@@ -260,14 +261,14 @@ func runEdit(ctx context.Context, opts *EditOptions, jopts *cmdutil.JSONOptions,
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "edit agent %s", opts.AgentID)
|
||||
}
|
||||
return emitAgent(jopts, updated)
|
||||
return emitAgent(fopts, updated)
|
||||
}
|
||||
|
||||
// computeKBList applies --add-kb / --remove-kb to current with idempotent
|
||||
// semantics. Ids present in both add and remove cancel out and surface a
|
||||
// stderr warning so users notice the conflict but don't see a hard error.
|
||||
// Stderr is the right channel here (not stdout) because callers piping
|
||||
// --json | jq would otherwise see corrupted JSON.
|
||||
// --format json | jq would otherwise see corrupted JSON.
|
||||
func computeKBList(current, add, remove []string) []string {
|
||||
// Detect ids in both add and remove; they net out to no-op and are
|
||||
// excluded from both operations.
|
||||
|
||||
+11
-11
@@ -54,7 +54,7 @@ func TestEdit_FetchThenUpdate_PreservesUntouchedFields(t *testing.T) {
|
||||
Description: "Updated",
|
||||
flags: editFlagSet{descriptionSet: true},
|
||||
}
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
require.NotNil(t, svc.updateReq)
|
||||
assert.Equal(t, "Original", svc.updateReq.Name, "Name must round-trip unchanged")
|
||||
assert.Equal(t, "Updated", svc.updateReq.Description)
|
||||
@@ -76,14 +76,14 @@ func TestEdit_AddRemoveKB_SameID_NetNoOpWithWarning(t *testing.T) {
|
||||
RemoveKBs: []string{"kb_b"},
|
||||
flags: editFlagSet{addKBsSet: true, removeKBsSet: true},
|
||||
}
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, []string{"kb_a"}, svc.updateReq.Config.KnowledgeBases, "net no-op preserves original list")
|
||||
assert.Contains(t, errBuf.String(), "cancel out", "warning emitted to stderr")
|
||||
}
|
||||
|
||||
func TestEdit_NoFlags_InvalidArgument(t *testing.T) {
|
||||
svc := &fakeEditSvc{}
|
||||
err := runEdit(context.Background(), &EditOptions{AgentID: "ag_abc"}, &cmdutil.JSONOptions{}, svc)
|
||||
err := runEdit(context.Background(), &EditOptions{AgentID: "ag_abc"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -102,7 +102,7 @@ func TestEdit_AddKB_AlreadyAttached_Silent(t *testing.T) {
|
||||
AddKBs: []string{"kb_a"}, // already attached
|
||||
flags: editFlagSet{addKBsSet: true},
|
||||
}
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, []string{"kb_a", "kb_b"}, svc.updateReq.Config.KnowledgeBases, "no duplicate")
|
||||
assert.NotContains(t, errBuf.String(), "warning", "already-attached is silent success")
|
||||
}
|
||||
@@ -118,7 +118,7 @@ func TestEdit_RemoveKB_Unattached_Silent(t *testing.T) {
|
||||
RemoveKBs: []string{"kb_zzz"},
|
||||
flags: editFlagSet{removeKBsSet: true},
|
||||
}
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, []string{"kb_a"}, svc.updateReq.Config.KnowledgeBases)
|
||||
assert.NotContains(t, errBuf.String(), "warning")
|
||||
}
|
||||
@@ -134,7 +134,7 @@ func TestEdit_ClearDescription_EmptyString(t *testing.T) {
|
||||
Description: "",
|
||||
flags: editFlagSet{descriptionSet: true},
|
||||
}
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, "", svc.updateReq.Description, "explicit empty must clear server-side")
|
||||
assert.Equal(t, "X", svc.updateReq.Name, "Name round-trip unchanged")
|
||||
}
|
||||
@@ -155,7 +155,7 @@ func TestEdit_ConfigFile_OverridesByFlag(t *testing.T) {
|
||||
ConfigFileKind: "json",
|
||||
flags: editFlagSet{temperatureSet: true, configFileSet: true},
|
||||
}
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
require.NotNil(t, svc.updateReq.Config)
|
||||
assert.Equal(t, "file-model", svc.updateReq.Config.ModelID, "file overrides current state")
|
||||
assert.InDelta(t, 0.9, svc.updateReq.Config.Temperature, 0.001, "flag overrides file")
|
||||
@@ -186,7 +186,7 @@ func TestEdit_ConfigFile_FullReplacesBaseline(t *testing.T) {
|
||||
ConfigFileKind: "json",
|
||||
flags: editFlagSet{configFileSet: true},
|
||||
}
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
require.NotNil(t, svc.updateReq.Config)
|
||||
assert.Equal(t, "file-only", svc.updateReq.Config.ModelID, "file's model_id applied")
|
||||
assert.Equal(t, "", svc.updateReq.Config.SystemPrompt, "file fully replaces baseline; unset fields are zeroed")
|
||||
@@ -199,7 +199,7 @@ func TestEdit_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeEditSvc{getErr: errBadHTTP404}
|
||||
opts := &EditOptions{AgentID: "ag_missing", Name: "x", flags: editFlagSet{nameSet: true}}
|
||||
err := runEdit(context.Background(), opts, &cmdutil.JSONOptions{}, svc)
|
||||
err := runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "resource.not_found")
|
||||
}
|
||||
@@ -215,7 +215,7 @@ func TestEdit_AddKB_AppendsToExisting(t *testing.T) {
|
||||
AddKBs: []string{"kb_b", "kb_c"},
|
||||
flags: editFlagSet{addKBsSet: true},
|
||||
}
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, []string{"kb_a", "kb_b", "kb_c"}, svc.updateReq.Config.KnowledgeBases)
|
||||
}
|
||||
|
||||
@@ -244,6 +244,6 @@ func TestEdit_SystemPromptFile(t *testing.T) {
|
||||
SystemPromptReader: strings.NewReader("new prompt\n"),
|
||||
flags: editFlagSet{systemPromptSet: true},
|
||||
}
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, "new prompt", svc.updateReq.Config.SystemPrompt)
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// agentListFields enumerates the fields surfaced for `--json` discovery
|
||||
// agentListFields enumerates the fields surfaced for `--format json` discovery
|
||||
// on `agent list`. Mirrors the json tags on sdk.Agent - nested Config is
|
||||
// omitted because its sub-fields make filtering noisy (use `--jq` instead).
|
||||
var agentListFields = []string{
|
||||
@@ -45,23 +45,24 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
Short: "List custom agents visible to the active tenant",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runList(c.Context(), opts, jopts, cli)
|
||||
return runList(c.Context(), opts, fopts, cli)
|
||||
},
|
||||
}
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (0 = no cap, 1..10000 = explicit)")
|
||||
cmdutil.AddJSONFlags(cmd, agentListFields)
|
||||
cmdutil.AddFormatFlag(cmd, agentListFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions, svc ListService) error {
|
||||
func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOptions, svc ListService) error {
|
||||
if opts == nil {
|
||||
opts = &ListOptions{}
|
||||
}
|
||||
@@ -88,8 +89,8 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
|
||||
items = items[:opts.Limit]
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return jopts.Emit(iostreams.IO.Out, items)
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, items)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
|
||||
+14
-13
@@ -25,7 +25,7 @@ func (f *fakeListSvc) ListAgents(_ context.Context) ([]sdk.Agent, error) {
|
||||
|
||||
func TestList_Empty_Human(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runList(context.Background(), &ListOptions{}, nil, &fakeListSvc{}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "(no agents)") {
|
||||
@@ -35,7 +35,7 @@ func TestList_Empty_Human(t *testing.T) {
|
||||
|
||||
func TestList_Empty_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.JSONOptions{}, &fakeListSvc{}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if got := strings.TrimSpace(out.String()); got != "[]" {
|
||||
@@ -50,7 +50,7 @@ func TestList_NonEmpty_Human_RendersColumns(t *testing.T) {
|
||||
{ID: "ag_a", Name: "Research", IsBuiltin: true, UpdatedAt: now.Add(-1 * time.Hour)},
|
||||
{ID: "ag_b", Name: "Triage", UpdatedAt: now.Add(-3 * 24 * time.Hour)},
|
||||
}
|
||||
if err := runList(context.Background(), &ListOptions{}, nil, &fakeListSvc{items: items}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -69,7 +69,7 @@ func TestList_NonEmpty_JSON_SortsByUpdatedAtDesc(t *testing.T) {
|
||||
{ID: "ag_new", Name: "new", UpdatedAt: now},
|
||||
{ID: "ag_mid", Name: "mid", UpdatedAt: now.Add(-1 * time.Hour)},
|
||||
}
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.JSONOptions{}, &fakeListSvc{items: items}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
var got []sdk.Agent
|
||||
@@ -87,21 +87,22 @@ func TestList_NonEmpty_JSON_SortsByUpdatedAtDesc(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_JSON_FieldFilter(t *testing.T) {
|
||||
func TestList_JSON_JQProjection(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
items := []sdk.Agent{
|
||||
{ID: "ag_x", Name: "Foo", Description: "long description"},
|
||||
}
|
||||
jopts := &cmdutil.JSONOptions{Fields: []string{"id", "name"}}
|
||||
if err := runList(context.Background(), &ListOptions{}, jopts, &fakeListSvc{items: items}); err != nil {
|
||||
// --jq is the canonical projection mechanism in v0.6+.
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".[] | {id, name}"}
|
||||
if err := runList(context.Background(), &ListOptions{}, fopts, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
var got []map[string]any
|
||||
var got map[string]any
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
if _, has := got[0]["description"]; has {
|
||||
t.Errorf("description should be filtered out: %+v", got[0])
|
||||
if _, has := got["description"]; has {
|
||||
t.Errorf("description should be filtered out: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,7 +122,7 @@ func makeAgents(n int) []sdk.Agent {
|
||||
|
||||
func TestList_Limit_CapsResults(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 5}, &cmdutil.JSONOptions{}, &fakeListSvc{items: makeAgents(20)}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 5}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: makeAgents(20)}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
got := strings.Count(out.String(), `"id":"ag_`)
|
||||
@@ -132,7 +133,7 @@ func TestList_Limit_CapsResults(t *testing.T) {
|
||||
|
||||
func TestList_Limit_Zero_NoCap(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 0}, &cmdutil.JSONOptions{}, &fakeListSvc{items: makeAgents(7)}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 0}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: makeAgents(7)}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
got := strings.Count(out.String(), `"id":"ag_`)
|
||||
@@ -143,7 +144,7 @@ func TestList_Limit_Zero_NoCap(t *testing.T) {
|
||||
|
||||
func TestList_Limit_Negative_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runList(context.Background(), &ListOptions{Limit: -1}, nil, &fakeListSvc{items: makeAgents(2)})
|
||||
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: makeAgents(2)})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for negative --limit")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// AgentStatusResult is the shallow health snapshot for `agent status <id>`.
|
||||
//
|
||||
// One HTTP call: reachable + model_id. For downstream KB reachability
|
||||
// verification use 'agent check <id>' (1 + N HTTP).
|
||||
//
|
||||
// model_reachable is intentionally OMITTED: the server has no per-agent
|
||||
// test endpoint, so we cannot verify model reachability from the agent
|
||||
// resource alone.
|
||||
type AgentStatusResult struct {
|
||||
ID string `json:"id"`
|
||||
Reachable bool `json:"reachable"`
|
||||
ModelID string `json:"model_id,omitempty"`
|
||||
}
|
||||
|
||||
// AgentStatusService is the narrow SDK surface needed for agent status.
|
||||
type AgentStatusService interface {
|
||||
GetAgent(ctx context.Context, id string) (*sdk.Agent, error)
|
||||
}
|
||||
|
||||
var agentStatusFields = []string{"id", "reachable", "model_id"}
|
||||
|
||||
func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "status <agent-id>",
|
||||
Short: "Show health status of a custom agent",
|
||||
Long: `Shallow health snapshot for an agent (1 HTTP call).
|
||||
|
||||
Returns: reachable / model_id.
|
||||
|
||||
For downstream KB reachability verification use 'weknora agent check <id>'
|
||||
(active verification, 1 + N HTTP). For full agent config / metadata use
|
||||
'weknora agent view <id>'.`,
|
||||
Example: ` weknora agent status ag_abc
|
||||
weknora agent status ag_abc --format json`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := runAgentStatus(c.Context(), cli, args[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return emitAgentStatus(res, fopts, iostreams.IO.Out)
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, agentStatusFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
// runAgentStatus is the testable core. Never errors for "agent not
|
||||
// reachable" — Reachable=false carries that signal.
|
||||
func runAgentStatus(ctx context.Context, svc AgentStatusService, id string) (*AgentStatusResult, error) {
|
||||
a, err := svc.GetAgent(ctx, id)
|
||||
if err != nil {
|
||||
return &AgentStatusResult{ID: id, Reachable: false}, nil
|
||||
}
|
||||
res := &AgentStatusResult{ID: a.ID, Reachable: true}
|
||||
if a.Config != nil {
|
||||
res.ModelID = a.Config.ModelID
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// emitAgentStatus renders res per --format. Mirrors emitStatus pattern from
|
||||
// cli/cmd/kb/status.go (C3).
|
||||
func emitAgentStatus(res *AgentStatusResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, res)
|
||||
case cmdutil.FormatText, "":
|
||||
return writeAgentStatusText(w, res)
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for agent status", fopts.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
func writeAgentStatusText(w io.Writer, res *AgentStatusResult) error {
|
||||
fmt.Fprintf(w, "ID: %s\n", res.ID)
|
||||
fmt.Fprintf(w, "Reachable: %v\n", res.Reachable)
|
||||
if !res.Reachable {
|
||||
return nil
|
||||
}
|
||||
if res.ModelID != "" {
|
||||
fmt.Fprintf(w, "Model: %s\n", res.ModelID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// compile-time check: SDK client satisfies AgentStatusService.
|
||||
var _ AgentStatusService = (*sdk.Client)(nil)
|
||||
@@ -0,0 +1,104 @@
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
type fakeAgentStatusSvc struct {
|
||||
agent *sdk.Agent
|
||||
agentErr error
|
||||
}
|
||||
|
||||
func (f *fakeAgentStatusSvc) GetAgent(_ context.Context, id string) (*sdk.Agent, error) {
|
||||
if f.agentErr != nil {
|
||||
return nil, f.agentErr
|
||||
}
|
||||
return f.agent, nil
|
||||
}
|
||||
|
||||
func TestRunAgentStatus_ShallowFields(t *testing.T) {
|
||||
svc := &fakeAgentStatusSvc{agent: &sdk.Agent{
|
||||
ID: "ag_x",
|
||||
Config: &sdk.AgentConfig{
|
||||
ModelID: "m_x",
|
||||
KnowledgeBases: []string{"kb_a", "kb_b"},
|
||||
},
|
||||
}}
|
||||
res, err := runAgentStatus(context.Background(), svc, "ag_x")
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
if !res.Reachable {
|
||||
t.Error("Reachable=false, want true")
|
||||
}
|
||||
if res.ModelID != "m_x" {
|
||||
t.Errorf("ModelID=%q, want m_x", res.ModelID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunAgentStatus_Unreachable(t *testing.T) {
|
||||
svc := &fakeAgentStatusSvc{agentErr: fmt.Errorf("404")}
|
||||
res, err := runAgentStatus(context.Background(), svc, "ag_x")
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
if res.Reachable {
|
||||
t.Error("Reachable=true on 404; want false")
|
||||
}
|
||||
if res.ID != "ag_x" {
|
||||
t.Errorf("ID=%q, want ag_x (echoed even on unreachable)", res.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunAgentStatus_NilConfig(t *testing.T) {
|
||||
// Defensive: Agent.Config is a pointer; nil should not panic
|
||||
svc := &fakeAgentStatusSvc{agent: &sdk.Agent{ID: "ag_x", Config: nil}}
|
||||
res, err := runAgentStatus(context.Background(), svc, "ag_x")
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
if !res.Reachable {
|
||||
t.Error("Reachable=false, want true on nil config")
|
||||
}
|
||||
if res.ModelID != "" {
|
||||
t.Errorf("ModelID=%q, want empty (no config)", res.ModelID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitAgentStatus_JSON(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
res := &AgentStatusResult{ID: "ag_x", Reachable: true, ModelID: "m_x"}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
|
||||
if err := emitAgentStatus(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
var got AgentStatusResult
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
if got.ModelID != "m_x" {
|
||||
t.Errorf("ModelID=%q, want m_x", got.ModelID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitAgentStatus_TextHuman(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
res := &AgentStatusResult{ID: "ag_x", Reachable: true, ModelID: "m_x"}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
if err := emitAgentStatus(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
for _, want := range []string{"ag_x", "m_x", "true"} {
|
||||
if !strings.Contains(buf.String(), want) {
|
||||
t.Errorf("output missing %q:\n%s", want, buf.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-17
@@ -19,13 +19,10 @@ import (
|
||||
// full multi-line treatment instead.
|
||||
const promptPreviewWidth = 80
|
||||
|
||||
// agentViewFields enumerates fields surfaced for `--json=` field discovery
|
||||
// on `agent view`. Only top-level Agent keys are listed because the
|
||||
// `--json=foo,bar` field-projection filter matches flat top-level keys
|
||||
// (see internal/format/filter.go). Nested AgentConfig fields are reachable
|
||||
// agentViewFields enumerates the top-level Agent keys surfaced in `--help`
|
||||
// as a hint for `--jq` projection. Nested AgentConfig fields are reachable
|
||||
// via `--jq '.config.system_prompt'` or by selecting `config` whole and
|
||||
// post-processing — listing them here would misleadingly advertise a
|
||||
// projection path that does not actually filter to them.
|
||||
// post-processing.
|
||||
var agentViewFields = []string{
|
||||
"id", "name", "description", "avatar",
|
||||
"is_builtin", "tenant_id", "created_by", "config",
|
||||
@@ -47,36 +44,36 @@ sections (Identity / LLM / KB attachment / Retrieval / Query rewrite /
|
||||
Tools / FAQ / Web search / Multi-turn / Fallback / Templates). Zero-value
|
||||
fields are omitted; sections with no set fields are suppressed entirely.
|
||||
|
||||
Pass --json for the bare SDK Agent object (config nested, not flattened).
|
||||
Field projection (--json=id,name) works on top-level keys only; reach
|
||||
nested config fields via --jq.`,
|
||||
Pass --format json for the bare SDK Agent object (config nested, not flattened).
|
||||
Use --jq to project specific fields or reach into nested config.`,
|
||||
Example: ` weknora agent view ag_abc
|
||||
weknora agent view ag_abc --json=id,name,config # top-level projection
|
||||
weknora agent view ag_abc --json --jq '.config.system_prompt'`,
|
||||
weknora agent view ag_abc --format json --jq '{id, name, config}' # top-level projection
|
||||
weknora agent view ag_abc --format json --jq '.config.system_prompt'`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runView(c.Context(), jopts, cli, args[0])
|
||||
return runView(c.Context(), fopts, cli, args[0])
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, agentViewFields)
|
||||
cmdutil.AddFormatFlag(cmd, agentViewFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runView(ctx context.Context, jopts *cmdutil.JSONOptions, svc ViewService, agentID string) error {
|
||||
func runView(ctx context.Context, fopts *cmdutil.FormatOptions, svc ViewService, agentID string) error {
|
||||
a, err := svc.GetAgent(ctx, agentID)
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "fetch agent %s", agentID)
|
||||
}
|
||||
if jopts.Enabled() {
|
||||
return jopts.Emit(iostreams.IO.Out, a)
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, a)
|
||||
}
|
||||
renderAgent(iostreams.IO.Out, a)
|
||||
return nil
|
||||
|
||||
@@ -41,7 +41,7 @@ func TestView_Human_RendersMetadataAndConfig(t *testing.T) {
|
||||
WebSearchEnabled: true,
|
||||
},
|
||||
}}
|
||||
if err := runView(context.Background(), nil, svc, "ag_abc"); err != nil {
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_abc"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -52,12 +52,9 @@ func TestView_Human_RendersMetadataAndConfig(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestAgentViewFields_TopLevelOnly pins the contract that `--json=` field
|
||||
// discovery on `agent view` only lists top-level Agent keys (including
|
||||
// `config` as a whole). Nested AgentConfig fields are NOT in the list
|
||||
// because the filter at internal/format/filter.go matches flat top-level
|
||||
// keys only — listing `config.system_prompt` etc. would advertise a
|
||||
// projection path that silently returns nothing.
|
||||
// TestAgentViewFields_TopLevelOnly pins the contract that the field-hint
|
||||
// list on `agent view` only lists top-level Agent keys (including `config`
|
||||
// as a whole). Nested AgentConfig fields are reachable via --jq.
|
||||
func TestAgentViewFields_TopLevelOnly(t *testing.T) {
|
||||
for _, want := range []string{"id", "name", "config", "created_at"} {
|
||||
if !slices.Contains(agentViewFields, want) {
|
||||
@@ -66,7 +63,7 @@ func TestAgentViewFields_TopLevelOnly(t *testing.T) {
|
||||
}
|
||||
for _, dotted := range []string{"config.system_prompt", "config.model_id", "config.fallback_strategy"} {
|
||||
if slices.Contains(agentViewFields, dotted) {
|
||||
t.Errorf("agentViewFields must not list dotted nested key %q (filter does not support nested projection)", dotted)
|
||||
t.Errorf("agentViewFields must not list dotted nested key %q (the --jq projection path handles nesting directly)", dotted)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,7 +126,7 @@ func TestView_Human_OmitsEmptyFields(t *testing.T) {
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}}
|
||||
if err := runView(context.Background(), nil, svc, "ag_min"); err != nil {
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_min"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -150,7 +147,7 @@ func TestView_Human_OmitsEmptyFields(t *testing.T) {
|
||||
func TestView_JSON_BareObject(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{resp: &sdk.Agent{ID: "ag_json", Name: "JSONy"}}
|
||||
if err := runView(context.Background(), &cmdutil.JSONOptions{}, svc, "ag_json"); err != nil {
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "ag_json"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
var got sdk.Agent
|
||||
@@ -168,7 +165,7 @@ func TestView_JSON_BareObject(t *testing.T) {
|
||||
func TestView_404_MapsToResourceNotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{err: errors.New("HTTP error 404: agent not found")}
|
||||
err := runView(context.Background(), nil, svc, "ag_missing")
|
||||
err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_missing")
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user