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.
This commit is contained in:
@@ -18,8 +18,9 @@ import (
|
||||
)
|
||||
|
||||
// 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 events).
|
||||
// `agent invoke`. Matches invokeData below — the single-shot result
|
||||
// object with the agent's final answer plus the trace (references,
|
||||
// tool events).
|
||||
var agentInvokeFields = []string{
|
||||
"answer", "references", "tool_events", "thinking",
|
||||
"session_id", "agent_id", "query",
|
||||
@@ -46,7 +47,7 @@ type InvokeService interface {
|
||||
AgentQAStreamWithRequest(ctx context.Context, sessionID string, req *sdk.AgentQARequest, cb sdk.AgentEventCallback) error
|
||||
}
|
||||
|
||||
// invokeData is the JSON envelope payload.
|
||||
// invokeData is the JSON payload emitted on the --json path.
|
||||
type invokeData struct {
|
||||
Answer string `json:"answer"`
|
||||
References []*sdk.SearchResult `json:"references"`
|
||||
@@ -71,7 +72,7 @@ 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`,
|
||||
Pipe / --no-stream / --json: buffered, single JSON object 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`,
|
||||
@@ -93,7 +94,7 @@ Modes:
|
||||
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)
|
||||
aiclient.SetAgentHelp(cmd, "Streams an agent's answer over SSE. Pass --json (or run non-TTY) to receive a single completed envelope with answer + references + tool_events instead of partial chunks. Errors: resource.not_found (unknown agent_id) / server.session_create_failed (auto-create) / local.sse_stream_aborted (mid-stream).")
|
||||
aiclient.SetAgentHelp(cmd, "Streams an agent's answer over SSE. Pass --json (or run non-TTY) to receive a single completed {answer, references, tool_events, …} JSON object instead of partial chunks. Errors: resource.not_found (unknown agent_id) / server.session_create_failed (auto-create) / local.sse_stream_aborted (mid-stream).")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -183,7 +184,7 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
|
||||
AgentID: opts.AgentID,
|
||||
Query: opts.Query,
|
||||
}
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, data, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, data)
|
||||
}
|
||||
|
||||
out := iostreams.IO.Out
|
||||
|
||||
@@ -62,7 +62,7 @@ func referencesEvent(refs []*sdk.SearchResult) *sdk.AgentStreamResponse {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvoke_AccumulateMode_EmitsJSONEnvelope(t *testing.T) {
|
||||
func TestInvoke_AccumulateMode_EmitsBareJSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &scriptedInvokeSvc{
|
||||
events: []*sdk.AgentStreamResponse{
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
@@ -60,7 +59,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
}
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (0 = no cap, 1..10000 = explicit)")
|
||||
cmdutil.AddJSONFlags(cmd, agentListFields)
|
||||
aiclient.SetAgentHelp(cmd, "Lists tenant-visible agents (built-in + custom) as a bare JSON array of Agent objects (empty `[]` when none). --limit caps the returned slice. Use `--json id,name` to project fields, `--jq` for arbitrary reshape.")
|
||||
aiclient.SetAgentHelp(cmd, "Lists tenant-visible agents (built-in + custom) as a bare JSON array of Agent objects (empty `[]` when none). --limit caps the returned slice. Use `--json=id,name` to project fields, `--jq` for arbitrary reshape.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -92,7 +91,7 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, items, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, items)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
)
|
||||
@@ -64,7 +63,7 @@ func runView(ctx context.Context, jopts *cmdutil.JSONOptions, svc ViewService, a
|
||||
return cmdutil.WrapHTTP(err, "fetch agent %s", agentID)
|
||||
}
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, a, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, a)
|
||||
}
|
||||
renderAgent(iostreams.IO.Out, a)
|
||||
return nil
|
||||
|
||||
+9
-7
@@ -3,7 +3,7 @@
|
||||
// Shape: one positional (path) + `-X/--method` flag, default GET (auto-
|
||||
// promoted to POST when a body is supplied via --data or --input). The two
|
||||
// body-source flags are mutually exclusive. Default raw response body to
|
||||
// stdout; --json wraps in CLI envelope. Reuses sdk.Client.Raw which already
|
||||
// stdout; --json emits a {status, headers, body} object. Reuses sdk.Client.Raw which already
|
||||
// applies tenant + auth headers.
|
||||
package api
|
||||
|
||||
@@ -26,7 +26,7 @@ import (
|
||||
)
|
||||
|
||||
// apiFields is intentionally a marker — api wraps arbitrary HTTP responses
|
||||
// whose schema the CLI doesn't know, so the `--json id,name` field-filter
|
||||
// whose schema the CLI doesn't know, so the `--json=id,name` field-filter
|
||||
// is a no-op here. The marker shows up in --help so users can tell.
|
||||
var apiFields = []string{"<response-shape-varies>"}
|
||||
|
||||
@@ -59,7 +59,7 @@ POST. Use -X/--method to override (DELETE / PUT / PATCH / HEAD).
|
||||
|
||||
Auth, tenant, and request-id headers are applied automatically from the
|
||||
active context. The response body is written to stdout by default; use
|
||||
--json to wrap it in the CLI envelope (status / headers / body).
|
||||
--json to emit a {status, headers, body} JSON object.
|
||||
|
||||
Examples:
|
||||
weknora api /api/v1/knowledge-bases # GET
|
||||
@@ -131,7 +131,7 @@ func resolveMethod(opts *Options) string {
|
||||
}
|
||||
|
||||
// runAPI is the testable core: validate inputs, dispatch via Service.Raw,
|
||||
// classify status, and emit either the raw body or a JSON envelope. The
|
||||
// classify status, and emit either the raw body or a JSON object. The
|
||||
// caller is responsible for resolving the method (defaults / auto-POST)
|
||||
// and uppercasing it; runAPI guards against unsupported values like
|
||||
// `-X PATCH-INVALID` reaching the wire.
|
||||
@@ -181,7 +181,7 @@ func runAPI(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
|
||||
out := iostreams.IO.Out
|
||||
if jopts.Enabled() {
|
||||
// Best-effort decode: if response body is valid JSON, surface the
|
||||
// parsed structure under .data.body so envelope consumers can drill
|
||||
// parsed structure under .body so JSON consumers can drill
|
||||
// in; otherwise fall back to the raw string.
|
||||
var bodyAny any
|
||||
if len(respBody) > 0 {
|
||||
@@ -195,11 +195,13 @@ func runAPI(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
|
||||
hdrs[k] = v[0]
|
||||
}
|
||||
}
|
||||
return format.WriteJSON(out, map[string]any{
|
||||
// --json field-filter is ignored (response shape unknown to the
|
||||
// CLI); --jq runs over the full {status, headers, body} object.
|
||||
return format.WriteJSONFiltered(out, map[string]any{
|
||||
"status": resp.StatusCode,
|
||||
"headers": hdrs,
|
||||
"body": bodyAny,
|
||||
})
|
||||
}, nil, jopts.JQ)
|
||||
}
|
||||
|
||||
if _, err := out.Write(respBody); err != nil {
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
)
|
||||
|
||||
// Credential-mode tokens used in the JSON envelope of auth list / login /
|
||||
// Credential-mode tokens used in the JSON output of auth list / login /
|
||||
// status / token. The string names describe the HTTP credential type rather
|
||||
// than the login flow (e.g. JWT → bearer regardless of whether it was
|
||||
// obtained via password or refresh) so an agent can branch directly on the
|
||||
|
||||
@@ -68,7 +68,7 @@ func runList(jopts *cmdutil.JSONOptions, f *cmdutil.Factory) error {
|
||||
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, entries, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, entries)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
fmt.Fprintln(iostreams.IO.Out, "No contexts configured. Run `weknora auth login` to create one.")
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
@@ -75,7 +74,7 @@ the current_context in ~/.config/weknora/config.yaml.`,
|
||||
cmd.Flags().StringVar(&opts.Context, "name", "default", "Context name to register in config.yaml")
|
||||
cmd.Flags().BoolVar(&opts.WithToken, "with-token", false, "Read an API key from stdin instead of prompting for password")
|
||||
cmdutil.AddJSONFlags(cmd, authLoginFields)
|
||||
cmdutil.MustRequireFlag(cmd, "host")
|
||||
_ = cmd.MarkFlagRequired("host")
|
||||
aiclient.SetAgentHelp(cmd, "Authenticates and stores credentials. --with-token reads an API key from stdin (no password prompt, agent-safe). Otherwise email/password prompts fire — non-TTY callers must pipe `--with-token` or pre-set --name. Errors: auth.bad_credential on wrong password; input.invalid_argument on bad --host; input.missing_flag when --with-token has empty stdin.")
|
||||
return cmd
|
||||
}
|
||||
@@ -211,7 +210,7 @@ func saveContextRef(opts *LoginOptions, jopts *cmdutil.JSONOptions, f *cmdutil.F
|
||||
result.User = user.Email
|
||||
result.TenantID = user.TenantID
|
||||
}
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, result, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, result)
|
||||
}
|
||||
who := opts.Context
|
||||
if user != nil {
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/secrets"
|
||||
)
|
||||
@@ -97,7 +96,7 @@ func runLogout(opts *LogoutOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Facto
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, logoutResult{Removed: targets}, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, logoutResult{Removed: targets})
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Logged out of %d context(s): %s\n", len(targets), strings.Join(targets, ", "))
|
||||
return nil
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
)
|
||||
@@ -113,7 +112,7 @@ func runRefresh(ctx context.Context, opts *RefreshOptions, jopts *cmdutil.JSONOp
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, refreshResult{Context: name}, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, refreshResult{Context: name})
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Refreshed access token for context %s\n", name)
|
||||
return nil
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
)
|
||||
@@ -82,7 +81,7 @@ func runStatus(ctx context.Context, jopts *cmdutil.JSONOptions, f *cmdutil.Facto
|
||||
if tenant != nil {
|
||||
result.TenantName = tenant.Name
|
||||
}
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, result, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, result)
|
||||
}
|
||||
|
||||
host := ""
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
|
||||
@@ -32,7 +31,7 @@ type tokenResult struct {
|
||||
// `auth list` shows which mode each context uses.
|
||||
//
|
||||
// Default output: raw token on stdout, no trailing newline (clean $(...)).
|
||||
// `--json[=fields]` wraps in envelope {token, mode, context}.
|
||||
// `--json[=fields]` emits a bare {token, mode, context} object.
|
||||
func NewCmdToken(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "token",
|
||||
@@ -61,7 +60,7 @@ to see which mode each context uses, and construct the matching HTTP header:
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, authTokenFields)
|
||||
aiclient.SetAgentHelp(cmd, "Prints the active context's credential to stdout for scripting. Default: raw secret, no trailing newline. With --json: envelope {token, mode, context}. Errors: auth.unauthenticated when no active context or no stored credential (run `auth login`); local.keychain_denied when the keyring rejects the read.")
|
||||
aiclient.SetAgentHelp(cmd, "Prints the active context's credential to stdout for scripting. Default: raw secret, no trailing newline. With --json: bare {token, mode, context} object. Errors: auth.unauthenticated when no active context or no stored credential (run `auth login`); local.keychain_denied when the keyring rejects the read.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -117,9 +116,7 @@ func runToken(f *cmdutil.Factory, jopts *cmdutil.JSONOptions) error {
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out,
|
||||
tokenResult{Token: token, Mode: mode, Context: ctxName},
|
||||
jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, tokenResult{Token: token, Mode: mode, Context: ctxName})
|
||||
}
|
||||
|
||||
// No trailing newline — clean $(weknora auth token) substitution.
|
||||
|
||||
+14
-14
@@ -9,13 +9,13 @@
|
||||
// "feels alive" UX a human typing in a terminal expects.
|
||||
//
|
||||
// - Accumulate mode (non-TTY, --no-stream, or --json): buffer every
|
||||
// fragment via sse.Accumulator and emit a single envelope (or a single
|
||||
// fragment via sse.Accumulator and emit a single JSON object (or a single
|
||||
// plain-text answer + references block) once Done. Agents and pipes
|
||||
// get a deterministic single record to parse.
|
||||
//
|
||||
// The SDK's KnowledgeQAStream callback contract is invoked sequentially on
|
||||
// one goroutine, so neither mode needs locking. The runChat core takes a
|
||||
// chatService interface so tests inject a fake without standing up a real
|
||||
// ChatService interface so tests inject a fake without standing up a real
|
||||
// SSE server.
|
||||
package chat
|
||||
|
||||
@@ -49,15 +49,15 @@ type Options struct {
|
||||
NoStream bool
|
||||
}
|
||||
|
||||
// chatService is the narrow SDK surface this command depends on. *sdk.Client
|
||||
// ChatService is the narrow SDK surface this command depends on. *sdk.Client
|
||||
// satisfies it; tests substitute a fake. Compile-time check is at the bottom
|
||||
// of this file.
|
||||
type chatService interface {
|
||||
type ChatService interface {
|
||||
CreateSession(ctx context.Context, req *sdk.CreateSessionRequest) (*sdk.Session, error)
|
||||
KnowledgeQAStream(ctx context.Context, sessionID string, req *sdk.KnowledgeQARequest, cb func(*sdk.StreamResponse) error) error
|
||||
}
|
||||
|
||||
// chatData is the success-envelope payload. Mirrors what an agent needs to
|
||||
// chatData is the JSON payload emitted on the --json path. Mirrors what an agent needs to
|
||||
// continue a conversation: the answer text, retrieval references, and the
|
||||
// session pointer to thread follow-ups.
|
||||
type chatData struct {
|
||||
@@ -116,13 +116,13 @@ Modes:
|
||||
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, chatFields)
|
||||
aiclient.SetAgentHelp(cmd, "Streams an LLM answer over SSE. Agent / non-TTY callers should pass --json so the full {answer, references, session_id, assistant_message_id} envelope is emitted at completion (no partial chunks). Pass --session to thread follow-ups. Errors: server.session_create_failed when auto-create fails; local.sse_stream_aborted on mid-stream disconnect.")
|
||||
aiclient.SetAgentHelp(cmd, "Streams an LLM answer over SSE. Agent / non-TTY callers should pass --json so the full {answer, references, session_id, assistant_message_id} object is emitted once at completion (no partial chunks). Pass --session to thread follow-ups. Errors: server.session_create_failed when auto-create fails; local.sse_stream_aborted on mid-stream disconnect.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// runChat is the testable core: validate, ensure a session, dispatch the
|
||||
// stream, and route output. Returns a typed error suitable for the envelope.
|
||||
func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc chatService) error {
|
||||
// stream, and route output. Returns a typed error.
|
||||
func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc ChatService) error {
|
||||
if opts.Query == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "query argument cannot be empty")
|
||||
}
|
||||
@@ -157,12 +157,12 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
|
||||
// Decide output mode. Stream mode requires:
|
||||
// 1. an interactive stdout (tty)
|
||||
// 2. no --no-stream
|
||||
// 3. no --json (envelope is single-record by definition)
|
||||
// 3. no --json (JSON output is single-record by definition)
|
||||
streamMode := iostreams.IO.IsStdoutTTY() && !opts.NoStream && !jsonOut
|
||||
|
||||
// Surface the auto-created session ID up-front so a user who hits ^C
|
||||
// mid-stream still has the pointer to resume — no need to scroll back
|
||||
// past tokens. Skipped in JSON mode (it ends up in the envelope) and
|
||||
// past tokens. Skipped in JSON mode (it ends up in the data object) and
|
||||
// when the caller already supplied --session.
|
||||
if autoCreated && !jsonOut {
|
||||
fmt.Fprintf(iostreams.IO.Err, "session: %s (use --session to continue)\n", sessionID)
|
||||
@@ -193,7 +193,7 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
|
||||
// Re-surface the auto-created session id on failure so a user who
|
||||
// missed the start-of-stream notice (it scrolls past mid-stream
|
||||
// tokens, especially on ^C) can still recover with --session.
|
||||
// Skipped in JSON mode — the envelope carries it in .data.session_id.
|
||||
// Skipped in JSON mode — the data object carries it in .session_id.
|
||||
if autoCreated && !jsonOut {
|
||||
fmt.Fprintf(iostreams.IO.Err, "session: %s (resume with --session %s)\n", sessionID, sessionID)
|
||||
}
|
||||
@@ -241,7 +241,7 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
|
||||
KBID: opts.KBID,
|
||||
Query: opts.Query,
|
||||
}
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, data, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, data)
|
||||
}
|
||||
|
||||
// Human / non-JSON paths: streaming mode already wrote the answer body
|
||||
@@ -264,5 +264,5 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
|
||||
return nil
|
||||
}
|
||||
|
||||
// compile-time check: the production SDK client implements chatService.
|
||||
var _ chatService = (*sdk.Client)(nil)
|
||||
// compile-time check: the production SDK client implements ChatService.
|
||||
var _ ChatService = (*sdk.Client)(nil)
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// fakeChatService implements chatService for unit tests. Tests configure the
|
||||
// fakeChatService implements ChatService for unit tests. Tests configure the
|
||||
// callback driver via streamEvents (delivered in order) and observe captured
|
||||
// inputs through the exported fields.
|
||||
type fakeChatService struct {
|
||||
@@ -37,7 +37,7 @@ func (f *fakeChatService) CreateSession(_ context.Context, req *sdk.CreateSessio
|
||||
return f.createSessionResp, nil
|
||||
}
|
||||
// Default: return a deterministic session id derived from the title so
|
||||
// envelope assertions don't depend on uuid generation.
|
||||
// JSON assertions don't depend on uuid generation.
|
||||
return &sdk.Session{ID: "sess_auto", Title: req.Title}, nil
|
||||
}
|
||||
|
||||
@@ -56,9 +56,9 @@ func (f *fakeChatService) KnowledgeQAStream(ctx context.Context, sessionID strin
|
||||
return f.streamErr
|
||||
}
|
||||
|
||||
// Sanity: fakeChatService must satisfy chatService. Mirrors the production
|
||||
// var _ chatService = (*sdk.Client)(nil) check at the bottom of chat.go.
|
||||
var _ chatService = (*fakeChatService)(nil)
|
||||
// Sanity: fakeChatService must satisfy ChatService. Mirrors the production
|
||||
// var _ ChatService = (*sdk.Client)(nil) check at the bottom of chat.go.
|
||||
var _ ChatService = (*fakeChatService)(nil)
|
||||
|
||||
func TestChat_StreamMode(t *testing.T) {
|
||||
out, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
@@ -117,7 +117,7 @@ func TestChat_JSONMode(t *testing.T) {
|
||||
}
|
||||
|
||||
// JSON mode must NOT print the human session-hint on stderr; the session
|
||||
// id is carried inside the envelope instead.
|
||||
// id is carried inside the JSON object instead.
|
||||
if errBuf.Len() != 0 {
|
||||
t.Errorf("expected empty stderr in JSON mode, got %q", errBuf.String())
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
|
||||
@@ -102,9 +101,7 @@ func runAdd(opts *AddOptions, jopts *cmdutil.JSONOptions, name string) error {
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out,
|
||||
addResult{Name: name, Host: host, User: opts.User, Current: wasFirst},
|
||||
jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, addResult{Name: name, Host: host, User: opts.User, Current: wasFirst})
|
||||
}
|
||||
if wasFirst {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added context %s (now current). Run `weknora auth login --name %s` to attach credentials.\n", name, name)
|
||||
|
||||
@@ -73,7 +73,7 @@ func runList(jopts *cmdutil.JSONOptions) error {
|
||||
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, entries, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, entries)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
fmt.Fprintln(iostreams.IO.Out, "No contexts configured. Run `weknora auth login` (or `weknora context add`) to create one.")
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
"github.com/Tencent/WeKnora/cli/internal/secrets"
|
||||
@@ -80,7 +79,6 @@ func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, sto
|
||||
return notFoundError(name, cfg)
|
||||
}
|
||||
wasCurrent := name == cfg.CurrentContext
|
||||
risk := riskForRemove(name, wasCurrent)
|
||||
|
||||
jsonOut := jopts.Enabled()
|
||||
// Confirmation only fires for removing the current context — non-current
|
||||
@@ -102,10 +100,9 @@ func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, sto
|
||||
}
|
||||
clearContextSecrets(store, ctx, name)
|
||||
|
||||
_ = risk // risk classification dropped in v0.4; exit code already signals
|
||||
result := removeResult{Name: name, Removed: true, WasCurrent: wasCurrent}
|
||||
if jsonOut {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, result, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, result)
|
||||
}
|
||||
if wasCurrent {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s (current context cleared — run `weknora context use <name>` to pick another)\n", name)
|
||||
@@ -115,19 +112,6 @@ func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, sto
|
||||
return nil
|
||||
}
|
||||
|
||||
// riskForRemove returns the operation risk: high-risk-write only when the
|
||||
// target is the currently-active context (subsequent commands will have no
|
||||
// default --context until the user picks one).
|
||||
func riskForRemove(name string, wasCurrent bool) *format.Risk {
|
||||
if wasCurrent {
|
||||
return &format.Risk{
|
||||
Level: format.RiskHighRiskWrite,
|
||||
Action: fmt.Sprintf("remove context %s (the current context — subsequent commands will need a new --context)", name),
|
||||
}
|
||||
}
|
||||
return &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("remove context %s", name)}
|
||||
}
|
||||
|
||||
// clearContextSecrets mirrors auth/logout.go: best-effort delete every secret
|
||||
// slot the context references. Errors are swallowed so a missing keyring
|
||||
// entry doesn't block remove (logout has had the same policy since v0.2).
|
||||
|
||||
+23
-9
@@ -9,10 +9,13 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
|
||||
// contextUseFields enumerates fields surfaced for `--json` discovery on
|
||||
// `context use`.
|
||||
var contextUseFields = []string{"current_context", "previous_context"}
|
||||
|
||||
// NewCmdUse builds the `weknora context use <name>` command.
|
||||
func NewCmdUse(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
@@ -29,13 +32,18 @@ you to. Context selection is a user preference; one-shot overrides should use
|
||||
the global --context flag instead, which writes nothing to disk.`,
|
||||
Example: ` weknora context use staging # persist switch
|
||||
weknora --context staging kb list # one-shot override (no disk write)
|
||||
weknora context use --help # this help`,
|
||||
weknora context use staging --json # {current_context, previous_context}`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
return runUse(args[0])
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runUse(args[0], jopts)
|
||||
},
|
||||
}
|
||||
aiclient.SetAgentHelp(cmd, "Switches default CLI context. Returns previous_context + current_context. Errors with hint when name unknown.")
|
||||
cmdutil.AddJSONFlags(cmd, contextUseFields)
|
||||
aiclient.SetAgentHelp(cmd, "Switches default CLI context. With --json: returns {current_context, previous_context}. Errors with local.context_not_found and a did-you-mean hint when name unknown.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -44,7 +52,7 @@ type useResult struct {
|
||||
PreviousContext string `json:"previous_context,omitempty"`
|
||||
}
|
||||
|
||||
func runUse(name string) error {
|
||||
func runUse(name string, jopts *cmdutil.JSONOptions) error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -57,10 +65,16 @@ func runUse(name string) error {
|
||||
if err := config.Save(cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
return format.WriteJSON(iostreams.IO.Out, useResult{
|
||||
CurrentContext: name,
|
||||
PreviousContext: prev,
|
||||
})
|
||||
result := useResult{CurrentContext: name, PreviousContext: prev}
|
||||
if jopts.Enabled() {
|
||||
return jopts.Emit(iostreams.IO.Out, result)
|
||||
}
|
||||
if prev != "" && prev != name {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Switched context to %s (was %s)\n", name, prev)
|
||||
} else {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Active context: %s\n", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func notFoundError(name string, cfg *config.Config) error {
|
||||
|
||||
@@ -24,7 +24,7 @@ func TestUse_OK(t *testing.T) {
|
||||
t.Fatalf("Save initial config: %v", err)
|
||||
}
|
||||
|
||||
if err := runUse("production"); err != nil {
|
||||
if err := runUse("production", nil); err != nil {
|
||||
t.Fatalf("runUse: %v", err)
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ func TestUse_NotFound_WithDidYouMean(t *testing.T) {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
err := runUse("prodution") // typo: missing 'c'
|
||||
err := runUse("prodution", nil) // typo: missing 'c'
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
@@ -84,7 +84,7 @@ func TestUse_NotFound_DeterministicTieBreak(t *testing.T) {
|
||||
}
|
||||
// "prox" is distance 1 from prod / prom (both win); lex tie-break → prod.
|
||||
for i := 0; i < 5; i++ {
|
||||
err := runUse("prox")
|
||||
err := runUse("prox", nil)
|
||||
if err == nil {
|
||||
t.Fatalf("iter %d: expected error", i)
|
||||
}
|
||||
@@ -99,7 +99,7 @@ func TestUse_NotFound_EmptyContexts(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
err := runUse("anything")
|
||||
err := runUse("anything", nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
@@ -118,7 +118,7 @@ func TestUse_CaseSensitive(t *testing.T) {
|
||||
}}
|
||||
_ = config.Save(cfg)
|
||||
|
||||
err := runUse("production") // lowercase — must NOT match "Production"
|
||||
err := runUse("production", nil) // lowercase — must NOT match "Production"
|
||||
if err == nil {
|
||||
t.Fatal("expected case-sensitive miss")
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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/prompt"
|
||||
)
|
||||
@@ -44,12 +43,12 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
||||
when stdout is a TTY and --json is not set; pass -y/--yes (global flag) to skip
|
||||
the prompt (required in agent / CI / piped contexts).
|
||||
|
||||
AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10 and
|
||||
returns an envelope describing the missing confirmation. NEVER auto-pass -y
|
||||
AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10
|
||||
and writes input.confirmation_required to stderr. NEVER auto-pass -y
|
||||
without the user's explicit go-ahead.`,
|
||||
Example: ` weknora doc delete doc_abc # interactive confirm
|
||||
weknora doc delete doc_abc -y # no prompt
|
||||
weknora doc delete doc_abc -y --json # envelope output`,
|
||||
weknora doc delete doc_abc -y --json # bare {id, deleted:true} JSON`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
@@ -79,7 +78,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, jopts *cmdutil.JSONOpti
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, deleteResult{ID: id, Deleted: true}, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, deleteResult{ID: id, Deleted: true})
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted document %s\n", id)
|
||||
return nil
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/testutil"
|
||||
)
|
||||
|
||||
// fakeDeleteSvc captures the id passed and returns a canned error.
|
||||
@@ -26,30 +27,13 @@ func (f *fakeDeleteSvc) DeleteKnowledge(_ context.Context, id string) error {
|
||||
return f.err
|
||||
}
|
||||
|
||||
// scriptedConfirm satisfies prompt.Prompter and returns predetermined answers.
|
||||
type scriptedConfirm struct{ confirmReturn bool }
|
||||
|
||||
func (s scriptedConfirm) Input(string, string) (string, error) { return "", nil }
|
||||
func (s scriptedConfirm) Password(string) (string, error) { return "", nil }
|
||||
func (s scriptedConfirm) Confirm(string, bool) (bool, error) { return s.confirmReturn, nil }
|
||||
|
||||
// errPrompter returns an error from Confirm — simulates a non-TTY agent
|
||||
// prompter.
|
||||
type errPrompter struct{}
|
||||
|
||||
func (errPrompter) Input(string, string) (string, error) { return "", nil }
|
||||
func (errPrompter) Password(string) (string, error) { return "", nil }
|
||||
func (errPrompter) Confirm(string, bool) (bool, error) {
|
||||
return false, errors.New("no tty")
|
||||
}
|
||||
|
||||
func TestDelete_Success_WithForce(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
opts := &DeleteOptions{Yes: true}
|
||||
// Force=true short-circuits the confirm path; the prompter must not be
|
||||
// consulted, so any value works.
|
||||
require.NoError(t, runDelete(context.Background(), opts, nil, svc, scriptedConfirm{confirmReturn: false}, "doc_abc"))
|
||||
require.NoError(t, runDelete(context.Background(), opts, nil, svc, &testutil.ConfirmPrompter{Answer: false}, "doc_abc"))
|
||||
|
||||
assert.Equal(t, "doc_abc", svc.got)
|
||||
assert.Equal(t, 1, svc.calls)
|
||||
@@ -61,7 +45,7 @@ func TestDelete_Success_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
opts := &DeleteOptions{Yes: true}
|
||||
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.JSONOptions{}, svc, scriptedConfirm{confirmReturn: true}, "doc_abc"))
|
||||
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.JSONOptions{}, svc, &testutil.ConfirmPrompter{Answer: true}, "doc_abc"))
|
||||
|
||||
got := out.String()
|
||||
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{"id":"doc_abc"`), "expected bare object; got %q", got)
|
||||
@@ -72,7 +56,7 @@ func TestDelete_Success_JSON(t *testing.T) {
|
||||
func TestDelete_NotFound_404(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{err: errors.New("HTTP error 404: not found")}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, nil, svc, scriptedConfirm{}, "doc_missing")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, nil, svc, &testutil.ConfirmPrompter{}, "doc_missing")
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -83,7 +67,7 @@ func TestDelete_NotFound_404(t *testing.T) {
|
||||
func TestDelete_HTTPError_500(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{err: errors.New("HTTP error 500: internal")}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, nil, svc, scriptedConfirm{}, "doc_x")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, nil, svc, &testutil.ConfirmPrompter{}, "doc_x")
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -94,7 +78,7 @@ func TestDelete_HTTPError_500(t *testing.T) {
|
||||
func TestDelete_ConfirmYes(t *testing.T) {
|
||||
out, _ := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, nil, svc, scriptedConfirm{confirmReturn: true}, "doc_abc")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, nil, svc, &testutil.ConfirmPrompter{Answer: true}, "doc_abc")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, svc.calls, "user said yes ⇒ delete proceeds")
|
||||
assert.Contains(t, out.String(), "✓")
|
||||
@@ -103,7 +87,7 @@ func TestDelete_ConfirmYes(t *testing.T) {
|
||||
func TestDelete_ConfirmNo(t *testing.T) {
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, nil, svc, scriptedConfirm{confirmReturn: false}, "doc_abc")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, nil, svc, &testutil.ConfirmPrompter{Answer: false}, "doc_abc")
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, 0, svc.calls, "user said no ⇒ SDK must NOT be called")
|
||||
|
||||
@@ -119,7 +103,7 @@ func TestDelete_ConfirmNo(t *testing.T) {
|
||||
func TestDelete_AgentPrompterErrors(t *testing.T) {
|
||||
_, _ = iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, nil, svc, errPrompter{}, "doc_abc")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, nil, svc, &testutil.ConfirmPrompter{Err: errors.New("no tty")}, "doc_abc")
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, 0, svc.calls)
|
||||
|
||||
@@ -135,7 +119,7 @@ func TestDelete_AgentPrompterErrors(t *testing.T) {
|
||||
func TestDelete_NoYes_NonTTY_RequiresConfirmation(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, nil, svc, errPrompter{}, "doc_abc")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, nil, svc, &testutil.ConfirmPrompter{Err: errors.New("no tty")}, "doc_abc")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
||||
+5
-14
@@ -13,7 +13,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
@@ -123,19 +122,14 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
|
||||
|
||||
// Pagination is always 1-indexed internally. --all-pages walks; the
|
||||
// non-walking path returns the first page only.
|
||||
var (
|
||||
items []sdk.Knowledge
|
||||
total int64
|
||||
)
|
||||
var items []sdk.Knowledge
|
||||
if opts.AllPages {
|
||||
accum := make([]sdk.Knowledge, 0)
|
||||
page := 1
|
||||
for {
|
||||
chunk, t, err := svc.ListKnowledgeWithFilter(ctx, kbID, page, opts.PageSize, filter)
|
||||
for page := 1; ; page++ {
|
||||
chunk, total, err := svc.ListKnowledgeWithFilter(ctx, kbID, page, opts.PageSize, filter)
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "list documents")
|
||||
}
|
||||
total = t
|
||||
accum = append(accum, chunk...)
|
||||
if opts.Limit > 0 && len(accum) >= opts.Limit {
|
||||
accum = accum[:opts.Limit]
|
||||
@@ -144,16 +138,14 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
|
||||
if int64(page*opts.PageSize) >= total || len(chunk) == 0 {
|
||||
break
|
||||
}
|
||||
page++
|
||||
}
|
||||
items = accum
|
||||
} else {
|
||||
chunk, t, err := svc.ListKnowledgeWithFilter(ctx, kbID, 1, opts.PageSize, filter)
|
||||
chunk, _, err := svc.ListKnowledgeWithFilter(ctx, kbID, 1, opts.PageSize, filter)
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "list documents")
|
||||
}
|
||||
items = chunk
|
||||
total = t
|
||||
}
|
||||
if items == nil {
|
||||
items = []sdk.Knowledge{} // ensure JSON [] not null
|
||||
@@ -169,10 +161,9 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
|
||||
if opts.Limit > 0 && len(items) > opts.Limit {
|
||||
items = items[:opts.Limit]
|
||||
}
|
||||
_ = total // pagination metadata is no longer surfaced; --all-pages drains for callers who need everything
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, items, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, items)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
)
|
||||
@@ -165,17 +164,17 @@ func runUploadFromURL(ctx context.Context, opts *UploadOptions, jopts *cmdutil.J
|
||||
return cmdutil.WrapHTTP(err, "ingest URL %s", opts.FromURL)
|
||||
}
|
||||
|
||||
return printUploadSuccess(k, jopts, "Ingested", opts.Name, opts.FromURL)
|
||||
return renderUploadSuccess(k, jopts, "Ingested", opts.Name, opts.FromURL)
|
||||
}
|
||||
|
||||
// printUploadSuccess emits the post-upload result. JSON path is the bare
|
||||
// renderUploadSuccess emits the post-upload result. JSON path is the bare
|
||||
// Knowledge object; human path prints a checkmark line. Shared by single-
|
||||
// file upload and URL ingest; humanVerb varies (uploaded/ingested) and
|
||||
// fallbackDisplay covers the case when the server-recorded file_name is
|
||||
// blank (URL ingest pre-redirect).
|
||||
func printUploadSuccess(k *sdk.Knowledge, jopts *cmdutil.JSONOptions, humanVerb, customName, fallbackDisplay string) error {
|
||||
func renderUploadSuccess(k *sdk.Knowledge, jopts *cmdutil.JSONOptions, humanVerb, customName, fallbackDisplay string) error {
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, k, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, k)
|
||||
}
|
||||
displayed := customName
|
||||
if displayed == "" {
|
||||
@@ -214,5 +213,5 @@ func runUpload(ctx context.Context, opts *UploadOptions, jopts *cmdutil.JSONOpti
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "upload %s", path)
|
||||
}
|
||||
return printUploadSuccess(k, jopts, "Uploaded", opts.Name, path)
|
||||
return renderUploadSuccess(k, jopts, "Uploaded", opts.Name, path)
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
|
||||
@@ -63,7 +62,7 @@ func runUploadRecursive(ctx context.Context, opts *UploadOptions, jopts *cmdutil
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, recursiveResult{KBID: kbID}, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, recursiveResult{KBID: kbID})
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "(no files matched %q under %s)\n", opts.Glob, dir)
|
||||
return nil
|
||||
@@ -80,7 +79,7 @@ func runUploadRecursive(ctx context.Context, opts *UploadOptions, jopts *cmdutil
|
||||
}
|
||||
failed = append(failed, uploadOutcome{Path: p, Error: err.Error()})
|
||||
// Per-file progress lines are human progress signal; suppress
|
||||
// under --json so they don't precede the envelope on stdout.
|
||||
// under --json so they don't precede the JSON object on stdout.
|
||||
if !jopts.Enabled() {
|
||||
fmt.Fprintf(iostreams.IO.Out, "FAIL %s: %v\n", filepath.Base(p), err)
|
||||
}
|
||||
@@ -98,7 +97,7 @@ func runUploadRecursive(ctx context.Context, opts *UploadOptions, jopts *cmdutil
|
||||
|
||||
if jopts.Enabled() {
|
||||
result := recursiveResult{KBID: kbID, Uploaded: uploaded, Failed: failed}
|
||||
if err := format.WriteJSONFiltered(iostreams.IO.Out, result, jopts.Fields, jopts.JQ); err != nil {
|
||||
if err := jopts.Emit(iostreams.IO.Out, result); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
|
||||
+1
-2
@@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
@@ -63,7 +62,7 @@ func runView(ctx context.Context, opts *ViewOptions, jopts *cmdutil.JSONOptions,
|
||||
return cmdutil.WrapHTTP(err, "get document %q", id)
|
||||
}
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, doc, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, doc)
|
||||
}
|
||||
w := iostreams.IO.Out
|
||||
fmt.Fprintf(w, "ID: %s\n", doc.ID)
|
||||
|
||||
@@ -32,7 +32,6 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/build"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/compat"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/secrets"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
@@ -207,7 +206,7 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string)
|
||||
// the loader knows authoritatively which branch it took, time-based
|
||||
// derivation from ProbedAt is unreliable since SaveCache uses time.Now().
|
||||
//
|
||||
// v0.2 mapping:
|
||||
// Mapping:
|
||||
//
|
||||
// compat.OK → StatusOK
|
||||
// compat.SoftWarn → StatusWarn (server older but in-range; soft skew)
|
||||
@@ -336,7 +335,7 @@ func summarize(cs []Check) Summary {
|
||||
// code, set by the caller).
|
||||
func emit(jopts *cmdutil.JSONOptions, r Result) {
|
||||
if jopts.Enabled() {
|
||||
_ = format.WriteJSONFiltered(iostreams.IO.Out, r, jopts.Fields, jopts.JQ)
|
||||
_ = jopts.Emit(iostreams.IO.Out, r)
|
||||
return
|
||||
}
|
||||
for _, c := range r.Checks {
|
||||
|
||||
@@ -236,11 +236,12 @@ func TestDoctor_NoCache_BypassesCache(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoctor_VersionSkewWarns covers the v0.2 soft-skew path: server is older
|
||||
// TestDoctor_VersionSkewWarns covers the soft-skew path: server is older
|
||||
// than CLI by ≥ 1 minor (same major, in compat range) → server_version=warn,
|
||||
// envelope.ok stays true, all_passed=false (so agents reading just the
|
||||
// boolean still notice). The compat decision lives in cli/internal/compat;
|
||||
// this test pins the doctor-side mapping (compat.SoftWarn → StatusWarn).
|
||||
// summary.failed=0 (exit 0), summary.all_passed=false (so agents reading
|
||||
// just the boolean still notice). The compat decision lives in
|
||||
// cli/internal/compat; this test pins the doctor-side mapping
|
||||
// (compat.SoftWarn → StatusWarn).
|
||||
func TestDoctor_VersionSkewWarns(t *testing.T) {
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
@@ -315,7 +316,7 @@ func TestDoctor_HardErrorStillFails(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoctor_KeychainFallbackWarns covers credential_storage's v0.2 third
|
||||
// TestDoctor_KeychainFallbackWarns covers credential_storage's third
|
||||
// state: keyring unavailable, fell back to FileStore (agent containers,
|
||||
// headless CI, WSL without DBus). The check should warn — secrets still
|
||||
// persist (0600 file perms) but the OS-backed path was unreachable.
|
||||
@@ -439,7 +440,7 @@ func TestDoctor_HumanMarker_Warn(t *testing.T) {
|
||||
|
||||
// TestDoctor_WarnedField_OmittedAtZero protects the JSON wire compactness:
|
||||
// `warned` carries omitempty, so a clean run has no warned key. Existing
|
||||
// agents inspecting older envelopes shouldn't see a sudden new field unless
|
||||
// agents inspecting older outputs shouldn't see a sudden new field unless
|
||||
// it actually fired.
|
||||
func TestDoctor_WarnedField_OmittedAtZero(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
@@ -455,14 +456,14 @@ func TestDoctor_WarnedField_OmittedAtZero(t *testing.T) {
|
||||
emit(&cmdutil.JSONOptions{}, r)
|
||||
got := out.String()
|
||||
if strings.Contains(got, `"warned"`) {
|
||||
t.Errorf("envelope should omit `warned` field when zero, got %q", got)
|
||||
t.Errorf("output should omit `warned` field when zero, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoctor_RunE_FailReturnsSilentError is a behavior test on NewCmd: when
|
||||
// any check is fail, RunE must return cmdutil.SilentError so the framework
|
||||
// exit-1 path runs WITHOUT overwriting the data envelope emit() already
|
||||
// wrote. This is the v0.2 contract change from v0.1's "always nil".
|
||||
// TestDoctor_RunE_FailReturnsSilentError is a behavior test on NewCmd:
|
||||
// when any check is fail, RunE must return cmdutil.SilentError so the
|
||||
// framework exit-1 path runs without writing a second error line on top
|
||||
// of the data object emit() already wrote.
|
||||
//
|
||||
// SilenceErrors/SilenceUsage on the leaf cobra.Command suppress cobra's own
|
||||
// "Error: ..." + usage dump that would otherwise leak to stderr when running
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
)
|
||||
@@ -62,13 +61,15 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd.Flags().StringVar(&opts.Description, "description", "", "Knowledge base description (optional)")
|
||||
cmd.Flags().StringVar(&opts.EmbeddingModel, "embedding-model", "", "Embedding model ID (optional; server picks default when unset)")
|
||||
cmdutil.AddJSONFlags(cmd, kbCreateFields)
|
||||
aiclient.SetAgentHelp(cmd, "Creates a knowledge base under the active context. --name is required; --description and --embedding-model are optional. Returns data: full KnowledgeBase object including the new id.")
|
||||
_ = cmd.MarkFlagRequired("name")
|
||||
aiclient.SetAgentHelp(cmd, "Creates a knowledge base under the active context. --name is required; --description and --embedding-model are optional. Returns the full KnowledgeBase object including the new id.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runCreate(ctx context.Context, opts *CreateOptions, jopts *cmdutil.JSONOptions, svc CreateService) error {
|
||||
// Validate locally before any HTTP — keeps `input.invalid_argument`
|
||||
// distinct from a server-side 400.
|
||||
// Trim defensively in case a caller invokes runCreate directly with
|
||||
// whitespace; the cobra layer marks --name required so the empty-string
|
||||
// case is unreachable from the CLI.
|
||||
if strings.TrimSpace(opts.Name) == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--name is required")
|
||||
}
|
||||
@@ -87,7 +88,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, jopts *cmdutil.JSONOpti
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, created, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, created)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Created knowledge base %q (id: %s)\n", created.Name, created.ID)
|
||||
return nil
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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/prompt"
|
||||
)
|
||||
@@ -46,13 +45,13 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
||||
Prompts for confirmation by default when stdout is a TTY and --json is not set.
|
||||
Pass -y/--yes (global flag) to skip the prompt (required in agent / CI / piped contexts).
|
||||
|
||||
AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10 and
|
||||
returns an envelope describing the missing confirmation. NEVER auto-pass -y
|
||||
without the user's explicit go-ahead — the exit-10 protocol exists exactly to
|
||||
guard against unintended deletes.`,
|
||||
AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10
|
||||
and writes input.confirmation_required to stderr. NEVER auto-pass -y
|
||||
without the user's explicit go-ahead — the exit-10 protocol exists
|
||||
exactly to guard against unintended deletes.`,
|
||||
Example: ` weknora kb delete kb_abc # interactive confirm
|
||||
weknora kb delete kb_abc -y # no prompt
|
||||
weknora kb delete kb_abc -y --json # envelope output`,
|
||||
weknora kb delete kb_abc -y --json # bare {id, deleted:true} JSON`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
@@ -82,7 +81,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, jopts *cmdutil.JSONOpti
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, deleteResult{ID: id, Deleted: true}, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, deleteResult{ID: id, Deleted: true})
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted knowledge base %s\n", id)
|
||||
return nil
|
||||
|
||||
+20
-33
@@ -12,13 +12,14 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
"github.com/Tencent/WeKnora/cli/internal/testutil"
|
||||
)
|
||||
|
||||
// fakeDeleteSvc records what id was deleted.
|
||||
type fakeDeleteSvc struct {
|
||||
err error
|
||||
gotID string
|
||||
called bool
|
||||
err error
|
||||
gotID string
|
||||
called bool
|
||||
}
|
||||
|
||||
func (f *fakeDeleteSvc) DeleteKnowledgeBase(_ context.Context, id string) error {
|
||||
@@ -27,30 +28,16 @@ func (f *fakeDeleteSvc) DeleteKnowledgeBase(_ context.Context, id string) error
|
||||
return f.err
|
||||
}
|
||||
|
||||
// confirmPrompter scripts a Confirm answer; Input/Password are unused here.
|
||||
type confirmPrompter struct {
|
||||
answer bool
|
||||
err error
|
||||
asked bool
|
||||
}
|
||||
|
||||
func (c *confirmPrompter) Input(string, string) (string, error) { return "", prompt.ErrAgentNoPrompt }
|
||||
func (c *confirmPrompter) Password(string) (string, error) { return "", prompt.ErrAgentNoPrompt }
|
||||
func (c *confirmPrompter) Confirm(string, bool) (bool, error) {
|
||||
c.asked = true
|
||||
return c.answer, c.err
|
||||
}
|
||||
|
||||
func TestDelete_Success_WithForce(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{}
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
opts := &DeleteOptions{Yes: true}
|
||||
require.NoError(t, runDelete(context.Background(), opts, nil, svc, p, "kb_force"))
|
||||
|
||||
assert.True(t, svc.called)
|
||||
assert.Equal(t, "kb_force", svc.gotID)
|
||||
assert.False(t, p.asked, "--force must skip the confirm prompt")
|
||||
assert.False(t, p.Asked, "--force must skip the confirm prompt")
|
||||
assert.Contains(t, out.String(), "✓ Deleted")
|
||||
assert.Contains(t, out.String(), "kb_force")
|
||||
}
|
||||
@@ -58,7 +45,7 @@ func TestDelete_Success_WithForce(t *testing.T) {
|
||||
func TestDelete_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{err: errors.New("HTTP error 404: not found")}
|
||||
p := &confirmPrompter{}
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, nil, svc, p, "kb_missing")
|
||||
require.Error(t, err)
|
||||
|
||||
@@ -73,7 +60,7 @@ func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
// silently proceed in scripted contexts.
|
||||
iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{}
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, nil, svc, p, "kb_nontty")
|
||||
|
||||
require.Error(t, err)
|
||||
@@ -81,14 +68,14 @@ func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, typed.Code)
|
||||
assert.False(t, svc.called, "non-TTY without -y must not call DeleteKnowledgeBase")
|
||||
assert.False(t, p.asked, "non-TTY ⇒ Confirm is never invoked")
|
||||
assert.False(t, p.Asked, "non-TTY ⇒ Confirm is never invoked")
|
||||
assert.Equal(t, 10, cmdutil.ExitCode(err), "exit code 10 per destructive-write protocol")
|
||||
}
|
||||
|
||||
func TestDelete_JSONOutput(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{}
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
opts := &DeleteOptions{Yes: true}
|
||||
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.JSONOptions{}, svc, p, "kb_json"))
|
||||
|
||||
@@ -104,10 +91,10 @@ func TestDelete_JSONOutput(t *testing.T) {
|
||||
func TestDelete_ConfirmYes(t *testing.T) {
|
||||
_, _ = iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{answer: true}
|
||||
p := &testutil.ConfirmPrompter{Answer: true}
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, nil, svc, p, "kb_yes"))
|
||||
|
||||
assert.True(t, p.asked, "confirm prompt should fire on TTY without --force")
|
||||
assert.True(t, p.Asked, "confirm prompt should fire on TTY without --force")
|
||||
assert.True(t, svc.called, "answer=yes ⇒ delete proceeds")
|
||||
assert.Equal(t, "kb_yes", svc.gotID)
|
||||
}
|
||||
@@ -115,14 +102,14 @@ func TestDelete_ConfirmYes(t *testing.T) {
|
||||
func TestDelete_ConfirmNo(t *testing.T) {
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{answer: false}
|
||||
p := &testutil.ConfirmPrompter{Answer: false}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, nil, svc, p, "kb_no")
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeUserAborted, typed.Code)
|
||||
assert.True(t, p.asked)
|
||||
assert.True(t, p.Asked)
|
||||
assert.False(t, svc.called, "answer=no ⇒ delete must NOT run")
|
||||
assert.Contains(t, errBuf.String(), "Aborted")
|
||||
}
|
||||
@@ -130,7 +117,7 @@ func TestDelete_ConfirmNo(t *testing.T) {
|
||||
func TestDelete_ConfirmPrompterError(t *testing.T) {
|
||||
_, _ = iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{err: prompt.ErrAgentNoPrompt}
|
||||
p := &testutil.ConfirmPrompter{Err: prompt.ErrAgentNoPrompt}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, nil, svc, p, "kb_err")
|
||||
require.Error(t, err)
|
||||
|
||||
@@ -146,7 +133,7 @@ func TestDelete_JSONOut_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
// Exit-10 protocol must fire when -y is absent.
|
||||
iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{}
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
opts := &DeleteOptions{}
|
||||
err := runDelete(context.Background(), opts, &cmdutil.JSONOptions{}, svc, p, "kb_jtty")
|
||||
|
||||
@@ -154,21 +141,21 @@ func TestDelete_JSONOut_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, typed.Code)
|
||||
assert.False(t, p.asked, "--json must skip the prompt even on TTY")
|
||||
assert.False(t, p.Asked, "--json must skip the prompt even on TTY")
|
||||
assert.False(t, svc.called, "--json without -y must not call DeleteKnowledgeBase")
|
||||
assert.Equal(t, 10, cmdutil.ExitCode(err))
|
||||
}
|
||||
|
||||
func TestDelete_JSONOut_WithYes_Proceeds(t *testing.T) {
|
||||
// --json + -y is the agent happy-path: scripted caller with explicit
|
||||
// approval. Must call SDK and emit envelope.
|
||||
// approval. Must call SDK and emit the bare result object.
|
||||
out, _ := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{}
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
opts := &DeleteOptions{Yes: true}
|
||||
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.JSONOptions{}, svc, p, "kb_jtty"))
|
||||
|
||||
assert.False(t, p.asked, "-y must skip the prompt")
|
||||
assert.False(t, p.Asked, "-y must skip the prompt")
|
||||
assert.True(t, svc.called)
|
||||
assert.Contains(t, out.String(), `"deleted":true`)
|
||||
}
|
||||
|
||||
+1
-2
@@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
)
|
||||
@@ -111,7 +110,7 @@ func runEdit(ctx context.Context, opts *EditOptions, jopts *cmdutil.JSONOptions,
|
||||
return cmdutil.WrapHTTP(err, "edit knowledge base %s", id)
|
||||
}
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, updated, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, updated)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Updated knowledge base %s\n", id)
|
||||
return nil
|
||||
|
||||
+1
-3
@@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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/prompt"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
@@ -83,8 +82,7 @@ func runEmpty(ctx context.Context, opts *EmptyOptions, jopts *cmdutil.JSONOption
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out,
|
||||
emptyResult{ID: id, DeletedCount: deleted}, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, emptyResult{ID: id, DeletedCount: deleted})
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Emptied knowledge base %s (%d document(s) cleared)\n", id, deleted)
|
||||
return nil
|
||||
|
||||
+3
-4
@@ -11,7 +11,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
@@ -20,7 +19,7 @@ import (
|
||||
// kbListFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `kb list`. Nested config structs (chunking / image / FAQ / VLM / storage
|
||||
// / extract) are intentionally omitted — users wanting those can use `--jq`
|
||||
// against the full envelope.
|
||||
// against the full object.
|
||||
var kbListFields = []string{
|
||||
"id", "name", "type", "description",
|
||||
"is_temporary", "is_pinned",
|
||||
@@ -66,7 +65,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd.Flags().BoolVar(&opts.Pinned, "pinned", false, "Only show pinned knowledge bases")
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (0 = no cap, 1..10000 = explicit)")
|
||||
cmdutil.AddJSONFlags(cmd, kbListFields)
|
||||
aiclient.SetAgentHelp(cmd, "Lists all knowledge bases as a bare JSON array of {id, name, ...} objects (empty `[]` when none). --pinned restricts to pinned KBs (client-side filter). --limit caps the returned slice. Use `--json` (bare) for full objects, `--json id,name` to project fields, or `--jq` for arbitrary reshape.")
|
||||
aiclient.SetAgentHelp(cmd, "Lists all knowledge bases as a bare JSON array of {id, name, ...} objects (empty `[]` when none). --pinned restricts to pinned KBs (client-side filter). --limit caps the returned slice. Use `--json` (bare) for full objects, `--json=id,name` to project fields, or `--jq` for arbitrary reshape.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -105,7 +104,7 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, items, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, items)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
|
||||
+2
-3
@@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
)
|
||||
@@ -80,7 +79,7 @@ func runPin(ctx context.Context, opts *PinOptions, jopts *cmdutil.JSONOptions, s
|
||||
// both fresh-toggle and no-op paths. Human path prints a confirming
|
||||
// line; agents observe via the unchanged is_pinned field.
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, current, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, current)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ %s is already %s\n", id, state)
|
||||
return nil
|
||||
@@ -91,7 +90,7 @@ func runPin(ctx context.Context, opts *PinOptions, jopts *cmdutil.JSONOptions, s
|
||||
return cmdutil.WrapHTTP(err, "%s knowledge base %s", verb, id)
|
||||
}
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, updated, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, updated)
|
||||
}
|
||||
state := "pinned"
|
||||
if !updated.IsPinned {
|
||||
|
||||
+1
-2
@@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
@@ -63,7 +62,7 @@ func runView(ctx context.Context, opts *ViewOptions, jopts *cmdutil.JSONOptions,
|
||||
return cmdutil.WrapHTTP(err, "get knowledge base %q", id)
|
||||
}
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, kb, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, kb)
|
||||
}
|
||||
// Human: KEY: VALUE
|
||||
w := iostreams.IO.Out
|
||||
|
||||
@@ -16,7 +16,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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/projectlink"
|
||||
)
|
||||
@@ -105,7 +104,7 @@ func runLink(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, f *
|
||||
ProjectLinkPath: linkPath,
|
||||
}
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, r, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, r)
|
||||
}
|
||||
if kbName != "" {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Linked %s to %s (kb=%s, id=%s)\n", linkPath, ctxName, kbName, kbID)
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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/projectlink"
|
||||
)
|
||||
@@ -39,7 +38,7 @@ discovery that ` + "`--kb`" + ` resolution uses; you do not need to cd to the
|
||||
project root to unlink. Errors with input.invalid_argument when no link
|
||||
is present anywhere in the parent chain.`,
|
||||
Example: ` weknora unlink # remove the binding for this project
|
||||
weknora unlink --json # envelope output (CI / agents)`,
|
||||
weknora unlink --json # bare JSON (CI / agents)`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
@@ -74,8 +73,7 @@ func runUnlink(opts *UnlinkOptions, jopts *cmdutil.JSONOptions) error {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "remove %s", linkPath)
|
||||
}
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out,
|
||||
unlinkResult{ProjectLinkPath: linkPath}, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, unlinkResult{ProjectLinkPath: linkPath})
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Unlinked %s\n", linkPath)
|
||||
return nil
|
||||
|
||||
+18
-65
@@ -3,7 +3,6 @@ package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
@@ -30,62 +29,16 @@ import (
|
||||
// Execute is the entry point invoked by main(). Returns the process exit code.
|
||||
func Execute() int {
|
||||
root := NewRootCmd(cmdutil.New())
|
||||
// ExecuteC returns the actually-invoked leaf (or root when invocation
|
||||
// failed before dispatch); we use it to honor the leaf's --json and
|
||||
// inherited --format without walking the tree ourselves.
|
||||
cmd, err := root.ExecuteC()
|
||||
if err == nil {
|
||||
return 0
|
||||
if err := root.Execute(); err != nil {
|
||||
// Errors go to stderr (matches gh/aws/stripe). Stdout stays
|
||||
// empty (or holds partial success the command produced) so
|
||||
// downstream `--json | jq` pipelines never filter error shapes
|
||||
// out of the success stream. The typed exit code (3/4/5/6/7/10)
|
||||
// carries the error class.
|
||||
cmdutil.PrintError(iostreams.IO.Err, MapCobraError(err))
|
||||
return cmdutil.ExitCode(MapCobraError(err))
|
||||
}
|
||||
err = MapCobraError(err)
|
||||
if WantsJSONOutput(cmd) {
|
||||
cmdutil.PrintErrorEnvelope(iostreams.IO.Out, err)
|
||||
} else {
|
||||
cmdutil.PrintError(iostreams.IO.Err, err)
|
||||
}
|
||||
return cmdutil.ExitCode(err)
|
||||
}
|
||||
|
||||
// WantsJSONOutput reports whether cmd was invoked with --json, so error
|
||||
// output matches the success format. Persistent flags inherit automatically
|
||||
// via cmd.Flags().
|
||||
//
|
||||
// Falls back to scanning os.Args when cobra never reached the leaf — e.g.
|
||||
// unknown subcommand or unknown flag at root level. Without this, `weknora
|
||||
// bogus --json` would emit a human stderr line instead of the envelope the
|
||||
// agent asked for.
|
||||
//
|
||||
// Exported so the acceptance/contract test helper can replicate Execute()'s
|
||||
// envelope-printing path without having to call os.Exit-bound Execute() itself.
|
||||
func WantsJSONOutput(cmd *cobra.Command) bool {
|
||||
// --json is a StringSlice in v0.4 (optional field filter). A
|
||||
// Changed=true flag indicates the user requested JSON output.
|
||||
if f := cmd.Flags().Lookup("json"); f != nil && f.Changed {
|
||||
return true
|
||||
}
|
||||
return argsRequestJSON(os.Args[1:])
|
||||
}
|
||||
|
||||
// argsRequestJSON scans a flag-only slice for --json in the forms pflag
|
||||
// accepts. Used as a fallback when cobra short-circuits before flag parsing
|
||||
// (unknown command / unknown flag at root). Recognizes `--json` bare,
|
||||
// `--json id,name`, and `--json=id,name` forms.
|
||||
func argsRequestJSON(args []string) bool {
|
||||
for i, a := range args {
|
||||
switch {
|
||||
case a == "--json":
|
||||
return true
|
||||
case strings.HasPrefix(a, "--json="):
|
||||
return true
|
||||
default:
|
||||
// `--json id,name` — split into two args; we don't try to
|
||||
// distinguish "next arg is a value" vs "next arg is a flag"
|
||||
// here, since false positives just mean we emit JSON for an
|
||||
// error that would otherwise be human (still parseable).
|
||||
_ = i
|
||||
}
|
||||
}
|
||||
return false
|
||||
return 0
|
||||
}
|
||||
|
||||
// MapCobraError tags the textually-emitted cobra errors as cmdutil.FlagError
|
||||
@@ -97,8 +50,8 @@ func argsRequestJSON(args []string) bool {
|
||||
// cobra/command.go: required-flag / unknown-command). TestMapCobraError_PinnedPrefixes
|
||||
// guards against a silent break on cobra bumps.
|
||||
//
|
||||
// Exported so the acceptance/contract test helper can reuse the mapping when
|
||||
// replicating Execute()'s error-envelope path in-process.
|
||||
// Exported so the acceptance/contract test helper can reuse the mapping
|
||||
// when replicating Execute()'s stderr error-path in-process.
|
||||
func MapCobraError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
@@ -143,8 +96,8 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`,
|
||||
SilenceErrors: true,
|
||||
// Version makes cobra auto-register a `--version` global flag that
|
||||
// prints this string. We accept both `--version` and a `version`
|
||||
// subcommand; the subcommand still owns the richer `--json` envelope
|
||||
// output.
|
||||
// subcommand; the subcommand still owns the richer `--json` output
|
||||
// (build commit + date).
|
||||
Version: fmt.Sprintf("%s (commit %s, built %s)", v, commit, date),
|
||||
PersistentPreRun: func(c *cobra.Command, args []string) {
|
||||
// Propagate the global --context flag into the Factory for this
|
||||
@@ -191,10 +144,10 @@ func addGlobalFlags(cmd *cobra.Command) {
|
||||
pf.String("context", "", "Override the active context for this invocation (no disk write)")
|
||||
}
|
||||
|
||||
// agentAwareHelpFunc wraps cobra's default help to append the AI agent guidance
|
||||
// (Annotations[aiclient.AIAgentHelpKey]) only when an AI coding agent env var is
|
||||
// detected (CLAUDECODE / CURSOR_AGENT). Help-only render — no behavior switch
|
||||
// (v0.2 ADR-3).
|
||||
// agentAwareHelpFunc wraps cobra's default help to append the AI agent
|
||||
// guidance (Annotations[aiclient.AIAgentHelpKey]) only when an AI coding
|
||||
// agent env var is detected (CLAUDECODE / CURSOR_AGENT). Help-only
|
||||
// render — no behavior switch.
|
||||
func agentAwareHelpFunc(orig func(*cobra.Command, []string)) func(*cobra.Command, []string) {
|
||||
return func(c *cobra.Command, args []string) {
|
||||
orig(c, args)
|
||||
@@ -213,7 +166,7 @@ func agentAwareHelpFunc(orig func(*cobra.Command, []string)) func(*cobra.Command
|
||||
}
|
||||
|
||||
// versionFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `version`. Mirrors the version envelope payload.
|
||||
// `version`. Mirrors the version object payload.
|
||||
var versionFields = []string{"version", "commit", "date"}
|
||||
|
||||
// newVersionCmd is the only leaf command shipped in the foundation PR. It
|
||||
|
||||
@@ -140,36 +140,3 @@ func TestRoot_ContextFlagPropagation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestArgsRequestJSON(t *testing.T) {
|
||||
// v0.4 R-1: --json is now StringSlice (gh-style field filter). Any
|
||||
// `--json` token in args means the user wants JSON output, regardless
|
||||
// of value (boolean string parsing dropped).
|
||||
cases := []struct {
|
||||
name string
|
||||
args []string
|
||||
want bool
|
||||
}{
|
||||
{"empty", nil, false},
|
||||
{"--json bare", []string{"version", "--json"}, true},
|
||||
{"--json=id,name", []string{"kb", "list", "--json=id,name"}, true},
|
||||
{"--json=anything", []string{"version", "--json=foo"}, true},
|
||||
{"unrelated", []string{"bogus", "--kb", "x"}, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert.Equal(t, tc.want, argsRequestJSON(tc.args))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWantsJSONOutput(t *testing.T) {
|
||||
// Build a minimal *cobra.Command with the json flag directly so we test
|
||||
// the helper without going through cobra's parse pipeline. WantsJSONOutput
|
||||
// reads cmd.Flags() which on a fresh command equals LocalFlags().
|
||||
c := &cobra.Command{Use: "x"}
|
||||
c.Flags().Bool("json", false, "")
|
||||
assert.False(t, WantsJSONOutput(c), "default: --json unset")
|
||||
|
||||
require.NoError(t, c.Flags().Set("json", "true"))
|
||||
assert.True(t, WantsJSONOutput(c), "--json=true honored")
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
)
|
||||
@@ -144,7 +143,7 @@ func runChunks(ctx context.Context, opts *ChunksOptions, jopts *cmdutil.JSONOpti
|
||||
if results == nil {
|
||||
results = []*sdk.SearchResult{}
|
||||
}
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, results, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, results)
|
||||
}
|
||||
return renderChunkResults(results, opts.KBID)
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ func TestRunSearch_HumanOutput(t *testing.T) {
|
||||
assert.Contains(t, got, "doc-1")
|
||||
}
|
||||
|
||||
// JSON envelope must surface match_type so machine consumers / agents can
|
||||
// JSON output must surface match_type so machine consumers / agents can
|
||||
// reason about retrieval channels without re-implementing the wire format.
|
||||
// (Human renderer keeps default minimal — diagnostic info opt-in via --json.)
|
||||
func TestRunSearch_JSONIncludesMatchType(t *testing.T) {
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
@@ -120,7 +119,7 @@ done:
|
||||
if matches == nil {
|
||||
matches = []sdk.Knowledge{}
|
||||
}
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, matches, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, matches)
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
fmt.Fprintln(iostreams.IO.Out, "(no matches)")
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
@@ -91,7 +90,7 @@ func runKBSearch(ctx context.Context, opts *KBSearchOptions, jopts *cmdutil.JSON
|
||||
if matches == nil {
|
||||
matches = []sdk.KnowledgeBase{}
|
||||
}
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, matches, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, matches)
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
fmt.Fprintln(iostreams.IO.Out, "(no matches)")
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
@@ -100,7 +99,7 @@ done:
|
||||
if matches == nil {
|
||||
matches = []sdk.Session{}
|
||||
}
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, matches, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, matches)
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
fmt.Fprintln(iostreams.IO.Out, "(no matches)")
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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/prompt"
|
||||
)
|
||||
@@ -44,8 +43,8 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
||||
Prompts for confirmation by default when stdout is a TTY and --json is not set.
|
||||
Pass -y/--yes (global flag) to skip the prompt (required in agent / CI / piped contexts).
|
||||
|
||||
AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10 and
|
||||
returns an envelope describing the missing confirmation. NEVER auto-pass -y
|
||||
AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10
|
||||
and writes input.confirmation_required to stderr. NEVER auto-pass -y
|
||||
without the user's explicit go-ahead.`,
|
||||
Example: ` weknora session delete s_abc # interactive confirm
|
||||
weknora session delete s_abc -y # no prompt
|
||||
@@ -79,7 +78,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, jopts *cmdutil.JSONOpti
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, deleteResult{ID: id, Deleted: true}, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, deleteResult{ID: id, Deleted: true})
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted session %s\n", id)
|
||||
return nil
|
||||
|
||||
+5
-15
@@ -12,14 +12,12 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultPageSize = 30
|
||||
maxPageSize = 1000
|
||||
)
|
||||
@@ -96,19 +94,14 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
|
||||
since = d
|
||||
}
|
||||
|
||||
var (
|
||||
items []sdk.Session
|
||||
total int
|
||||
)
|
||||
var items []sdk.Session
|
||||
if opts.AllPages {
|
||||
accum := make([]sdk.Session, 0)
|
||||
page := 1
|
||||
for {
|
||||
chunk, t, err := svc.GetSessionsByTenant(ctx, page, opts.PageSize)
|
||||
for page := 1; ; page++ {
|
||||
chunk, total, err := svc.GetSessionsByTenant(ctx, page, opts.PageSize)
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "list sessions")
|
||||
}
|
||||
total = t
|
||||
accum = append(accum, chunk...)
|
||||
if opts.Limit > 0 && len(accum) >= opts.Limit {
|
||||
accum = accum[:opts.Limit]
|
||||
@@ -117,16 +110,14 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
|
||||
if page*opts.PageSize >= total || len(chunk) == 0 {
|
||||
break
|
||||
}
|
||||
page++
|
||||
}
|
||||
items = accum
|
||||
} else {
|
||||
chunk, t, err := svc.GetSessionsByTenant(ctx, 1, opts.PageSize)
|
||||
chunk, _, err := svc.GetSessionsByTenant(ctx, 1, opts.PageSize)
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "list sessions")
|
||||
}
|
||||
items = chunk
|
||||
total = t
|
||||
}
|
||||
if items == nil {
|
||||
items = []sdk.Session{} // JSON [] not null
|
||||
@@ -149,10 +140,9 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
|
||||
if opts.Limit > 0 && len(items) > opts.Limit {
|
||||
items = items[:opts.Limit]
|
||||
}
|
||||
_ = total // pagination metadata no longer surfaced; --all-pages drains for callers who need everything
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, items, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, items)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
||||
"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"
|
||||
)
|
||||
@@ -60,7 +59,7 @@ func runView(ctx context.Context, opts *ViewOptions, jopts *cmdutil.JSONOptions,
|
||||
return cmdutil.WrapHTTP(err, "get session %q", id)
|
||||
}
|
||||
if jopts.Enabled() {
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, s, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, s)
|
||||
}
|
||||
w := iostreams.IO.Out
|
||||
fmt.Fprintf(w, "ID: %s\n", s.ID)
|
||||
|
||||
Reference in New Issue
Block a user