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
+6
View File
@@ -68,6 +68,12 @@ the agent's downstream dependencies are all reachable.`,
},
}
cmdutil.AddFormatFlag(cmd, agentCheckFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "verify a custom agent end-to-end: status plus kb_scope reachability",
RequiredFlags: []string{"<agent-id> (positional)"},
Examples: []string{"weknora agent check agent_abc"},
Output: "envelope.data is {id, reachable, ...} with kb_scope reachability folded in",
})
return cmd
}
+12 -7
View File
@@ -59,7 +59,7 @@ type createFlagSet struct {
}
const agentCreateExample = ` weknora agent create "Support Bot" --model <model-id>
weknora agent create "Code Reviewer" --model <model-id> --system-prompt-file ./prompt.md --kb kb_eng --kb kb_arch
weknora agent create "Code Reviewer" --model <model-id> --system-prompt-file ./prompt.md --attach-kb kb_eng --attach-kb kb_arch
weknora agent create "From Template" --model <model-id> --from ag_existing
weknora agent create --generate-skeleton > my-agent.yaml
weknora agent create "Tuned" --model <model-id> --config-file ./my-agent.yaml`
@@ -76,7 +76,7 @@ Precedence when both a config file and hot-path flags are supplied:
hot-path flag > config-file value > server default
--from <id> copies an existing agent (SDK CopyAgent) then applies any
hot-path overrides via UpdateAgent. --kb on --from REPLACES the copied
hot-path overrides via UpdateAgent. --attach-kb on --from REPLACES the copied
agent's KB list (not merge) — matches surgical-flag semantics.
AI agents: writes a new resource server-side. Failure surfaces as a
@@ -112,7 +112,7 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
opts.flags.rerankModelSet = cmd.Flags().Changed("rerank-model")
opts.flags.temperatureSet = cmd.Flags().Changed("temperature")
opts.flags.kbSelectionModeSet = cmd.Flags().Changed("kb-selection-mode")
opts.flags.kbsSet = cmd.Flags().Changed("kb")
opts.flags.kbsSet = cmd.Flags().Changed("attach-kb")
// --temperature is bounded 0.0..2.0. Reject out-of-range
// early with a typed input.invalid_argument so users don't
@@ -174,7 +174,7 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
cmd.Flags().StringVar(&systemPromptFile, "system-prompt-file", "", "Read system prompt from FILE, or '-' for stdin")
cmd.MarkFlagsMutuallyExclusive("system-prompt", "system-prompt-file")
cmd.Flags().StringVar(&opts.AgentMode, "agent-mode", "", "Agent operating mode: quick-answer | smart-reasoning")
cmd.Flags().StringSliceVar(&opts.KBs, "kb", nil, "Attach knowledge base id (repeatable)")
cmd.Flags().StringSliceVar(&opts.KBs, "attach-kb", nil, "Attach a knowledge base id (repeatable); aligns with 'agent edit --add-kb'")
cmd.Flags().StringVar(&opts.KBSelectionMode, "kb-selection-mode", "", "KB selection mode: all | selected | none")
cmd.Flags().StringVar(&opts.RerankModel, "rerank-model", "", "Rerank model id")
cmd.Flags().Float64Var(&opts.Temperature, "temperature", 0.0, "Generation temperature (0.0..2.0)")
@@ -186,6 +186,11 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
cmdutil.AddFormatFlag(cmd, agentViewFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Create a new custom agent. --model is required; --attach-kb takes KB ids (repeatable, not names). Emits the created Agent object.",
RequiredFlags: []string{"<name> (positional)", "--model"},
Output: "envelope.data is the created Agent object with id, name, config",
})
return cmd
}
@@ -230,7 +235,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOp
base = *copied.Config
}
// --kb on --from REPLACES the copied KB list; when --kb
// --attach-kb on --from REPLACES the copied KB list; when --attach-kb
// is not set, KnowledgeBasesSet stays false inside applyCreateOverrides
// and the copy's KB list passes through unchanged.
cfg := applyCreateOverrides(&base, opts)
@@ -266,7 +271,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOp
}
// applyCreateOverrides merges hot-path flag overrides into the base config,
// then applies the "--kb implies --kb-selection-mode=selected" fallback.
// then applies the "--attach-kb implies --kb-selection-mode=selected" fallback.
// Shared by the --from path (base=copied agent's config) and the plain
// create path (base=zero or --config-file). Keeping both paths on one
// helper prevents silent divergence when future flags are added.
@@ -282,7 +287,7 @@ func applyCreateOverrides(base *sdk.AgentConfig, opts *CreateOptions) *sdk.Agent
}
cfg := cmdutil.MergeAgentConfig(base, overrides)
// --kb without explicit --kb-selection-mode implies "selected".
// --attach-kb without explicit --kb-selection-mode implies "selected".
if opts.flags.kbsSet && !opts.flags.kbSelectionModeSet && cfg.KBSelectionMode == "" {
cfg.KBSelectionMode = "selected"
}
+23 -6
View File
@@ -132,7 +132,7 @@ func TestCreate_RepeatedKB_ImpliesSelectedMode(t *testing.T) {
}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.Equal(t, []string{"kb_a", "kb_b"}, svc.createReq.Config.KnowledgeBases)
assert.Equal(t, "selected", svc.createReq.Config.KBSelectionMode, "passing --kb implies selected mode")
assert.Equal(t, "selected", svc.createReq.Config.KBSelectionMode, "passing --attach-kb implies selected mode")
}
func TestCreate_SystemPromptFile_ReaderRead(t *testing.T) {
@@ -176,14 +176,14 @@ func TestCreate_From_PreservesSourceFieldsNotOverridden(t *testing.T) {
require.NotNil(t, svc.updateReq.Config)
assert.Equal(t, "Source prompt", svc.updateReq.Config.SystemPrompt, "source SystemPrompt must round-trip")
assert.Equal(t, "smart-reasoning", svc.updateReq.Config.AgentMode, "source AgentMode must round-trip")
assert.Equal(t, []string{"kb_src_a", "kb_src_b"}, svc.updateReq.Config.KnowledgeBases, "source KB list must round-trip when --kb not passed")
assert.Equal(t, []string{"kb_src_a", "kb_src_b"}, svc.updateReq.Config.KnowledgeBases, "source KB list must round-trip when --attach-kb not passed")
assert.InDelta(t, 0.9, svc.updateReq.Config.Temperature, 0.001, "Temperature overridden")
}
func TestCreate_From_KBReplacesSourceList(t *testing.T) {
// --kb on --from REPLACES the copied agent's KB list (instead of
// --attach-kb on --from REPLACES the copied agent's KB list (instead of
// merging with it). The override semantic matches a from-scratch
// `agent create --kb a --kb b`: whatever was on the source agent is
// `agent create --attach-kb a --attach-kb b`: whatever was on the source agent is
// discarded for KBs the caller explicitly listed.
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{
@@ -200,8 +200,8 @@ func TestCreate_From_KBReplacesSourceList(t *testing.T) {
}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
require.NotNil(t, svc.updateReq.Config)
assert.Equal(t, []string{"kb_new"}, svc.updateReq.Config.KnowledgeBases, "--kb replaces source KB list")
assert.Equal(t, "selected", svc.updateReq.Config.KBSelectionMode, "--kb on --from implies selected mode")
assert.Equal(t, []string{"kb_new"}, svc.updateReq.Config.KnowledgeBases, "--attach-kb replaces source KB list")
assert.Equal(t, "selected", svc.updateReq.Config.KBSelectionMode, "--attach-kb on --from implies selected mode")
}
func TestCreate_Temperature_Bounds(t *testing.T) {
@@ -235,3 +235,20 @@ var errBadHTTP404 = &simpleErr{msg: "HTTP error 404: not found"}
type simpleErr struct{ msg string }
func (e *simpleErr) Error() string { return e.msg }
// ---------------------------------------------------------------------------
// --attach-kb (renamed from --kb)
// ---------------------------------------------------------------------------
// TestCreate_AttachKBFlagExists asserts that `--attach-kb` is a registered flag
// on `agent create` and that the old `--kb` flag no longer exists.
func TestCreate_AttachKBFlagExists(t *testing.T) {
cmd := NewCmdCreate(nil)
// --attach-kb must exist
f := cmd.Flags().Lookup("attach-kb")
require.NotNil(t, f, "--attach-kb flag must be registered on 'agent create'")
// bare --kb must NOT exist (renamed)
old := cmd.Flags().Lookup("kb")
assert.Nil(t, old, "old --kb flag must not exist on 'agent create' (renamed to --attach-kb)")
}
+1 -1
View File
@@ -106,7 +106,7 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
}
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "agent", opts.AgentID, "agent.delete", "weknora agent delete "+opts.AgentID+" -y"); err != nil {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "agent", opts.AgentID, "agent.delete", "weknora agent delete "+opts.AgentID+" -y"); err != nil {
return err
}
if err := svc.DeleteAgent(ctx, opts.AgentID); err != nil {
+1 -1
View File
@@ -209,7 +209,7 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
yes, _ := cmd.Flags().GetBool("yes")
// Build the retry command from the flags the user actually passed.
retryCmd := buildAgentEditRetryCmd(cmd, opts.AgentID)
if err := cmdutil.ConfirmDestructive(f.Prompter(), yes, fopts.WantsJSON(), "agent", opts.AgentID, "agent.edit", retryCmd); err != nil {
if err := cmdutil.ConfirmDestructive(f.Prompter(), yes, fopts.WantsJSON(), "edit", "agent", opts.AgentID, "agent.edit", retryCmd); err != nil {
return err
}
cli, err := f.Client()
+5
View File
@@ -60,6 +60,11 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
}
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (1..10000)")
cmdutil.AddFormatFlag(cmd, agentListFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "List custom agents visible to the active tenant. The SDK returns all agents in one call (no server-side pagination); meta.count reflects the full tenant set, --limit caps client-side.",
Examples: []string{"weknora agent list --format json", "weknora agent list --limit 10 --format json"},
Output: "envelope.data is an array of Agent objects with id, name, is_builtin; meta.count is the total returned",
})
return cmd
}
+6
View File
@@ -65,6 +65,12 @@ For downstream KB reachability verification use 'weknora agent check <id>'
},
}
cmdutil.AddFormatFlag(cmd, agentStatusFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "shallow health probe of a custom agent: reachability without kb_scope verification",
RequiredFlags: []string{"<agent-id> (positional)"},
Examples: []string{"weknora agent status agent_abc"},
Output: "envelope.data is {id, reachable, ...}; use `agent check` for deep kb_scope verification",
})
return cmd
}
+6
View File
@@ -64,6 +64,12 @@ Use --jq to project specific fields or reach into nested config.`,
},
}
cmdutil.AddFormatFlag(cmd, agentViewFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "fetch one custom agent's full configuration by id",
RequiredFlags: []string{"<agent-id> (positional)"},
Examples: []string{"weknora agent view agent_abc"},
Output: "envelope.data is the custom agent (id, name, description, is_builtin, and a nested config object holding model/kb_scope/...)",
})
return cmd
}