refactor(cli): resource-command refactors — --kb resolver, MCP session_ask, session stop (BREAKING)

Unify the --kb resolver (accepts name or UUID) across kb/doc/chunk/session/
search/chat/link; `agent create` attaches knowledge bases via --attach-kb
(no longer --kb). Rename the MCP tool agent_invoke → session_ask and drop dead
MCP error codes. Add `session stop` (StopSession), completing the
start / continue-stream / stop triad.

Across these commands, bring the agent contract up to par: --dry-run previews
on mutations (incl. kb pin/unpin, session stop), agent-help blobs on the
read/health surface, accurate destructive-confirmation verbs, and search
has_more truncation signalling so an agent can tell its results were capped.
This commit is contained in:
nullkey
2026-05-29 20:06:30 +08:00
committed by lyingbug
parent a68cc59310
commit c90f4e895e
54 changed files with 807 additions and 93 deletions
+2 -2
View File
@@ -84,7 +84,7 @@ without the user's explicit go-ahead.`,
if len(args) == 1 {
return runDelete(c.Context(), opts, fopts, cli, f.Prompter(), args[0])
}
if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "session", len(args), "session.delete", "weknora session delete "+strings.Join(args, " ")+" -y"); err != nil {
if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "session", len(args), "session.delete", "weknora session delete "+strings.Join(args, " ")+" -y"); err != nil {
return err
}
outcomes, runErr := cmdutil.RunBatch(c.Context(), args, func(ctx context.Context, id string) error {
@@ -124,7 +124,7 @@ without the user's explicit go-ahead.`,
}
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter, id string) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "session", id, "session.delete", "weknora session delete "+id+" -y"); err != nil {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "session", id, "session.delete", "weknora session delete "+id+" -y"); err != nil {
return err
}
+1 -1
View File
@@ -146,7 +146,7 @@ func TestMultiDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeMultiDeleteSvc{}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, fopts.WantsJSON(), "session", 2, "session.delete", "")
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, fopts.WantsJSON(), "delete", "session", 2, "session.delete", "")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
+5
View File
@@ -69,6 +69,11 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
cmd.Flags().BoolVar(&opts.AllPages, "all-pages", false, "Walk all server pages until exhausted (or --limit hit)")
cmd.Flags().StringVar(&opts.Since, "since", "", "Only show sessions updated within `duration` (e.g. 7d, 24h, 30m)")
cmdutil.AddFormatFlag(cmd, sessionListFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "List chat sessions for the active profile. Results come with meta.count; use --limit to cap, --all-pages to walk every server page, --since to filter by recency (e.g. 7d).",
Examples: []string{"weknora session list --format json", "weknora session list --all-pages --since 7d --format json"},
Output: "envelope.data is an array of Session objects with id, title, updated_at; meta.count is the total returned",
})
return cmd
}
+2 -1
View File
@@ -1,5 +1,5 @@
// Package sessioncmd holds `weknora session` command tree (list / view /
// delete / ask) for chat history and agent invocation.
// delete / ask / continue-stream / stop) for chat history and agent invocation.
//
// Package name `sessioncmd` (not `session`) so callers can `import sdk
// "github.com/Tencent/WeKnora/client"` and use `sdk.Session` without
@@ -23,5 +23,6 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd.AddCommand(NewCmdDelete(f))
cmd.AddCommand(NewCmdAsk(f))
cmd.AddCommand(NewCmdContinueStream(f))
cmd.AddCommand(NewCmdStop(f))
return cmd
}
+118
View File
@@ -0,0 +1,118 @@
// stop.go implements `weknora session stop` — cancel server-side generation
// for a specific assistant message under a known session.
//
// Unlike Ctrl-C (which only drops the local connection while the server keeps
// generating and billing tokens), this tells the server to stop.
//
// This is the symmetric counterpart to `session continue-stream`: both key on
// (session_id, message_id). The message_id comes from the init event of the
// original chat / session ask / continue-stream stream.
package sessioncmd
import (
"context"
"fmt"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
var stopFields = []string{"session_id", "message_id", "stopped"}
// StopOptions captures `session stop` flag/arg state.
type StopOptions struct {
SessionID string
MessageID string
DryRun bool
}
// StopService is the narrow SDK surface this command depends on.
// *sdk.Client satisfies it; tests substitute a fake. Compile-time check
// at the bottom of this file.
type StopService interface {
StopSession(ctx context.Context, sessionID, messageID string) error
}
type stopResult struct {
SessionID string `json:"session_id"`
MessageID string `json:"message_id"`
Stopped bool `json:"stopped"`
}
// NewCmdStop builds `weknora session stop <session-id> --message <id>`.
func NewCmdStop(f *cmdutil.Factory) *cobra.Command {
opts := &StopOptions{}
cmd := &cobra.Command{
Use: "stop <session-id>",
Short: "Stop in-flight generation for an assistant message in a session",
Long: `Cancel server-side generation for a specific assistant message under a
session. Unlike Ctrl-C (which only drops the local connection while the server
keeps generating and billing tokens), this tells the server to stop.
Symmetric with 'session continue-stream': both key on (session_id, message_id).`,
Example: ` weknora session stop sess_xyz --message msg_abc`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts.SessionID = args[0]
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
if handled, err := cmdutil.HandleDryRun(c, opts.DryRun, cmdutil.DryRunPlan{
Action: "session.stop",
Args: map[string]any{"session": opts.SessionID, "message": opts.MessageID},
}); handled {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
return runStop(c.Context(), opts, fopts, cli)
},
}
cmd.Flags().StringVarP(&opts.MessageID, "message", "m", "",
"Assistant message id to stop (from the init event of the stream you're stopping)")
_ = cmd.MarkFlagRequired("message")
cmdutil.AddFormatFlag(cmd, stopFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Stop server-side generation for an in-flight assistant message (counterpart to continue-stream). The message_id comes from the init event of the chat / session ask / continue-stream stream you're stopping.",
RequiredFlags: []string{"--message (message_id from the init event of the stream you're stopping)"},
Examples: []string{"weknora session stop sess_xyz --message msg_abc"},
Output: "envelope {session_id, message_id, stopped:true}",
})
return cmd
}
// runStop is the testable core: validate, dispatch the stop, and emit the
// result envelope. Returns a typed error.
func runStop(ctx context.Context, opts *StopOptions, fopts *cmdutil.FormatOptions, svc StopService) error {
if opts.SessionID == "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "session-id argument cannot be empty")
}
if opts.MessageID == "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--message cannot be empty")
}
if svc == nil {
return cmdutil.NewError(cmdutil.CodeServerError, "session stop: no SDK client available")
}
if err := svc.StopSession(ctx, opts.SessionID, opts.MessageID); err != nil {
if cmdutil.IsCancelled(ctx, err) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "session stop cancelled")
}
return cmdutil.WrapHTTP(err, "stop session")
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, stopResult{SessionID: opts.SessionID, MessageID: opts.MessageID, Stopped: true}, nil)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Stopped generation for message %s\n", opts.MessageID)
return nil
}
// compile-time check: production SDK client satisfies StopService.
var _ StopService = (*sdk.Client)(nil)
+70
View File
@@ -0,0 +1,70 @@
package sessioncmd
import (
"bytes"
"context"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
)
// fakeStopSvc records the (sessionID, messageID) pair passed to StopSession
// and optionally returns a canned error.
type fakeStopSvc struct {
err error
gotSessID string
gotMsgID string
}
func (s *fakeStopSvc) StopSession(_ context.Context, sessionID, messageID string) error {
s.gotSessID = sessionID
s.gotMsgID = messageID
return s.err
}
// TestRunStop_CallsSDKAndEmits verifies that runStop passes (sessionID,
// messageID) to the SDK and emits a JSON envelope with stopped:true.
func TestRunStop_CallsSDKAndEmits(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeStopSvc{}
opts := &StopOptions{SessionID: "s1", MessageID: "m1"}
require.NoError(t, runStop(context.Background(), opts, jsonOpts(), svc))
assert.Equal(t, "s1", svc.gotSessID, "SDK must receive the session-id")
assert.Equal(t, "m1", svc.gotMsgID, "SDK must receive the message-id")
assert.Contains(t, out.String(), `"stopped":true`, "stdout must contain stopped:true")
}
// TestRunStop_TextMode verifies that runStop writes the human-readable success
// line and calls the SDK when format is text (not JSON).
func TestRunStop_TextMode(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeStopSvc{}
opts := &StopOptions{SessionID: "sess_xyz", MessageID: "msg_abc"}
require.NoError(t, runStop(context.Background(), opts, textOpts(), svc))
assert.Equal(t, "sess_xyz", svc.gotSessID, "SDK must receive the session-id")
assert.Equal(t, "msg_abc", svc.gotMsgID, "SDK must receive the message-id")
assert.Contains(t, out.String(), "✓ Stopped generation for message msg_abc")
}
// TestStop_MessageRequired verifies that NewCmdStop refuses to run without
// --message (the flag is marked required by cobra).
func TestStop_MessageRequired(t *testing.T) {
f := &cmdutil.Factory{}
cmd := NewCmdStop(f)
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.SetErr(&buf)
cmd.SetArgs([]string{"sess_xyz"}) // positional only, no --message
err := cmd.Execute()
require.Error(t, err, "expected required-flag error when --message is missing")
assert.True(t,
strings.Contains(err.Error(), "message") || strings.Contains(err.Error(), "required"),
"error should mention the required --message flag: %v", err)
}
+7 -1
View File
@@ -78,8 +78,14 @@ Pass --full to also load the chat history (LoadMessages SDK call). Use
},
}
cmd.Flags().BoolVar(&opts.Full, "full", false, "Also load chat history via LoadMessages")
cmd.Flags().IntVar(&opts.Limit, "limit", defaultFullLimit, "Max messages to load when --full is set (1..1000)")
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", defaultFullLimit, "Max messages to load when --full is set (1..1000)")
cmdutil.AddFormatFlag(cmd, sessionViewFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "fetch one chat session by id; --full also loads its message history",
RequiredFlags: []string{"<session-id> (positional)"},
Examples: []string{"weknora session view sess_abc", "weknora session view sess_abc --full --limit 50"},
Output: "envelope.data is the session object; with --full it also carries the loaded messages",
})
return cmd
}