2026-05-14 15:28:14 +00:00
|
|
|
package agentcmd
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"fmt"
|
|
|
|
|
"io"
|
2026-05-15 18:35:30 +00:00
|
|
|
"strings"
|
2026-05-14 15:28:14 +00:00
|
|
|
|
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
|
|
|
|
|
|
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
|
|
|
|
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
|
|
|
|
sdk "github.com/Tencent/WeKnora/client"
|
|
|
|
|
)
|
|
|
|
|
|
2026-05-15 18:35:30 +00:00
|
|
|
// agentViewFields enumerates fields surfaced for `--json=` field discovery
|
|
|
|
|
// on `agent view`. Only top-level Agent keys are listed because the
|
|
|
|
|
// `--json=foo,bar` field-projection filter matches flat top-level keys
|
|
|
|
|
// (see internal/format/filter.go). Nested AgentConfig fields are reachable
|
|
|
|
|
// via `--jq '.config.system_prompt'` or by selecting `config` whole and
|
|
|
|
|
// post-processing — listing them here would misleadingly advertise a
|
|
|
|
|
// projection path that does not actually filter to them.
|
2026-05-14 15:28:14 +00:00
|
|
|
var agentViewFields = []string{
|
|
|
|
|
"id", "name", "description", "avatar",
|
2026-05-15 18:35:30 +00:00
|
|
|
"is_builtin", "tenant_id", "created_by", "config",
|
2026-05-14 15:28:14 +00:00
|
|
|
"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",
|
2026-05-15 18:35:30 +00:00
|
|
|
Long: `Renders the agent's metadata and full AgentConfig as grouped KV
|
|
|
|
|
sections (Identity / LLM / KB attachment / Retrieval / Query rewrite /
|
|
|
|
|
Tools / FAQ / Web search / Multi-turn / Fallback / Templates). Zero-value
|
|
|
|
|
fields are omitted; sections with no set fields are suppressed entirely.
|
|
|
|
|
|
|
|
|
|
Pass --json for the bare SDK Agent object (config nested, not flattened).
|
|
|
|
|
Field projection (--json=id,name) works on top-level keys only; reach
|
|
|
|
|
nested config fields via --jq.`,
|
2026-05-14 15:28:14 +00:00
|
|
|
Example: ` weknora agent view ag_abc
|
2026-05-15 18:35:30 +00:00
|
|
|
weknora agent view ag_abc --json=id,name,config # top-level projection
|
|
|
|
|
weknora agent view ag_abc --json --jq '.config.system_prompt'`,
|
2026-05-14 15:28:14 +00:00
|
|
|
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)
|
|
|
|
|
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() {
|
refactor(cli): delete envelope infrastructure, errors to stderr
Removes the entire envelope machinery now that every success path
emits bare JSON:
- cli/internal/format/envelope.go (Envelope, Success, Failure,
SuccessWithRisk, WriteEnvelope, Meta, Notice, UpdateNotice,
VersionSkewNotice, Risk, RiskLevel, ErrorBody) + tests.
- cli/internal/format/filter.go envelope-specific helpers
(WriteEnvelopeFiltered, marshalEnvelope, applyFieldFilter,
filterDataPayload, filterObjectData); the reusable
filterArrayItems / filterObjectKeys / writeJQ stay for bare.go.
- cli/internal/cmdutil/exporter.go + tests (envelope-only).
- cli/internal/cmdutil/PrintErrorEnvelope + ToErrorBody +
operationRiskOf + Error.OperationRisk field + OperationRisk struct.
Error path: all errors now go to stderr via cmdutil.PrintError in
`code: message\nhint: ...` form, regardless of --json. Stdout stays
empty (or holds the partial-success the command already wrote) so
downstream `--json | jq` pipelines never have to filter error shapes
out of the success stream. Typed exit codes (3 auth.* / 4
resource.not_found / 5 input.* / 6 server.rate_limited / 7 server.*
+ network.* / 10 input.confirmation_required) carry the failure
class for agents that branch on it.
Acceptance contract:
- envelope_test.go → wire_test.go (TestEnvelopeGolden → TestWireGolden).
- testdata/envelopes/ → testdata/wire/.
- Error-path cases assert the typed code substring on stderr.
- Orphan whoami.*.json goldens deleted.
AGENTS.md + README.md rewritten for the bare-data contract:
- Drop envelope schema section + dry-run rule.
- Document bare JSON on stdout + `code: msg\nhint: …` on stderr.
- ADR-3 reframed around bare data and why error separation matters
for `--json | jq` pipelines.
WriteJSONFiltered short-circuits to WriteJSON when both filters are
empty (skip the marshal-buffer round-trip for the common case).
Final review pass:
- Fix wire-contract bug: `--json id,name` (space form) is broken by
pflag's NoOptDefVal; AGENTS.md / README.md / SetAgentHelp + the
field-discovery help text all switched to `--json=id,name`.
- Fix `weknora api --jq` silently ignored: api.go now routes through
WriteJSONFiltered with jopts.JQ.
- AGENTS.md: drop the false claim that `auth logout` honors `-y`
(logout is local-only with no ConfirmDestructive guard); list the
actual destructive commands instead.
- Rewrite cli/acceptance/e2e/e2e_test.go for the bare-data wire shape
(was still parsing `out["data"]` / `env["ok"]`).
- Add `JSONOptions.Emit(w, v)` helper; collapse ~33 repeated
`format.WriteJSONFiltered(iostreams.IO.Out, X, jopts.Fields,
jopts.JQ)` sites to `jopts.Emit(iostreams.IO.Out, X)` — drops the
format import from 22 cmd/* files.
- Delete single-caller `cmdutil.MustRequireFlag`; inline as
`_ = cmd.MarkFlagRequired(...)` everywhere.
- Add `_ = cmd.MarkFlagRequired("name")` to `kb create`; it was the
only write command relying on runtime --name validation while
`context add` already used the cobra-level mark.
- `context use`: register `--json` / `--jq` (was always emitting JSON
unconditionally with no human path and no flag — diverged from
every other write command); human mode now prints
`✓ Switched context to X (was Y)`.
- Replace per-package `confirmPrompter` / `scriptedConfirm` /
`errPrompter` test doubles with `testutil.ConfirmPrompter`.
- Rename `chatService` → `ChatService` (export to match siblings
`ListService` / `ViewService`); rename `printUploadSuccess` →
`renderUploadSuccess` (siblings use `render*`).
- `defaultHint(CodeResourceNotFound)`: drop the hardcoded
"list available with `weknora kb list`" — misleading on agent /
doc / session 404. Replaced with "verify the resource ID and try
again".
- Strip stale `v0.2/v0.3` / "envelope" / "v0.0/v0.1 supports only"
historical tags from production comments and a few test
descriptions.
2026-05-14 17:51:11 +00:00
|
|
|
return jopts.Emit(iostreams.IO.Out, a)
|
2026-05-14 15:28:14 +00:00
|
|
|
}
|
|
|
|
|
renderAgent(iostreams.IO.Out, a)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-15 18:35:30 +00:00
|
|
|
// renderAgent prints a single agent in human-readable form, grouped into
|
|
|
|
|
// 10 presentation sections (spec §2.9). Zero-value fields are omitted;
|
|
|
|
|
// a section header prints only when at least one of its fields is set.
|
|
|
|
|
// Group labels and order match the spec exactly so spec drift surfaces
|
|
|
|
|
// as test failure rather than silent divergence.
|
2026-05-14 15:28:14 +00:00
|
|
|
func renderAgent(w io.Writer, a *sdk.Agent) {
|
2026-05-15 18:35:30 +00:00
|
|
|
// Identity is always rendered — id/name/created_at/updated_at are
|
|
|
|
|
// never meaningfully empty for a fetched Agent.
|
|
|
|
|
fmt.Fprintln(w, "Identity:")
|
|
|
|
|
fmt.Fprintf(w, " ID: %s\n", a.ID)
|
|
|
|
|
fmt.Fprintf(w, " Name: %s\n", a.Name)
|
2026-05-14 15:28:14 +00:00
|
|
|
if a.Description != "" {
|
2026-05-15 18:35:30 +00:00
|
|
|
fmt.Fprintf(w, " Description: %s\n", a.Description)
|
2026-05-14 15:28:14 +00:00
|
|
|
}
|
|
|
|
|
if a.IsBuiltin {
|
2026-05-15 18:35:30 +00:00
|
|
|
fmt.Fprintln(w, " Builtin: yes")
|
2026-05-14 15:28:14 +00:00
|
|
|
}
|
|
|
|
|
if a.CreatedBy != "" {
|
2026-05-15 18:35:30 +00:00
|
|
|
fmt.Fprintf(w, " Created by: %s\n", a.CreatedBy)
|
|
|
|
|
}
|
|
|
|
|
if a.TenantID != 0 {
|
|
|
|
|
fmt.Fprintf(w, " Tenant ID: %d\n", a.TenantID)
|
2026-05-14 15:28:14 +00:00
|
|
|
}
|
2026-05-15 18:35:30 +00:00
|
|
|
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"))
|
|
|
|
|
|
2026-05-14 15:28:14 +00:00
|
|
|
if a.Config == nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-05-15 18:35:30 +00:00
|
|
|
c := a.Config
|
|
|
|
|
|
|
|
|
|
// Each group is rendered via a tiny helper: collect its set rows
|
|
|
|
|
// upfront, suppress the whole section if empty. Avoids the
|
|
|
|
|
// "header printed but no body" failure mode that plagues naive
|
|
|
|
|
// conditional rendering.
|
|
|
|
|
type row struct{ k, v string }
|
|
|
|
|
emit := func(label string, rows []row) {
|
|
|
|
|
if len(rows) == 0 {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
fmt.Fprintln(w)
|
|
|
|
|
fmt.Fprintf(w, "%s:\n", label)
|
|
|
|
|
for _, r := range rows {
|
|
|
|
|
fmt.Fprintf(w, " %-32s %s\n", r.k+":", r.v)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// LLM
|
|
|
|
|
llm := []row{}
|
|
|
|
|
if c.ModelID != "" {
|
|
|
|
|
llm = append(llm, row{"Model ID", c.ModelID})
|
|
|
|
|
}
|
|
|
|
|
if c.RerankModelID != "" {
|
|
|
|
|
llm = append(llm, row{"Rerank model ID", c.RerankModelID})
|
|
|
|
|
}
|
|
|
|
|
if c.Temperature != 0 {
|
|
|
|
|
llm = append(llm, row{"Temperature", fmt.Sprintf("%g", c.Temperature)})
|
|
|
|
|
}
|
|
|
|
|
if c.MaxCompletionTokens != 0 {
|
|
|
|
|
llm = append(llm, row{"Max completion tokens", fmt.Sprintf("%d", c.MaxCompletionTokens)})
|
|
|
|
|
}
|
|
|
|
|
if c.MaxIterations != 0 {
|
|
|
|
|
llm = append(llm, row{"Max iterations", fmt.Sprintf("%d", c.MaxIterations)})
|
|
|
|
|
}
|
|
|
|
|
if c.AgentMode != "" {
|
|
|
|
|
llm = append(llm, row{"Mode", c.AgentMode})
|
|
|
|
|
}
|
|
|
|
|
emit("LLM", llm)
|
|
|
|
|
|
|
|
|
|
// KB attachment
|
|
|
|
|
kb := []row{}
|
|
|
|
|
if c.KBSelectionMode != "" {
|
|
|
|
|
kb = append(kb, row{"KB selection mode", c.KBSelectionMode})
|
|
|
|
|
}
|
|
|
|
|
if len(c.KnowledgeBases) > 0 {
|
|
|
|
|
kb = append(kb, row{"Knowledge bases", strings.Join(c.KnowledgeBases, ", ")})
|
|
|
|
|
}
|
|
|
|
|
emit("KB attachment", kb)
|
|
|
|
|
|
|
|
|
|
// Retrieval
|
|
|
|
|
retr := []row{}
|
|
|
|
|
if c.EmbeddingTopK != 0 {
|
|
|
|
|
retr = append(retr, row{"Embedding top K", fmt.Sprintf("%d", c.EmbeddingTopK)})
|
|
|
|
|
}
|
|
|
|
|
if c.KeywordThreshold != 0 {
|
|
|
|
|
retr = append(retr, row{"Keyword threshold", fmt.Sprintf("%g", c.KeywordThreshold)})
|
|
|
|
|
}
|
|
|
|
|
if c.VectorThreshold != 0 {
|
|
|
|
|
retr = append(retr, row{"Vector threshold", fmt.Sprintf("%g", c.VectorThreshold)})
|
2026-05-14 15:28:14 +00:00
|
|
|
}
|
2026-05-15 18:35:30 +00:00
|
|
|
if c.RerankTopK != 0 {
|
|
|
|
|
retr = append(retr, row{"Rerank top K", fmt.Sprintf("%d", c.RerankTopK)})
|
2026-05-14 15:28:14 +00:00
|
|
|
}
|
2026-05-15 18:35:30 +00:00
|
|
|
if c.RerankThreshold != 0 {
|
|
|
|
|
retr = append(retr, row{"Rerank threshold", fmt.Sprintf("%g", c.RerankThreshold)})
|
2026-05-14 15:28:14 +00:00
|
|
|
}
|
2026-05-15 18:35:30 +00:00
|
|
|
emit("Retrieval", retr)
|
|
|
|
|
|
|
|
|
|
// Query rewrite
|
|
|
|
|
qr := []row{}
|
|
|
|
|
if c.EnableQueryExpansion {
|
|
|
|
|
qr = append(qr, row{"Query expansion", "enabled"})
|
|
|
|
|
}
|
|
|
|
|
if c.EnableRewrite {
|
|
|
|
|
qr = append(qr, row{"Rewrite", "enabled"})
|
|
|
|
|
}
|
|
|
|
|
if c.QueryUnderstandModelID != "" {
|
|
|
|
|
qr = append(qr, row{"Query understand model ID", c.QueryUnderstandModelID})
|
2026-05-14 15:28:14 +00:00
|
|
|
}
|
2026-05-15 18:35:30 +00:00
|
|
|
if c.RewritePromptSystem != "" {
|
|
|
|
|
qr = append(qr, row{"Rewrite prompt (system)", truncate1Line(c.RewritePromptSystem)})
|
|
|
|
|
}
|
|
|
|
|
if c.RewritePromptUser != "" {
|
|
|
|
|
qr = append(qr, row{"Rewrite prompt (user)", truncate1Line(c.RewritePromptUser)})
|
|
|
|
|
}
|
|
|
|
|
emit("Query rewrite", qr)
|
|
|
|
|
|
|
|
|
|
// Tools
|
|
|
|
|
tools := []row{}
|
|
|
|
|
if len(c.AllowedTools) > 0 {
|
|
|
|
|
tools = append(tools, row{"Allowed tools", strings.Join(c.AllowedTools, ", ")})
|
2026-05-14 15:28:14 +00:00
|
|
|
}
|
2026-05-15 18:35:30 +00:00
|
|
|
if c.MCPSelectionMode != "" {
|
|
|
|
|
tools = append(tools, row{"MCP selection mode", c.MCPSelectionMode})
|
2026-05-14 15:28:14 +00:00
|
|
|
}
|
2026-05-15 18:35:30 +00:00
|
|
|
if len(c.MCPServices) > 0 {
|
|
|
|
|
tools = append(tools, row{"MCP services", strings.Join(c.MCPServices, ", ")})
|
|
|
|
|
}
|
|
|
|
|
if len(c.SupportedFileTypes) > 0 {
|
|
|
|
|
tools = append(tools, row{"Supported file types", strings.Join(c.SupportedFileTypes, ", ")})
|
|
|
|
|
}
|
|
|
|
|
emit("Tools", tools)
|
|
|
|
|
|
|
|
|
|
// FAQ
|
|
|
|
|
faq := []row{}
|
|
|
|
|
if c.FAQPriorityEnabled {
|
|
|
|
|
faq = append(faq, row{"FAQ priority", "enabled"})
|
|
|
|
|
}
|
|
|
|
|
if c.FAQDirectAnswerThreshold != 0 {
|
|
|
|
|
faq = append(faq, row{"FAQ direct-answer threshold", fmt.Sprintf("%g", c.FAQDirectAnswerThreshold)})
|
|
|
|
|
}
|
|
|
|
|
if c.FAQScoreBoost != 0 {
|
|
|
|
|
faq = append(faq, row{"FAQ score boost", fmt.Sprintf("%g", c.FAQScoreBoost)})
|
|
|
|
|
}
|
|
|
|
|
emit("FAQ", faq)
|
|
|
|
|
|
|
|
|
|
// Web search
|
|
|
|
|
web := []row{}
|
|
|
|
|
if c.WebSearchEnabled {
|
|
|
|
|
web = append(web, row{"Web search", "enabled"})
|
|
|
|
|
}
|
|
|
|
|
if c.WebSearchMaxResults != 0 {
|
|
|
|
|
web = append(web, row{"Web search max results", fmt.Sprintf("%d", c.WebSearchMaxResults)})
|
|
|
|
|
}
|
|
|
|
|
emit("Web search", web)
|
|
|
|
|
|
|
|
|
|
// Multi-turn
|
|
|
|
|
mt := []row{}
|
|
|
|
|
if c.MultiTurnEnabled {
|
|
|
|
|
mt = append(mt, row{"Multi-turn", "enabled"})
|
|
|
|
|
}
|
|
|
|
|
if c.HistoryTurns != 0 {
|
|
|
|
|
mt = append(mt, row{"History turns", fmt.Sprintf("%d", c.HistoryTurns)})
|
|
|
|
|
}
|
|
|
|
|
emit("Multi-turn", mt)
|
|
|
|
|
|
|
|
|
|
// Fallback
|
|
|
|
|
fb := []row{}
|
|
|
|
|
if c.FallbackStrategy != "" {
|
|
|
|
|
fb = append(fb, row{"Strategy", c.FallbackStrategy})
|
|
|
|
|
}
|
|
|
|
|
if c.FallbackResponse != "" {
|
|
|
|
|
fb = append(fb, row{"Response", c.FallbackResponse})
|
|
|
|
|
}
|
|
|
|
|
if c.FallbackPrompt != "" {
|
|
|
|
|
fb = append(fb, row{"Prompt", truncate1Line(c.FallbackPrompt)})
|
|
|
|
|
}
|
|
|
|
|
emit("Fallback", fb)
|
|
|
|
|
|
|
|
|
|
// Templates — system_prompt and context_template can be multi-line;
|
|
|
|
|
// render headed blocks rather than KV rows for readability.
|
|
|
|
|
if c.SystemPrompt != "" || c.ContextTemplate != "" {
|
|
|
|
|
fmt.Fprintln(w)
|
|
|
|
|
fmt.Fprintln(w, "Templates:")
|
|
|
|
|
if c.SystemPrompt != "" {
|
|
|
|
|
fmt.Fprintln(w, " System prompt:")
|
|
|
|
|
writeIndented(w, c.SystemPrompt, " ")
|
|
|
|
|
}
|
|
|
|
|
if c.ContextTemplate != "" {
|
|
|
|
|
fmt.Fprintln(w, " Context template:")
|
|
|
|
|
writeIndented(w, c.ContextTemplate, " ")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// truncate1Line collapses newlines and clips long values for inline KV
|
|
|
|
|
// rows. Templates section gets full multi-line treatment instead.
|
|
|
|
|
func truncate1Line(s string) string {
|
|
|
|
|
s = strings.ReplaceAll(s, "\n", " ")
|
|
|
|
|
s = strings.ReplaceAll(s, "\r", " ")
|
|
|
|
|
const max = 80
|
|
|
|
|
if len(s) > max {
|
|
|
|
|
return s[:max-3] + "..."
|
|
|
|
|
}
|
|
|
|
|
return s
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// writeIndented prints s with the given prefix on every line. Trailing
|
|
|
|
|
// newline always added so the next section starts on its own line.
|
|
|
|
|
func writeIndented(w io.Writer, s, prefix string) {
|
|
|
|
|
for _, line := range strings.Split(strings.TrimRight(s, "\n"), "\n") {
|
|
|
|
|
fmt.Fprintf(w, "%s%s\n", prefix, line)
|
2026-05-14 15:28:14 +00:00
|
|
|
}
|
|
|
|
|
}
|