feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider

Adds the structured-output and agent-help surface plus root-level signal
handling so AI agents (and humans working through pipes) get a stable
wire contract.

* --format text|json|ndjson flag, registered per-command on outputs that
  need it; default text on TTY, json on pipe. --jq <expr> pairs with json
  / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON()
  helper for the JSON dispatch.
* WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value
  per line, arrays split element-per-line, empty slice → zero bytes).
* chat / agent invoke wire --format ndjson via SDK StreamResponse /
  AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled
  in every stream + session-create path and emit a stable
  "operation.cancelled" code on Ctrl-C / SIGTERM.
* main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root
  context so long-running commands run their cancellation cleanup
  (re-emit auto-created session id, etc); the process exits 130 when
  the context was signal-cancelled, matching Unix convention.
* MCP chat / agent_invoke output schemas extended with thinking /
  tool_calls / assistant_message_id (server-side accumulated; MCP
  tools/call has no standard partial-response). doc_view and doc_download
  now use doc_id (not knowledge_id) so agents see a single id naming
  convention across all tools — matches the chunk_list / search_chunks
  schemas and the CLI's <doc-id> positional.
* SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help
  payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list.
* kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets
  the new KB's storage_provider_config.provider at creation time (server
  does not expose it on update). Required on self-hosted deployments
  where the server-side default doesn't pre-populate a provider —
  without it, subsequent doc upload returns a misleading "kb not found".
