feat(cli): agent-first WeKnora CLI
The `weknora` command-line client for the WeKnora RAG server. Full command surface: kb / doc / chunk / session / message / agent / model / search / chat / auth / profile / link / api / mcp / skills / config / doctor / schema / exit-codes. Agent-first wire contract: JSON envelope by default, typed error codes mapped to stable exit codes, error.retry_argv / retryable / partial-failure status, global --dry-run preview, the exit-10 confirmation protocol for writes, and control/ANSI/Bidi input hygiene. Stateless env-credential auth (WEKNORA_API_KEY / WEKNORA_TOKEN + WEKNORA_HOST) for headless/CI/agent use. A curated read-only MCP tool surface (`mcp serve`) and embedded Agent Skills (`skills install`). Extensive unit + contract-golden tests and CI.
This commit is contained in:
@@ -98,7 +98,7 @@ both flags for the complete projected stream.`,
|
||||
cmdutil.AddFormatFlag(cmd, sessionAskFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "Invoke a custom agent in a session context. Default JSON returns a bounded answer-event projection. --reference adds indexed citations; --verbose adds reasoning, tools, and lifecycle events. --format ndjson streams raw SDK agent events; --format text renders the selected events live.",
|
||||
RequiredFlags: []string{"--agent"},
|
||||
RequiredFlags: []string{"<text> (positional)", "--agent"},
|
||||
Examples: []string{
|
||||
`weknora session ask --agent ag_x "Summarize Q3 sales"`,
|
||||
`weknora session ask --agent ag_x "Summarize Q3 sales" --jq '[.data.events[].content] | join("")'`,
|
||||
|
||||
@@ -23,12 +23,14 @@ package sessioncmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
"github.com/Tencent/WeKnora/cli/internal/sse"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
@@ -113,7 +115,7 @@ silently treated as NDJSON.`,
|
||||
cmdutil.AddFormatFlag(cmd, continueStreamFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "Resume an SSE event stream for an in-progress or completed assistant message. Produces an NDJSON event stream: init line (session_id, message_id) then raw SDK StreamResponse events.",
|
||||
RequiredFlags: []string{"--message (message_id from prior init / agent_query event)"},
|
||||
RequiredFlags: []string{"<session-id> (positional)", "--message (message_id from prior init / agent_query event)"},
|
||||
Examples: []string{
|
||||
"weknora session continue-stream sess_xyz --message msg_abc --format json",
|
||||
"# Network-blip recovery: replay with same session_id + message_id from the original 'session ask' init event",
|
||||
@@ -163,10 +165,40 @@ func runContinueStream(ctx context.Context, opts *ContinueStreamOptions, _ *cmdu
|
||||
// 2. Open the SDK replay stream and pass each event through as a bare
|
||||
// NDJSON line. The SDK's StreamResponse is the source of truth for
|
||||
// the event vocabulary; the CLI does not reshape it.
|
||||
var streamErrMsg string
|
||||
cb := func(r *sdk.StreamResponse) error {
|
||||
return output.EmitSDKEvent(w, r)
|
||||
isErr := r != nil && r.ResponseType == sdk.ResponseTypeError
|
||||
if isErr && streamErrMsg == "" {
|
||||
if r.Content != "" {
|
||||
streamErrMsg = r.Content
|
||||
} else if r.Data != nil {
|
||||
if e, ok := r.Data["error"].(string); ok {
|
||||
streamErrMsg = e
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := output.EmitSDKEvent(w, r); err != nil {
|
||||
return err
|
||||
}
|
||||
// Stop once the error frame is emitted rather than blocking on the SDK
|
||||
// read until the ~30s transport timeout (the server holds the stream
|
||||
// open after the error). streamErrMsg carries the real reason.
|
||||
if isErr {
|
||||
return sse.ErrTerminate
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := svc.ContinueStream(ctx, opts.SessionID, opts.MessageID, cb); err != nil {
|
||||
err := svc.ContinueStream(ctx, opts.SessionID, opts.MessageID, cb)
|
||||
if errors.Is(err, sse.ErrTerminate) {
|
||||
err = nil
|
||||
}
|
||||
// A server-delivered error frame is the authoritative failure reason —
|
||||
// surface it as operation.failed (exit 1) instead of the transport timeout
|
||||
// the server's stream-close triggers afterwards. Mirrors chat / session ask.
|
||||
if streamErrMsg != "" {
|
||||
return cmdutil.NewError(cmdutil.CodeOperationFailed, "continue stream failed: "+streamErrMsg)
|
||||
}
|
||||
if err != nil {
|
||||
// Ctrl-C / SIGTERM lineage (operator gave up on the resume).
|
||||
if cmdutil.IsCancelled(ctx, err) {
|
||||
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "session continue-stream cancelled")
|
||||
|
||||
@@ -3,7 +3,6 @@ package sessioncmd
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
@@ -84,7 +83,9 @@ 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(), "delete", "session", len(args), "session.delete", "weknora session delete "+strings.Join(args, " ")+" -y"); err != nil {
|
||||
batchRetry := append([]string{"weknora", "session", "delete"}, args...)
|
||||
batchRetry = append(batchRetry, "-y")
|
||||
if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "session", len(args), "session.delete", batchRetry); err != nil {
|
||||
return err
|
||||
}
|
||||
outcomes, runErr := cmdutil.RunBatch(c.Context(), args, func(ctx context.Context, id string) error {
|
||||
@@ -115,6 +116,7 @@ without the user's explicit go-ahead.`,
|
||||
"weknora session delete s_a s_b s_c -y",
|
||||
"weknora session delete s_abc -y --format json",
|
||||
},
|
||||
Output: "envelope.data shape depends on the form: a single session id -> {id, deleted:true}; multiple ids -> batch envelope (top-level status success|partial|error, ok=(failures==0), data per-item [{id, ok, error?}], meta.successes/failures — read data[].ok per id).",
|
||||
Warnings: []string{
|
||||
"Requires explicit user approval (exit 10 / input.confirmation_required); never auto-add -y.",
|
||||
"session delete is irreversible; loses the conversation + all messages + tool call history.",
|
||||
@@ -124,7 +126,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(), "delete", "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", []string{"weknora", "session", "delete", id, "-y"}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -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(), "delete", "session", 2, "session.delete", "")
|
||||
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, fopts.WantsJSON(), "delete", "session", 2, "session.delete", nil)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
||||
+24
-5
@@ -57,6 +57,12 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
// Validate static input before building the client so a bad
|
||||
// --page-size/--limit returns input.invalid_argument (exit 5), not
|
||||
// an auth error (exit 3).
|
||||
if err := validateListOpts(opts); err != nil {
|
||||
return err
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -65,19 +71,22 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
},
|
||||
}
|
||||
cmd.Flags().IntVar(&opts.PageSize, "page-size", defaultPageSize, "Items per server batch (1..1000)")
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (1..10000)")
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return — client-side cap; meta.has_more/total_count report the full size (1..10000)")
|
||||
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",
|
||||
Output: "envelope.data is an array of Session objects with id, title, updated_at; meta.count is the total returned; meta.total_count is the server-side total before --since filtering",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOptions, svc ListService) error {
|
||||
// validateListOpts checks --page-size / --limit. Called from RunE before the
|
||||
// client is built (so a bad value surfaces as exit 5, not an auth error) and at
|
||||
// runList's top for direct callers; idempotent.
|
||||
func validateListOpts(opts *ListOptions) error {
|
||||
if opts.PageSize < 1 || opts.PageSize > maxPageSize {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
@@ -90,6 +99,13 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
||||
Message: fmt.Sprintf("--limit must be in 1..10000, got %d", opts.Limit),
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOptions, svc ListService) error {
|
||||
if err := validateListOpts(opts); err != nil {
|
||||
return err
|
||||
}
|
||||
var since time.Duration
|
||||
if opts.Since != "" {
|
||||
d, err := parseSinceDuration(opts.Since)
|
||||
@@ -100,6 +116,7 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
||||
}
|
||||
|
||||
var items []sdk.Session
|
||||
var serverTotal int
|
||||
if opts.AllPages {
|
||||
accum := make([]sdk.Session, 0)
|
||||
for page := 1; ; page++ {
|
||||
@@ -107,6 +124,7 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "list sessions")
|
||||
}
|
||||
serverTotal = total
|
||||
accum = append(accum, chunk...)
|
||||
if opts.Limit > 0 && len(accum) >= opts.Limit {
|
||||
accum = accum[:opts.Limit]
|
||||
@@ -118,10 +136,11 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
||||
}
|
||||
items = accum
|
||||
} else {
|
||||
chunk, _, err := svc.GetSessionsByTenant(ctx, 1, opts.PageSize)
|
||||
chunk, total, err := svc.GetSessionsByTenant(ctx, 1, opts.PageSize)
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "list sessions")
|
||||
}
|
||||
serverTotal = total
|
||||
items = chunk
|
||||
}
|
||||
if items == nil {
|
||||
@@ -149,7 +168,7 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
||||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
meta := &output.Meta{Count: len(items), HasMore: truncated}
|
||||
meta := &output.Meta{Count: output.IntPtr(len(items)), HasMore: truncated, TotalCount: output.IntPtr(serverTotal)}
|
||||
return fopts.Emit(iostreams.IO.Out, items, meta)
|
||||
}
|
||||
|
||||
|
||||
@@ -271,3 +271,45 @@ func TestList_AllPages_WithLimit_StopsAtLimit(t *testing.T) {
|
||||
assert.Equal(t, 50, got)
|
||||
assert.LessOrEqual(t, len(svc.calls), 3, "must not fetch beyond what fills --limit")
|
||||
}
|
||||
|
||||
// TestList_JSON_TotalCount_SinglePage asserts that meta.total_count is populated
|
||||
// from the server total when doing a single-page fetch.
|
||||
func TestList_JSON_TotalCount_SinglePage(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeListService{
|
||||
items: []sdk.Session{{ID: "s_1", Title: "T1", UpdatedAt: "2026-05-12T14:00:00Z"}},
|
||||
total: 42,
|
||||
}
|
||||
require.NoError(t, runList(context.Background(),
|
||||
&ListOptions{PageSize: 10, Limit: 30},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
body := out.String()
|
||||
assert.Contains(t, body, `"total_count":42`, "single-page fetch must surface server total in meta.total_count")
|
||||
}
|
||||
|
||||
// TestList_JSON_TotalCount_AllPages asserts meta.total_count is populated
|
||||
// from the server total when walking all pages.
|
||||
func TestList_JSON_TotalCount_AllPages(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &pagedSessionSvc{all: makeSessions(45)}
|
||||
require.NoError(t, runList(context.Background(),
|
||||
&ListOptions{PageSize: 20, AllPages: true, Limit: 10000},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
body := out.String()
|
||||
assert.Contains(t, body, `"total_count":45`, "--all-pages fetch must surface server total in meta.total_count")
|
||||
}
|
||||
|
||||
// TestList_JSON_TotalCount_Zero_Present asserts that when server returns total=0
|
||||
// on an empty list, meta.total_count (and meta.count) still serialize as 0. The
|
||||
// *int + omitempty pattern omits only nil, so the agent contract stays stable:
|
||||
// an empty result reports 0, not a missing key.
|
||||
func TestList_JSON_TotalCount_Zero_Present(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeListService{items: nil, total: 0}
|
||||
require.NoError(t, runList(context.Background(),
|
||||
&ListOptions{PageSize: 30, Limit: 30},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
body := out.String()
|
||||
assert.Contains(t, body, `"total_count":0`, "zero server total must serialize as 0 on empty list")
|
||||
assert.Contains(t, body, `"count":0`, "empty list must report count:0, not omit it")
|
||||
}
|
||||
|
||||
@@ -24,5 +24,6 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd.AddCommand(NewCmdAsk(f))
|
||||
cmd.AddCommand(NewCmdContinueStream(f))
|
||||
cmd.AddCommand(NewCmdStop(f))
|
||||
cmd.AddCommand(NewCmdToolApproval(f))
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ Symmetric with 'session continue-stream': both key on (session_id, message_id).`
|
||||
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)"},
|
||||
RequiredFlags: []string{"<session-id> (positional)", "--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}",
|
||||
})
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
package sessioncmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
var resolveFields = []string{"pending_id", "decision", "resolved"}
|
||||
|
||||
// decision values sent to the server and surfaced in the result/dry-run JSON.
|
||||
const (
|
||||
decisionApprove = "approve"
|
||||
decisionReject = "reject"
|
||||
)
|
||||
|
||||
// ResolveOptions holds the parsed flags and positional argument for
|
||||
// `session tool-approval resolve`.
|
||||
type ResolveOptions struct {
|
||||
PendingID string
|
||||
Reject bool
|
||||
Reason string
|
||||
ModifiedArgs string
|
||||
Yes bool
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// ResolveService is the narrow SDK surface this command depends on.
|
||||
type ResolveService interface {
|
||||
ResolveToolApproval(ctx context.Context, pendingID string, req *sdk.ResolveToolApprovalRequest) error
|
||||
}
|
||||
|
||||
type resolveResult struct {
|
||||
PendingID string `json:"pending_id"`
|
||||
Decision string `json:"decision"`
|
||||
Resolved bool `json:"resolved"`
|
||||
}
|
||||
|
||||
const resolveLong = `Resolve a pending tool approval raised during an agent run.
|
||||
|
||||
When a server-side agent run (weknora session ask) needs to call a tool
|
||||
that requires approval, the stream emits a tool-approval event carrying a
|
||||
pending id and the run blocks. This command unblocks it: approve (default)
|
||||
lets the tool call execute, --reject cancels it. After resolving, resume
|
||||
the answer with weknora session continue-stream.
|
||||
|
||||
--modified-args replaces the tool call arguments on approve (JSON object).
|
||||
It conflicts with --reject (rejected calls never execute).
|
||||
|
||||
AI agents: approving a tool call is the human-approval step itself — that
|
||||
is exactly what the exit-10 protocol guards. Without -y/--yes the CLI
|
||||
exits 10 and writes input.confirmation_required to stderr. Surface the
|
||||
pending tool call to the user and only pass -y after their explicit
|
||||
go-ahead.`
|
||||
|
||||
// NewCmdToolApproval builds the `session tool-approval` subtree.
|
||||
func NewCmdToolApproval(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "tool-approval",
|
||||
Short: "Resolve pending tool approvals from agent runs",
|
||||
}
|
||||
cmd.AddCommand(newCmdResolve(f))
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newCmdResolve(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &ResolveOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "resolve <pending-id>",
|
||||
Short: "Approve or reject a pending tool call (high-risk write)",
|
||||
Long: resolveLong,
|
||||
Example: ` weknora session tool-approval resolve pend_abc -y # approve
|
||||
weknora session tool-approval resolve pend_abc --reject --reason "wrong target" -y
|
||||
weknora session tool-approval resolve pend_abc -y --format json`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
opts.PendingID = args[0]
|
||||
opts.Yes, _ = c.Flags().GetBool("yes")
|
||||
// Validate inputs BEFORE the dry-run gate so --dry-run previews a
|
||||
// valid action — an invalid --modified-args (e.g. "{}") must error
|
||||
// the same way whether or not --dry-run is passed.
|
||||
if _, err := validateModifiedArgs(opts); err != nil {
|
||||
return err
|
||||
}
|
||||
dryRunArgs := map[string]any{
|
||||
"pending_id": opts.PendingID,
|
||||
"decision": decisionOf(opts.Reject),
|
||||
"reason": opts.Reason,
|
||||
}
|
||||
if opts.ModifiedArgs != "" {
|
||||
dryRunArgs["modified_args"] = opts.ModifiedArgs
|
||||
}
|
||||
if handled, err := cmdutil.HandleDryRun(c, opts.DryRun, cmdutil.DryRunPlan{
|
||||
Action: "session.tool_approval.resolve",
|
||||
Args: dryRunArgs,
|
||||
}); handled {
|
||||
return err
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runResolve(c.Context(), opts, fopts, cli, f.Prompter())
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&opts.Reject, "reject", false, "Reject the pending tool call instead of approving")
|
||||
cmd.Flags().StringVar(&opts.Reason, "reason", "", "Reason recorded with the decision")
|
||||
cmd.Flags().StringVar(&opts.ModifiedArgs, "modified-args", "", "Replace tool call arguments on approve (JSON object; conflicts with --reject)")
|
||||
cmdutil.AddFormatFlag(cmd, resolveFields...)
|
||||
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
|
||||
cmdutil.SetRisk(cmd, "session.tool_approval.resolve")
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "approve or reject a pending tool call from an agent run; then resume with session continue-stream",
|
||||
RequiredFlags: []string{"<pending-id> (positional)"},
|
||||
Examples: []string{
|
||||
"weknora session tool-approval resolve pend_abc -y",
|
||||
"weknora session tool-approval resolve pend_abc --reject -y",
|
||||
},
|
||||
Output: "envelope.data is {pending_id, decision (approve|reject), resolved:true}",
|
||||
Warnings: []string{
|
||||
"Requires explicit user approval (exit 10 / input.confirmation_required); never auto-add -y.",
|
||||
"Approving executes the blocked tool call with the user's authority — show the user what tool/args are pending before resolving.",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func decisionOf(reject bool) string {
|
||||
if reject {
|
||||
return decisionReject
|
||||
}
|
||||
return decisionApprove
|
||||
}
|
||||
|
||||
// decisionPastTense returns the past tense of the decision verb for human output.
|
||||
func decisionPastTense(decision string) string {
|
||||
switch decision {
|
||||
case decisionReject:
|
||||
return "Rejected"
|
||||
default: // decisionApprove
|
||||
return "Approved"
|
||||
}
|
||||
}
|
||||
|
||||
// retryArgOf returns the extra --reject flag element to include in the retry
|
||||
// argv when the decision is reject; nil otherwise.
|
||||
func retryArgOf(reject bool) []string {
|
||||
if reject {
|
||||
return []string{"--reject"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateModifiedArgs checks the --reject/--modified-args invariants and
|
||||
// returns the validated raw JSON (nil when --modified-args is unset). Shared
|
||||
// by the RunE pre-dry-run gate and runResolve so both paths reject the same
|
||||
// inputs identically.
|
||||
func validateModifiedArgs(opts *ResolveOptions) (json.RawMessage, error) {
|
||||
if opts.Reject && opts.ModifiedArgs != "" {
|
||||
return nil, &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
Message: "--modified-args conflicts with --reject (rejected calls never execute)",
|
||||
}
|
||||
}
|
||||
if opts.ModifiedArgs == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var probe map[string]any
|
||||
if err := json.Unmarshal([]byte(opts.ModifiedArgs), &probe); err != nil || probe == nil {
|
||||
return nil, &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
Message: "--modified-args must be a non-null JSON object",
|
||||
}
|
||||
}
|
||||
if len(probe) == 0 {
|
||||
return nil, &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
Message: "--modified-args must not be an empty object (it would wipe the original tool arguments); omit the flag to keep them",
|
||||
}
|
||||
}
|
||||
return json.RawMessage(opts.ModifiedArgs), nil
|
||||
}
|
||||
|
||||
func runResolve(ctx context.Context, opts *ResolveOptions, fopts *cmdutil.FormatOptions, svc ResolveService, p prompt.Prompter) error {
|
||||
modified, err := validateModifiedArgs(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
decision := decisionOf(opts.Reject)
|
||||
retryCmd := append([]string{"weknora", "session", "tool-approval", "resolve", opts.PendingID}, retryArgOf(opts.Reject)...)
|
||||
retryCmd = append(retryCmd, "-y")
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), decision, "tool call", opts.PendingID, "session.tool_approval.resolve", retryCmd); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := svc.ResolveToolApproval(ctx, opts.PendingID, &sdk.ResolveToolApprovalRequest{
|
||||
Decision: decision,
|
||||
Reason: opts.Reason,
|
||||
ModifiedArgs: modified,
|
||||
}); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "resolve tool approval %s", opts.PendingID)
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, resolveResult{PendingID: opts.PendingID, Decision: decision, Resolved: true}, nil)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ %s tool call %s\n", decisionPastTense(decision), opts.PendingID)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package sessioncmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"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"
|
||||
"github.com/Tencent/WeKnora/cli/internal/testutil"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
type fakeResolveSvc struct {
|
||||
err error
|
||||
gotPendingID string
|
||||
gotReq *sdk.ResolveToolApprovalRequest
|
||||
}
|
||||
|
||||
func (s *fakeResolveSvc) ResolveToolApproval(_ context.Context, pendingID string, req *sdk.ResolveToolApprovalRequest) error {
|
||||
s.gotPendingID, s.gotReq = pendingID, req
|
||||
return s.err
|
||||
}
|
||||
|
||||
func TestRunResolve_ApproveWithYes(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeResolveSvc{}
|
||||
opts := &ResolveOptions{PendingID: "p1", Yes: true}
|
||||
require.NoError(t, runResolve(context.Background(), opts, jsonOpts(), svc, &testutil.ConfirmPrompter{}))
|
||||
assert.Equal(t, "p1", svc.gotPendingID)
|
||||
assert.Equal(t, "approve", svc.gotReq.Decision)
|
||||
assert.Contains(t, out.String(), `"decision":"approve"`)
|
||||
}
|
||||
|
||||
func TestRunResolve_ApproveWithYes_ConfirmationRequiredCode(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeResolveSvc{}
|
||||
// Verify the "no-yes" path yields CodeInputConfirmationRequired.
|
||||
err := runResolve(context.Background(), &ResolveOptions{PendingID: "p1", Yes: false}, jsonOpts(), svc, &testutil.ConfirmPrompter{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, typed.Code)
|
||||
assert.Empty(t, svc.gotPendingID, "SDK must not be called without confirmation")
|
||||
}
|
||||
|
||||
func TestRunResolve_RejectWithReason(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeResolveSvc{}
|
||||
opts := &ResolveOptions{PendingID: "p1", Reject: true, Reason: "wrong target", Yes: true}
|
||||
require.NoError(t, runResolve(context.Background(), opts, jsonOpts(), svc, &testutil.ConfirmPrompter{}))
|
||||
assert.Equal(t, "reject", svc.gotReq.Decision)
|
||||
assert.Equal(t, "wrong target", svc.gotReq.Reason)
|
||||
}
|
||||
|
||||
func TestRunResolve_NoYesIsConfirmationRequired(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeResolveSvc{}
|
||||
err := runResolve(context.Background(), &ResolveOptions{PendingID: "p1"}, jsonOpts(), svc, &testutil.ConfirmPrompter{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, typed.Code)
|
||||
assert.Empty(t, svc.gotPendingID, "SDK must not be called without confirmation")
|
||||
}
|
||||
|
||||
func TestRunResolve_ModifiedArgsMustBeJSONObject(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runResolve(context.Background(), &ResolveOptions{PendingID: "p1", ModifiedArgs: `["not","an","object"]`, Yes: true}, jsonOpts(), &fakeResolveSvc{}, &testutil.ConfirmPrompter{})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "JSON object")
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
|
||||
}
|
||||
|
||||
func TestRunResolve_RejectAndModifiedArgsConflict(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runResolve(context.Background(), &ResolveOptions{PendingID: "p1", Reject: true, ModifiedArgs: `{"a":1}`, Yes: true}, jsonOpts(), &fakeResolveSvc{}, &testutil.ConfirmPrompter{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
|
||||
}
|
||||
|
||||
// TestRunResolve_TTY_ConfirmYes verifies that on a TTY with Answer=true the SDK is called.
|
||||
func TestRunResolve_TTY_ConfirmYes(t *testing.T) {
|
||||
out, _ := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeResolveSvc{}
|
||||
p := &testutil.ConfirmPrompter{Answer: true}
|
||||
require.NoError(t, runResolve(context.Background(), &ResolveOptions{PendingID: "p1"}, textOpts(), svc, p))
|
||||
assert.True(t, p.Asked)
|
||||
assert.Equal(t, "p1", svc.gotPendingID)
|
||||
assert.Contains(t, out.String(), "Approved")
|
||||
}
|
||||
|
||||
// TestRunResolve_TTY_ConfirmNo verifies that on a TTY with Answer=false the SDK is NOT called.
|
||||
func TestRunResolve_TTY_ConfirmNo(t *testing.T) {
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeResolveSvc{}
|
||||
p := &testutil.ConfirmPrompter{Answer: false}
|
||||
err := runResolve(context.Background(), &ResolveOptions{PendingID: "p1"}, textOpts(), svc, p)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeUserAborted, typed.Code)
|
||||
assert.Empty(t, svc.gotPendingID, "answer=false must not call SDK")
|
||||
assert.Contains(t, errBuf.String(), "Aborted")
|
||||
}
|
||||
|
||||
// TestRunResolve_ServiceError_Propagates verifies that SDK errors are wrapped and propagated.
|
||||
func TestRunResolve_ServiceError_Propagates(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeResolveSvc{err: errors.New("HTTP error 404: not found")}
|
||||
err := runResolve(context.Background(), &ResolveOptions{PendingID: "p1", Yes: true}, jsonOpts(), svc, &testutil.ConfirmPrompter{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code)
|
||||
}
|
||||
|
||||
// TestRunResolve_ModifiedArgs_LegalObject verifies that a valid JSON object is passed through to the SDK.
|
||||
func TestRunResolve_ModifiedArgs_LegalObject(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeResolveSvc{}
|
||||
opts := &ResolveOptions{PendingID: "p1", ModifiedArgs: `{"key":"val"}`, Yes: true}
|
||||
require.NoError(t, runResolve(context.Background(), opts, jsonOpts(), svc, &testutil.ConfirmPrompter{}))
|
||||
require.NotNil(t, svc.gotReq.ModifiedArgs)
|
||||
var m map[string]any
|
||||
require.NoError(t, json.Unmarshal(svc.gotReq.ModifiedArgs, &m))
|
||||
assert.Equal(t, "val", m["key"])
|
||||
}
|
||||
|
||||
// TestRunResolve_ModifiedArgsEmptyObjectRejected verifies that {} is rejected before the SDK is called,
|
||||
// because an empty object would silently wipe the original tool arguments (downstream executor uses len>0 to decide replacement).
|
||||
func TestRunResolve_ModifiedArgsEmptyObjectRejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeResolveSvc{}
|
||||
opts := &ResolveOptions{PendingID: "p1", ModifiedArgs: `{}`, Yes: true}
|
||||
err := runResolve(context.Background(), opts, jsonOpts(), svc, &testutil.ConfirmPrompter{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
|
||||
assert.Contains(t, typed.Message, "empty object")
|
||||
assert.Empty(t, svc.gotPendingID, "SDK must not be called when --modified-args is an empty object")
|
||||
}
|
||||
|
||||
// TestValidateModifiedArgs covers the shared input validator that now runs
|
||||
// before the dry-run gate (so --dry-run --modified-args '{}' errors instead
|
||||
// of previewing an arg-wiping action). Each case mirrors a runResolve guard.
|
||||
func TestValidateModifiedArgs(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
opts *ResolveOptions
|
||||
wantErr string // substring; "" means expect success
|
||||
}{
|
||||
{"unset is ok", &ResolveOptions{}, ""},
|
||||
{"valid object", &ResolveOptions{ModifiedArgs: `{"path":"/x"}`}, ""},
|
||||
{"empty object rejected", &ResolveOptions{ModifiedArgs: `{}`}, "empty object"},
|
||||
{"array rejected", &ResolveOptions{ModifiedArgs: `[1,2]`}, "non-null JSON object"},
|
||||
{"null rejected", &ResolveOptions{ModifiedArgs: `null`}, "non-null JSON object"},
|
||||
{"reject+modified conflict", &ResolveOptions{Reject: true, ModifiedArgs: `{"a":1}`}, "conflicts with --reject"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, err := validateModifiedArgs(tc.opts)
|
||||
if tc.wantErr == "" {
|
||||
require.NoError(t, err)
|
||||
return
|
||||
}
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
|
||||
assert.Contains(t, typed.Message, tc.wantErr)
|
||||
assert.Nil(t, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
+16
-1
@@ -70,6 +70,11 @@ Pass --full to also load the chat history (LoadMessages SDK call). Use
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
// Validate static input before building the client so a bad --limit
|
||||
// returns input.invalid_argument (exit 5), not an auth error (exit 3).
|
||||
if err := validateViewOpts(opts); err != nil {
|
||||
return err
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -89,7 +94,10 @@ Pass --full to also load the chat history (LoadMessages SDK call). Use
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOptions, svc ViewService, id string) error {
|
||||
// validateViewOpts checks the --limit/--full invariants. Called from RunE
|
||||
// before the client is built (so a bad value surfaces as exit 5, not an auth
|
||||
// error) and at runView's top for direct callers; idempotent.
|
||||
func validateViewOpts(opts *ViewOptions) error {
|
||||
if !opts.Full && opts.LimitSet {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
@@ -104,6 +112,13 @@ func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOption
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOptions, svc ViewService, id string) error {
|
||||
if err := validateViewOpts(opts); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s, err := svc.GetSession(ctx, id)
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user