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:
+62
-26
@@ -2,6 +2,7 @@ package agentcmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -16,10 +17,10 @@ import (
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// agentInvokeFields enumerates fields surfaced for `--json` discovery on
|
||||
// `agent invoke`. Matches invokeData below - the single-shot result
|
||||
// object with the agent's final answer plus the trace (references,
|
||||
// tool events).
|
||||
// agentInvokeFields enumerates fields surfaced for `--format json` discovery
|
||||
// on `agent invoke`. Matches invokeData below — the single-shot result
|
||||
// object with the agent's final answer plus the trace (references, tool
|
||||
// events).
|
||||
var agentInvokeFields = []string{
|
||||
"answer", "references", "tool_events", "thinking",
|
||||
"session_id", "agent_id", "query",
|
||||
@@ -30,12 +31,11 @@ type InvokeOptions struct {
|
||||
AgentID string
|
||||
Query string
|
||||
SessionID string // --session: continue an existing session (skip auto-create)
|
||||
NoStream bool // --no-stream: force accumulate-and-emit (TTY default streams)
|
||||
}
|
||||
|
||||
// InvokeService is the narrow SDK surface this command depends on.
|
||||
//
|
||||
// CreateSession is called when --session is omitted - sessions are
|
||||
// CreateSession is called when --session is omitted — sessions are
|
||||
// agent-agnostic at creation (verified against
|
||||
// internal/handler/session/handler.go CreateSession, which only persists
|
||||
// {title, description}). The agent ID is supplied per-request via
|
||||
@@ -46,7 +46,7 @@ type InvokeService interface {
|
||||
AgentQAStreamWithRequest(ctx context.Context, sessionID string, req *sdk.AgentQARequest, cb sdk.AgentEventCallback) error
|
||||
}
|
||||
|
||||
// invokeData is the JSON payload emitted on the --json path.
|
||||
// invokeData is the JSON payload emitted on the JSON path.
|
||||
type invokeData struct {
|
||||
Answer string `json:"answer"`
|
||||
References []*sdk.SearchResult `json:"references"`
|
||||
@@ -67,36 +67,36 @@ func NewCmdInvoke(f *cmdutil.Factory) *cobra.Command {
|
||||
tools, KB scope, retrieval thresholds) over SSE. By default a fresh session
|
||||
is auto-created; pass --session to continue an existing conversation. The
|
||||
agent picks the model, retrieval params, and tool surface from its own
|
||||
config - agent invoke is the thin shim that streams the result.
|
||||
config — agent invoke is the thin shim that streams the result.
|
||||
|
||||
Modes:
|
||||
TTY (default): live answer streaming + tool-trace footer
|
||||
Pipe / --no-stream / --json: buffered, single JSON object at completion`,
|
||||
TTY (text format, default): live answer streaming + tool-trace footer
|
||||
--format json / pipe: buffered, single JSON object at completion`,
|
||||
Example: ` weknora agent invoke ag_abc "Summarise the Q3 plan"
|
||||
weknora agent invoke ag_abc "Continue?" --session sess_xyz
|
||||
weknora agent invoke ag_abc "What did we ship?" --json`,
|
||||
weknora agent invoke ag_abc "What did we ship?" --format json`,
|
||||
Args: cobra.ExactArgs(2),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
opts.AgentID = args[0]
|
||||
opts.Query = strings.TrimSpace(args[1])
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runInvoke(c.Context(), opts, jopts, cli)
|
||||
return runInvoke(c.Context(), opts, fopts, cli)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.SessionID, "session", "", "Continue an existing chat session (skip auto-create)")
|
||||
cmd.Flags().BoolVar(&opts.NoStream, "no-stream", false, "Buffer the full answer before printing (forces accumulate mode)")
|
||||
cmdutil.AddJSONFlags(cmd, agentInvokeFields)
|
||||
cmdutil.AddFormatFlag(cmd, agentInvokeFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOptions, svc InvokeService) error {
|
||||
func runInvoke(ctx context.Context, opts *InvokeOptions, fopts *cmdutil.FormatOptions, svc InvokeService) error {
|
||||
if opts.Query == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "query argument cannot be empty")
|
||||
}
|
||||
@@ -107,13 +107,16 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
|
||||
return cmdutil.NewError(cmdutil.CodeServerError, "agent invoke: no SDK client available")
|
||||
}
|
||||
|
||||
jsonOut := jopts.Enabled()
|
||||
jsonOut := fopts != nil && fopts.Mode == cmdutil.FormatJSON
|
||||
|
||||
sessionID := opts.SessionID
|
||||
autoCreated := false
|
||||
if sessionID == "" {
|
||||
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora agent invoke"})
|
||||
if err != nil {
|
||||
if isCancelled(ctx, err) {
|
||||
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "agent invoke cancelled")
|
||||
}
|
||||
code := cmdutil.ClassifyHTTPError(err)
|
||||
if code == cmdutil.CodeNetworkError || code == cmdutil.CodeServerError {
|
||||
code = cmdutil.CodeSessionCreateFailed
|
||||
@@ -124,10 +127,12 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
|
||||
autoCreated = true
|
||||
}
|
||||
|
||||
// Streaming requires interactive stdout + no --no-stream + no --json.
|
||||
// Matches chat.go's mode-selection contract so users get the same
|
||||
// muscle memory across both commands.
|
||||
streamMode := iostreams.IO.IsStdoutTTY() && !opts.NoStream && !jsonOut
|
||||
// Streaming requires interactive stdout + no --format json + no
|
||||
// --format ndjson (handled by early-return below). Matches chat.go's
|
||||
// mode-selection contract so users get the same muscle memory across
|
||||
// both commands.
|
||||
streamMode := iostreams.IO.IsStdoutTTY() && !jsonOut &&
|
||||
(fopts == nil || fopts.Mode != cmdutil.FormatNDJSON)
|
||||
|
||||
// Surface auto-created session id up-front so a ^C mid-stream still
|
||||
// leaves a recoverable pointer.
|
||||
@@ -142,6 +147,23 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
|
||||
Channel: "api",
|
||||
}
|
||||
|
||||
// --format ndjson: stream raw SDK events as NDJSON. Encoder hoisted out
|
||||
// of the callback to avoid per-event allocation.
|
||||
if fopts != nil && fopts.Mode == cmdutil.FormatNDJSON {
|
||||
enc := json.NewEncoder(iostreams.IO.Out)
|
||||
enc.SetEscapeHTML(false)
|
||||
cb := func(r *sdk.AgentStreamResponse) error {
|
||||
return enc.Encode(r)
|
||||
}
|
||||
if err := svc.AgentQAStreamWithRequest(ctx, sessionID, req, cb); err != nil {
|
||||
if isCancelled(ctx, err) {
|
||||
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "agent invoke cancelled")
|
||||
}
|
||||
return cmdutil.WrapHTTP(err, "agent-chat stream")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
acc := &sse.AgentAccumulator{}
|
||||
cb := func(r *sdk.AgentStreamResponse) error {
|
||||
if streamMode && r != nil && r.ResponseType == sdk.AgentResponseTypeAnswer && r.Content != "" {
|
||||
@@ -156,8 +178,8 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
|
||||
if autoCreated && !jsonOut {
|
||||
fmt.Fprintf(iostreams.IO.Err, "session: %s (resume with --session %s)\n", sessionID, sessionID)
|
||||
}
|
||||
if errors.Is(streamErr, context.Canceled) || errors.Is(ctx.Err(), context.Canceled) {
|
||||
return cmdutil.Wrapf(cmdutil.CodeUserAborted, streamErr, "agent invoke cancelled")
|
||||
if isCancelled(ctx, streamErr) {
|
||||
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, streamErr, "agent invoke cancelled")
|
||||
}
|
||||
if acc.Answer() != "" && !acc.Done() {
|
||||
return cmdutil.Wrapf(cmdutil.CodeSSEStreamAborted, streamErr, "stream aborted before completion")
|
||||
@@ -165,7 +187,7 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
|
||||
return cmdutil.WrapHTTP(streamErr, "agent-chat stream")
|
||||
}
|
||||
|
||||
// Server closed cleanly but never sent a Done event - treat as aborted
|
||||
// Server closed cleanly but never sent a Done event — treat as aborted
|
||||
// so agents don't silently emit a truncated answer as ok=true.
|
||||
if !acc.Done() {
|
||||
return cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")
|
||||
@@ -182,7 +204,7 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
|
||||
AgentID: opts.AgentID,
|
||||
Query: opts.Query,
|
||||
}
|
||||
return jopts.Emit(iostreams.IO.Out, data)
|
||||
return fopts.Emit(iostreams.IO.Out, data)
|
||||
}
|
||||
|
||||
out := iostreams.IO.Out
|
||||
@@ -202,7 +224,7 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
|
||||
}
|
||||
|
||||
// renderToolTrace prints a compact tool-event footer in human mode.
|
||||
// Skipped when the agent emitted no tool events - silent beats an empty
|
||||
// Skipped when the agent emitted no tool events — silent beats an empty
|
||||
// banner.
|
||||
func renderToolTrace(w io.Writer, events []sse.AgentToolEvent) {
|
||||
if len(events) == 0 {
|
||||
@@ -229,5 +251,19 @@ func truncateInline(s string, maxLen int) string {
|
||||
return s[:maxLen-1] + "…"
|
||||
}
|
||||
|
||||
// isCancelled reports whether err or ctx represents a context-cancelled
|
||||
// state — true on Ctrl-C / SIGTERM after main.go's signal.NotifyContext
|
||||
// fires. Wrapping URL/transport layers may rewrite context.Canceled into
|
||||
// something errors.Is no longer recognises, so we fall back to ctx.Err().
|
||||
func isCancelled(ctx context.Context, err error) bool {
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return true
|
||||
}
|
||||
if ctx.Err() == context.Canceled {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// compile-time check: production SDK client satisfies InvokeService.
|
||||
var _ InvokeService = (*sdk.Client)(nil)
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -62,6 +64,17 @@ func referencesEvent(refs []*sdk.SearchResult) *sdk.AgentStreamResponse {
|
||||
}
|
||||
}
|
||||
|
||||
// textOpts returns a FormatOptions configured for the text (human) render
|
||||
// path — the most common shape under test.
|
||||
func textOpts() *cmdutil.FormatOptions {
|
||||
return &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
}
|
||||
|
||||
// jsonOpts returns a FormatOptions configured for the JSON path.
|
||||
func jsonOpts() *cmdutil.FormatOptions {
|
||||
return &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
|
||||
}
|
||||
|
||||
func TestInvoke_AccumulateMode_EmitsBareJSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &scriptedInvokeSvc{
|
||||
@@ -73,7 +86,7 @@ func TestInvoke_AccumulateMode_EmitsBareJSON(t *testing.T) {
|
||||
},
|
||||
}
|
||||
opts := &InvokeOptions{AgentID: "ag_x", Query: "ping"}
|
||||
if err := runInvoke(context.Background(), opts, &cmdutil.JSONOptions{}, svc); err != nil {
|
||||
if err := runInvoke(context.Background(), opts, jsonOpts(), svc); err != nil {
|
||||
t.Fatalf("runInvoke: %v", err)
|
||||
}
|
||||
var got invokeData
|
||||
@@ -101,7 +114,7 @@ func TestInvoke_AutoCreatedSessionID_PassedAsAgentRequest(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &scriptedInvokeSvc{events: []*sdk.AgentStreamResponse{doneEvent()}}
|
||||
opts := &InvokeOptions{AgentID: "ag_42", Query: "x"}
|
||||
if err := runInvoke(context.Background(), opts, &cmdutil.JSONOptions{}, svc); err != nil {
|
||||
if err := runInvoke(context.Background(), opts, jsonOpts(), svc); err != nil {
|
||||
t.Fatalf("runInvoke: %v", err)
|
||||
}
|
||||
if svc.got.sessionID != "sess_auto" {
|
||||
@@ -123,7 +136,7 @@ func TestInvoke_ExistingSessionID_SkipsCreate(t *testing.T) {
|
||||
svc.createResp = &sdk.Session{ID: "should_not_be_used"}
|
||||
wrapped := &createSessionTracker{InvokeService: svc, called: &created}
|
||||
opts := &InvokeOptions{AgentID: "ag", Query: "x", SessionID: "sess_existing"}
|
||||
if err := runInvoke(context.Background(), opts, &cmdutil.JSONOptions{}, wrapped); err != nil {
|
||||
if err := runInvoke(context.Background(), opts, jsonOpts(), wrapped); err != nil {
|
||||
t.Fatalf("runInvoke: %v", err)
|
||||
}
|
||||
if created {
|
||||
@@ -152,7 +165,7 @@ func TestInvoke_ToolEventsCaptured(t *testing.T) {
|
||||
doneEvent(),
|
||||
}}
|
||||
opts := &InvokeOptions{AgentID: "ag", Query: "x"}
|
||||
if err := runInvoke(context.Background(), opts, &cmdutil.JSONOptions{}, svc); err != nil {
|
||||
if err := runInvoke(context.Background(), opts, jsonOpts(), svc); err != nil {
|
||||
t.Fatalf("runInvoke: %v", err)
|
||||
}
|
||||
var got invokeData
|
||||
@@ -171,7 +184,7 @@ func TestInvoke_EmptyQuery_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &scriptedInvokeSvc{}
|
||||
opts := &InvokeOptions{AgentID: "ag", Query: ""}
|
||||
err := runInvoke(context.Background(), opts, nil, svc)
|
||||
err := runInvoke(context.Background(), opts, textOpts(), svc)
|
||||
if err == nil {
|
||||
t.Fatal("expected input.invalid_argument, got nil")
|
||||
}
|
||||
@@ -190,7 +203,7 @@ func TestInvoke_StreamAbortBeforeDone_MapsToSSEStreamAborted(t *testing.T) {
|
||||
streamErr: errors.New("connection reset"),
|
||||
}
|
||||
opts := &InvokeOptions{AgentID: "ag", Query: "x"}
|
||||
err := runInvoke(context.Background(), opts, &cmdutil.JSONOptions{}, svc)
|
||||
err := runInvoke(context.Background(), opts, jsonOpts(), svc)
|
||||
if err == nil {
|
||||
t.Fatal("expected stream-aborted error")
|
||||
}
|
||||
@@ -204,7 +217,7 @@ func TestInvoke_NoDoneEvent_MapsToSSEStreamAborted(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &scriptedInvokeSvc{events: []*sdk.AgentStreamResponse{answerEvent("incomplete")}}
|
||||
opts := &InvokeOptions{AgentID: "ag", Query: "x"}
|
||||
err := runInvoke(context.Background(), opts, &cmdutil.JSONOptions{}, svc)
|
||||
err := runInvoke(context.Background(), opts, jsonOpts(), svc)
|
||||
if err == nil {
|
||||
t.Fatal("expected stream-aborted error")
|
||||
}
|
||||
@@ -218,7 +231,7 @@ func TestInvoke_CreateSessionFails_MapsToSessionCreateFailed(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &scriptedInvokeSvc{createErr: errors.New("connection refused")}
|
||||
opts := &InvokeOptions{AgentID: "ag", Query: "x"}
|
||||
err := runInvoke(context.Background(), opts, nil, svc)
|
||||
err := runInvoke(context.Background(), opts, textOpts(), svc)
|
||||
if err == nil {
|
||||
t.Fatal("expected session_create_failed")
|
||||
}
|
||||
@@ -228,19 +241,19 @@ func TestInvoke_CreateSessionFails_MapsToSessionCreateFailed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvoke_Cancellation_MapsToUserAborted(t *testing.T) {
|
||||
func TestInvoke_Cancellation_MapsToOperationCancelled(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel() // pre-cancel
|
||||
svc := &scriptedInvokeSvc{streamErr: context.Canceled}
|
||||
opts := &InvokeOptions{AgentID: "ag", Query: "x"}
|
||||
err := runInvoke(ctx, opts, &cmdutil.JSONOptions{}, svc)
|
||||
err := runInvoke(ctx, opts, jsonOpts(), svc)
|
||||
if err == nil {
|
||||
t.Fatal("expected user_aborted")
|
||||
t.Fatal("expected operation.cancelled")
|
||||
}
|
||||
var typed *cmdutil.Error
|
||||
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeUserAborted {
|
||||
t.Errorf("expected local.user_aborted, got %v", err)
|
||||
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeOperationCancelled {
|
||||
t.Errorf("expected operation.cancelled, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,8 +265,8 @@ func TestInvoke_Human_Accumulate_PrintsAnswerAndFooter(t *testing.T) {
|
||||
toolCallEvent("c1", "knowledge_search"),
|
||||
doneEvent(),
|
||||
}}
|
||||
opts := &InvokeOptions{AgentID: "ag", Query: "x", NoStream: true}
|
||||
if err := runInvoke(context.Background(), opts, nil, svc); err != nil {
|
||||
opts := &InvokeOptions{AgentID: "ag", Query: "x"}
|
||||
if err := runInvoke(context.Background(), opts, textOpts(), svc); err != nil {
|
||||
t.Fatalf("runInvoke: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -264,3 +277,68 @@ func TestInvoke_Human_Accumulate_PrintsAnswerAndFooter(t *testing.T) {
|
||||
t.Errorf("tool trace footer missing: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentInvoke_FormatNDJSON_PassthroughsSDKEvents(t *testing.T) {
|
||||
// Fake stream emits 3 events: tool_call, answer, done.
|
||||
// Mirrors TestChat_FormatNDJSON_PassthroughsSDKEvents in chat_test.go but
|
||||
// uses AgentStreamResponse instead of StreamResponse.
|
||||
svc := &scriptedInvokeSvc{
|
||||
events: []*sdk.AgentStreamResponse{
|
||||
toolCallEvent("call_1", "knowledge_search"),
|
||||
answerEvent("hello"),
|
||||
doneEvent(),
|
||||
},
|
||||
}
|
||||
|
||||
var stdout bytes.Buffer
|
||||
prev := iostreams.IO.Out
|
||||
iostreams.IO.Out = &stdout
|
||||
defer func() { iostreams.IO.Out = prev }()
|
||||
// Redirect stderr so the auto-created session hint doesn't write to real
|
||||
// stderr during the test.
|
||||
prevErr := iostreams.IO.Err
|
||||
iostreams.IO.Err = os.Stderr
|
||||
defer func() { iostreams.IO.Err = prevErr }()
|
||||
|
||||
opts := &InvokeOptions{AgentID: "ag_x", Query: "hi"}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
|
||||
if err := runInvoke(context.Background(), opts, fopts, svc); err != nil {
|
||||
t.Fatalf("runInvoke: %v", err)
|
||||
}
|
||||
|
||||
lines := strings.Split(strings.TrimRight(stdout.String(), "\n"), "\n")
|
||||
if len(lines) != 3 {
|
||||
t.Fatalf("got %d lines, want 3:\n%s", len(lines), stdout.String())
|
||||
}
|
||||
// Each line must be valid JSON.
|
||||
for i, line := range lines {
|
||||
var obj map[string]any
|
||||
if err := json.Unmarshal([]byte(line), &obj); err != nil {
|
||||
t.Fatalf("line %d not valid JSON: %v\n %s", i+1, err, line)
|
||||
}
|
||||
}
|
||||
// First line: tool_call event.
|
||||
var first map[string]any
|
||||
if err := json.Unmarshal([]byte(lines[0]), &first); err != nil {
|
||||
t.Fatalf("line 1 not JSON: %v", err)
|
||||
}
|
||||
if first["response_type"] != string(sdk.AgentResponseTypeToolCall) {
|
||||
t.Errorf("first event response_type=%v, want %s", first["response_type"], sdk.AgentResponseTypeToolCall)
|
||||
}
|
||||
// Second line: answer event.
|
||||
var second map[string]any
|
||||
if err := json.Unmarshal([]byte(lines[1]), &second); err != nil {
|
||||
t.Fatalf("line 2 not JSON: %v", err)
|
||||
}
|
||||
if second["response_type"] != string(sdk.AgentResponseTypeAnswer) {
|
||||
t.Errorf("second event response_type=%v, want %s", second["response_type"], sdk.AgentResponseTypeAnswer)
|
||||
}
|
||||
// Third line: done event.
|
||||
var third map[string]any
|
||||
if err := json.Unmarshal([]byte(lines[2]), &third); err != nil {
|
||||
t.Fatalf("line 3 not JSON: %v", err)
|
||||
}
|
||||
if third["done"] != true {
|
||||
t.Errorf("third event done=%v, want true", third["done"])
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user