This commit is contained in:
nullkey
2026-05-18 01:37:47 +08:00
committed by lyingbug
parent 5deffbd769
commit 567d7ac74e
18 changed files with 983 additions and 475 deletions
+62 -26
View File
@@ -2,6 +2,7 @@ package agentcmd
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
@@ -16,10 +17,10 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// agentInvokeFields enumerates fields surfaced for `--json` discovery on
// `agent invoke`. Matches invokeData below - the single-shot result
// object with the agent's final answer plus the trace (references,
// tool events).
// agentInvokeFields enumerates fields surfaced for `--format json` discovery
// on `agent invoke`. Matches invokeData below — the single-shot result
// object with the agent's final answer plus the trace (references, tool
// events).
var agentInvokeFields = []string{
"answer", "references", "tool_events", "thinking",
"session_id", "agent_id", "query",
@@ -30,12 +31,11 @@ type InvokeOptions struct {
AgentID string
Query string
SessionID string // --session: continue an existing session (skip auto-create)
NoStream bool // --no-stream: force accumulate-and-emit (TTY default streams)
}
// InvokeService is the narrow SDK surface this command depends on.
//
// CreateSession is called when --session is omitted - sessions are
// CreateSession is called when --session is omitted — sessions are
// agent-agnostic at creation (verified against
// internal/handler/session/handler.go CreateSession, which only persists
// {title, description}). The agent ID is supplied per-request via
@@ -46,7 +46,7 @@ type InvokeService interface {
AgentQAStreamWithRequest(ctx context.Context, sessionID string, req *sdk.AgentQARequest, cb sdk.AgentEventCallback) error
}
// invokeData is the JSON payload emitted on the --json path.
// invokeData is the JSON payload emitted on the JSON path.
type invokeData struct {
Answer string `json:"answer"`
References []*sdk.SearchResult `json:"references"`
@@ -67,36 +67,36 @@ func NewCmdInvoke(f *cmdutil.Factory) *cobra.Command {
tools, KB scope, retrieval thresholds) over SSE. By default a fresh session
is auto-created; pass --session to continue an existing conversation. The
agent picks the model, retrieval params, and tool surface from its own
config - agent invoke is the thin shim that streams the result.
config — agent invoke is the thin shim that streams the result.
Modes:
TTY (default): live answer streaming + tool-trace footer
Pipe / --no-stream / --json: buffered, single JSON object at completion`,
TTY (text format, default): live answer streaming + tool-trace footer
--format json / pipe: buffered, single JSON object at completion`,
Example: ` weknora agent invoke ag_abc "Summarise the Q3 plan"
weknora agent invoke ag_abc "Continue?" --session sess_xyz
weknora agent invoke ag_abc "What did we ship?" --json`,
weknora agent invoke ag_abc "What did we ship?" --format json`,
Args: cobra.ExactArgs(2),
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())
opts.AgentID = args[0]
opts.Query = strings.TrimSpace(args[1])
cli, err := f.Client()
if err != nil {
return err
}
return runInvoke(c.Context(), opts, jopts, cli)
return runInvoke(c.Context(), opts, fopts, cli)
},
}
cmd.Flags().StringVar(&opts.SessionID, "session", "", "Continue an existing chat session (skip auto-create)")
cmd.Flags().BoolVar(&opts.NoStream, "no-stream", false, "Buffer the full answer before printing (forces accumulate mode)")
cmdutil.AddJSONFlags(cmd, agentInvokeFields)
cmdutil.AddFormatFlag(cmd, agentInvokeFields...)
return cmd
}
func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOptions, svc InvokeService) error {
func runInvoke(ctx context.Context, opts *InvokeOptions, fopts *cmdutil.FormatOptions, svc InvokeService) error {
if opts.Query == "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "query argument cannot be empty")
}
@@ -107,13 +107,16 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
return cmdutil.NewError(cmdutil.CodeServerError, "agent invoke: no SDK client available")
}
jsonOut := jopts.Enabled()
jsonOut := fopts != nil && fopts.Mode == cmdutil.FormatJSON
sessionID := opts.SessionID
autoCreated := false
if sessionID == "" {
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora agent invoke"})
if err != nil {
if isCancelled(ctx, err) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "agent invoke cancelled")
}
code := cmdutil.ClassifyHTTPError(err)
if code == cmdutil.CodeNetworkError || code == cmdutil.CodeServerError {
code = cmdutil.CodeSessionCreateFailed
@@ -124,10 +127,12 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
autoCreated = true
}
// Streaming requires interactive stdout + no --no-stream + no --json.
// Matches chat.go's mode-selection contract so users get the same
// muscle memory across both commands.
streamMode := iostreams.IO.IsStdoutTTY() && !opts.NoStream && !jsonOut
// Streaming requires interactive stdout + no --format json + no
// --format ndjson (handled by early-return below). Matches chat.go's
// mode-selection contract so users get the same muscle memory across
// both commands.
streamMode := iostreams.IO.IsStdoutTTY() && !jsonOut &&
(fopts == nil || fopts.Mode != cmdutil.FormatNDJSON)
// Surface auto-created session id up-front so a ^C mid-stream still
// leaves a recoverable pointer.
@@ -142,6 +147,23 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
Channel: "api",
}
// --format ndjson: stream raw SDK events as NDJSON. Encoder hoisted out
// of the callback to avoid per-event allocation.
if fopts != nil && fopts.Mode == cmdutil.FormatNDJSON {
enc := json.NewEncoder(iostreams.IO.Out)
enc.SetEscapeHTML(false)
cb := func(r *sdk.AgentStreamResponse) error {
return enc.Encode(r)
}
if err := svc.AgentQAStreamWithRequest(ctx, sessionID, req, cb); err != nil {
if isCancelled(ctx, err) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "agent invoke cancelled")
}
return cmdutil.WrapHTTP(err, "agent-chat stream")
}
return nil
}
acc := &sse.AgentAccumulator{}
cb := func(r *sdk.AgentStreamResponse) error {
if streamMode && r != nil && r.ResponseType == sdk.AgentResponseTypeAnswer && r.Content != "" {
@@ -156,8 +178,8 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
if autoCreated && !jsonOut {
fmt.Fprintf(iostreams.IO.Err, "session: %s (resume with --session %s)\n", sessionID, sessionID)
}
if errors.Is(streamErr, context.Canceled) || errors.Is(ctx.Err(), context.Canceled) {
return cmdutil.Wrapf(cmdutil.CodeUserAborted, streamErr, "agent invoke cancelled")
if isCancelled(ctx, streamErr) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, streamErr, "agent invoke cancelled")
}
if acc.Answer() != "" && !acc.Done() {
return cmdutil.Wrapf(cmdutil.CodeSSEStreamAborted, streamErr, "stream aborted before completion")
@@ -165,7 +187,7 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
return cmdutil.WrapHTTP(streamErr, "agent-chat stream")
}
// Server closed cleanly but never sent a Done event - treat as aborted
// Server closed cleanly but never sent a Done event — treat as aborted
// so agents don't silently emit a truncated answer as ok=true.
if !acc.Done() {
return cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")
@@ -182,7 +204,7 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
AgentID: opts.AgentID,
Query: opts.Query,
}
return jopts.Emit(iostreams.IO.Out, data)
return fopts.Emit(iostreams.IO.Out, data)
}
out := iostreams.IO.Out
@@ -202,7 +224,7 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
}
// renderToolTrace prints a compact tool-event footer in human mode.
// Skipped when the agent emitted no tool events - silent beats an empty
// Skipped when the agent emitted no tool events — silent beats an empty
// banner.
func renderToolTrace(w io.Writer, events []sse.AgentToolEvent) {
if len(events) == 0 {
@@ -229,5 +251,19 @@ func truncateInline(s string, maxLen int) string {
return s[:maxLen-1] + "…"
}
// isCancelled reports whether err or ctx represents a context-cancelled
// state — true on Ctrl-C / SIGTERM after main.go's signal.NotifyContext
// fires. Wrapping URL/transport layers may rewrite context.Canceled into
// something errors.Is no longer recognises, so we fall back to ctx.Err().
func isCancelled(ctx context.Context, err error) bool {
if errors.Is(err, context.Canceled) {
return true
}
if ctx.Err() == context.Canceled {
return true
}
return false
}
// compile-time check: production SDK client satisfies InvokeService.
var _ InvokeService = (*sdk.Client)(nil)
+93 -15
View File
@@ -1,9 +1,11 @@
package agentcmd
import (
"bytes"
"context"
"encoding/json"
"errors"
"os"
"strings"
"testing"
@@ -62,6 +64,17 @@ func referencesEvent(refs []*sdk.SearchResult) *sdk.AgentStreamResponse {
}
}
// textOpts returns a FormatOptions configured for the text (human) render
// path — the most common shape under test.
func textOpts() *cmdutil.FormatOptions {
return &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
}
// jsonOpts returns a FormatOptions configured for the JSON path.
func jsonOpts() *cmdutil.FormatOptions {
return &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
}
func TestInvoke_AccumulateMode_EmitsBareJSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &scriptedInvokeSvc{
@@ -73,7 +86,7 @@ func TestInvoke_AccumulateMode_EmitsBareJSON(t *testing.T) {
},
}
opts := &InvokeOptions{AgentID: "ag_x", Query: "ping"}
if err := runInvoke(context.Background(), opts, &cmdutil.JSONOptions{}, svc); err != nil {
if err := runInvoke(context.Background(), opts, jsonOpts(), svc); err != nil {
t.Fatalf("runInvoke: %v", err)
}
var got invokeData
@@ -101,7 +114,7 @@ func TestInvoke_AutoCreatedSessionID_PassedAsAgentRequest(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &scriptedInvokeSvc{events: []*sdk.AgentStreamResponse{doneEvent()}}
opts := &InvokeOptions{AgentID: "ag_42", Query: "x"}
if err := runInvoke(context.Background(), opts, &cmdutil.JSONOptions{}, svc); err != nil {
if err := runInvoke(context.Background(), opts, jsonOpts(), svc); err != nil {
t.Fatalf("runInvoke: %v", err)
}
if svc.got.sessionID != "sess_auto" {
@@ -123,7 +136,7 @@ func TestInvoke_ExistingSessionID_SkipsCreate(t *testing.T) {
svc.createResp = &sdk.Session{ID: "should_not_be_used"}
wrapped := &createSessionTracker{InvokeService: svc, called: &created}
opts := &InvokeOptions{AgentID: "ag", Query: "x", SessionID: "sess_existing"}
if err := runInvoke(context.Background(), opts, &cmdutil.JSONOptions{}, wrapped); err != nil {
if err := runInvoke(context.Background(), opts, jsonOpts(), wrapped); err != nil {
t.Fatalf("runInvoke: %v", err)
}
if created {
@@ -152,7 +165,7 @@ func TestInvoke_ToolEventsCaptured(t *testing.T) {
doneEvent(),
}}
opts := &InvokeOptions{AgentID: "ag", Query: "x"}
if err := runInvoke(context.Background(), opts, &cmdutil.JSONOptions{}, svc); err != nil {
if err := runInvoke(context.Background(), opts, jsonOpts(), svc); err != nil {
t.Fatalf("runInvoke: %v", err)
}
var got invokeData
@@ -171,7 +184,7 @@ func TestInvoke_EmptyQuery_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &scriptedInvokeSvc{}
opts := &InvokeOptions{AgentID: "ag", Query: ""}
err := runInvoke(context.Background(), opts, nil, svc)
err := runInvoke(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected input.invalid_argument, got nil")
}
@@ -190,7 +203,7 @@ func TestInvoke_StreamAbortBeforeDone_MapsToSSEStreamAborted(t *testing.T) {
streamErr: errors.New("connection reset"),
}
opts := &InvokeOptions{AgentID: "ag", Query: "x"}
err := runInvoke(context.Background(), opts, &cmdutil.JSONOptions{}, svc)
err := runInvoke(context.Background(), opts, jsonOpts(), svc)
if err == nil {
t.Fatal("expected stream-aborted error")
}
@@ -204,7 +217,7 @@ func TestInvoke_NoDoneEvent_MapsToSSEStreamAborted(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &scriptedInvokeSvc{events: []*sdk.AgentStreamResponse{answerEvent("incomplete")}}
opts := &InvokeOptions{AgentID: "ag", Query: "x"}
err := runInvoke(context.Background(), opts, &cmdutil.JSONOptions{}, svc)
err := runInvoke(context.Background(), opts, jsonOpts(), svc)
if err == nil {
t.Fatal("expected stream-aborted error")
}
@@ -218,7 +231,7 @@ func TestInvoke_CreateSessionFails_MapsToSessionCreateFailed(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &scriptedInvokeSvc{createErr: errors.New("connection refused")}
opts := &InvokeOptions{AgentID: "ag", Query: "x"}
err := runInvoke(context.Background(), opts, nil, svc)
err := runInvoke(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected session_create_failed")
}
@@ -228,19 +241,19 @@ func TestInvoke_CreateSessionFails_MapsToSessionCreateFailed(t *testing.T) {
}
}
func TestInvoke_Cancellation_MapsToUserAborted(t *testing.T) {
func TestInvoke_Cancellation_MapsToOperationCancelled(t *testing.T) {
_, _ = iostreams.SetForTest(t)
ctx, cancel := context.WithCancel(context.Background())
cancel() // pre-cancel
svc := &scriptedInvokeSvc{streamErr: context.Canceled}
opts := &InvokeOptions{AgentID: "ag", Query: "x"}
err := runInvoke(ctx, opts, &cmdutil.JSONOptions{}, svc)
err := runInvoke(ctx, opts, jsonOpts(), svc)
if err == nil {
t.Fatal("expected user_aborted")
t.Fatal("expected operation.cancelled")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeUserAborted {
t.Errorf("expected local.user_aborted, got %v", err)
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeOperationCancelled {
t.Errorf("expected operation.cancelled, got %v", err)
}
}
@@ -252,8 +265,8 @@ func TestInvoke_Human_Accumulate_PrintsAnswerAndFooter(t *testing.T) {
toolCallEvent("c1", "knowledge_search"),
doneEvent(),
}}
opts := &InvokeOptions{AgentID: "ag", Query: "x", NoStream: true}
if err := runInvoke(context.Background(), opts, nil, svc); err != nil {
opts := &InvokeOptions{AgentID: "ag", Query: "x"}
if err := runInvoke(context.Background(), opts, textOpts(), svc); err != nil {
t.Fatalf("runInvoke: %v", err)
}
got := out.String()
@@ -264,3 +277,68 @@ func TestInvoke_Human_Accumulate_PrintsAnswerAndFooter(t *testing.T) {
t.Errorf("tool trace footer missing: %q", got)
}
}
func TestAgentInvoke_FormatNDJSON_PassthroughsSDKEvents(t *testing.T) {
// Fake stream emits 3 events: tool_call, answer, done.
// Mirrors TestChat_FormatNDJSON_PassthroughsSDKEvents in chat_test.go but
// uses AgentStreamResponse instead of StreamResponse.
svc := &scriptedInvokeSvc{
events: []*sdk.AgentStreamResponse{
toolCallEvent("call_1", "knowledge_search"),
answerEvent("hello"),
doneEvent(),
},
}
var stdout bytes.Buffer
prev := iostreams.IO.Out
iostreams.IO.Out = &stdout
defer func() { iostreams.IO.Out = prev }()
// Redirect stderr so the auto-created session hint doesn't write to real
// stderr during the test.
prevErr := iostreams.IO.Err
iostreams.IO.Err = os.Stderr
defer func() { iostreams.IO.Err = prevErr }()
opts := &InvokeOptions{AgentID: "ag_x", Query: "hi"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
if err := runInvoke(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runInvoke: %v", err)
}
lines := strings.Split(strings.TrimRight(stdout.String(), "\n"), "\n")
if len(lines) != 3 {
t.Fatalf("got %d lines, want 3:\n%s", len(lines), stdout.String())
}
// Each line must be valid JSON.
for i, line := range lines {
var obj map[string]any
if err := json.Unmarshal([]byte(line), &obj); err != nil {
t.Fatalf("line %d not valid JSON: %v\n %s", i+1, err, line)
}
}
// First line: tool_call event.
var first map[string]any
if err := json.Unmarshal([]byte(lines[0]), &first); err != nil {
t.Fatalf("line 1 not JSON: %v", err)
}
if first["response_type"] != string(sdk.AgentResponseTypeToolCall) {
t.Errorf("first event response_type=%v, want %s", first["response_type"], sdk.AgentResponseTypeToolCall)
}
// Second line: answer event.
var second map[string]any
if err := json.Unmarshal([]byte(lines[1]), &second); err != nil {
t.Fatalf("line 2 not JSON: %v", err)
}
if second["response_type"] != string(sdk.AgentResponseTypeAnswer) {
t.Errorf("second event response_type=%v, want %s", second["response_type"], sdk.AgentResponseTypeAnswer)
}
// Third line: done event.
var third map[string]any
if err := json.Unmarshal([]byte(lines[2]), &third); err != nil {
t.Fatalf("line 3 not JSON: %v", err)
}
if third["done"] != true {
t.Errorf("third event done=%v, want true", third["done"])
}
}
+75 -31
View File
@@ -3,15 +3,15 @@
//
// Two output modes share a single SDK call:
//
// - Stream mode (TTY + no --no-stream + no --json): write each
// StreamResponse.Content fragment directly to iostreams.IO.Out as it
// arrives, then print a footer with knowledge references. This is the
// "feels alive" UX a human typing in a terminal expects.
// - Stream mode (TTY + text format): write each StreamResponse.Content
// fragment directly to iostreams.IO.Out as it arrives, then print a
// footer with knowledge references. This is the "feels alive" UX a
// human typing in a terminal expects.
//
// - Accumulate mode (non-TTY, --no-stream, or --json): buffer every
// fragment via sse.Accumulator and emit a single JSON object (or a single
// plain-text answer + references block) once Done. Agents and pipes
// get a deterministic single record to parse.
// - Accumulate mode (--format json / pipe): buffer every fragment via
// sse.Accumulator and emit a single JSON object (or a single plain-text
// answer + references block) once Done. Agents and pipes get a
// deterministic single record to parse.
//
// The SDK's KnowledgeQAStream callback contract is invoked sequentially on
// one goroutine, so neither mode needs locking. The runChat core takes a
@@ -21,6 +21,7 @@ package chat
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
@@ -34,8 +35,8 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// chatFields enumerates the fields surfaced for `--json` discovery on `chat`.
// Mirrors the chatData struct json tags.
// chatFields enumerates the fields surfaced for `--format json` discovery
// on `chat`. Mirrors the chatData struct json tags.
var chatFields = []string{
"answer", "references", "thinking",
"session_id", "assistant_message_id", "kb_id", "query",
@@ -45,7 +46,6 @@ type Options struct {
Query string
KBID string
SessionID string
NoStream bool
}
// ChatService is the narrow SDK surface this command depends on. *sdk.Client
@@ -56,9 +56,9 @@ type ChatService interface {
KnowledgeQAStream(ctx context.Context, sessionID string, req *sdk.KnowledgeQARequest, cb func(*sdk.StreamResponse) error) error
}
// chatData is the JSON payload emitted on the --json path. Mirrors what an agent needs to
// continue a conversation: the answer text, retrieval references, and the
// session pointer to thread follow-ups.
// chatData is the JSON payload emitted on the JSON path. Mirrors what an
// agent needs to continue a conversation: the answer text, retrieval
// references, and the session pointer to thread follow-ups.
type chatData struct {
Answer string `json:"answer"`
References []*sdk.SearchResult `json:"references"`
@@ -77,17 +77,17 @@ type chatData struct {
func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{}
cmd := &cobra.Command{
Use: `chat <text>`,
Use: `chat "<text>"`,
Short: "Ask a streaming RAG question against a knowledge base",
Long: `Send a query to the WeKnora knowledge-chat endpoint and stream the
answer back. By default a fresh session is created on first invocation; pass
--session to continue an existing conversation.
Modes:
TTY (default): live token streaming + reference footer
Pipe / --no-stream / --json: buffered, emitted once on completion`,
TTY (text format, default): live token streaming + reference footer
--format json / pipe: buffered, emitted once on completion`,
Example: ` weknora chat "What is RRF?" --kb a32a63ff-fb36-4874-bcaa-30f48570a694
weknora chat "Summarise this design doc" --kb my-kb --json
weknora chat "Summarise this design doc" --kb my-kb --format json
weknora chat "Continue?" --session sess_abc`,
Args: cobra.MinimumNArgs(1),
RunE: func(c *cobra.Command, args []string) error {
@@ -95,10 +95,11 @@ Modes:
if opts.Query == "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "query argument cannot be empty")
}
jopts, err := cmdutil.CheckJSONFlags(c)
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
kbID, err := f.ResolveKB(c)
if err != nil {
return err
@@ -108,19 +109,24 @@ Modes:
if err != nil {
return err
}
return runChat(c.Context(), opts, jopts, cli)
return runChat(c.Context(), opts, fopts, cli)
},
}
cmd.Flags().String("kb", "", "Knowledge base UUID or name (overrides project link / env)")
cmd.Flags().StringVar(&opts.SessionID, "session", "", "Continue an existing chat session (skip auto-create)")
cmd.Flags().BoolVar(&opts.NoStream, "no-stream", false, "Buffer the full answer before printing (forces accumulate mode)")
cmdutil.AddJSONFlags(cmd, chatFields)
cmdutil.AddFormatFlag(cmd, chatFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Ask a streaming RAG question against a knowledge base and get a single answer + cited chunks. Agents should use --format json for parseable output.",
RequiredFlags: []string{"--kb"},
Examples: []string{`weknora chat "What is RRF?" --kb kb_abc --format json`},
Output: "answer / references / session_id / thinking — see chatData struct (chat.go)",
})
return cmd
}
// runChat is the testable core: validate, ensure a session, dispatch the
// stream, and route output. Returns a typed error.
func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc ChatService) error {
func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, svc ChatService) error {
if opts.Query == "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "query argument cannot be empty")
}
@@ -133,13 +139,19 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
return cmdutil.NewError(cmdutil.CodeServerError, "chat: no SDK client available")
}
jsonOut := jopts.Enabled()
jsonOut := fopts != nil && fopts.Mode == cmdutil.FormatJSON
sessionID := opts.SessionID
autoCreated := false
if sessionID == "" {
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora chat"})
if err != nil {
// Ctrl-C during session creation: classify as cancelled so the
// hint nudges the user toward retry-with-signal-clean, not
// "pass --session" as session_create_failed would.
if isCancelled(ctx, err) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "chat cancelled")
}
// Map HTTP-shaped failures, but tag generic transport / unknown
// errors as session_create_failed so the dedicated hint fires.
code := cmdutil.ClassifyHTTPError(err)
@@ -154,9 +166,10 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
// Decide output mode. Stream mode requires:
// 1. an interactive stdout (tty)
// 2. no --no-stream
// 3. no --json (JSON output is single-record by definition)
streamMode := iostreams.IO.IsStdoutTTY() && !opts.NoStream && !jsonOut
// 2. no --format json (JSON output is single-record by definition)
// 3. no --format ndjson (handled by the early-return branch below)
streamMode := iostreams.IO.IsStdoutTTY() && !jsonOut &&
(fopts == nil || fopts.Mode != cmdutil.FormatNDJSON)
// Surface the auto-created session ID up-front so a user who hits ^C
// mid-stream still has the pointer to resume - no need to scroll back
@@ -174,6 +187,23 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
Channel: "api",
}
// --format ndjson: stream raw SDK events as NDJSON. Encoder hoisted out
// of callback to avoid per-event allocation.
if fopts != nil && fopts.Mode == cmdutil.FormatNDJSON {
enc := json.NewEncoder(iostreams.IO.Out)
enc.SetEscapeHTML(false)
cb := func(r *sdk.StreamResponse) error {
return enc.Encode(r)
}
if err := svc.KnowledgeQAStream(ctx, sessionID, req, cb); err != nil {
if isCancelled(ctx, err) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "chat cancelled")
}
return cmdutil.WrapHTTP(err, "knowledge qa stream")
}
return nil
}
acc := &sse.Accumulator{}
cb := func(r *sdk.StreamResponse) error {
@@ -196,12 +226,12 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
fmt.Fprintf(iostreams.IO.Err, "session: %s (resume with --session %s)\n", sessionID, sessionID)
}
// Context cancelled (Ctrl-C) → user-aborted, exit 130 lineage.
if errors.Is(streamErr, context.Canceled) || errors.Is(ctx.Err(), context.Canceled) {
return cmdutil.Wrapf(cmdutil.CodeUserAborted, streamErr, "chat cancelled")
if isCancelled(ctx, streamErr) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, streamErr, "chat cancelled")
}
// Stream began (we observed at least one event) but never reached a
// terminal Done frame: typed as sse_stream_aborted so the hint
// nudges the user toward --no-stream / retry.
// nudges the user toward a retry.
if acc.Result() != "" && !acc.Done() {
return cmdutil.Wrapf(cmdutil.CodeSSEStreamAborted, streamErr, "stream aborted before completion")
}
@@ -239,7 +269,7 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
KBID: opts.KBID,
Query: opts.Query,
}
return jopts.Emit(iostreams.IO.Out, data)
return fopts.Emit(iostreams.IO.Out, data)
}
// Human / non-JSON paths: streaming mode already wrote the answer body
@@ -262,5 +292,19 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
return nil
}
// isCancelled reports whether err or ctx represents a context-cancelled
// state — true on Ctrl-C / SIGTERM after main.go's signal.NotifyContext
// fires. Wrapping URL/transport layers may rewrite context.Canceled into
// something errors.Is no longer recognises, so we fall back to ctx.Err().
func isCancelled(ctx context.Context, err error) bool {
if errors.Is(err, context.Canceled) {
return true
}
if ctx.Err() == context.Canceled {
return true
}
return false
}
// compile-time check: the production SDK client implements ChatService.
var _ ChatService = (*sdk.Client)(nil)
+76 -36
View File
@@ -1,9 +1,11 @@
package chat
import (
"bytes"
"context"
"encoding/json"
"errors"
"os"
"strings"
"testing"
@@ -60,6 +62,12 @@ func (f *fakeChatService) KnowledgeQAStream(ctx context.Context, sessionID strin
// var _ ChatService = (*sdk.Client)(nil) check at the bottom of chat.go.
var _ ChatService = (*fakeChatService)(nil)
// textOpts returns a FormatOptions configured for the text (human) render
// path — the most common shape under test.
func textOpts() *cmdutil.FormatOptions {
return &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
}
func TestChat_StreamMode(t *testing.T) {
out, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeChatService{
@@ -73,7 +81,7 @@ func TestChat_StreamMode(t *testing.T) {
},
}
opts := &Options{Query: "hi", KBID: "kb_1"}
if err := runChat(context.Background(), opts, nil, svc); err != nil {
if err := runChat(context.Background(), opts, textOpts(), svc); err != nil {
t.Fatalf("runChat: %v", err)
}
got := out.String()
@@ -112,7 +120,7 @@ func TestChat_JSONMode(t *testing.T) {
},
}
opts := &Options{Query: "q", KBID: "kb_42"}
if err := runChat(context.Background(), opts, &cmdutil.JSONOptions{}, svc); err != nil {
if err := runChat(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
@@ -155,30 +163,8 @@ func TestChat_JSONMode(t *testing.T) {
}
}
func TestChat_NoStreamFlag(t *testing.T) {
// TTY enabled, but --no-stream forces accumulate mode → no live writes
// during callback; entire answer printed once after Done.
out, _ := iostreams.SetForTestWithTTY(t)
var written string
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeAnswer, Content: "buffered "},
{ResponseType: sdk.ResponseTypeAnswer, Content: "answer"},
{ResponseType: sdk.ResponseTypeComplete, Done: true},
},
}
opts := &Options{Query: "q", KBID: "kb", NoStream: true}
if err := runChat(context.Background(), opts, nil, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
written = out.String()
if !strings.Contains(written, "buffered answer") {
t.Errorf("expected concatenated answer, got %q", written)
}
}
func TestChat_NonTTY_AccumulateMode(t *testing.T) {
// Non-TTY iostreams forces accumulate mode even without --no-stream.
// Non-TTY iostreams forces accumulate mode.
out, _ := iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
@@ -187,7 +173,7 @@ func TestChat_NonTTY_AccumulateMode(t *testing.T) {
},
}
opts := &Options{Query: "q", KBID: "kb"}
if err := runChat(context.Background(), opts, nil, svc); err != nil {
if err := runChat(context.Background(), opts, textOpts(), svc); err != nil {
t.Fatalf("runChat: %v", err)
}
if !strings.Contains(out.String(), "piped") {
@@ -201,7 +187,7 @@ func TestChat_SessionIDProvided(t *testing.T) {
streamEvents: []*sdk.StreamResponse{{ResponseType: sdk.ResponseTypeComplete, Done: true}},
}
opts := &Options{Query: "q", KBID: "kb", SessionID: "sess_existing"}
if err := runChat(context.Background(), opts, nil, svc); err != nil {
if err := runChat(context.Background(), opts, textOpts(), svc); err != nil {
t.Fatalf("runChat: %v", err)
}
if svc.createCalled {
@@ -221,7 +207,7 @@ func TestChat_KBIDRequired(t *testing.T) {
svc := &fakeChatService{}
// Run with KBID empty (bypassing the cobra resolver).
opts := &Options{Query: "q"}
err := runChat(context.Background(), opts, nil, svc)
err := runChat(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected error, got nil")
}
@@ -241,7 +227,7 @@ func TestChat_EmptyQuery(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeChatService{}
opts := &Options{Query: "", KBID: "kb"}
err := runChat(context.Background(), opts, nil, svc)
err := runChat(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected error, got nil")
}
@@ -262,7 +248,7 @@ func TestChat_SDKError_PreStream(t *testing.T) {
streamErr: errors.New("HTTP error 401: token rejected"),
}
opts := &Options{Query: "q", KBID: "kb"}
err := runChat(context.Background(), opts, nil, svc)
err := runChat(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected error, got nil")
}
@@ -284,7 +270,7 @@ func TestChat_SDKError_MidStream_AbortsAsSSE(t *testing.T) {
streamErr: errors.New("connection reset"),
}
opts := &Options{Query: "q", KBID: "kb"}
err := runChat(context.Background(), opts, nil, svc)
err := runChat(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected error, got nil")
}
@@ -303,7 +289,7 @@ func TestChat_ContextCancelled(t *testing.T) {
cancel() // simulate Ctrl-C delivered before the SDK returns.
svc := &fakeChatService{streamErr: context.Canceled}
opts := &Options{Query: "q", KBID: "kb"}
err := runChat(ctx, opts, nil, svc)
err := runChat(ctx, opts, textOpts(), svc)
if err == nil {
t.Fatal("expected error, got nil")
}
@@ -311,8 +297,8 @@ func TestChat_ContextCancelled(t *testing.T) {
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %T", err)
}
if typed.Code != cmdutil.CodeUserAborted {
t.Errorf("code: got %q want %q", typed.Code, cmdutil.CodeUserAborted)
if typed.Code != cmdutil.CodeOperationCancelled {
t.Errorf("code: got %q want %q", typed.Code, cmdutil.CodeOperationCancelled)
}
}
@@ -322,7 +308,7 @@ func TestChat_SessionCreateFails(t *testing.T) {
createSessionErr: errors.New("dial tcp: connection refused"),
}
opts := &Options{Query: "q", KBID: "kb"}
err := runChat(context.Background(), opts, nil, svc)
err := runChat(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected error, got nil")
}
@@ -347,7 +333,7 @@ func TestChat_SessionCreate404SurfacesNotFound(t *testing.T) {
createSessionErr: errors.New("HTTP error 404: tenant not found"),
}
opts := &Options{Query: "q", KBID: "kb"}
err := runChat(context.Background(), opts, nil, svc)
err := runChat(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected error, got nil")
}
@@ -359,3 +345,57 @@ func TestChat_SessionCreate404SurfacesNotFound(t *testing.T) {
t.Errorf("code: got %q want %q", typed.Code, cmdutil.CodeResourceNotFound)
}
}
func TestChat_FormatNDJSON_PassthroughsSDKEvents(t *testing.T) {
// Fake stream emits 3 events: thinking, answer, complete.
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeThinking, Content: "search KB"},
{ResponseType: sdk.ResponseTypeAnswer, Content: "hello"},
{ResponseType: sdk.ResponseTypeComplete, Done: true, SessionID: "sess_x"},
},
}
var stdout bytes.Buffer
prev := iostreams.IO.Out
iostreams.IO.Out = &stdout
defer func() { iostreams.IO.Out = prev }()
// Also redirect stderr so the auto-created session hint doesn't write to
// real stderr during tests.
prevErr := iostreams.IO.Err
iostreams.IO.Err = os.Stderr
defer func() { iostreams.IO.Err = prevErr }()
opts := &Options{Query: "hi", KBID: "kb_x"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
lines := strings.Split(strings.TrimRight(stdout.String(), "\n"), "\n")
if len(lines) != 3 {
t.Fatalf("got %d lines, want 3:\n%s", len(lines), stdout.String())
}
// Each line must be valid JSON with the right response_type.
var first map[string]any
if err := json.Unmarshal([]byte(lines[0]), &first); err != nil {
t.Fatalf("line 1 not JSON: %v", err)
}
if first["response_type"] != "thinking" {
t.Errorf("first event response_type=%v, want thinking", first["response_type"])
}
// Second line: answer.
var second map[string]any
if err := json.Unmarshal([]byte(lines[1]), &second); err != nil {
t.Fatalf("line 2 not JSON: %v", err)
}
if second["response_type"] != "answer" {
t.Errorf("second event response_type=%v, want answer", second["response_type"])
}
// Third line: complete with done=true.
var third map[string]any
if err := json.Unmarshal([]byte(lines[2]), &third); err != nil {
t.Fatalf("line 3 not JSON: %v", err)
}
if third["done"] != true {
t.Errorf("third event done=%v, want true", third["done"])
}
}
+39 -22
View File
@@ -3,6 +3,7 @@ package kb
import (
"context"
"fmt"
"slices"
"strings"
"github.com/spf13/cobra"
@@ -12,10 +13,10 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// kbCreateFields enumerates the fields surfaced for `--json` discovery on
// `kb create`. The result is the full KnowledgeBase struct; these mirror its
// top-level json tags. Nested config objects are intentionally omitted -
// users wanting them can drop --json (no filter) or use --jq.
// kbCreateFields enumerates the fields surfaced for `--format json` discovery
// on `kb create`. The result is the full KnowledgeBase struct; these mirror
// its top-level json tags. Nested config objects are intentionally omitted —
// users wanting them can drop the projection or use --jq.
var kbCreateFields = []string{
"id", "name", "type", "description",
"is_temporary", "is_pinned",
@@ -26,50 +27,57 @@ var kbCreateFields = []string{
}
type CreateOptions struct {
Name string
Description string
EmbeddingModel string
Name string
Description string
EmbeddingModel string
StorageProvider string
}
// storageProviderValues mirrors the server enum in
// internal/types/knowledgebase.go:StorageProviderConfig.Provider.
var storageProviderValues = []string{"local", "minio", "cos", "tos", "s3", "oss", "ks3"}
// CreateService is the narrow SDK surface this command depends on.
// *sdk.Client satisfies it via duck typing.
type CreateService interface {
CreateKnowledgeBase(ctx context.Context, kb *sdk.KnowledgeBase) (*sdk.KnowledgeBase, error)
}
// NewCmdCreate builds `weknora kb create`.
// NewCmdCreate builds `weknora kb create <name>`. Positional <name> only,
// consistent with `agent create <name>`.
func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
opts := &CreateOptions{}
cmd := &cobra.Command{
Use: "create --name <name>",
Use: "create <name>",
Short: "Create a new knowledge base",
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
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())
opts.Name = args[0]
cli, err := f.Client()
if err != nil {
return err
}
return runCreate(c.Context(), opts, jopts, cli)
return runCreate(c.Context(), opts, fopts, cli)
},
}
cmd.Flags().StringVar(&opts.Name, "name", "", "Knowledge base name (required)")
cmd.Flags().StringVar(&opts.Description, "description", "", "Knowledge base description (optional)")
cmd.Flags().StringVar(&opts.EmbeddingModel, "embedding-model", "", "Embedding model ID (optional; server picks default when unset)")
cmdutil.AddJSONFlags(cmd, kbCreateFields)
_ = cmd.MarkFlagRequired("name")
cmd.Flags().StringVar(&opts.StorageProvider, "storage-provider", "",
"Storage provider for documents in this KB: "+strings.Join(storageProviderValues, " | ")+" (optional; server default when unset)")
cmdutil.AddFormatFlag(cmd, kbCreateFields...)
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 {
// Trim defensively in case a caller invokes runCreate directly with
// whitespace; the cobra layer marks --name required so the empty-string
// case is unreachable from the CLI.
// whitespace; the cobra layer enforces a non-empty positional from the CLI.
if strings.TrimSpace(opts.Name) == "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--name is required")
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "knowledge base name is required")
}
req := &sdk.KnowledgeBase{
@@ -79,14 +87,23 @@ func runCreate(ctx context.Context, opts *CreateOptions, jopts *cmdutil.JSONOpti
if opts.EmbeddingModel != "" {
req.EmbeddingModelID = opts.EmbeddingModel
}
if opts.StorageProvider != "" {
v := strings.ToLower(strings.TrimSpace(opts.StorageProvider))
if !slices.Contains(storageProviderValues, v) {
return cmdutil.NewFlagError(fmt.Errorf(
"invalid --storage-provider %q: must be %s",
opts.StorageProvider, strings.Join(storageProviderValues, " | ")))
}
req.StorageProviderConfig = &sdk.StorageProviderConfig{Provider: v}
}
created, err := svc.CreateKnowledgeBase(ctx, req)
if err != nil {
return cmdutil.WrapHTTP(err, "create knowledge base")
}
if jopts.Enabled() {
return jopts.Emit(iostreams.IO.Out, created)
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, created)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Created knowledge base %q (id: %s)\n", created.Name, created.ID)
return nil
+38 -7
View File
@@ -39,7 +39,7 @@ func TestCreate_Success_Human(t *testing.T) {
Description: "team docs",
EmbeddingModel: "model_x",
}
require.NoError(t, runCreate(context.Background(), opts, nil, svc))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
// Body sent to SDK matches flags.
require.NotNil(t, svc.got)
@@ -59,7 +59,7 @@ func TestCreate_Success_OmitsEmbeddingModelWhenEmpty(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_x", Name: "n"}}
opts := &CreateOptions{Name: "n"}
require.NoError(t, runCreate(context.Background(), opts, nil, svc))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
require.NotNil(t, svc.got)
assert.Equal(t, "", svc.got.EmbeddingModelID, "embedding-model unset ⇒ empty in request")
@@ -68,7 +68,7 @@ func TestCreate_Success_OmitsEmbeddingModelWhenEmpty(t *testing.T) {
func TestCreate_NameRequired(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{}
err := runCreate(context.Background(), &CreateOptions{}, nil, svc)
err := runCreate(context.Background(), &CreateOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
@@ -80,7 +80,7 @@ func TestCreate_NameRequired(t *testing.T) {
func TestCreate_NameWhitespaceOnly(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{}
err := runCreate(context.Background(), &CreateOptions{Name: " "}, nil, svc)
err := runCreate(context.Background(), &CreateOptions{Name: " "}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
@@ -91,7 +91,7 @@ func TestCreate_NameWhitespaceOnly(t *testing.T) {
func TestCreate_HTTPError_500(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{err: errors.New("HTTP error 500: internal")}
err := runCreate(context.Background(), &CreateOptions{Name: "x"}, nil, svc)
err := runCreate(context.Background(), &CreateOptions{Name: "x"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
@@ -102,7 +102,7 @@ func TestCreate_HTTPError_500(t *testing.T) {
func TestCreate_HTTPError_409Conflict(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{err: errors.New("HTTP error 409: name exists")}
err := runCreate(context.Background(), &CreateOptions{Name: "dup"}, nil, svc)
err := runCreate(context.Background(), &CreateOptions{Name: "dup"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
@@ -114,10 +114,41 @@ func TestCreate_JSONOutput(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_99", Name: "Eng"}}
opts := &CreateOptions{Name: "Eng"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
got := out.String()
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{"id":"kb_99"`), "expected bare KnowledgeBase object; got %q", got)
assert.Contains(t, got, `"name":"Eng"`)
assert.NotContains(t, got, `"ok":`)
}
func TestCreate_StorageProvider_InjectsRequest(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_s", Name: "n"}}
opts := &CreateOptions{Name: "n", StorageProvider: "Local"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
require.NotNil(t, svc.got.StorageProviderConfig)
assert.Equal(t, "local", svc.got.StorageProviderConfig.Provider, "value should be lowercased + trimmed before send")
}
func TestCreate_StorageProvider_InvalidValueReturnsFlagError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{}
opts := &CreateOptions{Name: "n", StorageProvider: "azure"}
err := runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
assert.Equal(t, 2, cmdutil.ExitCode(err), "invalid --storage-provider must exit 2 (flag validation)")
assert.Contains(t, err.Error(), "invalid --storage-provider")
assert.Nil(t, svc.got, "SDK must not be called when flag validation fails")
}
func TestCreate_StorageProvider_OmittedWhenEmpty(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_n", Name: "n"}}
opts := &CreateOptions{Name: "n"} // no --storage-provider
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Nil(t, svc.got.StorageProviderConfig, "empty flag must omit StorageProviderConfig (let server pick default)")
}
+51
View File
@@ -0,0 +1,51 @@
// Package-level note:
//
// SetAgentHelp wires structured agent-targeted help onto a cobra command.
// Current coverage: chat, kb list. Adding it to another command requires
// touching only that command's NewCmd (a 5-line copy of the existing call
// sites).
package cmdutil
import (
"encoding/json"
"io"
"os"
"github.com/spf13/cobra"
)
// AgentHelp is the structured help blob emitted when an agent invokes
// `weknora <command> --help` with WEKNORA_AGENT_HELP=1. Distinct from
// cobra's human help text — agent-readable JSON keyed by stable fields
// so an LLM doesn't need to scrape the human help table.
type AgentHelp struct {
UsedFor string `json:"used_for"`
RequiredFlags []string `json:"required_flags,omitempty"`
Examples []string `json:"examples,omitempty"`
Output string `json:"output,omitempty"`
}
// SetAgentHelp attaches agent-targeted help metadata to a command. The
// original HelpFunc is preserved for the human path; the agent path
// activates only when WEKNORA_AGENT_HELP=1 (so human `--help` is
// unaffected).
//
// Currently applied to a small set of representative commands (chat,
// kb list); extend by calling SetAgentHelp in each command's NewCmd.
func SetAgentHelp(cmd *cobra.Command, ah AgentHelp) {
origHelp := cmd.HelpFunc()
cmd.SetHelpFunc(func(c *cobra.Command, args []string) {
if os.Getenv("WEKNORA_AGENT_HELP") == "1" {
emitAgentHelp(c.OutOrStdout(), ah)
return
}
origHelp(c, args)
})
}
func emitAgentHelp(w io.Writer, ah AgentHelp) {
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
_ = enc.Encode(ah)
}
+57
View File
@@ -0,0 +1,57 @@
package cmdutil
import (
"bytes"
"encoding/json"
"testing"
"github.com/spf13/cobra"
)
func TestSetAgentHelp_EmitsJSONWhenEnvSet(t *testing.T) {
t.Setenv("WEKNORA_AGENT_HELP", "1")
cmd := &cobra.Command{Use: "foo"}
ah := AgentHelp{
UsedFor: "frob a bar",
RequiredFlags: []string{"--name"},
Examples: []string{"weknora foo --name=x"},
}
SetAgentHelp(cmd, ah)
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.Help()
var got AgentHelp
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("output not JSON: %v\n%s", err, buf.String())
}
if got.UsedFor != "frob a bar" {
t.Errorf("UsedFor=%q, want %q", got.UsedFor, "frob a bar")
}
if len(got.RequiredFlags) != 1 || got.RequiredFlags[0] != "--name" {
t.Errorf("RequiredFlags=%v", got.RequiredFlags)
}
}
func TestSetAgentHelp_FallsThroughToHumanHelp(t *testing.T) {
t.Setenv("WEKNORA_AGENT_HELP", "")
cmd := &cobra.Command{
Use: "foo",
Short: "frob a bar",
Long: "Detailed human help here.",
}
SetAgentHelp(cmd, AgentHelp{UsedFor: "ignored"})
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.Help()
// Should NOT be JSON (human help is text)
if json.Valid(buf.Bytes()) {
t.Errorf("expected human text, got JSON:\n%s", buf.String())
}
if !bytes.Contains(buf.Bytes(), []byte("Detailed human help")) {
t.Errorf("human help missing from output:\n%s", buf.String())
}
}
+135
View File
@@ -0,0 +1,135 @@
package cmdutil
import (
"errors"
"fmt"
"io"
"sort"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/format"
)
// Typed format modes. Defined as constants to keep mode comparisons
// type-safe and prevent string drift across call sites.
const (
FormatText = "text"
FormatJSON = "json"
FormatNDJSON = "ndjson"
)
// FormatOptions captures the resolved --format + --jq state for a command.
// Mode is one of FormatText / FormatJSON / FormatNDJSON, or "" before
// ResolveDefault has been called.
type FormatOptions struct {
Mode string
JQ string
}
// AddFormatFlag registers --format and --jq on cmd. Optional fieldHints are
// appended to cmd.Long as a documentation aid for --jq projection
// (e.g., `weknora kb list --format json --jq '.[] | {id, name}'`).
//
// Uses cmd.Flags() (local) rather than a root persistent flag — only
// commands that actually honor --format register it, so cobra rejects
// --format on others with "unknown flag" rather than silently ignoring it.
func AddFormatFlag(cmd *cobra.Command, fieldHints ...string) {
cmd.Flags().String("format", "", "Output format: text | json | ndjson (default: text in TTY, json in pipe)")
cmd.Flags().StringP("jq", "q", "", "Filter JSON output using a jq `expression` (requires --format json|ndjson)")
if len(fieldHints) > 0 {
sorted := append([]string(nil), fieldHints...)
sort.Strings(sorted)
hdr := "\n\nJSON fields available (for --jq projection):\n " +
strings.Join(sorted, "\n ")
if cmd.Long != "" {
cmd.Long += hdr
} else {
cmd.Long = strings.TrimSpace(cmd.Short) + hdr
}
}
}
// CheckFormatFlag resolves --format + --jq from cmd. Returns:
// - (*FormatOptions{Mode:""}, nil) flag not set; caller should call ResolveDefault
// - (*FormatOptions{Mode:v,JQ:q}, nil) valid values
// - (nil, *FlagError) invalid --format, or --jq with explicit --format text
//
// --jq with --format unset is accepted: ResolveDefault below will promote
// the mode to FormatJSON so the filter has somewhere to apply.
func CheckFormatFlag(cmd *cobra.Command) (*FormatOptions, error) {
fopts := &FormatOptions{}
if f := cmd.Flags().Lookup("format"); f != nil {
v := f.Value.String()
switch v {
case "", FormatText, FormatJSON, FormatNDJSON:
fopts.Mode = v
default:
return nil, NewFlagError(fmt.Errorf("invalid --format %q: must be text | json | ndjson", v))
}
}
if f := cmd.Flags().Lookup("jq"); f != nil {
fopts.JQ = f.Value.String()
}
// --jq only meaningful for JSON-shaped output. Reject the explicit
// `--format text --jq ...` combination; the `--jq` with --format unset
// case is handled by ResolveDefault.
if fopts.JQ != "" && fopts.Mode == FormatText {
return nil, NewFlagError(errors.New("--jq requires --format json|ndjson"))
}
return fopts, nil
}
// WantsJSON reports whether the resolved mode is JSON or NDJSON. Used by
// callers to choose between the JSON emit path and human text rendering.
func (o *FormatOptions) WantsJSON() bool {
return o.Mode == FormatJSON || o.Mode == FormatNDJSON
}
// Emit serializes v according to the resolved Mode + JQ. For ndjson, slice
// values are split element-per-line (per ndjson.org); for json, v is
// emitted as-is. When JQ is set, the jq expression runs against the
// marshaled JSON and each result becomes a line. Text mode is the caller's
// job — Emit returns an error so a missed dispatch surfaces loudly.
func (o *FormatOptions) Emit(w io.Writer, v any) error {
switch o.Mode {
case FormatJSON:
return format.WriteJSONFiltered(w, v, nil, o.JQ)
case FormatNDJSON:
// jq output is naturally line-per-result → already valid NDJSON.
// Without jq, split arrays per ndjson.org (one object per line).
if o.JQ != "" {
return format.WriteJSONFiltered(w, v, nil, o.JQ)
}
return format.WriteNDJSON(w, v)
case FormatText:
return fmt.Errorf("FormatOptions.Emit: cannot emit text mode as JSON; caller must render text separately")
default:
return fmt.Errorf("FormatOptions.Emit: unknown mode %q", o.Mode)
}
}
// ResolveDefault fills in Mode using TTY detection when the user didn't pass
// --format explicitly. Pass iostreams.IO.IsStdoutTTY() as isTTY.
// No-op if Mode is already set.
//
// `--jq` without an explicit `--format` forces JSON regardless of TTY:
// the filter has no meaning in text mode, so silently dropping it would
// surprise the user. The `--jq` + `--format text` combination is caught
// up-front by CheckFormatFlag.
func (o *FormatOptions) ResolveDefault(isTTY bool) {
if o.Mode != "" {
return
}
if o.JQ != "" {
o.Mode = FormatJSON
return
}
if isTTY {
o.Mode = FormatText
} else {
o.Mode = FormatJSON
}
}
+146
View File
@@ -0,0 +1,146 @@
package cmdutil
import (
"bytes"
"encoding/json"
"errors"
"testing"
"github.com/spf13/cobra"
)
func TestCheckFormatFlags(t *testing.T) {
cases := []struct {
name string
args []string
wantMode string // "text" | "json" | "ndjson" | "" (unset)
wantErr bool
}{
// Unset → Mode is "" (caller resolves TTY default via ResolveDefault).
{"default", []string{}, "", false},
{"explicit text", []string{"--format", "text"}, "text", false},
{"json", []string{"--format", "json"}, "json", false},
{"ndjson", []string{"--format", "ndjson"}, "ndjson", false},
{"invalid value", []string{"--format", "yaml"}, "", true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cmd := &cobra.Command{}
AddFormatFlag(cmd)
cmd.SetArgs(tc.args)
cmd.RunE = func(c *cobra.Command, _ []string) error {
opts, err := CheckFormatFlag(c)
if (err != nil) != tc.wantErr {
t.Fatalf("err=%v wantErr=%v", err, tc.wantErr)
}
if err == nil && opts.Mode != tc.wantMode {
t.Errorf("mode=%q want %q", opts.Mode, tc.wantMode)
}
return nil
}
_ = cmd.Execute()
})
}
}
func TestFormatOptions_NDJSONSplitsList(t *testing.T) {
var buf bytes.Buffer
fopts := &FormatOptions{Mode: "ndjson"}
arr := []map[string]string{{"id": "a"}, {"id": "b"}}
if err := fopts.Emit(&buf, arr); err != nil {
t.Fatalf("Emit: %v", err)
}
want := `{"id":"a"}` + "\n" + `{"id":"b"}` + "\n"
if buf.String() != want {
t.Errorf("got %q want %q", buf.String(), want)
}
}
func TestFormatOptions_JSONEmitsArray(t *testing.T) {
var buf bytes.Buffer
fopts := &FormatOptions{Mode: "json"}
arr := []map[string]string{{"id": "a"}, {"id": "b"}}
if err := fopts.Emit(&buf, arr); err != nil {
t.Fatalf("Emit: %v", err)
}
// Expect a single JSON array, e.g. [{"id":"a"},{"id":"b"}]
var got []map[string]string
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("not valid JSON: %v\n%s", err, buf.String())
}
if len(got) != 2 {
t.Errorf("got %d items, want 2", len(got))
}
}
func TestFormatOptions_TextModeReturnsError(t *testing.T) {
fopts := &FormatOptions{Mode: "text"}
err := fopts.Emit(&bytes.Buffer{}, map[string]string{"a": "b"})
if err == nil {
t.Error("expected error for text mode, got nil")
}
}
func TestResolveDefault(t *testing.T) {
cases := []struct {
name string
mode string // pre-set Mode
jq string
isTTY bool
wantMode string
}{
{"empty isTTY", "", "", true, "text"},
{"empty no-tty", "", "", false, "json"},
{"already set keeps value tty", "ndjson", "", true, "ndjson"},
{"already set keeps value no-tty", "json", "", false, "json"},
// --jq with unset --format promotes to JSON regardless of TTY so the
// filter has somewhere to apply (silent text drop would surprise users).
{"jq forces json on TTY", "", ".[]", true, "json"},
{"jq with explicit ndjson preserved", "ndjson", ".[]", true, "ndjson"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
o := &FormatOptions{Mode: tc.mode, JQ: tc.jq}
o.ResolveDefault(tc.isTTY)
if o.Mode != tc.wantMode {
t.Errorf("mode=%q want %q", o.Mode, tc.wantMode)
}
})
}
}
// TestCheckFormatFlag_InvalidExitTwo guards the contract that flag-value
// validation maps to exit 2 (FlagError class), not the unclassified bucket.
func TestCheckFormatFlag_InvalidExitTwo(t *testing.T) {
cases := []struct {
name string
args []string
}{
{"invalid format value", []string{"--format", "yaml"}},
{"jq with explicit text mode", []string{"--format", "text", "--jq", ".id"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cmd := &cobra.Command{}
AddFormatFlag(cmd)
cmd.SetArgs(tc.args)
var got error
cmd.RunE = func(c *cobra.Command, _ []string) error {
_, err := CheckFormatFlag(c)
got = err
return err
}
_ = cmd.Execute()
if got == nil {
t.Fatal("expected error, got nil")
}
var fe *FlagError
if !errors.As(got, &fe) {
t.Fatalf("error %v is not a *FlagError; would map to exit 1 instead of 2", got)
}
if ExitCode(got) != 2 {
t.Errorf("ExitCode=%d, want 2", ExitCode(got))
}
})
}
}
-119
View File
@@ -1,119 +0,0 @@
package cmdutil
import (
"errors"
"io"
"sort"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/Tencent/WeKnora/cli/internal/format"
)
// JSONOptions captures the resolved --json + --jq state after CheckJSONFlags.
// A non-nil value means the user requested JSON output; Fields restricts
// each top-level object (or each element of a top-level array) to the
// listed keys; JQ is a jq expression applied to the final JSON.
type JSONOptions struct {
Fields []string
JQ string
}
// Enabled reports whether the caller asked for JSON output. Convenience
// shorthand for `opts != nil`.
func (o *JSONOptions) Enabled() bool { return o != nil }
// Emit serializes v as bare JSON to w, honoring the resolved field-filter
// and jq expression. Equivalent to calling format.WriteJSONFiltered with
// o.Fields / o.JQ, but lets call sites stay free of the format import.
// Safe to call on a nil receiver in case the caller composes it with
// Enabled().
func (o *JSONOptions) Emit(w io.Writer, v any) error {
if o == nil {
return format.WriteJSON(w, v)
}
return format.WriteJSONFiltered(w, v, o.Fields, o.JQ)
}
// jsonNoOptSentinel marks a bare `--json` (no comma-separated values after
// it). pflag's NoOptDefVal mechanism stores this sentinel into the slice;
// CheckJSONFlags then maps it to "no field filter" (full payload).
//
// Field discovery moves to per-command `--help` "JSON fields available"
// sections rendered by AddJSONFlags.
const jsonNoOptSentinel = "\x00json-no-value"
// AddJSONFlags registers --json and --jq on cmd.
//
// - `--json` → bare JSON payload, no field filter
// - `--json=id,name` → each object restricted to the listed fields
// - `--jq <expr>` → apply a jq expression to the JSON; requires
// --json to be set explicitly
//
// `fields` is the set of available fields the user may pass; rendered in
// the command's help. Pass nil to skip the help annotation (uncommon).
func AddJSONFlags(cmd *cobra.Command, fields []string) {
f := cmd.Flags()
// Backticks reserved for pflag's UnquoteUsage to extract the varname;
// avoid them in the description so the help doesn't render the flag
// name twice.
f.StringSlice("json", nil, "Output bare JSON (--json=id,name to project `fields`)")
f.Lookup("json").NoOptDefVal = jsonNoOptSentinel
f.StringP("jq", "q", "", "Filter JSON output using a jq `expression` (requires --json)")
if len(fields) > 0 {
sorted := append([]string(nil), fields...)
sort.Strings(sorted)
// Append to Long without overwriting per-command prose.
hdr := "\n\nJSON fields available via `--json=id,name,...`:\n " +
strings.Join(sorted, "\n ")
if cmd.Long != "" {
cmd.Long += hdr
} else {
cmd.Long = strings.TrimSpace(cmd.Short) + hdr
}
}
}
// CheckJSONFlags resolves the --json + --jq state from cmd. Returns:
// - (nil, nil) neither flag set (human output mode)
// - (*JSONOptions, nil) --json set (possibly with --jq)
// - (nil, error) --jq without --json (plain error, exit 1)
//
// Bare `--json` yields Fields == nil (no field filter). Explicit field
// list yields Fields == []string{"id", "name", ...} (filter applied).
func CheckJSONFlags(cmd *cobra.Command) (*JSONOptions, error) {
f := cmd.Flags()
jsonFlag := f.Lookup("json")
jqFlag := f.Lookup("jq")
if jsonFlag == nil {
return nil, nil
}
if jsonFlag.Changed {
sv, ok := jsonFlag.Value.(pflag.SliceValue)
if !ok {
return nil, errors.New("internal: --json flag is not a StringSlice")
}
raw := sv.GetSlice()
opts := &JSONOptions{}
// Strip the bare-flag sentinel if present.
for _, v := range raw {
if v == jsonNoOptSentinel {
continue
}
opts.Fields = append(opts.Fields, v)
}
if jqFlag != nil {
opts.JQ = jqFlag.Value.String()
}
return opts, nil
}
if jqFlag != nil && jqFlag.Changed {
// Plain error, exit 1 (not FlagError → exit 2): the flag itself
// parsed fine, the combination is what's wrong.
return nil, errors.New("cannot use `--jq` without specifying `--json`")
}
return nil, nil
}
-190
View File
@@ -1,190 +0,0 @@
package cmdutil_test
import (
"bytes"
"errors"
"strings"
"testing"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
var testFields = []string{"id", "name", "kb_id", "updated_at"}
func newTestCmd(t *testing.T, captured **cmdutil.JSONOptions) *cobra.Command {
t.Helper()
cmd := &cobra.Command{
Use: "test",
SilenceErrors: true,
SilenceUsage: true,
RunE: func(c *cobra.Command, args []string) error {
opts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
*captured = opts
return nil
},
}
cmdutil.AddJSONFlags(cmd, testFields)
return cmd
}
func TestAddJSONFlags_BareYieldsEnabledOptsWithNoFields(t *testing.T) {
// `--json` bare → Enabled() with empty Fields → caller emits full payload.
var captured *cmdutil.JSONOptions
cmd := newTestCmd(t, &captured)
cmd.SetArgs([]string{"--json"})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() err = %v", err)
}
if !captured.Enabled() {
t.Fatalf("expected Enabled, got nil")
}
if len(captured.Fields) != 0 {
t.Errorf("bare --json must produce empty Fields, got %v", captured.Fields)
}
}
func TestAddJSONFlags_FieldsFlagParsing(t *testing.T) {
// NoOptDefVal sentinel means the `=` form is required for value passing.
// Space form `--json id,name` parses as bare + positional; bare `--json`
// (no value) is reserved as a shortcut for the unfiltered payload.
cases := []struct {
args []string
want []string
}{
{[]string{"--json=id,name"}, []string{"id", "name"}},
{[]string{"--json=id,name,kb_id"}, []string{"id", "name", "kb_id"}},
{[]string{"--json=id"}, []string{"id"}},
}
for _, tc := range cases {
t.Run(strings.Join(tc.args, " "), func(t *testing.T) {
var captured *cmdutil.JSONOptions
cmd := newTestCmd(t, &captured)
cmd.SetArgs(tc.args)
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() err = %v", err)
}
if captured == nil {
t.Fatalf("expected JSONOptions captured, got nil")
}
if !equalSlice(captured.Fields, tc.want) {
t.Errorf("Fields = %v, want %v", captured.Fields, tc.want)
}
if captured.JQ != "" {
t.Errorf("JQ should be empty, got %q", captured.JQ)
}
})
}
}
func TestAddJSONFlags_NoFlagsSet(t *testing.T) {
var captured *cmdutil.JSONOptions
cmd := newTestCmd(t, &captured)
cmd.SetArgs([]string{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() err = %v", err)
}
if captured != nil {
t.Errorf("expected nil JSONOptions for human mode, got %+v", captured)
}
}
func TestAddJSONFlags_JQWithoutJSON(t *testing.T) {
var captured *cmdutil.JSONOptions
cmd := newTestCmd(t, &captured)
cmd.SetArgs([]string{"--jq", ".data.items[]"})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
err := cmd.Execute()
if err == nil {
t.Fatalf("expected mutual-dep error, got nil")
}
want := "cannot use `--jq` without specifying `--json`"
if err.Error() != want {
t.Errorf("wrong message.\nwant: %q\ngot: %q", want, err.Error())
}
// Must NOT be a FlagError - gh emits this as a plain error so exit
// code stays 1, not 2.
var fe *cmdutil.FlagError
if errors.As(err, &fe) {
t.Errorf("error should not be FlagError; gh treats this as exit 1")
}
}
func TestAddJSONFlags_JQWithJSON(t *testing.T) {
var captured *cmdutil.JSONOptions
cmd := newTestCmd(t, &captured)
cmd.SetArgs([]string{"--json=id,name", "--jq", ".data.items[0].id"})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() err = %v", err)
}
if captured == nil {
t.Fatalf("expected JSONOptions, got nil")
}
if !equalSlice(captured.Fields, []string{"id", "name"}) {
t.Errorf("Fields = %v, want [id name]", captured.Fields)
}
if captured.JQ != ".data.items[0].id" {
t.Errorf("JQ = %q, want %q", captured.JQ, ".data.items[0].id")
}
}
func TestAddJSONFlags_JQShortFlag(t *testing.T) {
// gh uses -q as shorthand for --jq.
var captured *cmdutil.JSONOptions
cmd := newTestCmd(t, &captured)
cmd.SetArgs([]string{"--json=id", "-q", ".data"})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() err = %v", err)
}
if captured == nil || captured.JQ != ".data" {
t.Errorf("expected JQ=.data, got %+v", captured)
}
}
func TestAddJSONFlags_HelpListsFields(t *testing.T) {
cmd := &cobra.Command{Use: "test", Short: "A test command"}
cmdutil.AddJSONFlags(cmd, []string{"name", "id", "updated_at"})
if !strings.Contains(cmd.Long, "JSON fields available") {
t.Errorf("expected help to include 'JSON fields available'; got Long=%q", cmd.Long)
}
// Fields should appear alphabetically sorted.
idAt := strings.Index(cmd.Long, "id")
nameAt := strings.Index(cmd.Long, "name")
updatedAt := strings.Index(cmd.Long, "updated_at")
if !(idAt < nameAt && nameAt < updatedAt) {
t.Errorf("fields not sorted in Long: idAt=%d nameAt=%d updatedAt=%d", idAt, nameAt, updatedAt)
}
}
func equalSlice(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
+25
View File
@@ -0,0 +1,25 @@
package format
import (
"io"
"reflect"
)
// WriteNDJSON serializes v as NDJSON: one JSON value per line, '\n' terminated.
// If v is a slice or array, each element gets its own line; otherwise v is
// emitted as a single line. Per http://ndjson.org.
//
// HTML escaping is disabled (via WriteJSON) so '<', '>', '&' stay literal —
// cleaner for agent stream-parsers that don't need HTML-safe output.
func WriteNDJSON(w io.Writer, v any) error {
rv := reflect.ValueOf(v)
if rv.IsValid() && (rv.Kind() == reflect.Slice || rv.Kind() == reflect.Array) {
for i := 0; i < rv.Len(); i++ {
if err := WriteJSON(w, rv.Index(i).Interface()); err != nil {
return err
}
}
return nil
}
return WriteJSON(w, v)
}
+67
View File
@@ -0,0 +1,67 @@
package format_test
import (
"bytes"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/format"
)
func TestWriteNDJSON_ArraySplitsPerElement(t *testing.T) {
var buf bytes.Buffer
arr := []map[string]any{{"id": "1"}, {"id": "2"}, {"id": "3"}}
if err := format.WriteNDJSON(&buf, arr); err != nil {
t.Fatalf("WriteNDJSON: %v", err)
}
want := `{"id":"1"}` + "\n" + `{"id":"2"}` + "\n" + `{"id":"3"}` + "\n"
if buf.String() != want {
t.Errorf("got %q want %q", buf.String(), want)
}
}
func TestWriteNDJSON_SingleRecord(t *testing.T) {
var buf bytes.Buffer
rec := map[string]string{"id": "abc"}
if err := format.WriteNDJSON(&buf, rec); err != nil {
t.Fatalf("WriteNDJSON: %v", err)
}
want := `{"id":"abc"}` + "\n"
if buf.String() != want {
t.Errorf("got %q want %q", buf.String(), want)
}
}
func TestWriteNDJSON_EmptySlice(t *testing.T) {
var buf bytes.Buffer
if err := format.WriteNDJSON(&buf, []string{}); err != nil {
t.Fatalf("WriteNDJSON: %v", err)
}
if buf.String() != "" {
t.Errorf("got %q want empty", buf.String())
}
}
func TestWriteNDJSON_TypedSlice(t *testing.T) {
type item struct {
ID string `json:"id"`
}
var buf bytes.Buffer
if err := format.WriteNDJSON(&buf, []item{{ID: "x"}, {ID: "y"}}); err != nil {
t.Fatalf("WriteNDJSON: %v", err)
}
want := `{"id":"x"}` + "\n" + `{"id":"y"}` + "\n"
if buf.String() != want {
t.Errorf("got %q want %q", buf.String(), want)
}
}
func TestWriteNDJSON_NoHTMLEscape(t *testing.T) {
var buf bytes.Buffer
if err := format.WriteNDJSON(&buf, map[string]string{"k": "a<b>c&d"}); err != nil {
t.Fatalf("WriteNDJSON: %v", err)
}
if !strings.Contains(buf.String(), "a<b>c&d") {
t.Errorf("expected unescaped HTML chars, got %q", buf.String())
}
}
+26 -18
View File
@@ -196,7 +196,7 @@ func addDocList(server *mcpsdk.Server, svc knowledgeService) {
// ---- doc_view ------------------------------------------------------------
type docViewInput struct {
KnowledgeID string `json:"knowledge_id" jsonschema:"document (knowledge entry) ID"`
DocID string `json:"doc_id" jsonschema:"document ID (same value as the doc-id positional in CLI commands)"`
}
func addDocView(server *mcpsdk.Server, svc knowledgeService) {
@@ -204,10 +204,10 @@ func addDocView(server *mcpsdk.Server, svc knowledgeService) {
Name: "doc_view",
Description: "Fetch a single document by ID. Returns the Knowledge record (file_name, title, type, parse_status, size, embedding_model_id, source URL if any, etc.).",
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docViewInput) (*mcpsdk.CallToolResult, *sdk.Knowledge, error) {
if in.KnowledgeID == "" {
return nil, nil, fmt.Errorf("knowledge_id is required")
if in.DocID == "" {
return nil, nil, fmt.Errorf("doc_id is required")
}
k, err := svc.GetKnowledge(ctx, in.KnowledgeID)
k, err := svc.GetKnowledge(ctx, in.DocID)
if err != nil {
return nil, nil, fmt.Errorf("get knowledge: %w", err)
}
@@ -218,13 +218,13 @@ func addDocView(server *mcpsdk.Server, svc knowledgeService) {
// ---- doc_download --------------------------------------------------------
type docDownloadInput struct {
KnowledgeID string `json:"knowledge_id" jsonschema:"document (knowledge entry) ID"`
DocID string `json:"doc_id" jsonschema:"document ID (same value as the doc-id positional in CLI commands)"`
}
type docDownloadOutput struct {
KnowledgeID string `json:"knowledge_id"`
FileName string `json:"file_name"`
Bytes int `json:"bytes"`
DocID string `json:"doc_id"`
FileName string `json:"file_name"`
Bytes int `json:"bytes"`
// Content is the file contents (UTF-8 if text, base64 if the SDK
// reports a binary-looking blob). For binary, agents should decode
// before consuming.
@@ -243,10 +243,10 @@ func addDocDownload(server *mcpsdk.Server, svc knowledgeService) {
Name: "doc_download",
Description: "Download a document's raw bytes by ID. Capped at 1 MiB per call - for larger documents, use search_chunks to find the relevant excerpts. is_base64 reports whether content was base64-encoded (heuristic: presence of NUL byte in the first 512 bytes).",
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docDownloadInput) (*mcpsdk.CallToolResult, docDownloadOutput, error) {
if in.KnowledgeID == "" {
return nil, docDownloadOutput{}, fmt.Errorf("knowledge_id is required")
if in.DocID == "" {
return nil, docDownloadOutput{}, fmt.Errorf("doc_id is required")
}
name, body, err := svc.OpenKnowledgeFile(ctx, in.KnowledgeID)
name, body, err := svc.OpenKnowledgeFile(ctx, in.DocID)
if err != nil {
return nil, docDownloadOutput{}, fmt.Errorf("open knowledge file: %w", err)
}
@@ -260,11 +260,11 @@ func addDocDownload(server *mcpsdk.Server, svc knowledgeService) {
}
content, isBase64 := encodeDownload(buf)
return nil, docDownloadOutput{
KnowledgeID: in.KnowledgeID,
FileName: name,
Bytes: len(buf),
Content: content,
IsBase64: isBase64,
DocID: in.DocID,
FileName: name,
Bytes: len(buf),
Content: content,
IsBase64: isBase64,
}, nil
})
}
@@ -338,14 +338,17 @@ type chatInput struct {
type chatOutput struct {
Answer string `json:"answer"`
References []*sdk.SearchResult `json:"references"`
Thinking string `json:"thinking,omitempty"` // reasoning text from response_type=thinking; empty for non-reasoning models
SessionID string `json:"session_id"`
AssistantMessageID string `json:"assistant_message_id,omitempty"`
KBID string `json:"kb_id"`
Query string `json:"query"`
}
func addChat(server *mcpsdk.Server, svc chatService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "chat",
Description: "Stream a RAG answer from the LLM, grounded in the given knowledge base. The SSE stream is accumulated server-side; this tool returns the full answer + references + session_id once the stream completes. Pass session_id to continue a multi-turn conversation; otherwise a fresh session is auto-created.",
Description: "Stream a RAG answer from the LLM, grounded in the given knowledge base. The SSE stream is accumulated server-side (MCP tools/call has no standard partial-response, so this is NOT streaming); the tool returns the full accumulated response once the stream completes. Pass session_id to continue a multi-turn conversation; otherwise a fresh session is auto-created.",
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in chatInput) (*mcpsdk.CallToolResult, any, error) {
if in.KBID == "" {
return nil, nil, fmt.Errorf("kb_id is required")
@@ -385,8 +388,11 @@ func addChat(server *mcpsdk.Server, svc chatService) {
return nil, chatOutput{
Answer: acc.Result(),
References: acc.References,
Thinking: acc.Thinking(),
SessionID: sid,
AssistantMessageID: acc.AssistantMessageID,
KBID: in.KBID,
Query: in.Query,
}, nil
})
}
@@ -430,12 +436,13 @@ type agentInvokeOutput struct {
Thinking string `json:"thinking,omitempty"`
SessionID string `json:"session_id"`
AgentID string `json:"agent_id"`
Query string `json:"query"`
}
func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "agent_invoke",
Description: "Run a query through a custom agent (system prompt + tool allow-list + KB scope). The agent's SSE stream is accumulated server-side; this tool returns the final answer plus the trace (references, tool_events, thinking).",
Description: "Run a query through a custom agent (system prompt + tool allow-list + KB scope). The agent's SSE stream is accumulated server-side (MCP tools/call has no standard partial-response, so this is NOT streaming); the tool returns the final accumulated response once the stream completes.",
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in agentInvokeInput) (*mcpsdk.CallToolResult, any, error) {
if in.AgentID == "" {
return nil, nil, fmt.Errorf("agent_id is required")
@@ -477,6 +484,7 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) {
Thinking: acc.Thinking(),
SessionID: sessionID,
AgentID: in.AgentID,
Query: in.Query,
}, nil
})
}
+51 -3
View File
@@ -326,7 +326,7 @@ func TestTool_DocView(t *testing.T) {
svc := &fakeSvc{getDoc: &sdk.Knowledge{ID: "k1", FileName: "a.pdf"}}
c, _ := newTestServer(t, svc)
var out sdk.Knowledge
callTool(t, c, "doc_view", map[string]any{"knowledge_id": "k1"}, &out)
callTool(t, c, "doc_view", map[string]any{"doc_id": "k1"}, &out)
if out.ID != "k1" {
t.Errorf("got %+v", out)
}
@@ -339,7 +339,7 @@ func TestTool_DocDownload_Text(t *testing.T) {
}
c, _ := newTestServer(t, svc)
var out docDownloadOutput
callTool(t, c, "doc_download", map[string]any{"knowledge_id": "k1"}, &out)
callTool(t, c, "doc_download", map[string]any{"doc_id": "k1"}, &out)
if out.Content != "hello world" {
t.Errorf("content = %q", out.Content)
}
@@ -357,7 +357,7 @@ func TestTool_DocDownload_BinaryBase64(t *testing.T) {
}
c, _ := newTestServer(t, svc)
var out docDownloadOutput
callTool(t, c, "doc_download", map[string]any{"knowledge_id": "k1"}, &out)
callTool(t, c, "doc_download", map[string]any{"doc_id": "k1"}, &out)
if !out.IsBase64 {
t.Errorf("binary should be base64; got is_base64=%v content=%q", out.IsBase64, out.Content)
}
@@ -423,6 +423,54 @@ func TestTool_Chat_AccumulateAnswerAndReferences(t *testing.T) {
}
}
func TestMCP_ChatToolReturnsThinking(t *testing.T) {
svc := &fakeSvc{
kbStreamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeThinking, Content: "let me reason..."},
{ResponseType: sdk.ResponseTypeAnswer, Content: "final answer"},
{ResponseType: sdk.ResponseTypeComplete},
},
}
c, _ := newTestServer(t, svc)
var out chatOutput
callTool(t, c, "chat", map[string]any{"kb_id": "kb_x", "query": "deep question"}, &out)
if out.Thinking != "let me reason..." {
t.Errorf("thinking = %q, want %q", out.Thinking, "let me reason...")
}
if out.Answer != "final answer" {
t.Errorf("answer = %q, want %q", out.Answer, "final answer")
}
if out.KBID != "kb_x" {
t.Errorf("kb_id = %q, want %q", out.KBID, "kb_x")
}
if out.Query != "deep question" {
t.Errorf("query = %q, want %q", out.Query, "deep question")
}
}
func TestMCP_AgentInvokeToolReturnsToolCalls(t *testing.T) {
svc := &fakeSvc{
agentEvents: []*sdk.AgentStreamResponse{
{ResponseType: sdk.AgentResponseTypeThinking, Content: "agent thinks"},
{ResponseType: sdk.AgentResponseTypeToolCall, ID: "tc1", Content: "knowledge_search"},
{ResponseType: sdk.AgentResponseTypeAnswer, Content: "agent answer"},
{Done: true},
},
}
c, _ := newTestServer(t, svc)
var out agentInvokeOutput
callTool(t, c, "agent_invoke", map[string]any{"agent_id": "ag1", "query": "tool question"}, &out)
if out.Thinking != "agent thinks" {
t.Errorf("thinking = %q, want %q", out.Thinking, "agent thinks")
}
if len(out.ToolEvents) != 1 || out.ToolEvents[0].ID != "tc1" {
t.Errorf("tool_events = %+v, want 1 event with id tc1", out.ToolEvents)
}
if out.Query != "tool question" {
t.Errorf("query = %q, want %q", out.Query, "tool question")
}
}
func TestTool_Chat_ExistingSessionSkipsCreate(t *testing.T) {
svc := &fakeSvc{
kbStreamEvents: []*sdk.StreamResponse{{ResponseType: sdk.ResponseTypeComplete}},
+18 -1
View File
@@ -2,11 +2,28 @@
package main
import (
"context"
"os"
"os/signal"
"syscall"
"github.com/Tencent/WeKnora/cli/cmd"
)
func main() {
os.Exit(cmd.Execute())
// Wire SIGINT/SIGTERM into the root context so long-running commands
// (chat / agent invoke / doc wait) observe ctx.Done() and can run their
// cancellation cleanup paths (e.g., re-emit the auto-created session id
// so users can resume with --session). On signal-triggered cancellation
// the process exits 130 regardless of what Execute returned — matches
// the wire contract documented in cli/README.md "Exit codes".
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
rc := cmd.Execute(ctx)
if ctx.Err() == context.Canceled {
os.Exit(130)
}
os.Exit(rc)
}
+24 -7
View File
@@ -1,20 +1,37 @@
// Package client uses an opt-in slog logger for SDK-internal trace output.
// Default behavior writes to io.Discard so SDK consumers (CLI, server) never
// see SDK trace output on stdout/stderr. Set WEKNORA_SDK_DEBUG=1 to route
// trace events to stderr.
// see SDK trace output on stdout/stderr. Embedders enable debug output by
// calling SetDebugLevel("debug") at startup.
package client
import (
"io"
"log/slog"
"os"
"strings"
)
var debugLogger = newDebugLogger()
var debugLogger = slog.New(slog.NewTextHandler(io.Discard, nil))
func newDebugLogger() *slog.Logger {
if os.Getenv("WEKNORA_SDK_DEBUG") == "1" {
return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}))
// SetDebugLevel replaces the SDK's internal debug logger so callers can
// programmatically control SDK trace output (e.g., the CLI's --log-level
// flag). Accepted levels: "debug" / "info" / "warn" / "error" (case-
// insensitive); any other value (including "") disables output entirely
// (writes to io.Discard).
//
// Not safe for concurrent use while SDK calls are in flight — call once
// at startup before any client method is invoked.
func SetDebugLevel(level string) {
switch strings.ToLower(level) {
case "debug":
debugLogger = slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}))
case "info":
debugLogger = slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo}))
case "warn":
debugLogger = slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}))
default:
// "error" or unrecognized → silent. SDK only emits Debug calls today,
// so error-level discards everything in practice.
debugLogger = slog.New(slog.NewTextHandler(io.Discard, nil))
}
return slog.New(slog.NewTextHandler(io.Discard, nil))
}