feat(cli)!: add agent-first chat and session ask output modes

This commit is contained in:
coconut-yc
2026-06-21 02:41:36 +08:00
committed by lyingbug
parent 238297e2c5
commit 9437e1ac3c
18 changed files with 1317 additions and 355 deletions
+135 -71
View File
@@ -1,21 +1,22 @@
// Package chat implements `weknora chat <text>` - the streaming RAG answer
// entry point.
//
// Two output modes share a single SDK call:
// Three output modes share a single SDK call:
//
// - Stream mode (TTY + --format text): 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.
// - JSON mode (--format json, the default): buffer a bounded projection of
// the stream into one success envelope. The default projection contains
// answer events only; --reference adds indexed citations and --verbose
// adds reasoning, tools, and lifecycle frames.
//
// - NDJSON mode (--format json / --format ndjson / pipe): inject a CLI
// "init" event at stream head, then pass through every SDK event verbatim
// as NDJSON lines. Agents and pipes get a live event stream they can
// parse incrementally. --format json routes here too — buffered JSON
// envelope makes no sense for a streaming command.
// - Text mode (--format text): render the same projection as JSON
// directly to iostreams.IO.Out as it arrives.
//
// - NDJSON mode (--format ndjson): inject a CLI "init" event at stream
// head, then pass through every SDK event verbatim as NDJSON lines —
// the raw protocol trace, for debugging / advanced consumers.
//
// The SDK's KnowledgeQAStream callback contract is invoked sequentially on
// one goroutine, so neither mode needs locking. The runChat core takes a
// one goroutine, so no mode needs locking. The runChat core takes a
// ChatService interface so tests inject a fake without standing up a real
// SSE server.
package chat
@@ -28,26 +29,31 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
"github.com/Tencent/WeKnora/cli/internal/sse"
sdk "github.com/Tencent/WeKnora/client"
)
// chatFields enumerates the NDJSON init-event fields surfaced for
// `--format json` / `--format ndjson` discovery on `chat`. Reflects the
// InitEvent head line + the raw SDK event vocabulary.
// chatFields enumerates the fields surfaced for `--jq` projection discovery
// on `chat`: the json object's data fields + the raw SDK event vocabulary
// used by --format ndjson.
var chatFields = []string{
"session_id", "kb_id",
// SDK event fields (pass-through): response_type, content, done,
// knowledge_references, assistant_message_id, session_id
"events", "session_id", "assistant_message_id", "kb_id", "query",
// NDJSON init + SDK event fields.
"type", "kb_id", "profile", "response_type", "content", "done", "knowledge_references", "data",
}
type Options struct {
Query string
KBID string
SessionID string
// Reference adds bounded kb_id/chunk_id reference events to JSON/text.
Reference bool
// Verbose surfaces the projected execution trace in JSON/text,
// including reasoning, tools, and lifecycle events.
// NDJSON is always raw and is unaffected by presentation flags.
Verbose bool
}
// ChatService is the narrow SDK surface this command depends on. *sdk.Client
@@ -69,12 +75,14 @@ answer back. By default a fresh session is created on first invocation; pass
--session to continue an existing conversation.
Modes:
--format text: live token streaming + reference footer
--format json / --format ndjson / pipe (default): NDJSON event stream —
one init line at head (session_id, kb_id),
then raw SDK events verbatim. Both json
and ndjson flags produce the same NDJSON
stream.`,
--format json (default): one JSON envelope with answer events
--format text: live human-readable answer stream
--format ndjson: raw NDJSON event stream — init line (session_id,
kb_id) then SDK events verbatim. Debug / advanced.
Pass --reference to include bounded kb_id/chunk_id reference indexes. Pass
--verbose to include reasoning, tool activity, and lifecycle frames. Combine
both flags for the complete projected stream.`,
Example: ` weknora chat "What is RRF?" --kb a32a63ff-fb36-4874-bcaa-30f48570a694
weknora chat "Summarise this design doc" --kb my-kb --format json
weknora chat "Continue?" --session sess_abc`,
@@ -103,12 +111,17 @@ Modes:
}
cmdutil.AddKBFlag(cmd)
cmd.Flags().StringVar(&opts.SessionID, "session", "", "Continue an existing chat session (skip auto-create)")
cmd.Flags().BoolVar(&opts.Reference, "reference", false, "Include indexed references in JSON/text output")
cmd.Flags().BoolVar(&opts.Verbose, "verbose", false, "Include reasoning, tools, and lifecycle events in JSON/text output")
cmdutil.AddFormatFlag(cmd, chatFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Ask a streaming RAG question against a knowledge base. Produces an NDJSON event stream: init line (session_id, kb_id) then raw SDK events. Use --format json or --format ndjson.",
UsedFor: "Ask a RAG question against a knowledge base. Default JSON returns a bounded answer-event projection. --reference adds indexed citations; --verbose adds reasoning, tools, and lifecycle events. --format ndjson streams raw SDK events; --format text renders the selected events live.",
RequiredFlags: []string{"--kb"},
Examples: []string{`weknora chat "What is RRF?" --kb kb_abc --format json`},
Output: "NDJSON stream: {type:init, session_id, kb_id} then SDK events (response_type, content, done, knowledge_references, ...)",
Examples: []string{
`weknora chat "What is RRF?" --kb kb_abc`,
`weknora chat "What is RRF?" --kb kb_abc --jq '[.data.events[].content] | join("")'`,
},
Output: "Default --format json: {ok,data:{events:[answer...],session_id,kb_id,query}}. --reference adds kb_id/chunk_id reference events; --verbose adds execution events. --format ndjson remains raw.",
})
return cmd
}
@@ -128,11 +141,8 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
return cmdutil.NewError(cmdutil.CodeServerError, "chat: no SDK client available")
}
// Streaming commands route --format json AND --format ndjson to the
// NDJSON event-stream path. A buffered envelope makes no sense for a
// streaming command. Only --format text uses the live renderer.
ndjsonMode := fopts != nil && (fopts.Mode == cmdutil.FormatJSON || fopts.Mode == cmdutil.FormatNDJSON)
// --format selects the output shape: json (default) accumulates and
// emits one object, ndjson streams raw SDK events, text renders live.
sessionID := opts.SessionID
autoCreated := false
if sessionID == "" {
@@ -156,13 +166,16 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
autoCreated = true
}
if ndjsonMode {
if fopts != nil && fopts.Mode == cmdutil.FormatNDJSON {
return runChatNDJSON(ctx, opts, sessionID, svc)
}
if fopts != nil && fopts.Mode == cmdutil.FormatJSON {
return runChatJSON(ctx, opts, fopts, sessionID, svc)
}
// 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
// past tokens. Skipped in NDJSON mode (it appears in the init event).
// past tokens. Skipped in json/ndjson mode (session_id is in the output).
if autoCreated {
fmt.Fprintf(iostreams.IO.Err, "session: %s (use --session to continue)\n", sessionID)
}
@@ -170,10 +183,9 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
return runChatText(ctx, opts, sessionID, autoCreated, svc)
}
// runChatNDJSON handles --format json and --format ndjson paths.
// Emits a CLI init event at stream head, then passes every SDK event through
// verbatim as NDJSON lines. No buffering — callers parse the stream
// incrementally.
// runChatNDJSON handles the --format ndjson path: emits a CLI init event at
// stream head, then passes every SDK event through verbatim as NDJSON lines.
// No buffering — callers parse the stream incrementally.
func runChatNDJSON(ctx context.Context, opts *Options, sessionID string, svc ChatService) error {
w := iostreams.IO.Out
@@ -198,6 +210,8 @@ func runChatNDJSON(ctx context.Context, opts *Options, sessionID string, svc Cha
Channel: "api",
}
cb := func(r *sdk.StreamResponse) error {
// NDJSON is the raw protocol/debug surface: do not filter events or
// mutate their payloads. JSON/text modes own presentation filtering.
return output.EmitSDKEvent(w, r)
}
if err := svc.KnowledgeQAStream(ctx, sessionID, req, cb); err != nil {
@@ -209,12 +223,9 @@ func runChatNDJSON(ctx context.Context, opts *Options, sessionID string, svc Cha
return nil
}
// runChatText handles the --format text path. Streams content fragments
// live on TTY; accumulates then renders on non-TTY pipes.
// runChatText handles the --format text path. It renders the same
// projection as JSON immediately for both terminals and pipes.
func runChatText(ctx context.Context, opts *Options, sessionID string, autoCreated bool, svc ChatService) error {
// Stream mode requires an interactive stdout.
streamMode := iostreams.IO.IsStdoutTTY()
req := &sdk.KnowledgeQARequest{
Query: opts.Query,
KnowledgeBaseIDs: []string{opts.KBID},
@@ -223,16 +234,15 @@ func runChatText(ctx context.Context, opts *Options, sessionID string, autoCreat
Channel: "api",
}
acc := &sse.Accumulator{}
projector := sse.NewProjector(opts.Verbose, opts.Reference, opts.KBID)
renderer := sse.NewTextRenderer(iostreams.IO.Out, opts.Verbose)
cb := func(r *sdk.StreamResponse) error {
if streamMode && r != nil && r.Content != "" {
// Best-effort write; if stdout dies the SDK will surface the
// error on the next iteration. No need to bail early.
_, _ = iostreams.IO.Out.Write([]byte(r.Content))
event, include := projector.Chat(r)
if !include {
return nil
}
acc.Append(r)
return nil
return renderer.Write(event)
}
streamErr := svc.KnowledgeQAStream(ctx, sessionID, req, cb)
@@ -250,7 +260,7 @@ func runChatText(ctx context.Context, opts *Options, sessionID string, autoCreat
// 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 a retry.
if acc.Result() != "" && !acc.Done() {
if projector.Seen() && !projector.Done() {
return cmdutil.Wrapf(cmdutil.CodeSSEStreamAborted, streamErr, "stream aborted before completion")
}
// Pre-stream HTTP / transport failure: route through the canonical
@@ -264,30 +274,84 @@ func runChatText(ctx context.Context, opts *Options, sessionID string, autoCreat
// case (Done frame never arrived AND no content): better to surface the
// abort than emit ok=true with answer="" - agents can't distinguish the
// model genuinely had nothing to say from the stream getting cut.
if !acc.Done() {
if !projector.Done() {
return cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")
}
return renderer.Close()
}
answer := acc.Result()
references := acc.References
// Streaming mode already wrote the answer body via the callback, so we
// only need to render the trailing references (and a closing newline).
// Non-TTY accumulate path writes the answer here for the first time.
out := iostreams.IO.Out
if streamMode {
// Ensure the answer line ends cleanly before the references footer.
if !strings.HasSuffix(answer, "\n") {
fmt.Fprintln(out)
}
} else {
fmt.Fprint(out, answer)
if !strings.HasSuffix(answer, "\n") {
fmt.Fprintln(out)
}
// runChatJSON handles the --format json path (the default): collect the
// projection and emit it in one normal success envelope.
func runChatJSON(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, sessionID string, svc ChatService) error {
req := &sdk.KnowledgeQARequest{
Query: opts.Query,
KnowledgeBaseIDs: []string{opts.KBID},
AgentEnabled: false,
WebSearchEnabled: false,
Channel: "api",
}
format.WriteReferences(out, references)
return nil
projector := sse.NewProjector(opts.Verbose, opts.Reference, opts.KBID)
events := make([]sse.ProjectedEvent, 0)
cb := func(r *sdk.StreamResponse) error {
if event, include := projector.Chat(r); include {
events = append(events, event)
}
return nil
}
if err := svc.KnowledgeQAStream(ctx, sessionID, req, cb); err != nil {
if cmdutil.IsCancelled(ctx, err) {
return chatStreamError(cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "chat cancelled"), sessionID, projector.AssistantMessageID())
}
return chatStreamError(cmdutil.WrapHTTP(err, "knowledge qa stream"), sessionID, projector.AssistantMessageID())
}
if !projector.Done() {
return chatStreamError(
cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event"),
sessionID,
projector.AssistantMessageID(),
)
}
sid := projector.SessionID()
if sid == "" {
sid = sessionID
}
data := chatResult{
Events: events,
SessionID: sid,
AssistantMessageID: projector.AssistantMessageID(),
KBID: opts.KBID,
Query: opts.Query,
}
// Reaching here means fopts.Mode is FormatJSON (the only caller). Route
// through FormatOptions.Emit so --jq projection and the success-envelope
// contract apply, matching every other non-streaming command. A nil fopts
// (direct-test entry) defaults to JSON so the object still emits.
if fopts == nil {
fopts = &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
}
return fopts.Emit(iostreams.IO.Out, data, nil)
}
func chatStreamError(err *cmdutil.Error, sessionID, assistantMessageID string) *cmdutil.Error {
detail := map[string]any{"session_id": sessionID}
if assistantMessageID != "" {
detail["assistant_message_id"] = assistantMessageID
}
return err.WithDetail(detail)
}
// chatResult is the --format json data payload. The projector controls default
// versus verbose coverage.
type chatResult struct {
Events []sse.ProjectedEvent `json:"events"`
SessionID string `json:"session_id"`
AssistantMessageID string `json:"assistant_message_id,omitempty"`
KBID string `json:"kb_id"`
Query string `json:"query"`
}
// compile-time check: the production SDK client implements ChatService.
+198 -53
View File
@@ -9,6 +9,7 @@ import (
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/sse"
sdk "github.com/Tencent/WeKnora/client"
)
@@ -86,11 +87,8 @@ func TestChat_StreamMode(t *testing.T) {
if !strings.Contains(got, "Hello world") {
t.Errorf("stdout missing streamed content: %q", got)
}
if !strings.Contains(got, "References") {
t.Errorf("stdout missing references footer: %q", got)
}
if !strings.Contains(got, "Doc One") {
t.Errorf("references should render KnowledgeTitle, got %q", got)
if strings.Contains(got, "references") || strings.Contains(got, "Doc One") {
t.Errorf("default text output leaked references: %q", got)
}
// auto-created session must announce itself on stderr
if !strings.Contains(errBuf.String(), "session: sess_auto") {
@@ -107,7 +105,7 @@ func TestChat_StreamMode(t *testing.T) {
}
}
// TestChat_NDJSON_FirstLineIsInit verifies that the NDJSON path (--format json)
// TestChat_NDJSON_FirstLineIsInit verifies that the NDJSON path (--format ndjson)
// always injects an "init" line first carrying session_id and kb_id.
func TestChat_NDJSON_FirstLineIsInit(t *testing.T) {
out, errBuf := iostreams.SetForTest(t)
@@ -119,7 +117,7 @@ func TestChat_NDJSON_FirstLineIsInit(t *testing.T) {
},
}
opts := &Options{Query: "q", KBID: "kb_42"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
@@ -164,7 +162,7 @@ func TestChat_NDJSON_PassthroughEvents(t *testing.T) {
},
}
opts := &Options{Query: "q", KBID: "kb_x"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
@@ -183,34 +181,7 @@ func TestChat_NDJSON_PassthroughEvents(t *testing.T) {
}
}
// TestChat_NDJSON_JSONEqualsNDJSON verifies that --format json and --format ndjson
// produce identical byte output on a streaming command.
func TestChat_NDJSON_JSONEqualsNDJSON(t *testing.T) {
events := []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeAnswer, Content: "hello"},
{ResponseType: sdk.ResponseTypeComplete, Done: true},
}
runWith := func(mode cmdutil.FormatMode) string {
out, _ := iostreams.SetForTest(t)
svc := &fakeChatService{streamEvents: events}
opts := &Options{Query: "q", KBID: "kb_x"}
fopts := &cmdutil.FormatOptions{Mode: mode}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat(%s): %v", mode, err)
}
return out.String()
}
jsonOut := runWith(cmdutil.FormatJSON)
ndjsonOut := runWith(cmdutil.FormatNDJSON)
if jsonOut != ndjsonOut {
t.Errorf("--format json and --format ndjson differ:\n json: %q\n ndjson: %q", jsonOut, ndjsonOut)
}
}
func TestChat_NonTTY_AccumulateMode(t *testing.T) {
// Non-TTY iostreams forces accumulate mode.
func TestChat_NonTTY_StreamsSameProjection(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
@@ -227,6 +198,24 @@ func TestChat_NonTTY_AccumulateMode(t *testing.T) {
}
}
func TestChat_NonTTY_VerboseIncludesThinking(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeThinking, Content: "REASONING"},
{ResponseType: sdk.ResponseTypeAnswer, Content: "answer"},
{ResponseType: sdk.ResponseTypeComplete, Done: true},
},
}
opts := &Options{Query: "q", KBID: "kb", Verbose: true}
if err := runChat(context.Background(), opts, textOpts(), svc); err != nil {
t.Fatalf("runChat: %v", err)
}
if got := out.String(); !strings.Contains(got, "REASONING") || !strings.Contains(got, "answer") {
t.Errorf("non-TTY verbose output missing thinking or answer: %q", got)
}
}
func TestChat_SessionIDProvided(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeChatService{
@@ -430,8 +419,8 @@ func TestChat_NDJSON_InitIncludesProfile(t *testing.T) {
}
func TestChat_FormatNDJSON_PassthroughsSDKEvents(t *testing.T) {
// Fake stream emits 3 events: thinking, answer, complete.
// With the init injection, total output is 4 lines (1 init + 3 SDK events).
// NDJSON is the raw protocol surface: every SDK event passes through,
// including reasoning, regardless of the presentation-oriented --verbose.
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeThinking, Content: "search KB"},
@@ -447,11 +436,23 @@ func TestChat_FormatNDJSON_PassthroughsSDKEvents(t *testing.T) {
t.Fatalf("runChat: %v", err)
}
lines := strings.Split(strings.TrimRight(out.String(), "\n"), "\n")
// 1 init + 3 SDK events = 4 lines.
// 1 init + thinking + answer + complete = 4 lines.
if len(lines) != 4 {
t.Fatalf("got %d lines, want 4:\n%s", len(lines), out.String())
}
sawThinking := false
for i, line := range lines {
var ev map[string]any
if err := json.Unmarshal([]byte(line), &ev); err != nil {
t.Fatalf("line %d not JSON: %v", i+1, err)
}
if ev["response_type"] == "thinking" {
sawThinking = true
}
}
if !sawThinking {
t.Error("thinking event was filtered from raw NDJSON output")
}
// First line: CLI-injected init event.
var initLine map[string]any
if err := json.Unmarshal([]byte(lines[0]), &initLine); err != nil {
@@ -460,8 +461,30 @@ func TestChat_FormatNDJSON_PassthroughsSDKEvents(t *testing.T) {
if initLine["type"] != "init" {
t.Errorf("first line type=%v, want init", initLine["type"])
}
}
// Second line: thinking event (SDK passthrough).
func TestChat_FormatNDJSON_VerboseDoesNotAlterRawStream(t *testing.T) {
// --verbose is presentation-only; NDJSON remains the same raw stream and
// therefore still contains thinking alongside 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"},
},
}
out, _ := iostreams.SetForTest(t)
opts := &Options{Query: "hi", KBID: "kb_x", Verbose: true}
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(out.String(), "\n"), "\n")
// 1 init + thinking + answer + complete = 4 lines.
if len(lines) != 4 {
t.Fatalf("got %d lines, want 4:\n%s", len(lines), out.String())
}
var second map[string]any
if err := json.Unmarshal([]byte(lines[1]), &second); err != nil {
t.Fatalf("line 2 not JSON: %v", err)
@@ -469,20 +492,142 @@ func TestChat_FormatNDJSON_PassthroughsSDKEvents(t *testing.T) {
if second["response_type"] != "thinking" {
t.Errorf("second event response_type=%v, want thinking", second["response_type"])
}
// Third line: answer.
var third map[string]any
if err := json.Unmarshal([]byte(lines[2]), &third); err != nil {
t.Fatalf("line 3 not JSON: %v", err)
}
func TestChat_FormatJSON_ReferenceAddsIndexes(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeAnswer, Content: "the answer"},
{ResponseType: sdk.ResponseTypeReferences, KnowledgeReferences: []*sdk.SearchResult{
{ID: "c1", Content: "BULKY FULL CHUNK CONTENT", ParentChunkID: "p1", KnowledgeTitle: "Doc One", Score: 0.5},
}},
{ResponseType: sdk.ResponseTypeComplete, Done: true, SessionID: "sess_auto"},
},
}
if third["response_type"] != "answer" {
t.Errorf("third event response_type=%v, want answer", third["response_type"])
opts := &Options{Query: "hi", KBID: "kb_1", Reference: true}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
// Fourth line: complete with done=true.
var fourth map[string]any
if err := json.Unmarshal([]byte(lines[3]), &fourth); err != nil {
t.Fatalf("line 4 not JSON: %v", err)
// A single envelope, not multiple NDJSON lines.
outStr := strings.TrimRight(out.String(), "\n")
if strings.Contains(outStr, "\n") {
t.Fatalf("expected single-line envelope, got multiple lines:\n%s", outStr)
}
if fourth["done"] != true {
t.Errorf("fourth event done=%v, want true", fourth["done"])
var env struct {
OK bool `json:"ok"`
Data struct {
Events []sse.ProjectedEvent `json:"events"`
SessionID string `json:"session_id"`
} `json:"data"`
}
if err := json.Unmarshal([]byte(outStr), &env); err != nil {
t.Fatalf("envelope not JSON: %v\n%s", err, outStr)
}
if !env.OK {
t.Error("ok=false, want true")
}
wantTypes := []string{"answer", "references"}
if len(env.Data.Events) != len(wantTypes) {
t.Fatalf("events=%+v", env.Data.Events)
}
for i, want := range wantTypes {
if env.Data.Events[i].ResponseType != want {
t.Errorf("events[%d].response_type=%q, want %q", i, env.Data.Events[i].ResponseType, want)
}
}
refs := env.Data.Events[1].KnowledgeReferences
if len(refs) != 1 || refs[0].KBID != "kb_1" || refs[0].ChunkID != "c1" || refs[0].ParentChunkID != "p1" {
t.Errorf("reference indexes=%+v", refs)
}
if env.Data.SessionID == "" {
t.Error("session_id empty")
}
}
func TestChat_FormatNDJSON_PreservesReflection(t *testing.T) {
// Reflection is part of the raw SDK protocol and must not be filtered.
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeReflection, Content: "reflecting"},
{ResponseType: sdk.ResponseTypeAnswer, Content: "hello"},
{ResponseType: sdk.ResponseTypeComplete, Done: true, SessionID: "sess_x"},
},
}
out, _ := iostreams.SetForTest(t)
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)
}
sawReflection := false
for i, line := range strings.Split(strings.TrimRight(out.String(), "\n"), "\n") {
var ev map[string]any
if err := json.Unmarshal([]byte(line), &ev); err != nil {
t.Fatalf("line %d not JSON: %v", i+1, err)
}
if ev["response_type"] == "reflection" {
sawReflection = true
}
}
if !sawReflection {
t.Error("reflection event was filtered from raw NDJSON output")
}
}
func TestChat_FormatJSON_HonorsJQ(t *testing.T) {
// --format json routes through FormatOptions.Emit, so --jq projects the
// envelope instead of dumping it whole. Guards the agent output protocol
// contract: consumers can join answer event fragments.
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeAnswer, Content: "the answer"},
{ResponseType: sdk.ResponseTypeReferences, KnowledgeReferences: []*sdk.SearchResult{
{ID: "c1", Content: "bulk", KnowledgeTitle: "Doc"},
}},
{ResponseType: sdk.ResponseTypeComplete, Done: true, SessionID: "sess_x"},
},
}
out, _ := iostreams.SetForTest(t)
opts := &Options{Query: "hi", KBID: "kb_1"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: `[.data.events[].content] | join("")`}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
got := strings.TrimSpace(out.String())
if !strings.Contains(got, "the answer") {
t.Errorf("jq output missing projected answer: %q", got)
}
// A projection must not dump the full envelope scaffolding.
if strings.Contains(got, "references") || strings.Contains(got, "session_id") {
t.Errorf("jq output looks like a full envelope, not a projection: %q", got)
}
}
func TestChat_FormatJSON_StreamErrorIncludesSessionDetail(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{{
ResponseType: sdk.ResponseTypeAgentQuery,
AssistantMessageID: "msg_123",
}},
streamErr: errors.New("connection reset"),
}
err := runChat(
context.Background(),
&Options{Query: "q", KBID: "kb"},
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON},
svc,
)
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %v", err)
}
detail, ok := typed.Detail.(map[string]any)
if !ok || detail["session_id"] != "sess_auto" || detail["assistant_message_id"] != "msg_123" {
t.Errorf("error detail=%v, want session and assistant message ids", typed.Detail)
}
}
+106 -79
View File
@@ -3,26 +3,24 @@ package sessioncmd
import (
"context"
"fmt"
"io"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
"github.com/Tencent/WeKnora/cli/internal/sse"
sdk "github.com/Tencent/WeKnora/client"
)
// sessionAskFields enumerates the NDJSON init-event fields surfaced for
// `--format json` / `--format ndjson` discovery on `session ask`. Reflects
// the InitEvent head line + the raw SDK agent event vocabulary.
// sessionAskFields enumerates the fields surfaced for `--jq` projection
// discovery on `session ask`: the json object's data fields + the raw SDK
// agent event vocabulary used by --format ndjson.
var sessionAskFields = []string{
"session_id", "agent_id",
// SDK event fields (pass-through): response_type, content, done,
// knowledge_references, tool_call_id, tool_result
"events", "session_id", "agent_id", "query",
// NDJSON init + SDK event fields.
"type", "profile", "response_type", "content", "done", "knowledge_references", "data",
}
// AskOptions captures `session ask` flag state.
@@ -30,6 +28,12 @@ type AskOptions struct {
AgentID string
Query string
SessionID string // --session: continue an existing session (skip auto-create)
// Reference adds bounded kb_id/chunk_id reference events to JSON/text.
Reference bool
// Verbose surfaces the projected execution trace in JSON/text,
// including reasoning, tools, and lifecycle events.
// NDJSON is always raw and is unaffected by presentation flags.
Verbose bool
}
// AskService is the narrow SDK surface this command depends on.
@@ -60,12 +64,14 @@ The 'weknora agent' subtree handles CRUD only (list / view / create /
edit / delete / status / check).
Modes:
--format text: live answer streaming + tool-trace footer
--format json / --format ndjson / pipe (default): NDJSON event stream —
one init line at head (session_id, agent_id),
then raw SDK agent events verbatim. Both
json and ndjson flags produce the same
NDJSON stream.`,
--format json (default): one JSON envelope with answer events
--format text: live human-readable answer stream
--format ndjson: raw NDJSON event stream — init line (session_id,
agent_id) then SDK agent events verbatim. Debug.
Pass --reference to include bounded kb_id/chunk_id reference indexes. Pass
--verbose to include reasoning, tool activity, and lifecycle frames. Combine
both flags for the complete projected stream.`,
Example: ` weknora session ask --agent ag_x "Summarize Q3 sales"
weknora session ask --session sess_x --agent ag_x "Follow-up question"
weknora session ask --agent ag_x "Multi-step task" --format ndjson`,
@@ -87,15 +93,18 @@ Modes:
cmd.Flags().StringVarP(&opts.AgentID, "agent", "a", "", "Agent ID to invoke (required)")
_ = cmd.MarkFlagRequired("agent")
cmd.Flags().StringVar(&opts.SessionID, "session", "", "Continue an existing chat session (skip auto-create)")
cmd.Flags().BoolVar(&opts.Reference, "reference", false, "Include indexed references in JSON/text output")
cmd.Flags().BoolVar(&opts.Verbose, "verbose", false, "Include reasoning, tools, and lifecycle events in JSON/text output")
cmdutil.AddFormatFlag(cmd, sessionAskFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Invoke a custom agent in a session context. Produces an NDJSON event stream: init line (session_id, agent_id) then raw SDK agent events. Use --format json or --format ndjson.",
UsedFor: "Invoke a custom agent in a session context. Default JSON returns a bounded answer-event projection. --reference adds indexed citations; --verbose adds reasoning, tools, and lifecycle events. --format ndjson streams raw SDK agent events; --format text renders the selected events live.",
RequiredFlags: []string{"--agent"},
Examples: []string{
`weknora session ask --agent ag_x "Summarize Q3 sales" --format json`,
`weknora session ask --session sess_x --agent ag_x "Follow-up question" --format json`,
`weknora session ask --agent ag_x "Summarize Q3 sales"`,
`weknora session ask --agent ag_x "Summarize Q3 sales" --jq '[.data.events[].content] | join("")'`,
`weknora session ask --session sess_x --agent ag_x "Follow-up question"`,
},
Output: "NDJSON stream: {type:init, session_id, agent_id} then SDK agent events (response_type, content, done, knowledge_references, ...)",
Output: "Default --format json: {ok,data:{events:[answer...],session_id,agent_id,query}}. --reference adds kb_id/chunk_id reference events; --verbose adds execution events. --format ndjson remains raw.",
})
return cmd
}
@@ -111,11 +120,8 @@ func runAsk(ctx context.Context, opts *AskOptions, fopts *cmdutil.FormatOptions,
return cmdutil.NewError(cmdutil.CodeServerError, "session ask: no SDK client available")
}
// Streaming commands route --format json AND --format ndjson to the
// NDJSON event-stream path. A buffered envelope makes no sense for a
// streaming command. Only --format text uses the live renderer.
ndjsonMode := fopts != nil && (fopts.Mode == cmdutil.FormatJSON || fopts.Mode == cmdutil.FormatNDJSON)
// --format selects the output shape: json (default) accumulates and
// emits one object, ndjson streams raw SDK agent events, text renders.
sessionID := opts.SessionID
autoCreated := false
if sessionID == "" {
@@ -134,13 +140,16 @@ func runAsk(ctx context.Context, opts *AskOptions, fopts *cmdutil.FormatOptions,
autoCreated = true
}
if ndjsonMode {
if fopts != nil && fopts.Mode == cmdutil.FormatNDJSON {
return runAskNDJSON(ctx, opts, sessionID, svc)
}
if fopts != nil && fopts.Mode == cmdutil.FormatJSON {
return runAskJSON(ctx, opts, fopts, sessionID, svc)
}
// Surface auto-created session id up-front so a ^C mid-stream still
// leaves a recoverable pointer. Skipped in NDJSON mode (it appears in
// the init event).
// leaves a recoverable pointer. Skipped in json/ndjson mode (session_id
// is in the output).
if autoCreated {
fmt.Fprintf(iostreams.IO.Err, "session: %s (use --session to continue)\n", sessionID)
}
@@ -148,9 +157,9 @@ func runAsk(ctx context.Context, opts *AskOptions, fopts *cmdutil.FormatOptions,
return runAskText(ctx, opts, sessionID, autoCreated, svc)
}
// runAskNDJSON handles --format json and --format ndjson paths.
// Emits a CLI init event at stream head, then passes every SDK agent event
// through verbatim as NDJSON lines. No buffering.
// runAskNDJSON handles the --format ndjson path: emits a CLI init event at
// stream head, then passes every SDK agent event through verbatim as NDJSON
// lines. No buffering.
func runAskNDJSON(ctx context.Context, opts *AskOptions, sessionID string, svc AskService) error {
w := iostreams.IO.Out
@@ -173,6 +182,8 @@ func runAskNDJSON(ctx context.Context, opts *AskOptions, sessionID string, svc A
Channel: "api",
}
cb := func(r *sdk.AgentStreamResponse) error {
// NDJSON is the raw protocol/debug surface: do not filter events or
// mutate their payloads. JSON/text modes own presentation filtering.
return output.EmitSDKEvent(w, r)
}
if err := svc.AgentQAStreamWithRequest(ctx, sessionID, req, cb); err != nil {
@@ -184,12 +195,9 @@ func runAskNDJSON(ctx context.Context, opts *AskOptions, sessionID string, svc A
return nil
}
// runAskText handles the --format text path. Streams answer fragments
// live on TTY; accumulates then renders on non-TTY pipes.
// runAskText handles the --format text path. It renders the same
// projection as JSON immediately for both terminals and pipes.
func runAskText(ctx context.Context, opts *AskOptions, sessionID string, autoCreated bool, svc AskService) error {
// Stream mode requires an interactive stdout.
streamMode := iostreams.IO.IsStdoutTTY()
req := &sdk.AgentQARequest{
Query: opts.Query,
AgentEnabled: true,
@@ -197,13 +205,14 @@ func runAskText(ctx context.Context, opts *AskOptions, sessionID string, autoCre
Channel: "api",
}
acc := &sse.AgentAccumulator{}
projector := sse.NewProjector(opts.Verbose, opts.Reference, "")
renderer := sse.NewTextRenderer(iostreams.IO.Out, opts.Verbose)
cb := func(r *sdk.AgentStreamResponse) error {
if streamMode && r != nil && r.ResponseType == sdk.AgentResponseTypeAnswer && r.Content != "" {
_, _ = iostreams.IO.Out.Write([]byte(r.Content))
event, include := projector.Agent(r)
if !include {
return nil
}
acc.Append(r)
return nil
return renderer.Write(event)
}
streamErr := svc.AgentQAStreamWithRequest(ctx, sessionID, req, cb)
@@ -214,61 +223,79 @@ func runAskText(ctx context.Context, opts *AskOptions, sessionID string, autoCre
if cmdutil.IsCancelled(ctx, streamErr) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, streamErr, "session ask cancelled")
}
if acc.Answer() != "" && !acc.Done() {
if projector.Seen() && !projector.Done() {
return cmdutil.Wrapf(cmdutil.CodeSSEStreamAborted, streamErr, "stream aborted before completion")
}
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 complete event — treat as aborted
// so agents don't silently emit a truncated answer as ok=true.
if !acc.Done() {
if !projector.Done() {
return cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")
}
answer := acc.Answer()
out := iostreams.IO.Out
if streamMode {
if !strings.HasSuffix(answer, "\n") {
fmt.Fprintln(out)
}
} else {
fmt.Fprint(out, answer)
if !strings.HasSuffix(answer, "\n") {
fmt.Fprintln(out)
}
}
renderAskToolTrace(out, acc.ToolEvents)
format.WriteReferences(out, acc.References)
return nil
return renderer.Close()
}
// renderAskToolTrace prints a compact tool-event footer in --format text
// mode. Skipped when the agent emitted no tool events — silent beats an
// empty banner.
func renderAskToolTrace(w io.Writer, events []sse.AgentToolEvent) {
if len(events) == 0 {
return
// runAskJSON handles the --format json path (the default): collect the
// projection and emit it in one normal success envelope.
func runAskJSON(ctx context.Context, opts *AskOptions, fopts *cmdutil.FormatOptions, sessionID string, svc AskService) error {
req := &sdk.AgentQARequest{
Query: opts.Query,
AgentEnabled: true,
AgentID: opts.AgentID,
Channel: "api",
}
fmt.Fprintln(w)
fmt.Fprintln(w, "──── Tool trace ────")
for i, e := range events {
fmt.Fprintf(w, "[%d] %s", i+1, e.Kind)
if e.Result != "" {
fmt.Fprintf(w, " %s", truncateAskInline(e.Result, 80))
projector := sse.NewProjector(opts.Verbose, opts.Reference, "")
events := make([]sse.ProjectedEvent, 0)
cb := func(r *sdk.AgentStreamResponse) error {
if event, include := projector.Agent(r); include {
events = append(events, event)
}
fmt.Fprintln(w)
return nil
}
if err := svc.AgentQAStreamWithRequest(ctx, sessionID, req, cb); err != nil {
if cmdutil.IsCancelled(ctx, err) {
return askStreamError(cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "session ask cancelled"), sessionID)
}
return askStreamError(cmdutil.WrapHTTP(err, "agent-chat stream"), sessionID)
}
if !projector.Done() {
return askStreamError(
cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event"),
sessionID,
)
}
data := askResult{
Events: events,
SessionID: sessionID,
AgentID: opts.AgentID,
Query: opts.Query,
}
// Reaching here means fopts.Mode is FormatJSON (the only caller). Route
// through FormatOptions.Emit so --jq projection and the success-envelope
// contract apply. A nil fopts (direct-test entry) defaults to JSON.
if fopts == nil {
fopts = &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
}
return fopts.Emit(iostreams.IO.Out, data, nil)
}
// truncateAskInline shrinks a multi-line result to a single line + ellipsis
// for the text tool-trace footer.
func truncateAskInline(s string, maxLen int) string {
s = strings.ReplaceAll(s, "\n", " ")
if len(s) <= maxLen {
return s
}
return s[:maxLen-1] + "…"
func askStreamError(err *cmdutil.Error, sessionID string) *cmdutil.Error {
return err.WithDetail(map[string]any{"session_id": sessionID})
}
// askResult is the --format json data payload. The projector controls default
// versus verbose coverage.
type askResult struct {
Events []sse.ProjectedEvent `json:"events"`
SessionID string `json:"session_id"`
AgentID string `json:"agent_id"`
Query string `json:"query"`
}
// compile-time check: production SDK client satisfies AskService.
+227 -30
View File
@@ -10,6 +10,7 @@ import (
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/sse"
sdk "github.com/Tencent/WeKnora/client"
)
@@ -69,19 +70,19 @@ func textOpts() *cmdutil.FormatOptions {
return &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
}
// ndjsonOpts returns a FormatOptions for the NDJSON event-stream path.
// --format json routes here too for streaming commands.
// ndjsonOpts returns a FormatOptions for the NDJSON event-stream path
// (--format ndjson: raw SDK agent events, one per line).
func ndjsonOpts() *cmdutil.FormatOptions {
return &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
}
// jsonOpts returns a FormatOptions configured for the JSON path.
// In v0.7 --format json routes to the NDJSON stream path for streaming commands.
// jsonOpts returns a FormatOptions configured for the JSON object path
// (--format json: one accumulated {ok,data} envelope).
func jsonOpts() *cmdutil.FormatOptions {
return &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
}
// TestSessionAsk_NDJSON_FirstLineIsInit verifies that the NDJSON path (--format json)
// TestSessionAsk_NDJSON_FirstLineIsInit verifies that the NDJSON path (--format ndjson)
// always injects an "init" line first, carrying session_id and agent_id.
func TestSessionAsk_NDJSON_FirstLineIsInit(t *testing.T) {
out, errBuf := iostreams.SetForTest(t)
@@ -92,7 +93,7 @@ func TestSessionAsk_NDJSON_FirstLineIsInit(t *testing.T) {
},
}
opts := &AskOptions{AgentID: "ag_x", Query: "ping"}
if err := runAsk(context.Background(), opts, jsonOpts(), svc); err != nil {
if err := runAsk(context.Background(), opts, ndjsonOpts(), svc); err != nil {
t.Fatalf("runAsk: %v", err)
}
@@ -134,7 +135,7 @@ func TestSessionAsk_NDJSON_PassthroughEvents(t *testing.T) {
},
}
opts := &AskOptions{AgentID: "ag_x", Query: "hi"}
if err := runAsk(context.Background(), opts, jsonOpts(), svc); err != nil {
if err := runAsk(context.Background(), opts, ndjsonOpts(), svc); err != nil {
t.Fatalf("runAsk: %v", err)
}
@@ -152,29 +153,155 @@ func TestSessionAsk_NDJSON_PassthroughEvents(t *testing.T) {
}
}
// TestSessionAsk_NDJSON_JSONEqualsNDJSON verifies that --format json and --format ndjson
// produce identical NDJSON streams for session ask.
func TestSessionAsk_NDJSON_JSONEqualsNDJSON(t *testing.T) {
events := []*sdk.AgentStreamResponse{
answerEvent("hello"),
// TestSessionAsk_FormatJSON_EmitsSingleEnvelope verifies that default JSON
// keeps answer events only.
func TestSessionAsk_FormatJSON_EmitsSingleEnvelope(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &scriptedAskSvc{events: []*sdk.AgentStreamResponse{
// Per-event Done markers are not terminal for the whole agent run.
{ResponseType: sdk.AgentResponseTypeThinking, Content: "hidden reasoning", Done: true},
toolCallEvent("call_1", "knowledge_search"),
referencesEvent([]*sdk.SearchResult{{ID: "c1", Content: "BULKY PASSAGE", KnowledgeTitle: "Doc"}}),
answerEvent("the answer"),
{ResponseType: sdk.AgentResponseTypeAnswer, Done: true},
doneEvent(),
}}
opts := &AskOptions{AgentID: "ag_x", Query: "hi"}
if err := runAsk(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc); err != nil {
t.Fatalf("runAsk: %v", err)
}
runWith := func(mode cmdutil.FormatMode) string {
out, _ := iostreams.SetForTest(t)
svc := &scriptedAskSvc{events: events}
opts := &AskOptions{AgentID: "ag_x", Query: "q"}
fopts := &cmdutil.FormatOptions{Mode: mode}
if err := runAsk(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runAsk(%s): %v", mode, err)
// A single envelope, not multiple NDJSON lines.
outStr := strings.TrimRight(out.String(), "\n")
if strings.Contains(outStr, "\n") {
t.Fatalf("expected single-line envelope, got multiple lines:\n%s", outStr)
}
var env struct {
OK bool `json:"ok"`
Data struct {
Events []sse.ProjectedEvent `json:"events"`
SessionID string `json:"session_id"`
AgentID string `json:"agent_id"`
Query string `json:"query"`
} `json:"data"`
}
if err := json.Unmarshal([]byte(outStr), &env); err != nil {
t.Fatalf("envelope not JSON: %v\n%s", err, outStr)
}
if !env.OK {
t.Error("ok=false, want true")
}
if len(env.Data.Events) != 2 {
t.Fatalf("events=%+v, want two answer frames", env.Data.Events)
}
for i, event := range env.Data.Events {
if event.ResponseType != "answer" {
t.Errorf("events[%d].response_type=%q, want answer", i, event.ResponseType)
}
return out.String()
}
if env.Data.Events[0].Content != "the answer" {
t.Errorf("answer content=%q", env.Data.Events[0].Content)
}
if env.Data.AgentID != "ag_x" || env.Data.Query != "hi" {
t.Errorf("echo fields: agent_id=%q query=%q", env.Data.AgentID, env.Data.Query)
}
if env.Data.SessionID == "" {
t.Error("session_id empty")
}
}
jsonOut := runWith(cmdutil.FormatJSON)
ndjsonOut := runWith(cmdutil.FormatNDJSON)
if jsonOut != ndjsonOut {
t.Errorf("--format json and --format ndjson differ:\n json: %q\n ndjson: %q", jsonOut, ndjsonOut)
func TestSessionAsk_FormatJSON_VerboseAndReferenceIncludeBothDetailClasses(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &scriptedAskSvc{events: []*sdk.AgentStreamResponse{
{ID: "think", ResponseType: sdk.AgentResponseTypeThinking, Content: "reasoning", Done: true},
toolCallEvent("call_1", "knowledge_search"),
referencesEvent([]*sdk.SearchResult{{ID: "c1", KnowledgeBaseID: "kb1", ParentChunkID: "p1", Content: "BULK"}}),
answerEvent("answer [chunk:c1]"),
doneEvent(),
}}
opts := &AskOptions{AgentID: "ag_x", Query: "hi", Verbose: true, Reference: true}
if err := runAsk(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc); err != nil {
t.Fatalf("runAsk: %v", err)
}
var env struct {
Data struct {
Events []sse.ProjectedEvent `json:"events"`
} `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatal(err)
}
want := []string{"thinking", "tool_call", "references", "answer", "complete"}
if len(env.Data.Events) != len(want) {
t.Fatalf("events=%+v", env.Data.Events)
}
for i, responseType := range want {
if env.Data.Events[i].ResponseType != responseType {
t.Errorf("events[%d]=%q, want %q", i, env.Data.Events[i].ResponseType, responseType)
}
}
refs := env.Data.Events[2].KnowledgeReferences
if len(refs) != 1 || refs[0].KBID != "kb1" || refs[0].ChunkID != "c1" || refs[0].ParentChunkID != "p1" {
t.Errorf("reference indexes=%+v", refs)
}
}
// TestSessionAsk_Text_VerboseIncludesThinking verifies the --format text path
// honors --verbose: the agent's thinking streams inline with the answer.
// (Regresses the original bug: runAskText ignored opts.Verbose entirely, so
// thinking never appeared in text mode under any flag.)
func TestSessionAsk_Text_VerboseIncludesThinking(t *testing.T) {
out, _ := iostreams.SetForTestWithTTY(t)
svc := &scriptedAskSvc{events: []*sdk.AgentStreamResponse{
{ResponseType: sdk.AgentResponseTypeThinking, Content: "REASONING"},
answerEvent("answer"),
doneEvent(),
}}
opts := &AskOptions{AgentID: "ag_x", Query: "hi", Verbose: true}
if err := runAsk(context.Background(), opts, textOpts(), svc); err != nil {
t.Fatalf("runAsk: %v", err)
}
if !strings.Contains(out.String(), "REASONING") {
t.Errorf("verbose text output missing thinking: %q", out.String())
}
if !strings.Contains(out.String(), "answer") {
t.Errorf("answer body missing: %q", out.String())
}
}
func TestSessionAsk_Text_NonTTYVerboseIncludesThinking(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &scriptedAskSvc{events: []*sdk.AgentStreamResponse{
{ResponseType: sdk.AgentResponseTypeThinking, Content: "REASONING", Done: true},
answerEvent("answer"),
doneEvent(),
}}
opts := &AskOptions{AgentID: "ag_x", Query: "hi", Verbose: true}
if err := runAsk(context.Background(), opts, textOpts(), svc); err != nil {
t.Fatalf("runAsk: %v", err)
}
if got := out.String(); !strings.Contains(got, "REASONING") || !strings.Contains(got, "answer") {
t.Errorf("non-TTY verbose output missing thinking or answer: %q", got)
}
}
// TestSessionAsk_Text_HidesThinkingByDefault: without --verbose the text path
// must NOT stream the reasoning pass, only the answer.
func TestSessionAsk_Text_HidesThinkingByDefault(t *testing.T) {
out, _ := iostreams.SetForTestWithTTY(t)
svc := &scriptedAskSvc{events: []*sdk.AgentStreamResponse{
{ResponseType: sdk.AgentResponseTypeThinking, Content: "REASONING"},
answerEvent("answer"),
doneEvent(),
}}
opts := &AskOptions{AgentID: "ag_x", Query: "hi"}
if err := runAsk(context.Background(), opts, textOpts(), svc); err != nil {
t.Fatalf("runAsk: %v", err)
}
if strings.Contains(out.String(), "REASONING") {
t.Errorf("non-verbose text output leaked thinking: %q", out.String())
}
if !strings.Contains(out.String(), "answer") {
t.Errorf("answer body missing: %q", out.String())
}
}
@@ -280,6 +407,25 @@ func TestSessionAsk_NoDoneEvent_MapsToSSEStreamAborted(t *testing.T) {
}
}
func TestSessionAsk_FormatJSON_StreamErrorIncludesSessionDetail(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &scriptedAskSvc{streamErr: errors.New("connection reset")}
err := runAsk(
context.Background(),
&AskOptions{AgentID: "ag", Query: "x"},
jsonOpts(),
svc,
)
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %v", err)
}
detail, ok := typed.Detail.(map[string]any)
if !ok || detail["session_id"] != "sess_auto" {
t.Errorf("error detail=%v, want auto-created session_id", typed.Detail)
}
}
func TestSessionAsk_CreateSessionFails_MapsToSessionCreateFailed(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &scriptedAskSvc{createErr: errors.New("connection refused")}
@@ -311,8 +457,8 @@ func TestSessionAsk_Cancellation_MapsToOperationCancelled(t *testing.T) {
}
}
// Sanity: text-mode output writes the answer body and a tool-trace footer.
func TestSessionAsk_Text_Accumulate_PrintsAnswerAndFooter(t *testing.T) {
// Default text writes answer events but filters tool events.
func TestSessionAsk_Text_DefaultHidesTools(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &scriptedAskSvc{events: []*sdk.AgentStreamResponse{
answerEvent("hello"),
@@ -327,8 +473,8 @@ func TestSessionAsk_Text_Accumulate_PrintsAnswerAndFooter(t *testing.T) {
if !strings.Contains(got, "hello") {
t.Errorf("answer body missing: %q", got)
}
if !strings.Contains(got, "Tool trace") {
t.Errorf("tool trace footer missing: %q", got)
if strings.Contains(got, "tool_call") || strings.Contains(got, "knowledge_search") {
t.Errorf("default text output leaked tool event: %q", got)
}
}
@@ -437,7 +583,7 @@ func TestSessionAsk_NDJSON_IncludesReferencesViaSDKEvent(t *testing.T) {
},
}
opts := &AskOptions{AgentID: "ag_x", Query: "ping"}
if err := runAsk(context.Background(), opts, jsonOpts(), svc); err != nil {
if err := runAsk(context.Background(), opts, ndjsonOpts(), svc); err != nil {
t.Fatalf("runAsk: %v", err)
}
@@ -463,3 +609,54 @@ func TestSessionAsk_NDJSON_IncludesReferencesViaSDKEvent(t *testing.T) {
t.Errorf("expected references event at line 3, got response_type=%v", refsLine["response_type"])
}
}
func TestSessionAsk_NDJSON_PreservesReferencesAndThinking(t *testing.T) {
// NDJSON is the raw protocol surface: reasoning and full reference payloads
// pass through unchanged. Index projection is limited to JSON/text/MCP.
svc := &scriptedAskSvc{
events: []*sdk.AgentStreamResponse{
{ResponseType: sdk.AgentResponseTypeThinking, Content: "reasoning"},
referencesEvent([]*sdk.SearchResult{{ID: "c1", Content: "BULKY PASSAGE", KnowledgeTitle: "Doc"}}),
answerEvent("hello"),
doneEvent(),
},
}
out, _ := iostreams.SetForTest(t)
opts := &AskOptions{AgentID: "ag_x", Query: "hi"}
if err := runAsk(context.Background(), opts, ndjsonOpts(), svc); err != nil {
t.Fatalf("runAsk: %v", err)
}
var refsLine map[string]any
sawThinking := false
for _, line := range strings.Split(strings.TrimRight(out.String(), "\n"), "\n") {
var ev map[string]any
if err := json.Unmarshal([]byte(line), &ev); err != nil {
continue
}
if ev["response_type"] == "thinking" {
sawThinking = true
}
if ev["response_type"] == "references" {
refsLine = ev
}
}
if !sawThinking {
t.Error("thinking event was filtered from raw NDJSON output")
}
if refsLine == nil {
t.Fatal("references event not emitted")
}
refs, _ := refsLine["knowledge_references"].([]any)
if len(refs) != 1 {
t.Fatalf("knowledge_references=%d, want 1", len(refs))
}
first, _ := refs[0].(map[string]any)
if first["content"] != "BULKY PASSAGE" {
t.Errorf("references[0].content=%v, want original content", first["content"])
}
if first["id"] != "c1" {
t.Errorf("references[0].id=%v, want c1", first["id"])
}
}