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
+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"])
}
}