feat(cli)!: add agent-first chat and session ask output modes
This commit is contained in:
+106
-79
@@ -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
@@ -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"])
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user