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
+22 -13
View File
@@ -13,10 +13,13 @@ import (
"github.com/Tencent/WeKnora/cli/internal/prompt"
)
// sessionDeleteFields enumerates the fields surfaced for `--json` discovery on
// `session delete`. Tracks the small result struct.
var sessionDeleteFields = []string{"id", "deleted"}
type DeleteOptions struct {
Yes bool // sourced from the global -y/--yes persistent flag
JSONOut bool
DryRun bool
Yes bool // sourced from the global -y/--yes persistent flag
DryRun bool
}
// DeleteService is the narrow SDK surface this command depends on.
@@ -52,30 +55,34 @@ without the user's explicit go-ahead.`,
RunE: func(c *cobra.Command, args []string) error {
opts.Yes, _ = c.Flags().GetBool("yes")
opts.DryRun = cmdutil.IsDryRun(c)
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
if opts.DryRun {
return runDelete(c.Context(), opts, nil, f.Prompter(), args[0])
return runDelete(c.Context(), opts, jopts, nil, f.Prompter(), args[0])
}
cli, err := f.Client()
if err != nil {
return err
}
return runDelete(c.Context(), opts, cli, f.Prompter(), args[0])
return runDelete(c.Context(), opts, jopts, cli, f.Prompter(), args[0])
},
}
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmdutil.AddJSONFlags(cmd, sessionDeleteFields)
agent.SetAgentHelp(cmd, "Destructively deletes a chat session by id. ALWAYS pass -y/--yes in agent mode (no TTY ⇒ confirm prompt fails). Returns data: {id, deleted:true}.")
return cmd
}
func runDelete(ctx context.Context, opts *DeleteOptions, svc DeleteService, p prompt.Prompter, id string) error {
func runDelete(ctx context.Context, opts *DeleteOptions, jopts *cmdutil.JSONOptions, svc DeleteService, p prompt.Prompter, id string) error {
risk := &format.Risk{Level: format.RiskHighRiskWrite, Action: fmt.Sprintf("delete session %s", id)}
if opts.DryRun {
return cmdutil.EmitDryRun(opts.JSONOut,
return cmdutil.EmitDryRun(jopts.Enabled(),
deleteResult{ID: id, Deleted: false}, nil, risk)
}
if err := cmdutil.ConfirmDestructive(p, opts.Yes, opts.JSONOut, "session", id); err != nil {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jopts.Enabled(), "session", id); err != nil {
return err
}
@@ -83,10 +90,12 @@ func runDelete(ctx context.Context, opts *DeleteOptions, svc DeleteService, p pr
return cmdutil.WrapHTTP(err, "delete session %s", id)
}
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(
deleteResult{ID: id, Deleted: true}, nil, risk,
))
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(
iostreams.IO.Out,
format.SuccessWithRisk(deleteResult{ID: id, Deleted: true}, nil, risk),
jopts.Fields, jopts.JQ,
)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted session %s\n", id)
return nil
+6 -6
View File
@@ -31,7 +31,7 @@ func TestDelete_WithYes(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{}
require.NoError(t, runDelete(context.Background(), &DeleteOptions{Yes: true}, svc, p, "s_abc"))
require.NoError(t, runDelete(context.Background(), &DeleteOptions{Yes: true}, nil, svc, p, "s_abc"))
assert.True(t, svc.called)
assert.Equal(t, "s_abc", svc.gotID)
assert.False(t, p.Asked, "-y must skip prompt")
@@ -41,7 +41,7 @@ func TestDelete_WithYes(t *testing.T) {
func TestDelete_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDeleteSvc{err: errors.New("HTTP error 404: not found")}
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, svc, &testutil.ConfirmPrompter{}, "s_missing")
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, nil, svc, &testutil.ConfirmPrompter{}, "s_missing")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -51,7 +51,7 @@ func TestDelete_NotFound(t *testing.T) {
func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
err := runDelete(context.Background(), &DeleteOptions{}, svc, &testutil.ConfirmPrompter{}, "s_x")
err := runDelete(context.Background(), &DeleteOptions{}, nil, svc, &testutil.ConfirmPrompter{}, "s_x")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -64,7 +64,7 @@ func TestDelete_TTY_ConfirmYes(t *testing.T) {
_, _ = iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Answer: true}
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, svc, p, "s_yes"))
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, nil, svc, p, "s_yes"))
assert.True(t, p.Asked)
assert.True(t, svc.called)
}
@@ -73,7 +73,7 @@ func TestDelete_TTY_ConfirmNo(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Answer: false}
err := runDelete(context.Background(), &DeleteOptions{}, svc, p, "s_no")
err := runDelete(context.Background(), &DeleteOptions{}, nil, svc, p, "s_no")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -85,7 +85,7 @@ func TestDelete_TTY_ConfirmNo(t *testing.T) {
func TestDelete_DryRun_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
require.NoError(t, runDelete(context.Background(), &DeleteOptions{DryRun: true, JSONOut: true}, svc, &testutil.ConfirmPrompter{}, "s_dry"))
require.NoError(t, runDelete(context.Background(), &DeleteOptions{DryRun: true}, &cmdutil.JSONOptions{}, svc, &testutil.ConfirmPrompter{}, "s_dry"))
body := out.String()
assert.True(t, strings.HasPrefix(body, `{"ok":true`))
assert.Contains(t, body, `"dry_run":true`)
+19 -6
View File
@@ -22,10 +22,15 @@ const (
maxPageSize = 1000
)
// sessionListFields enumerates the fields surfaced for `--json` discovery on
// `session list`. Mirrors sdk.Session json tags.
var sessionListFields = []string{
"id", "tenant_id", "title", "description", "created_at", "updated_at",
}
type ListOptions struct {
Page int
PageSize int
JSONOut bool
}
// ListService is the narrow SDK surface this command depends on.
@@ -47,21 +52,25 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
Short: "List chat sessions for the active context",
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
return runList(c.Context(), opts, cli)
return runList(c.Context(), opts, jopts, cli)
},
}
cmd.Flags().IntVar(&opts.Page, "page", defaultPage, "Page number (1-indexed)")
cmd.Flags().IntVar(&opts.PageSize, "page-size", defaultPageSize, "Items per page (1..1000)")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmdutil.AddJSONFlags(cmd, sessionListFields)
agent.SetAgentHelp(cmd, "Lists chat sessions. _meta.has_more is set when more pages exist; bump --page and retry to walk them.")
return cmd
}
func runList(ctx context.Context, opts *ListOptions, svc ListService) error {
func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions, svc ListService) error {
if opts.Page < 1 {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
@@ -83,9 +92,13 @@ func runList(ctx context.Context, opts *ListOptions, svc ListService) error {
items = []sdk.Session{} // JSON [] not null
}
if opts.JSONOut {
if jopts.Enabled() {
meta := &format.Meta{HasMore: opts.Page*opts.PageSize < total}
return format.WriteEnvelope(iostreams.IO.Out, format.Success(listResult{Items: items}, meta))
return format.WriteEnvelopeFiltered(
iostreams.IO.Out,
format.Success(listResult{Items: items}, meta),
jopts.Fields, jopts.JQ,
)
}
if len(items) == 0 {
+8 -8
View File
@@ -34,7 +34,7 @@ func (f *fakeListService) GetSessionsByTenant(_ context.Context, page, pageSize
func TestList_Empty(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{items: nil, total: 0}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, svc))
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, nil, svc))
assert.Contains(t, out.String(), "no sessions")
}
@@ -47,7 +47,7 @@ func TestList_Table(t *testing.T) {
},
total: 2,
}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, svc))
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, nil, svc))
got := out.String()
assert.Contains(t, got, "s_1")
assert.Contains(t, got, "Design review")
@@ -64,7 +64,7 @@ func TestList_JSON_WithMeta(t *testing.T) {
},
total: 47,
}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 2, PageSize: 10, JSONOut: true}, svc))
require.NoError(t, runList(context.Background(), &ListOptions{Page: 2, PageSize: 10}, &cmdutil.JSONOptions{}, svc))
var env format.Envelope
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
@@ -86,7 +86,7 @@ func TestList_JSON_LastPage_NoHasMore(t *testing.T) {
items: []sdk.Session{{ID: "s_1"}},
total: 11,
}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 2, PageSize: 10, JSONOut: true}, svc))
require.NoError(t, runList(context.Background(), &ListOptions{Page: 2, PageSize: 10}, &cmdutil.JSONOptions{}, svc))
// page*size = 20 ≥ total 11 → has_more must be false (omitempty drops the key)
body := out.String()
assert.NotContains(t, body, `"has_more":true`)
@@ -95,7 +95,7 @@ func TestList_JSON_LastPage_NoHasMore(t *testing.T) {
func TestList_NilItems_RendersAsEmptyArray(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{items: nil, total: 0}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30, JSONOut: true}, svc))
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, &cmdutil.JSONOptions{}, svc))
assert.Contains(t, out.String(), `"items":[]`)
}
@@ -112,7 +112,7 @@ func TestList_BadPagination(t *testing.T) {
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := runList(context.Background(), &ListOptions{Page: tc.page, PageSize: tc.size}, &fakeListService{})
err := runList(context.Background(), &ListOptions{Page: tc.page, PageSize: tc.size}, nil, &fakeListService{})
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -124,7 +124,7 @@ func TestList_BadPagination(t *testing.T) {
func TestList_NetworkError_TypedCode(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListService{err: errors.New("HTTP error 401: unauthenticated")}
err := runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, svc)
err := runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, nil, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -135,6 +135,6 @@ func TestList_NetworkError_TypedCode(t *testing.T) {
func TestList_NonASCIITitle(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{items: []sdk.Session{{ID: "s_zh", Title: strings.Repeat("中文", 50)}}, total: 1}
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, svc))
require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 30}, nil, svc))
assert.Contains(t, out.String(), "s_zh")
}
+19 -7
View File
@@ -14,10 +14,14 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
type ViewOptions struct {
JSONOut bool
// sessionViewFields enumerates the fields surfaced for `--json` discovery on
// `session view`. Mirrors sdk.Session json tags.
var sessionViewFields = []string{
"id", "tenant_id", "title", "description", "created_at", "updated_at",
}
type ViewOptions struct{}
// ViewService is the narrow SDK surface this command depends on.
type ViewService interface {
GetSession(ctx context.Context, id string) (*sdk.Session, error)
@@ -34,25 +38,33 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
Short: "Show a chat session by ID",
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
return runView(c.Context(), opts, cli, args[0])
return runView(c.Context(), opts, jopts, cli, args[0])
},
}
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmdutil.AddJSONFlags(cmd, sessionViewFields)
agent.SetAgentHelp(cmd, "Shows a chat session's metadata (title, description, timestamps). Errors with resource.not_found if id is unknown.")
return cmd
}
func runView(ctx context.Context, opts *ViewOptions, svc ViewService, id string) error {
func runView(ctx context.Context, opts *ViewOptions, jopts *cmdutil.JSONOptions, svc ViewService, id string) error {
s, err := svc.GetSession(ctx, id)
if err != nil {
return cmdutil.WrapHTTP(err, "get session %q", id)
}
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out, format.Success(s, nil))
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(
iostreams.IO.Out,
format.Success(s, nil),
jopts.Fields, jopts.JQ,
)
}
w := iostreams.IO.Out
fmt.Fprintf(w, "ID: %s\n", s.ID)
+4 -4
View File
@@ -37,7 +37,7 @@ func TestView_Human(t *testing.T) {
CreatedAt: "2026-05-10T09:00:00Z",
UpdatedAt: "2026-05-12T14:00:00Z",
}}
require.NoError(t, runView(context.Background(), &ViewOptions{}, svc, "s_abc"))
require.NoError(t, runView(context.Background(), &ViewOptions{}, nil, svc, "s_abc"))
got := out.String()
for _, want := range []string{"s_abc", "Design review", "RAG chunking strategy review", "2026-05-12"} {
assert.Contains(t, got, want)
@@ -48,7 +48,7 @@ func TestView_Human(t *testing.T) {
func TestView_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewService{s: &sdk.Session{ID: "s_abc", Title: "T", UpdatedAt: "2026-05-12T14:00:00Z"}}
require.NoError(t, runView(context.Background(), &ViewOptions{JSONOut: true}, svc, "s_abc"))
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.JSONOptions{}, svc, "s_abc"))
var env format.Envelope
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
@@ -60,7 +60,7 @@ func TestView_JSON(t *testing.T) {
func TestView_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeViewService{err: errors.New("HTTP error 404: not found")}
err := runView(context.Background(), &ViewOptions{}, svc, "s_missing")
err := runView(context.Background(), &ViewOptions{}, nil, svc, "s_missing")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -70,7 +70,7 @@ func TestView_NotFound(t *testing.T) {
func TestView_OmitsEmptyDescription(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewService{s: &sdk.Session{ID: "s_min", Title: "Bare"}}
require.NoError(t, runView(context.Background(), &ViewOptions{}, svc, "s_min"))
require.NoError(t, runView(context.Background(), &ViewOptions{}, nil, svc, "s_min"))
// Empty Description should not produce an empty `DESC:` line.
for line := range strings.SplitSeq(out.String(), "\n") {
if strings.HasPrefix(line, "DESC:") {