refactor(cli): command-surface rename — session ask / doc fetch / doc create / doc delete --all
Three command renames consolidate the v0.7 verb table:
- `weknora agent invoke` → `weknora session ask --agent <id>`.
Server route POST /sessions/{session_id}/agent-qa is session-
anchored, so the verb moves with it. `weknora agent` subtree keeps
CRUD only (list / view / create / edit / delete / status / check).
SDK call (AgentQAStreamWithRequest) preserved verbatim; only the
command surface + flag layout move.
- `weknora doc upload` split into three commands:
- `weknora doc upload <file>` — local file (only).
- `weknora doc fetch <url>` — server-side remote fetch (was
`upload --from-url`). URL-only flags (--title / --file-type /
--tag-id) move with the verb.
- `weknora doc create --text` — direct text knowledge entry via
server CreateManualKnowledge.
- `weknora kb empty <id>` → `weknora doc delete --all --kb=<id>`.
Atomic server ClearKnowledgeBaseContents (no list-then-delete
race). Same exit-10 -y/--yes guard as other destructive verbs;
unified through the extended ConfirmDestructive helper.
Parent commands (agent, kb, doc, chunk, session, auth, profile,
search) lose their explicit Args:NoArgs + Run:cmd.Help so the
unknown-subcommand guard fires correctly — `weknora agent invoke
ag_x q` now emits the typed input.unknown_subcommand envelope with
detail.available[] instead of cobra's free-form exit-2 prose.
Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3.4 / §10.7
This commit is contained in:
+8
-12
@@ -1,13 +1,12 @@
|
||||
// Package agentcmd holds the `weknora agent` command tree:
|
||||
// list / view / invoke / create / edit / delete. The directory is named
|
||||
// `agent/` to match the cobra subcommand; the Go package is `agentcmd`
|
||||
// list / view / create / edit / delete / status / check. The directory is
|
||||
// named `agent/` to match the cobra subcommand; the Go package is `agentcmd`
|
||||
// to avoid colliding with cobra's *cobra.Command identifier.
|
||||
//
|
||||
// "agent" in this subtree refers to WeKnora's user-defined Custom
|
||||
// Agents (server resource: GET/POST /agents/...). The CLI's
|
||||
// `agent invoke` calls /agent-chat/:session_id which dispatches the
|
||||
// agent's configured workflow (system prompt, allowed tools, KB scope,
|
||||
// retrieval thresholds).
|
||||
// Agents (server resource: GET/POST /agents/...) and handles CRUD
|
||||
// operations only. Agent invocation has moved to `weknora session ask
|
||||
// --agent <id>` (see cli/cmd/session/ask.go).
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
@@ -21,16 +20,13 @@ import (
|
||||
func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "agent",
|
||||
Short: "Manage and invoke custom agents",
|
||||
Short: "Manage custom agents (CRUD + status/check)",
|
||||
Long: `Custom Agents bundle a system prompt, model, tool allow-list, and KB
|
||||
scope into an addressable resource. Create, edit, list, view, invoke,
|
||||
or delete agents.`,
|
||||
Args: cobra.NoArgs,
|
||||
Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
|
||||
scope into an addressable resource. Create, edit, list, view, check,
|
||||
or delete agents. To invoke an agent, use: weknora session ask --agent <id>`,
|
||||
}
|
||||
cmd.AddCommand(NewCmdList(f))
|
||||
cmd.AddCommand(NewCmdView(f))
|
||||
cmd.AddCommand(NewCmdInvoke(f))
|
||||
cmd.AddCommand(NewCmdCreate(f))
|
||||
cmd.AddCommand(NewCmdEdit(f))
|
||||
cmd.AddCommand(NewCmdDelete(f))
|
||||
|
||||
@@ -1,269 +0,0 @@
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"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/sse"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// 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",
|
||||
}
|
||||
|
||||
// InvokeOptions captures `agent invoke` flag state.
|
||||
type InvokeOptions struct {
|
||||
AgentID string
|
||||
Query string
|
||||
SessionID string // --session: continue an existing session (skip auto-create)
|
||||
}
|
||||
|
||||
// InvokeService is the narrow SDK surface this command depends on.
|
||||
//
|
||||
// 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
|
||||
// AgentQARequest.AgentID, so the same session can be reused across
|
||||
// agent / KB-chat invocations.
|
||||
type InvokeService interface {
|
||||
CreateSession(ctx context.Context, req *sdk.CreateSessionRequest) (*sdk.Session, error)
|
||||
AgentQAStreamWithRequest(ctx context.Context, sessionID string, req *sdk.AgentQARequest, cb sdk.AgentEventCallback) error
|
||||
}
|
||||
|
||||
// invokeData is the JSON payload emitted on the JSON path.
|
||||
type invokeData struct {
|
||||
Answer string `json:"answer"`
|
||||
References []*sdk.SearchResult `json:"references"`
|
||||
ToolEvents []sse.AgentToolEvent `json:"tool_events,omitempty"`
|
||||
Thinking string `json:"thinking,omitempty"`
|
||||
SessionID string `json:"session_id"`
|
||||
AgentID string `json:"agent_id"`
|
||||
Query string `json:"query"`
|
||||
}
|
||||
|
||||
// NewCmdInvoke builds `weknora agent invoke <agent-id> "<text>"`.
|
||||
func NewCmdInvoke(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &InvokeOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: `invoke <agent-id> "<text>"`,
|
||||
Short: "Run a query through a custom agent",
|
||||
Long: `Sends a query to the agent's configured workflow (system prompt, allowed
|
||||
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.
|
||||
|
||||
Modes:
|
||||
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?" --format json`,
|
||||
Args: cobra.ExactArgs(2),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
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, fopts, cli)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.SessionID, "session", "", "Continue an existing chat session (skip auto-create)")
|
||||
cmdutil.AddFormatFlag(cmd, agentInvokeFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
if opts.AgentID == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "agent-id argument cannot be empty")
|
||||
}
|
||||
if svc == nil {
|
||||
return cmdutil.NewError(cmdutil.CodeServerError, "agent invoke: no SDK client available")
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
return cmdutil.Wrapf(code, err, "create chat session")
|
||||
}
|
||||
sessionID = sess.ID
|
||||
autoCreated = true
|
||||
}
|
||||
|
||||
// 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.
|
||||
if autoCreated && !jsonOut {
|
||||
fmt.Fprintf(iostreams.IO.Err, "session: %s (use --session to continue)\n", sessionID)
|
||||
}
|
||||
|
||||
req := &sdk.AgentQARequest{
|
||||
Query: opts.Query,
|
||||
AgentEnabled: true,
|
||||
AgentID: opts.AgentID,
|
||||
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 != "" {
|
||||
_, _ = iostreams.IO.Out.Write([]byte(r.Content))
|
||||
}
|
||||
acc.Append(r)
|
||||
return nil
|
||||
}
|
||||
|
||||
streamErr := svc.AgentQAStreamWithRequest(ctx, sessionID, req, cb)
|
||||
if streamErr != nil {
|
||||
if autoCreated && !jsonOut {
|
||||
fmt.Fprintf(iostreams.IO.Err, "session: %s (resume with --session %s)\n", sessionID, sessionID)
|
||||
}
|
||||
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")
|
||||
}
|
||||
return cmdutil.WrapHTTP(streamErr, "agent-chat stream")
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
|
||||
answer := acc.Answer()
|
||||
if jsonOut {
|
||||
data := invokeData{
|
||||
Answer: answer,
|
||||
References: acc.References,
|
||||
ToolEvents: acc.ToolEvents,
|
||||
Thinking: acc.Thinking(),
|
||||
SessionID: sessionID,
|
||||
AgentID: opts.AgentID,
|
||||
Query: opts.Query,
|
||||
}
|
||||
return fopts.Emit(iostreams.IO.Out, data)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
renderToolTrace(out, acc.ToolEvents)
|
||||
format.WriteReferences(out, acc.References)
|
||||
return nil
|
||||
}
|
||||
|
||||
// renderToolTrace prints a compact tool-event footer in human mode.
|
||||
// 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 {
|
||||
return
|
||||
}
|
||||
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", truncateInline(e.Result, 80))
|
||||
}
|
||||
fmt.Fprintln(w)
|
||||
}
|
||||
}
|
||||
|
||||
// truncateInline shrinks a multi-line result to a single line + ellipsis
|
||||
// for the human tool-trace footer.
|
||||
func truncateInline(s string, maxLen int) string {
|
||||
s = strings.ReplaceAll(s, "\n", " ")
|
||||
if len(s) <= maxLen {
|
||||
return s
|
||||
}
|
||||
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,344 +0,0 @@
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// scriptedInvokeSvc serves a canned stream of agent events to runInvoke.
|
||||
type scriptedInvokeSvc struct {
|
||||
createResp *sdk.Session
|
||||
createErr error
|
||||
events []*sdk.AgentStreamResponse
|
||||
streamErr error
|
||||
got struct {
|
||||
sessionID string
|
||||
req *sdk.AgentQARequest
|
||||
}
|
||||
}
|
||||
|
||||
func (s *scriptedInvokeSvc) CreateSession(_ context.Context, req *sdk.CreateSessionRequest) (*sdk.Session, error) {
|
||||
if s.createResp == nil && s.createErr == nil {
|
||||
return &sdk.Session{ID: "sess_auto", Title: req.Title}, nil
|
||||
}
|
||||
return s.createResp, s.createErr
|
||||
}
|
||||
|
||||
func (s *scriptedInvokeSvc) AgentQAStreamWithRequest(_ context.Context, sessionID string, req *sdk.AgentQARequest, cb sdk.AgentEventCallback) error {
|
||||
s.got.sessionID = sessionID
|
||||
s.got.req = req
|
||||
for _, e := range s.events {
|
||||
if err := cb(e); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return s.streamErr
|
||||
}
|
||||
|
||||
func answerEvent(content string) *sdk.AgentStreamResponse {
|
||||
return &sdk.AgentStreamResponse{ResponseType: sdk.AgentResponseTypeAnswer, Content: content}
|
||||
}
|
||||
func doneEvent() *sdk.AgentStreamResponse {
|
||||
return &sdk.AgentStreamResponse{ResponseType: sdk.AgentResponseTypeAnswer, Done: true}
|
||||
}
|
||||
func toolCallEvent(id, name string) *sdk.AgentStreamResponse {
|
||||
return &sdk.AgentStreamResponse{
|
||||
ResponseType: sdk.AgentResponseTypeToolCall,
|
||||
ID: id,
|
||||
Content: name,
|
||||
}
|
||||
}
|
||||
func referencesEvent(refs []*sdk.SearchResult) *sdk.AgentStreamResponse {
|
||||
return &sdk.AgentStreamResponse{
|
||||
ResponseType: sdk.AgentResponseTypeReferences,
|
||||
KnowledgeReferences: refs,
|
||||
}
|
||||
}
|
||||
|
||||
// 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{
|
||||
events: []*sdk.AgentStreamResponse{
|
||||
answerEvent("Hello "),
|
||||
answerEvent("world."),
|
||||
referencesEvent([]*sdk.SearchResult{{KnowledgeID: "k1", KnowledgeTitle: "Doc 1"}}),
|
||||
doneEvent(),
|
||||
},
|
||||
}
|
||||
opts := &InvokeOptions{AgentID: "ag_x", Query: "ping"}
|
||||
if err := runInvoke(context.Background(), opts, jsonOpts(), svc); err != nil {
|
||||
t.Fatalf("runInvoke: %v", err)
|
||||
}
|
||||
var got invokeData
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
t.Fatalf("parse: %v\n%s", err, out.String())
|
||||
}
|
||||
if got.Answer != "Hello world." {
|
||||
t.Errorf("answer = %q, want %q", got.Answer, "Hello world.")
|
||||
}
|
||||
if got.AgentID != "ag_x" {
|
||||
t.Errorf("agent_id = %q, want ag_x", got.AgentID)
|
||||
}
|
||||
if got.Query != "ping" {
|
||||
t.Errorf("query = %q, want ping", got.Query)
|
||||
}
|
||||
if got.SessionID != "sess_auto" {
|
||||
t.Errorf("session_id = %q, want sess_auto", got.SessionID)
|
||||
}
|
||||
if len(got.References) != 1 || got.References[0].KnowledgeID != "k1" {
|
||||
t.Errorf("references missing: %+v", got.References)
|
||||
}
|
||||
}
|
||||
|
||||
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, jsonOpts(), svc); err != nil {
|
||||
t.Fatalf("runInvoke: %v", err)
|
||||
}
|
||||
if svc.got.sessionID != "sess_auto" {
|
||||
t.Errorf("agent-chat got sessionID=%q, want sess_auto", svc.got.sessionID)
|
||||
}
|
||||
if svc.got.req == nil || svc.got.req.AgentID != "ag_42" {
|
||||
t.Errorf("AgentID not forwarded: %+v", svc.got.req)
|
||||
}
|
||||
if !svc.got.req.AgentEnabled {
|
||||
t.Error("AgentEnabled must be true for agent invoke")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvoke_ExistingSessionID_SkipsCreate(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
created := false
|
||||
svc := &scriptedInvokeSvc{events: []*sdk.AgentStreamResponse{doneEvent()}}
|
||||
// Wrap CreateSession to detect call.
|
||||
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, jsonOpts(), wrapped); err != nil {
|
||||
t.Fatalf("runInvoke: %v", err)
|
||||
}
|
||||
if created {
|
||||
t.Error("CreateSession should not be called when --session is set")
|
||||
}
|
||||
if svc.got.sessionID != "sess_existing" {
|
||||
t.Errorf("agent-chat got sessionID=%q, want sess_existing", svc.got.sessionID)
|
||||
}
|
||||
}
|
||||
|
||||
type createSessionTracker struct {
|
||||
InvokeService
|
||||
called *bool
|
||||
}
|
||||
|
||||
func (c *createSessionTracker) CreateSession(ctx context.Context, req *sdk.CreateSessionRequest) (*sdk.Session, error) {
|
||||
*c.called = true
|
||||
return c.InvokeService.CreateSession(ctx, req)
|
||||
}
|
||||
|
||||
func TestInvoke_ToolEventsCaptured(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &scriptedInvokeSvc{events: []*sdk.AgentStreamResponse{
|
||||
toolCallEvent("call_1", "knowledge_search"),
|
||||
answerEvent("answer text"),
|
||||
doneEvent(),
|
||||
}}
|
||||
opts := &InvokeOptions{AgentID: "ag", Query: "x"}
|
||||
if err := runInvoke(context.Background(), opts, jsonOpts(), svc); err != nil {
|
||||
t.Fatalf("runInvoke: %v", err)
|
||||
}
|
||||
var got invokeData
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
if len(got.ToolEvents) != 1 {
|
||||
t.Fatalf("expected 1 tool call, got %d", len(got.ToolEvents))
|
||||
}
|
||||
if got.ToolEvents[0].ID != "call_1" {
|
||||
t.Errorf("tool_calls[0].id = %q, want call_1", got.ToolEvents[0].ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvoke_EmptyQuery_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &scriptedInvokeSvc{}
|
||||
opts := &InvokeOptions{AgentID: "ag", Query: ""}
|
||||
err := runInvoke(context.Background(), opts, textOpts(), svc)
|
||||
if err == nil {
|
||||
t.Fatal("expected input.invalid_argument, got nil")
|
||||
}
|
||||
var typed *cmdutil.Error
|
||||
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeInputInvalidArgument {
|
||||
t.Errorf("expected input.invalid_argument, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvoke_StreamAbortBeforeDone_MapsToSSEStreamAborted(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &scriptedInvokeSvc{
|
||||
events: []*sdk.AgentStreamResponse{
|
||||
answerEvent("partial"),
|
||||
},
|
||||
streamErr: errors.New("connection reset"),
|
||||
}
|
||||
opts := &InvokeOptions{AgentID: "ag", Query: "x"}
|
||||
err := runInvoke(context.Background(), opts, jsonOpts(), svc)
|
||||
if err == nil {
|
||||
t.Fatal("expected stream-aborted error")
|
||||
}
|
||||
var typed *cmdutil.Error
|
||||
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeSSEStreamAborted {
|
||||
t.Errorf("expected local.sse_stream_aborted, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
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, jsonOpts(), svc)
|
||||
if err == nil {
|
||||
t.Fatal("expected stream-aborted error")
|
||||
}
|
||||
var typed *cmdutil.Error
|
||||
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeSSEStreamAborted {
|
||||
t.Errorf("expected local.sse_stream_aborted, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
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, textOpts(), svc)
|
||||
if err == nil {
|
||||
t.Fatal("expected session_create_failed")
|
||||
}
|
||||
var typed *cmdutil.Error
|
||||
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeSessionCreateFailed {
|
||||
t.Errorf("expected server.session_create_failed, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
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, jsonOpts(), svc)
|
||||
if err == nil {
|
||||
t.Fatal("expected operation.cancelled")
|
||||
}
|
||||
var typed *cmdutil.Error
|
||||
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeOperationCancelled {
|
||||
t.Errorf("expected operation.cancelled, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Sanity: human-mode output writes the answer body and a tool-trace footer.
|
||||
func TestInvoke_Human_Accumulate_PrintsAnswerAndFooter(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &scriptedInvokeSvc{events: []*sdk.AgentStreamResponse{
|
||||
answerEvent("hello"),
|
||||
toolCallEvent("c1", "knowledge_search"),
|
||||
doneEvent(),
|
||||
}}
|
||||
opts := &InvokeOptions{AgentID: "ag", Query: "x"}
|
||||
if err := runInvoke(context.Background(), opts, textOpts(), svc); err != nil {
|
||||
t.Fatalf("runInvoke: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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