feat(cli): agent subtree (list/view/invoke)

Manages WeKnora's first-class Custom Agent resources — server-side
records (system prompt + model + allowed tools + KB scope) that the
user authored in the web UI.

Commands:
- `weknora agent list` — tenant-visible agents (built-in + custom),
  sorted updated_at desc; `--limit`/`-L` caps the slice client-side.
- `weknora agent view <id>` — full sdk.Agent including nested
  AgentConfig (mode / model / allowed_tools / KB scope). Human mode
  prints a compact KV layout + Config: block.
- `weknora agent invoke <agent-id> "<text>"` — streams the agent's
  configured workflow against a query over SSE. Auto-creates a fresh
  session unless `--session` is passed. Streaming defaults to TTY +
  no-stream/no-json; agent-friendly buffered single-object output
  with `--json` (or `--no-stream`).

Decoupled from the existing `chat` subtree: agents bring their own
system prompt / tool surface / KB selection, so the chat / agent split
matches the server-side resource boundary.
This commit is contained in:
nullkey
2026-05-14 23:28:14 +08:00
committed by lyingbug
parent 3b67986863
commit 493fc41e98
9 changed files with 1095 additions and 0 deletions
+13
View File
@@ -8,6 +8,19 @@
> This is **not** a contributor guide. If you are an AI coding agent
> editing weknora's source, see the repo root `README.md` (and, if added
> later, a separate contributor `AGENTS.md` at the repo root).
>
> **Naming note.** "Agent" appears in two distinct WeKnora contexts:
>
> - **This file (`AGENTS.md`) + the `agent` annotation on each command's
> `--help`**: documents the contract for AI coding agents (you, the
> LLM-driven CLI consumer).
> - **The `weknora agent` subtree** (`agent list / view / invoke`):
> manages WeKnora's first-class *Custom Agent* resources — server-side
> records (system prompt + model + allowed tools + KB scope) that the
> user authored in the web UI. `agent invoke` calls the agent's
> configured workflow against a query; it is **not** how you, the AI
> coding agent, drive WeKnora — that's `kb` / `doc` / `search` / `chat`
> / `mcp serve`.
`weknora` is designed to be agent-friendly: error messages, output format,
and flag design follow conventions agents can rely on. Wire-contract
+45
View File
@@ -0,0 +1,45 @@
// Package agentcmd holds the `weknora agent` command tree:
// list / view / invoke. The directory is named `agent/` (matches cobra
// noun-verb convention) but the Go package is `agentcmd` to avoid
// shadowing cli/internal/agent (which owns SetAgentHelp + agent-aware
// help rendering for AI coding agents — a distinct concept from
// WeKnora's first-class custom-agent resources).
//
// Disambiguation in cli/AGENTS.md: "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, etc.). This is
// orthogonal to AGENTS.md / SetAgentHelp, which exists so AI coding
// agents (Claude Code, Cursor) consuming the CLI can read structured
// hints from --help.
package agentcmd
import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
// NewCmd builds the `weknora agent` parent and registers leaves. Called
// from cli/cmd/root.go.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "agent",
Short: "Manage and invoke custom agents",
Long: `Custom Agents bundle a system prompt, model, tool allow-list, and KB
scope into an addressable resource. List visible agents, view a single
agent's configuration, or invoke an agent against a query.
Distinct from the per-CLI ` + "`AGENTS.md`" + ` reference: that file documents the
contract for AI coding agents (Claude Code / Cursor) running ` + "`weknora`" + `
on a user's behalf. This subtree manages WeKnora's first-class custom-agent
resources stored on the server.`,
Args: cobra.NoArgs,
Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
}
cmd.AddCommand(NewCmdList(f))
cmd.AddCommand(NewCmdView(f))
cmd.AddCommand(NewCmdInvoke(f))
return cmd
}
+321
View File
@@ -0,0 +1,321 @@
package agentcmd
import (
"context"
"errors"
"fmt"
"io"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// agentInvokeFields enumerates fields surfaced for `--json` discovery on
// `agent invoke`. Matches invokeData below — single-shot result envelope
// with the agent's final answer plus the trace (references, tool calls).
var agentInvokeFields = []string{
"answer", "references", "tool_calls", "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)
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
// 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
}
// toolCallTrace mirrors a single SSE `tool_call` event so agents can see
// which tools the WeKnora-side agent invoked (and their results). Only the
// fields the server actually emits are captured.
type toolCallTrace struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
Result string `json:"result,omitempty"`
Data map[string]any `json:"data,omitempty"`
}
// invokeData is the JSON envelope payload.
type invokeData struct {
Answer string `json:"answer"`
References []*sdk.SearchResult `json:"references"`
ToolCalls []toolCallTrace `json:"tool_calls,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 (default): live answer streaming + tool-trace footer
Pipe / --no-stream / --json: buffered, single envelope 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`,
Args: cobra.ExactArgs(2),
RunE: func(c *cobra.Command, args []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
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)
},
}
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)
agent.SetAgentHelp(cmd, "Invokes a custom agent. Default: streams the answer to stdout (TTY) and renders a tool-trace footer. Agent / non-TTY callers should pass --json so the full {answer, references, tool_calls, thinking, session_id, agent_id, query} envelope is emitted once at completion (no partial chunks). Errors: resource.not_found when agent_id unknown; server.session_create_failed when auto-create fails; local.sse_stream_aborted on mid-stream disconnect.")
return cmd
}
func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOptions, 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 := jopts.Enabled()
sessionID := opts.SessionID
autoCreated := false
if sessionID == "" {
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora agent invoke"})
if err != nil {
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 --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
// 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",
}
acc := newAgentAccumulator()
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 errors.Is(streamErr, context.Canceled) || errors.Is(ctx.Err(), context.Canceled) {
return cmdutil.Wrapf(cmdutil.CodeUserAborted, streamErr, "agent invoke cancelled")
}
if acc.answer.Len() > 0 && !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.String()
if jsonOut {
data := invokeData{
Answer: answer,
References: acc.references,
ToolCalls: acc.toolCalls,
Thinking: acc.thinking.String(),
SessionID: sessionID,
AgentID: opts.AgentID,
Query: opts.Query,
}
return format.WriteEnvelopeFiltered(
iostreams.IO.Out,
format.Success(data, nil),
jopts.Fields, jopts.JQ,
)
}
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.toolCalls)
renderReferences(out, acc.references)
return nil
}
// agentAccumulator buffers an AgentQAStream callback sequence. Distinct
// from internal/sse.Accumulator because the agent event model is wider
// (thinking / tool_call / tool_result / answer / references / reflection /
// error) and uses a flat r.Done bool instead of the
// ResponseType=complete sentinel that KnowledgeQAStream emits.
type agentAccumulator struct {
answer strings.Builder
thinking strings.Builder
references []*sdk.SearchResult
toolCalls []toolCallTrace
done bool
}
func newAgentAccumulator() *agentAccumulator { return &agentAccumulator{} }
func (a *agentAccumulator) append(r *sdk.AgentStreamResponse) {
if r == nil || a.done {
return
}
switch r.ResponseType {
case sdk.AgentResponseTypeAnswer:
if r.Content != "" {
a.answer.WriteString(r.Content)
}
case sdk.AgentResponseTypeThinking, sdk.AgentResponseTypeReflection:
if r.Content != "" {
a.thinking.WriteString(r.Content)
}
case sdk.AgentResponseTypeReferences:
if r.KnowledgeReferences != nil {
a.references = r.KnowledgeReferences
}
case sdk.AgentResponseTypeToolCall, sdk.AgentResponseTypeToolResult:
a.toolCalls = append(a.toolCalls, toolCallTrace{
ID: r.ID,
Name: string(r.ResponseType),
Result: r.Content,
Data: r.Data,
})
}
// References can also arrive on the terminal frame.
if r.KnowledgeReferences != nil && a.references == nil {
a.references = r.KnowledgeReferences
}
if r.Done {
a.done = true
}
}
// renderToolTrace prints a compact tool-call footer in human mode. Skipped
// when the agent invoked no tools — silent beats an empty banner.
func renderToolTrace(w io.Writer, calls []toolCallTrace) {
if len(calls) == 0 {
return
}
fmt.Fprintln(w)
fmt.Fprintln(w, "──── Tool trace ────")
for i, c := range calls {
fmt.Fprintf(w, "[%d] %s", i+1, c.Name)
if c.Result != "" {
fmt.Fprintf(w, " %s", truncateInline(c.Result, 80))
}
fmt.Fprintln(w)
}
}
// renderReferences mirrors chat.go's references footer for parity.
func renderReferences(w io.Writer, refs []*sdk.SearchResult) {
if len(refs) == 0 {
return
}
fmt.Fprintln(w)
fmt.Fprintln(w, "──── References ────")
for i, r := range refs {
if r == nil {
continue
}
title := r.KnowledgeTitle
if title == "" {
title = r.KnowledgeFilename
}
if title == "" {
title = r.KnowledgeID
}
fmt.Fprintf(w, "[%d] %s", i+1, title)
if r.Score > 0 {
fmt.Fprintf(w, " score=%.3f", r.Score)
}
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] + "…"
}
// compile-time check: production SDK client satisfies InvokeService.
var _ InvokeService = (*sdk.Client)(nil)
+274
View File
@@ -0,0 +1,274 @@
package agentcmd
import (
"context"
"encoding/json"
"errors"
"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,
}
}
func TestInvoke_AccumulateMode_EmitsJSONEnvelope(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, &cmdutil.JSONOptions{}, svc); err != nil {
t.Fatalf("runInvoke: %v", err)
}
var env struct {
OK bool `json:"ok"`
Data invokeData `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("parse: %v\n%s", err, out.String())
}
if !env.OK {
t.Fatalf("ok=false: %s", out.String())
}
if env.Data.Answer != "Hello world." {
t.Errorf("answer = %q, want %q", env.Data.Answer, "Hello world.")
}
if env.Data.AgentID != "ag_x" {
t.Errorf("agent_id = %q, want ag_x", env.Data.AgentID)
}
if env.Data.Query != "ping" {
t.Errorf("query = %q, want ping", env.Data.Query)
}
if env.Data.SessionID != "sess_auto" {
t.Errorf("session_id = %q, want sess_auto", env.Data.SessionID)
}
if len(env.Data.References) != 1 || env.Data.References[0].KnowledgeID != "k1" {
t.Errorf("references missing: %+v", env.Data.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, &cmdutil.JSONOptions{}, 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, &cmdutil.JSONOptions{}, 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_ToolCallsCaptured(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, &cmdutil.JSONOptions{}, svc); err != nil {
t.Fatalf("runInvoke: %v", err)
}
var env struct {
Data invokeData `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("parse: %v", err)
}
if len(env.Data.ToolCalls) != 1 {
t.Fatalf("expected 1 tool call, got %d", len(env.Data.ToolCalls))
}
if env.Data.ToolCalls[0].ID != "call_1" {
t.Errorf("tool_calls[0].id = %q, want call_1", env.Data.ToolCalls[0].ID)
}
}
func TestInvoke_EmptyQuery_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &scriptedInvokeSvc{}
opts := &InvokeOptions{AgentID: "ag", Query: ""}
err := runInvoke(context.Background(), opts, nil, 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, &cmdutil.JSONOptions{}, 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, &cmdutil.JSONOptions{}, 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, nil, 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_MapsToUserAborted(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)
if err == nil {
t.Fatal("expected user_aborted")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeUserAborted {
t.Errorf("expected local.user_aborted, 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", NoStream: true}
if err := runInvoke(context.Background(), opts, nil, 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)
}
}
+101
View File
@@ -0,0 +1,101 @@
package agentcmd
import (
"context"
"fmt"
"sort"
"text/tabwriter"
"time"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"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/text"
sdk "github.com/Tencent/WeKnora/client"
)
// agentListFields enumerates the fields surfaced for `--json` discovery
// on `agent list`. Mirrors the json tags on sdk.Agent — nested Config is
// omitted because its sub-fields make filtering noisy (use `--jq` instead).
var agentListFields = []string{
"id", "name", "description", "avatar",
"is_builtin", "tenant_id", "created_by",
"created_at", "updated_at",
}
// ListService is the narrow SDK surface this command depends on.
type ListService interface {
ListAgents(ctx context.Context) ([]sdk.Agent, error)
}
// listResult is the typed payload emitted under data.items.
type listResult struct {
Items []sdk.Agent `json:"items"`
}
// NewCmdList builds `weknora agent list`.
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "List custom agents visible to the active tenant",
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
return runList(c.Context(), jopts, cli)
},
}
cmdutil.AddJSONFlags(cmd, agentListFields)
agent.SetAgentHelp(cmd, "Lists tenant-visible agents (built-in + custom). Returns data.items: [{id, name, description, ...}]; empty array when none. Use --json id,name to project, --jq for arbitrary reshape.")
return cmd
}
func runList(ctx context.Context, jopts *cmdutil.JSONOptions, svc ListService) error {
items, err := svc.ListAgents(ctx)
if err != nil {
return cmdutil.WrapHTTP(err, "list agents")
}
if items == nil {
items = []sdk.Agent{} // ensure JSON [] not null
}
// Default sort: updated_at desc — most recently-edited agents surface
// first. Mirrors kb list / doc list behavior.
sort.Slice(items, func(i, j int) bool {
return items[i].UpdatedAt.After(items[j].UpdatedAt)
})
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(
iostreams.IO.Out,
format.Success(listResult{Items: items}, nil),
jopts.Fields, jopts.JQ,
)
}
if len(items) == 0 {
fmt.Fprintln(iostreams.IO.Out, "(no agents)")
return nil
}
tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0)
fmt.Fprintln(tw, "ID\tNAME\tBUILTIN\tUPDATED")
now := time.Now()
for _, a := range items {
name := text.Truncate(40, a.Name)
builtin := "-"
if a.IsBuiltin {
builtin = "yes"
}
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", a.ID, name, builtin, text.FuzzyAgo(now, a.UpdatedAt))
}
return tw.Flush()
}
+112
View File
@@ -0,0 +1,112 @@
package agentcmd
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
type fakeListSvc struct {
items []sdk.Agent
err error
}
func (f *fakeListSvc) ListAgents(_ context.Context) ([]sdk.Agent, error) {
return f.items, f.err
}
func TestList_Empty_Human(t *testing.T) {
out, _ := iostreams.SetForTest(t)
if err := runList(context.Background(), nil, &fakeListSvc{}); err != nil {
t.Fatalf("runList: %v", err)
}
if !strings.Contains(out.String(), "(no agents)") {
t.Errorf("expected '(no agents)', got %q", out.String())
}
}
func TestList_Empty_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
if err := runList(context.Background(), &cmdutil.JSONOptions{}, &fakeListSvc{}); err != nil {
t.Fatalf("runList: %v", err)
}
if !strings.Contains(out.String(), `"items":[]`) {
t.Errorf("expected items:[], got %q", out.String())
}
}
func TestList_NonEmpty_Human_RendersColumns(t *testing.T) {
out, _ := iostreams.SetForTest(t)
now := time.Now()
items := []sdk.Agent{
{ID: "ag_a", Name: "Research", IsBuiltin: true, UpdatedAt: now.Add(-1 * time.Hour)},
{ID: "ag_b", Name: "Triage", UpdatedAt: now.Add(-3 * 24 * time.Hour)},
}
if err := runList(context.Background(), nil, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
got := out.String()
for _, w := range []string{"ID", "NAME", "BUILTIN", "ag_a", "Research", "yes", "ag_b", "Triage"} {
if !strings.Contains(got, w) {
t.Errorf("output missing %q in:\n%s", w, got)
}
}
}
func TestList_NonEmpty_JSON_SortsByUpdatedAtDesc(t *testing.T) {
out, _ := iostreams.SetForTest(t)
now := time.Now()
items := []sdk.Agent{
{ID: "ag_old", Name: "old", UpdatedAt: now.Add(-7 * 24 * time.Hour)},
{ID: "ag_new", Name: "new", UpdatedAt: now},
{ID: "ag_mid", Name: "mid", UpdatedAt: now.Add(-1 * time.Hour)},
}
if err := runList(context.Background(), &cmdutil.JSONOptions{}, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
var env struct {
Data struct {
Items []sdk.Agent `json:"items"`
} `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("parse: %v", err)
}
if len(env.Data.Items) != 3 {
t.Fatalf("len = %d, want 3", len(env.Data.Items))
}
wantOrder := []string{"ag_new", "ag_mid", "ag_old"}
for i, w := range wantOrder {
if env.Data.Items[i].ID != w {
t.Errorf("position %d: got %s, want %s (updated_at desc)", i, env.Data.Items[i].ID, w)
}
}
}
func TestList_JSON_FieldFilter(t *testing.T) {
out, _ := iostreams.SetForTest(t)
items := []sdk.Agent{
{ID: "ag_x", Name: "Foo", Description: "long description"},
}
jopts := &cmdutil.JSONOptions{Fields: []string{"id", "name"}}
if err := runList(context.Background(), jopts, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
var env struct {
Data struct {
Items []map[string]any `json:"items"`
} `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("parse: %v", err)
}
if _, has := env.Data.Items[0]["description"]; has {
t.Errorf("description should be filtered out: %+v", env.Data.Items[0])
}
}
+118
View File
@@ -0,0 +1,118 @@
package agentcmd
import (
"context"
"fmt"
"io"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// agentViewFields enumerates fields surfaced for `--json` discovery on
// `agent view`. Single-resource shape: filter applies to data itself.
// Config sub-fields are intentionally omitted — too granular for naked
// projection; use `--jq '.data.config'` to reach them.
var agentViewFields = []string{
"id", "name", "description", "avatar",
"is_builtin", "tenant_id", "created_by",
"created_at", "updated_at",
}
// ViewService is the narrow SDK surface this command depends on.
type ViewService interface {
GetAgent(ctx context.Context, agentID string) (*sdk.Agent, error)
}
// NewCmdView builds `weknora agent view <agent-id>`.
func NewCmdView(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "view <agent-id>",
Short: "Show a custom agent's configuration",
Long: `Renders the agent's metadata (id / name / description / created-by /
timestamps) plus a compact config summary (mode, model, allowed tools, KB
scope). Pass --json for the full envelope including the nested config
struct — or --jq '.data.config' to extract just the config.`,
Example: ` weknora agent view ag_abc
weknora agent view ag_abc --json | jq '.data.config.allowed_tools'`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
return runView(c.Context(), jopts, cli, args[0])
},
}
cmdutil.AddJSONFlags(cmd, agentViewFields)
agent.SetAgentHelp(cmd, "Fetches an agent by ID. Returns data: full sdk.Agent (with nested config). Errors: resource.not_found when the agent ID does not exist or is not visible to the active tenant.")
return cmd
}
func runView(ctx context.Context, jopts *cmdutil.JSONOptions, svc ViewService, agentID string) error {
a, err := svc.GetAgent(ctx, agentID)
if err != nil {
return cmdutil.WrapHTTP(err, "fetch agent %s", agentID)
}
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
format.Success(a, nil),
jopts.Fields, jopts.JQ)
}
renderAgent(iostreams.IO.Out, a)
return nil
}
// renderAgent prints a single agent in human-readable KV form. Empty
// fields are omitted (mirrors doc view / kb view); the Config block is
// compacted to its agent-mode-defining keys.
func renderAgent(w io.Writer, a *sdk.Agent) {
fmt.Fprintf(w, "ID: %s\n", a.ID)
fmt.Fprintf(w, "Name: %s\n", a.Name)
if a.Description != "" {
fmt.Fprintf(w, "Description: %s\n", a.Description)
}
if a.IsBuiltin {
fmt.Fprintln(w, "Builtin: yes")
}
if a.CreatedBy != "" {
fmt.Fprintf(w, "Created by: %s\n", a.CreatedBy)
}
fmt.Fprintf(w, "Created at: %s\n", a.CreatedAt.Format("2006-01-02 15:04:05"))
fmt.Fprintf(w, "Updated at: %s\n", a.UpdatedAt.Format("2006-01-02 15:04:05"))
if a.Config == nil {
return
}
fmt.Fprintln(w)
fmt.Fprintln(w, "Config:")
if a.Config.AgentMode != "" {
fmt.Fprintf(w, " Mode: %s\n", a.Config.AgentMode)
}
if a.Config.ModelID != "" {
fmt.Fprintf(w, " Model ID: %s\n", a.Config.ModelID)
}
if a.Config.RerankModelID != "" {
fmt.Fprintf(w, " Rerank model ID: %s\n", a.Config.RerankModelID)
}
if a.Config.KBSelectionMode != "" {
fmt.Fprintf(w, " KB selection mode: %s\n", a.Config.KBSelectionMode)
}
if len(a.Config.KnowledgeBases) > 0 {
fmt.Fprintf(w, " Knowledge bases: %v\n", a.Config.KnowledgeBases)
}
if len(a.Config.AllowedTools) > 0 {
fmt.Fprintf(w, " Allowed tools: %v\n", a.Config.AllowedTools)
}
if a.Config.WebSearchEnabled {
fmt.Fprintln(w, " Web search: enabled")
}
}
+109
View File
@@ -0,0 +1,109 @@
package agentcmd
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
type fakeViewSvc struct {
resp *sdk.Agent
err error
}
func (f *fakeViewSvc) GetAgent(_ context.Context, _ string) (*sdk.Agent, error) {
return f.resp, f.err
}
func TestView_Human_RendersMetadataAndConfig(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{resp: &sdk.Agent{
ID: "ag_abc",
Name: "Research",
Description: "deep-dive helper",
IsBuiltin: true,
CreatedAt: time.Date(2026, 5, 1, 12, 0, 0, 0, time.UTC),
UpdatedAt: time.Date(2026, 5, 2, 13, 30, 0, 0, time.UTC),
Config: &sdk.AgentConfig{
AgentMode: "smart-reasoning",
ModelID: "model_42",
KBSelectionMode: "selected",
KnowledgeBases: []string{"kb_x", "kb_y"},
AllowedTools: []string{"knowledge_search", "web_search"},
WebSearchEnabled: true,
},
}}
if err := runView(context.Background(), nil, svc, "ag_abc"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
for _, want := range []string{"ag_abc", "Research", "deep-dive helper", "Builtin:", "Config:", "smart-reasoning", "model_42", "selected", "kb_x", "knowledge_search", "Web search:"} {
if !strings.Contains(got, want) {
t.Errorf("missing %q in:\n%s", want, got)
}
}
}
func TestView_Human_OmitsEmptyFields(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{resp: &sdk.Agent{
ID: "ag_min",
Name: "Minimal",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}}
if err := runView(context.Background(), nil, svc, "ag_min"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
if strings.Contains(got, "Description:") {
t.Errorf("empty description should be omitted, got:\n%s", got)
}
if strings.Contains(got, "Builtin:") {
t.Errorf("non-builtin should not render Builtin: line, got:\n%s", got)
}
if strings.Contains(got, "Config:") {
t.Errorf("nil Config should not render Config: section, got:\n%s", got)
}
}
func TestView_JSON_Envelope(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{resp: &sdk.Agent{ID: "ag_json", Name: "JSONy"}}
if err := runView(context.Background(), &cmdutil.JSONOptions{}, svc, "ag_json"); err != nil {
t.Fatalf("runView: %v", err)
}
var env struct {
OK bool `json:"ok"`
Data sdk.Agent `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("parse: %v", err)
}
if !env.OK || env.Data.ID != "ag_json" {
t.Errorf("envelope shape wrong: ok=%v id=%s", env.OK, env.Data.ID)
}
}
func TestView_404_MapsToResourceNotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeViewSvc{err: errors.New("HTTP error 404: agent not found")}
err := runView(context.Background(), nil, svc, "ag_missing")
if err == nil {
t.Fatal("expected error, got nil")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %T", err)
}
if typed.Code != cmdutil.CodeResourceNotFound {
t.Errorf("expected resource.not_found, got %s", typed.Code)
}
}
+2
View File
@@ -8,6 +8,7 @@ import (
"github.com/spf13/cobra"
agentcmd "github.com/Tencent/WeKnora/cli/cmd/agent"
apicmd "github.com/Tencent/WeKnora/cli/cmd/api"
"github.com/Tencent/WeKnora/cli/cmd/auth"
chatcmd "github.com/Tencent/WeKnora/cli/cmd/chat"
@@ -175,6 +176,7 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`,
cmd.AddCommand(apicmd.NewCmd(f))
cmd.AddCommand(chatcmd.NewCmd(f))
cmd.AddCommand(sessioncmd.NewCmd(f))
cmd.AddCommand(agentcmd.NewCmd(f))
return cmd
}