feat(cli): --json field-select, --jq, auth token, doc --from-url

Output ergonomics:
- `--json` accepts a comma-separated field list (gh-parity); selects
  named keys from the per-command payload. Bare `--json` keeps the
  full shape.
- `--jq <expr>` evaluates a gojq expression over the JSON; pairs with
  `--json field-list` so projection runs before jq.
- `--version` is a global cobra flag in addition to the `version`
  subcommand; both render the same line.
- Per-command `--help` now renders the available JSON field list under
  "JSON fields available via `--json id,name,...`" (field-discovery
  parity with gh / kubectl `-o jsonpath`).

New commands:
- `auth token` — print the active context's credential to stdout for
  shell command substitution (`WEKNORA_TOKEN=$(weknora auth token)`).
  Default: raw secret, no trailing newline. `--json` emits
  `{token, mode, context}`.
- `doc upload --from-url <URL>` — ingest a remote URL via the SDK
  `CreateKnowledgeFromURL`. `--name` forwarded as `FileName` so the
  server's known-extension heuristic upgrades crawl-mode to
  file-download-mode where appropriate.

Includes the simplify post-review polish pass (field-filter unit
tests, --json/--jq compose check, agent_help copy fixes).
This commit is contained in:
nullkey
2026-05-14 23:28:14 +08:00
committed by lyingbug
parent 4fb089d4d7
commit 1b20b06f5e
81 changed files with 2351 additions and 642 deletions
+27 -6
View File
@@ -14,6 +14,15 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// chunksFields enumerates the fields surfaced for `--json` discovery on
// `search chunks`. Lists data.items[*] (SearchResult) fields.
var chunksFields = []string{
"id", "content", "knowledge_id", "chunk_index", "knowledge_title",
"start_at", "end_at", "seq", "score", "match_type", "chunk_type",
"image_info", "metadata", "knowledge_filename", "knowledge_source",
"knowledge_channel", "matched_content",
}
type ChunksOptions struct {
Query string
KB string // raw --kb (UUID or name)
@@ -23,7 +32,11 @@ type ChunksOptions struct {
KeywordThreshold float64
NoVector bool
NoKeyword bool
JSONOut bool
}
// chunksResult is the typed payload emitted under data.items.
type chunksResult struct {
Items []*sdk.SearchResult `json:"items"`
}
// ChunksService is the narrow SDK surface used by runChunks. *sdk.Client
@@ -54,6 +67,10 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
if opts.Limit < 1 || opts.Limit > 1000 {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--limit must be between 1 and 1000")
}
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
@@ -63,7 +80,7 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
return err
}
opts.KBID = kbID
return runChunks(c.Context(), opts, cli)
return runChunks(c.Context(), opts, jopts, cli)
},
}
bindChunksFlags(cmd, opts)
@@ -81,7 +98,7 @@ func bindChunksFlags(cmd *cobra.Command, opts *ChunksOptions) {
cmd.Flags().Float64Var(&opts.KeywordThreshold, "keyword-threshold", 0, "Keyword retrieval score floor (per-channel, pre-fusion); 0 = no filter")
cmd.Flags().BoolVar(&opts.NoVector, "no-vector", false, "Disable the vector channel")
cmd.Flags().BoolVar(&opts.NoKeyword, "no-keyword", false, "Disable the keyword channel")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmdutil.AddJSONFlags(cmd, chunksFields)
}
// validate checks the option set before any SDK call. Limit bounds are
@@ -97,7 +114,7 @@ func (o *ChunksOptions) validate() error {
return nil
}
func runChunks(ctx context.Context, opts *ChunksOptions, svc ChunksService) error {
func runChunks(ctx context.Context, opts *ChunksOptions, jopts *cmdutil.JSONOptions, svc ChunksService) error {
if err := opts.validate(); err != nil {
return err
}
@@ -127,8 +144,12 @@ func runChunks(ctx context.Context, opts *ChunksOptions, svc ChunksService) erro
results = results[:opts.Limit]
}
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out, format.Success(results, &format.Meta{KBID: opts.KBID}))
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(
iostreams.IO.Out,
format.Success(chunksResult{Items: results}, &format.Meta{KBID: opts.KBID}),
jopts.Fields, jopts.JQ,
)
}
return renderChunkResults(results, opts.KBID)
}
+12 -12
View File
@@ -34,7 +34,7 @@ func TestRunSearch_HumanOutput(t *testing.T) {
{Score: 0.81, Content: "second chunk", KnowledgeID: "doc-2", MatchType: sdk.MatchTypeKeyword},
}}
opts := &ChunksOptions{Query: "hello", KBID: "kb_abc", Limit: 5}
require.NoError(t, runChunks(context.Background(), opts, svc))
require.NoError(t, runChunks(context.Background(), opts, nil, svc))
assert.Equal(t, "kb_abc", svc.gotKB)
assert.Equal(t, "hello", svc.gotQ)
@@ -52,15 +52,15 @@ func TestRunSearch_JSONIncludesMatchType(t *testing.T) {
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
{Score: 0.9, Content: "x", MatchType: sdk.MatchTypeKeyword},
}}
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", JSONOut: true}, svc))
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.JSONOptions{}, svc))
assert.Contains(t, out.String(), `"match_type":1`)
}
func TestRunSearch_JSONOutput(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChunksSvc{results: []*sdk.SearchResult{{Score: 0.9, Content: "x"}}}
opts := &ChunksOptions{Query: "q", KBID: "kb1", Limit: 1, JSONOut: true}
require.NoError(t, runChunks(context.Background(), opts, svc))
opts := &ChunksOptions{Query: "q", KBID: "kb1", Limit: 1}
require.NoError(t, runChunks(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
assert.True(t, strings.HasPrefix(out.String(), `{"ok":true`), "got: %q", out.String())
assert.Contains(t, out.String(), `"kb_id":"kb1"`)
}
@@ -68,7 +68,7 @@ func TestRunSearch_JSONOutput(t *testing.T) {
func TestRunSearch_EmptyResults(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChunksSvc{results: nil}
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, svc))
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, nil, svc))
assert.Contains(t, out.String(), "(no results)")
}
@@ -84,7 +84,7 @@ func TestRunSearch_LimitHardCap(t *testing.T) {
{Score: 0, Content: "enrichment parent"}, // server-padded
{Score: 0, Content: "enrichment nearby"}, // server-padded
}}
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", Limit: 3}, svc))
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", Limit: 3}, nil, svc))
got := out.String()
assert.Contains(t, got, "3 result(s)")
assert.NotContains(t, got, "enrichment parent")
@@ -93,7 +93,7 @@ func TestRunSearch_LimitHardCap(t *testing.T) {
func TestRunSearch_BothChannelsDisabled(t *testing.T) {
iostreams.SetForTest(t)
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", NoVector: true, NoKeyword: true}, &fakeChunksSvc{})
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", NoVector: true, NoKeyword: true}, nil, &fakeChunksSvc{})
require.Error(t, err)
assert.Contains(t, err.Error(), "input.invalid_argument")
}
@@ -101,7 +101,7 @@ func TestRunSearch_BothChannelsDisabled(t *testing.T) {
func TestRunSearch_ServiceError_Transport(t *testing.T) {
iostreams.SetForTest(t)
svc := &fakeChunksSvc{err: assert.AnError}
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, svc)
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, nil, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -112,7 +112,7 @@ func TestRunSearch_ServiceError_Transport(t *testing.T) {
func TestRunSearch_ServiceError_HTTPNotFound(t *testing.T) {
iostreams.SetForTest(t)
svc := &fakeChunksSvc{err: errors.New("HTTP error 404: knowledge base not found")}
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "missing"}, svc)
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "missing"}, nil, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -126,7 +126,7 @@ func TestIndent(t *testing.T) {
func TestRunSearch_NilService(t *testing.T) {
iostreams.SetForTest(t)
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, nil)
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, nil, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "server.error")
}
@@ -162,7 +162,7 @@ func TestRunSearch_NoVectorPassedThrough(t *testing.T) {
svc := &capturingChunksSvc{capture: func(p *sdk.SearchParams) { got = p }}
require.NoError(t, runChunks(context.Background(), &ChunksOptions{
Query: "q", KBID: "kb1", NoVector: true,
}, svc))
}, nil, svc))
require.NotNil(t, got)
assert.True(t, got.DisableVectorMatch)
assert.False(t, got.DisableKeywordsMatch)
@@ -174,7 +174,7 @@ func TestRunSearch_NoKeywordPassedThrough(t *testing.T) {
svc := &capturingChunksSvc{capture: func(p *sdk.SearchParams) { got = p }}
require.NoError(t, runChunks(context.Background(), &ChunksOptions{
Query: "q", KBID: "kb1", NoKeyword: true,
}, svc))
}, nil, svc))
require.NotNil(t, got)
assert.True(t, got.DisableKeywordsMatch)
assert.False(t, got.DisableVectorMatch)
+35 -10
View File
@@ -22,12 +22,26 @@ import (
// 1000 (per the doc/list bound this branch already added).
const docsPageSize = 200
// docsFields enumerates the fields surfaced for `--json` discovery on
// `search docs`. Mirrors sdk.Knowledge json tags.
var docsFields = []string{
"id", "tenant_id", "knowledge_base_id", "tag_id", "type", "title",
"description", "source", "channel", "parse_status", "summary_status",
"enable_status", "embedding_model_id", "file_name", "file_type",
"file_size", "file_hash", "file_path", "storage_size", "metadata",
"created_at", "updated_at", "processed_at", "error_message",
}
type DocsSearchOptions struct {
Query string
KB string // raw --kb (UUID or name)
KBID string // resolved id; populated before listing
Limit int
JSONOut bool
Query string
KB string // raw --kb (UUID or name)
KBID string // resolved id; populated before listing
Limit int
}
// docsResult is the typed payload emitted under data.items.
type docsResult struct {
Items []sdk.Knowledge `json:"items"`
}
// DocsSearchService is the narrow SDK surface this command depends on.
@@ -57,6 +71,10 @@ func NewCmdDocs(f *cmdutil.Factory) *cobra.Command {
if opts.Limit < 1 || opts.Limit > 1000 {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--limit must be between 1 and 1000")
}
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
@@ -66,18 +84,18 @@ func NewCmdDocs(f *cmdutil.Factory) *cobra.Command {
return err
}
opts.KBID = kbID
return runDocsSearch(c.Context(), opts, cli)
return runDocsSearch(c.Context(), opts, jopts, cli)
},
}
cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name (required)")
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 20, "Maximum results to return")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmdutil.AddJSONFlags(cmd, docsFields)
_ = cmd.MarkFlagRequired("kb")
agent.SetAgentHelp(cmd, "Lists documents in --kb whose title or file_name contains the query. Pages through the KB sequentially; stops once limit hits found. Returns the full Knowledge object so agents can derive id / file_size / processed_at without a second call.")
return cmd
}
func runDocsSearch(ctx context.Context, opts *DocsSearchOptions, svc DocsSearchService) error {
func runDocsSearch(ctx context.Context, opts *DocsSearchOptions, jopts *cmdutil.JSONOptions, svc DocsSearchService) error {
needle := strings.ToLower(opts.Query)
var matches []sdk.Knowledge
@@ -103,8 +121,15 @@ func runDocsSearch(ctx context.Context, opts *DocsSearchOptions, svc DocsSearchS
done:
sortKnowledgeByRecency(matches)
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out, format.Success(matches, &format.Meta{KBID: opts.KBID}))
if jopts.Enabled() {
if matches == nil {
matches = []sdk.Knowledge{}
}
return format.WriteEnvelopeFiltered(
iostreams.IO.Out,
format.Success(docsResult{Items: matches}, &format.Meta{KBID: opts.KBID}),
jopts.Fields, jopts.JQ,
)
}
if len(matches) == 0 {
fmt.Fprintln(iostreams.IO.Out, "(no matches)")
+6 -6
View File
@@ -45,7 +45,7 @@ func TestDocsSearch_Substring(t *testing.T) {
},
total: 3,
}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "q3", KBID: "kb1", Limit: 20}, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "q3", KBID: "kb1", Limit: 20}, nil, svc))
got := out.String()
assert.Contains(t, got, "d1")
assert.Contains(t, got, "d3")
@@ -58,7 +58,7 @@ func TestDocsSearch_MatchesFileName(t *testing.T) {
pages: map[int][]sdk.Knowledge{1: {{ID: "d1", Title: "Untitled", FileName: "report.pdf"}}},
total: 1,
}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "report", KBID: "kb1", Limit: 20}, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "report", KBID: "kb1", Limit: 20}, nil, svc))
assert.Contains(t, out.String(), "d1")
}
@@ -73,7 +73,7 @@ func TestDocsSearch_PaginatesUntilTotal(t *testing.T) {
pages: map[int][]sdk.Knowledge{1: page1, 2: page2},
total: int64(docsPageSize) + 1,
}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 20}, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 20}, nil, svc))
assert.Contains(t, out.String(), "found")
assert.Equal(t, []int{1, 2}, svc.calls, "must page past the first batch when no match on page 1")
}
@@ -85,7 +85,7 @@ func TestDocsSearch_StopsAtLimit(t *testing.T) {
page1[i] = sdk.Knowledge{ID: "match", Title: "needle"}
}
svc := &fakeDocsSearchSvc{pages: map[int][]sdk.Knowledge{1: page1}, total: 1000}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3}, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3}, nil, svc))
// Must not request page 2 because limit was hit mid-page.
assert.Equal(t, []int{1}, svc.calls)
}
@@ -96,7 +96,7 @@ func TestDocsSearch_JSON(t *testing.T) {
pages: map[int][]sdk.Knowledge{1: {{ID: "d1", Title: "match"}}},
total: 1,
}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "match", KBID: "kb1", Limit: 20, JSONOut: true}, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "match", KBID: "kb1", Limit: 20}, &cmdutil.JSONOptions{}, svc))
var env format.Envelope
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
require.True(t, env.OK)
@@ -106,7 +106,7 @@ func TestDocsSearch_JSON(t *testing.T) {
func TestDocsSearch_NetworkError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDocsSearchSvc{err: errors.New("HTTP error 404: kb not found")}
err := runDocsSearch(context.Background(), &DocsSearchOptions{Query: "x", KBID: "missing", Limit: 20}, svc)
err := runDocsSearch(context.Background(), &DocsSearchOptions{Query: "x", KBID: "missing", Limit: 20}, nil, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
+34 -8
View File
@@ -17,10 +17,25 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// kbSearchFields enumerates the fields surfaced for `--json` discovery on
// `search kb`. Subset of KnowledgeBase suitable for list/filter results.
var kbSearchFields = []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 KBSearchOptions struct {
Query string
Limit int
JSONOut bool
Query string
Limit int
}
// kbSearchResult is the typed payload emitted under data.items.
type kbSearchResult struct {
Items []sdk.KnowledgeBase `json:"items"`
}
// KBSearchService is the narrow SDK surface this command depends on.
@@ -50,20 +65,24 @@ func NewCmdKB(f *cmdutil.Factory) *cobra.Command {
if opts.Limit < 1 || opts.Limit > 1000 {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--limit must be between 1 and 1000")
}
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
return runKBSearch(c.Context(), opts, cli)
return runKBSearch(c.Context(), opts, jopts, cli)
},
}
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 20, "Maximum results to return")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmdutil.AddJSONFlags(cmd, kbSearchFields)
agent.SetAgentHelp(cmd, "Lists KBs whose name or description contains the query (case-insensitive). Useful to discover --kb identifiers before running search chunks / doc list.")
return cmd
}
func runKBSearch(ctx context.Context, opts *KBSearchOptions, svc KBSearchService) error {
func runKBSearch(ctx context.Context, opts *KBSearchOptions, jopts *cmdutil.JSONOptions, svc KBSearchService) error {
items, err := svc.ListKnowledgeBases(ctx)
if err != nil {
return cmdutil.WrapHTTP(err, "list knowledge bases")
@@ -73,8 +92,15 @@ func runKBSearch(ctx context.Context, opts *KBSearchOptions, svc KBSearchService
matches = matches[:opts.Limit]
}
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out, format.Success(matches, nil))
if jopts.Enabled() {
if matches == nil {
matches = []sdk.KnowledgeBase{}
}
return format.WriteEnvelopeFiltered(
iostreams.IO.Out,
format.Success(kbSearchResult{Items: matches}, nil),
jopts.Fields, jopts.JQ,
)
}
if len(matches) == 0 {
fmt.Fprintln(iostreams.IO.Out, "(no matches)")
+8 -8
View File
@@ -32,7 +32,7 @@ func TestKBSearch_Substring(t *testing.T) {
{ID: "kb2", Name: "Engineering Docs", KnowledgeCount: 50},
{ID: "kb3", Name: "Marketing Q4 Plan", KnowledgeCount: 5},
}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, nil, svc))
got := out.String()
assert.Contains(t, got, "kb1")
assert.Contains(t, got, "kb3")
@@ -44,7 +44,7 @@ func TestKBSearch_CaseInsensitive(t *testing.T) {
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{
{ID: "kb1", Name: "ENGINEERING"},
}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "engineering", Limit: 20}, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "engineering", Limit: 20}, nil, svc))
assert.Contains(t, out.String(), "kb1")
}
@@ -53,7 +53,7 @@ func TestKBSearch_MatchesDescription(t *testing.T) {
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{
{ID: "kb1", Name: "Engineering", Description: "all marketing docs are here"},
}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, nil, svc))
assert.Contains(t, out.String(), "kb1")
}
@@ -64,7 +64,7 @@ func TestKBSearch_SortByNameLength(t *testing.T) {
{ID: "kb_short", Name: "marketing"},
{ID: "kb_mid", Name: "marketing 2024"},
}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, nil, svc))
got := out.String()
// Order: shortest name first.
iShort := strings.Index(got,"kb_short")
@@ -80,7 +80,7 @@ func TestKBSearch_LimitHardCap(t *testing.T) {
{ID: "a", Name: "match-a"}, {ID: "b", Name: "match-b"},
{ID: "c", Name: "match-c"}, {ID: "d", Name: "match-d"},
}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "match", Limit: 2}, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "match", Limit: 2}, nil, svc))
got := out.String()
count := 0
for _, id := range []string{"a", "b", "c", "d"} {
@@ -94,14 +94,14 @@ func TestKBSearch_LimitHardCap(t *testing.T) {
func TestKBSearch_NoMatches(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{{Name: "foo"}}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "bar", Limit: 20}, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "bar", Limit: 20}, nil, svc))
assert.Contains(t, out.String(), "(no matches)")
}
func TestKBSearch_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{{ID: "kb1", Name: "marketing"}}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20, JSONOut: true}, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.JSONOptions{}, svc))
var env format.Envelope
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
@@ -112,7 +112,7 @@ func TestKBSearch_JSON(t *testing.T) {
func TestKBSearch_NetworkError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeKBSearchSvc{err: errors.New("HTTP error 401: unauthenticated")}
err := runKBSearch(context.Background(), &KBSearchOptions{Query: "x", Limit: 20}, svc)
err := runKBSearch(context.Background(), &KBSearchOptions{Query: "x", Limit: 20}, nil, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
+29 -8
View File
@@ -19,10 +19,20 @@ import (
const sessionsPageSize = 200
// sessionsSearchFields enumerates the fields surfaced for `--json` discovery
// on `search sessions`. Mirrors sdk.Session json tags.
var sessionsSearchFields = []string{
"id", "tenant_id", "title", "description", "created_at", "updated_at",
}
type SessionsSearchOptions struct {
Query string
Limit int
JSONOut bool
Query string
Limit int
}
// sessionsSearchResult is the typed payload emitted under data.items.
type sessionsSearchResult struct {
Items []sdk.Session `json:"items"`
}
// SessionsSearchService is the narrow SDK surface this command depends on.
@@ -50,20 +60,24 @@ func NewCmdSessions(f *cmdutil.Factory) *cobra.Command {
if opts.Limit < 1 || opts.Limit > 1000 {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--limit must be between 1 and 1000")
}
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
return runSessionsSearch(c.Context(), opts, cli)
return runSessionsSearch(c.Context(), opts, jopts, cli)
},
}
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 20, "Maximum results to return")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmdutil.AddJSONFlags(cmd, sessionsSearchFields)
agent.SetAgentHelp(cmd, "Lists chat sessions whose title or description contains the query. Pages through the tenant sequentially; stops once limit matches found. Returns full Session objects so agents can pivot to session view/delete by id.")
return cmd
}
func runSessionsSearch(ctx context.Context, opts *SessionsSearchOptions, svc SessionsSearchService) error {
func runSessionsSearch(ctx context.Context, opts *SessionsSearchOptions, jopts *cmdutil.JSONOptions, svc SessionsSearchService) error {
needle := strings.ToLower(opts.Query)
var matches []sdk.Session
@@ -87,8 +101,15 @@ func runSessionsSearch(ctx context.Context, opts *SessionsSearchOptions, svc Ses
done:
sortSessionsByRecency(matches)
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out, format.Success(matches, nil))
if jopts.Enabled() {
if matches == nil {
matches = []sdk.Session{}
}
return format.WriteEnvelopeFiltered(
iostreams.IO.Out,
format.Success(sessionsSearchResult{Items: matches}, nil),
jopts.Fields, jopts.JQ,
)
}
if len(matches) == 0 {
fmt.Fprintln(iostreams.IO.Out, "(no matches)")
+4 -4
View File
@@ -38,7 +38,7 @@ func TestSessionsSearch_TitleAndDescription(t *testing.T) {
}},
total: 3,
}
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "design", Limit: 20}, svc))
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "design", Limit: 20}, nil, svc))
got := out.String()
assert.Contains(t, got, "s1")
assert.Contains(t, got, "s2")
@@ -51,7 +51,7 @@ func TestSessionsSearch_NoMatches(t *testing.T) {
pages: map[int][]sdk.Session{1: {{Title: "foo"}}},
total: 1,
}
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "missing", Limit: 20}, svc))
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "missing", Limit: 20}, nil, svc))
assert.Contains(t, out.String(), "(no matches)")
}
@@ -62,14 +62,14 @@ func TestSessionsSearch_PaginatesAndStopsAtLimit(t *testing.T) {
page1[i] = sdk.Session{ID: "m", Title: "needle"}
}
svc := &fakeSessionsSearchSvc{pages: map[int][]sdk.Session{1: page1}, total: 1000}
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 5}, svc))
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 5}, nil, svc))
assert.Equal(t, []int{1}, svc.calls, "stops paging when limit reached")
}
func TestSessionsSearch_NetworkError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeSessionsSearchSvc{err: errors.New("HTTP error 500: internal")}
err := runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "x", Limit: 20}, svc)
err := runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "x", Limit: 20}, nil, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)