Files
WeKnora/cli/cmd/session/ask.go
T
nullkey d3c03b2f34 feat(cli)!: v0.10 reliability, agent-UX, and command-surface hardening
A hardening + finalization pass over the agent-first CLI: correctness fixes,
richer machine-readable signals, flag/naming consistency, and a symmetric
config surface. Pre-1.0, so it includes breaking renames.

Correctness:
- agent update: resolve/validate --model/--rerank-model (was storing a bogus
  name verbatim, corrupting config.model_id).
- doctor: honor WEKNORA_HOST / WEKNORA_API_KEY (headless path no longer reports
  "no host configured").
- session ask / MCP session_ask: text answer was empty on non-TTY — the agent
  stream sets Done=true on an intermediate agent_query frame before the answer,
  and AgentAccumulator treated the first Done as terminal. Terminate on the
  `complete` event (new sdk.AgentResponseTypeComplete), not a per-frame Done.
- batch exit codes: any per-item failure collapses to operation.failed (exit 1),
  including `doc upload --recursive` partial failures — a permanent per-file
  failure (e.g. a duplicate) no longer surfaces as a retryable exit 7 an agent
  would loop on; per-item typed errors stay in the envelope.

Agent-first signals & discovery:
- error.exit_code in the envelope (type + exit_code disambiguate the
  input.invalid_argument exit-2-vs-5 split in one JSON read).
- meta.hint on empty content search and on draft doc create; doc wait fails fast
  on a never-parsing draft instead of hanging to --timeout.
- retrieval-readiness is visible in the natural flow: kb status / kb check emit
  retrieval_ready, and kb create hints the fix when no embedding model is bound
  — an unconfigured KB no longer looks silently healthy.
- schema contract completeness: every leaf declares output + >=1 example
  (drift-guarded); output strings match the meta actually emitted; chunk list
  and search docs now emit meta.total_count (both previously dropped it).
- schema tolerates a quoted multi-word command label; zero-state auth — and
  `link` with no profile — point at profile setup / the headless WEKNORA_KB_ID
  path instead of looping on `auth login`.
- id-addressed reads tolerate a redundant --kb (doc view/wait, chunk list/view
  accept and ignore it, declared in schema) so a carried-over --kb doesn't
  exit 2; streaming commands warn that --jq does not apply to an NDJSON stream.
- keep JSON-always as the default; --jq hints spell out the .data path.

Consistency & gating:
- doc create: drop the deprecated --name alias (--title only; pre-1.0 break).
- chunk list --limit aligned to 1..10000; model list --limit/-L with
  has_more/total_count; api write-gates -X PUT/PATCH (exit 10); skills install
  expands a leading ~.
- docs corrected: search docs / doc list --keyword help is case-insensitive
  (server does LOWER LIKE); AGENTS.md risk-action list (no phantom kb.init; add
  model.update / kb.config.set) and batch example (failed item carries `error`);
  session resume --message id comes from `message list`, not the stream.
- auth/profile ergonomics: env credentials are now first-class — `auth token`
  prints the active WEKNORA_API_KEY / WEKNORA_TOKEN, and auth login/logout/refresh
  give an env-aware message instead of looping on "run auth login". `auth logout`
  clears credentials but keeps the profile registered (host preserved for
  re-login); deleting a profile is `profile remove`'s job (clean logout/remove
  separation, matching gh / lark).

Config surface (symmetric read/write, in-place model edits):
- kb config now returns a secret-free KBModelConfigView (was {}); `kb config`
  reads, new `kb config set` writes; `kb init` removed (misnomer).
- kb create --chat-model: retrieval-ready in one step.
- model update: edit a model in place (id preserved, references survive) —
  rotate --api-key-stdin, change base-url / display-name / etc.
- session continue-stream renamed to session resume.

Docs: AGENTS.md is the single wire-contract source; CHANGELOG slimmed; stale
kb-init / continue-stream references removed; skill wire-vocab guard extended.
AGENTS.md / weknora-shared SKILL document retrieval_ready (a KB needs an
embedding model to be searchable), that --jq does not apply to NDJSON
streams, and the env-credential-first auth path; the KB quickstart example
now creates a retrieval-ready KB.
2026-07-06 22:53:01 +08:00

303 lines
12 KiB
Go

package sessioncmd
import (
"context"
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
"github.com/Tencent/WeKnora/cli/internal/sse"
sdk "github.com/Tencent/WeKnora/client"
)
// sessionAskFields enumerates the fields surfaced for `--jq` projection
// discovery on `session ask`: the json object's data fields + the raw SDK
// agent event vocabulary used by --format ndjson.
var sessionAskFields = []string{
"events", "session_id", "agent_id", "query",
// NDJSON init + SDK event fields.
"type", "profile", "response_type", "content", "done", "knowledge_references", "data",
}
// AskOptions captures `session ask` flag state.
type AskOptions struct {
AgentID string
Query string
SessionID string // --session: continue an existing session (skip auto-create)
// Reference adds bounded kb_id/chunk_id reference events to JSON/text.
Reference bool
// Verbose surfaces the projected execution trace in JSON/text,
// including reasoning, tools, and lifecycle events.
// NDJSON is always raw and is unaffected by presentation flags.
Verbose bool
}
// AskService is the narrow SDK surface this command depends on.
//
// CreateSession is called when --session is omitted — sessions are
// agent-agnostic at creation (verified against
// internal/handler/session/handler.go CreateSession, which only persists
// {title, description}). The agent ID is supplied per-request via
// AgentQARequest.AgentID, so the same session can be reused across
// agent / KB-chat invocations.
type AskService interface {
CreateSession(ctx context.Context, req *sdk.CreateSessionRequest) (*sdk.Session, error)
AgentQAStreamWithRequest(ctx context.Context, sessionID string, req *sdk.AgentQARequest, cb sdk.AgentEventCallback) error
}
// NewCmdAsk builds `weknora session ask --agent <agent-id> "<text>"`.
func NewCmdAsk(f *cmdutil.Factory) *cobra.Command {
opts := &AskOptions{}
cmd := &cobra.Command{
Use: `ask "<text>"`,
Short: "Ask a server-side agent in a session context",
Long: `Invoke a server-side agent within a session. If --session is omitted,
a new session is auto-created and its id is reported in the output for
the caller to thread follow-ups.
AI agents: this is the primary entrypoint for invoking custom agents.
The 'weknora agent' subtree handles CRUD only (list / view / create /
update / delete / status / check).
Modes:
--format json (default): one JSON envelope with answer events
--format text: live human-readable answer stream
--format ndjson: raw NDJSON event stream — init line (session_id,
agent_id) then SDK agent events verbatim. Debug.
Pass --reference to include bounded kb_id/chunk_id reference indexes. Pass
--verbose to include reasoning, tool activity, and lifecycle frames. Combine
both flags for the complete projected stream.`,
Example: ` weknora session ask --agent ag_x "Summarize Q3 sales"
weknora session ask --session sess_x --agent ag_x "Follow-up question"
weknora session ask --agent ag_x "Multi-step task" --format ndjson`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
opts.Query = strings.TrimSpace(args[0])
cli, err := f.Client()
if err != nil {
return err
}
return runAsk(c.Context(), opts, fopts, cli)
},
}
cmd.Flags().StringVarP(&opts.AgentID, "agent", "a", "", "Agent ID to invoke (required)")
_ = cmd.MarkFlagRequired("agent")
cmd.Flags().StringVar(&opts.SessionID, "session", "", "Continue an existing chat session (skip auto-create)")
cmd.Flags().BoolVar(&opts.Reference, "reference", false, "Include indexed references in JSON/text output")
cmd.Flags().BoolVar(&opts.Verbose, "verbose", false, "Include reasoning, tools, and lifecycle events in JSON/text output")
cmdutil.AddFormatFlag(cmd, sessionAskFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Invoke a custom agent in a session context. Default JSON returns a bounded answer-event projection. --reference adds indexed citations; --verbose adds reasoning, tools, and lifecycle events. --format ndjson streams raw SDK agent events; --format text renders the selected events live.",
RequiredFlags: []string{"<text> (positional)", "--agent"},
Examples: []string{
`weknora session ask --agent ag_x "Summarize Q3 sales"`,
`weknora session ask --agent ag_x "Summarize Q3 sales" --jq '[.data.events[].content] | join("")'`,
`weknora session ask --session sess_x --agent ag_x "Follow-up question"`,
},
Output: "Default --format json: {ok,data:{events:[answer...],session_id,agent_id,query}}. --reference adds kb_id/chunk_id reference events; --verbose adds execution events. --format ndjson remains raw.",
})
return cmd
}
func runAsk(ctx context.Context, opts *AskOptions, fopts *cmdutil.FormatOptions, svc AskService) error {
if opts.Query == "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "query argument cannot be empty")
}
if opts.AgentID == "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "agent-id argument cannot be empty")
}
if svc == nil {
return cmdutil.NewError(cmdutil.CodeServerError, "session ask: no SDK client available")
}
// --format selects the output shape: json (default) accumulates and
// emits one object, ndjson streams raw SDK agent events, text renders.
sessionID := opts.SessionID
autoCreated := false
if sessionID == "" {
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora session ask"})
if err != nil {
if cmdutil.IsCancelled(ctx, err) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "session ask cancelled")
}
code := cmdutil.ClassifyHTTPError(err)
if code == cmdutil.CodeNetworkError || code == cmdutil.CodeServerError {
code = cmdutil.CodeSessionCreateFailed
}
return cmdutil.Wrapf(code, err, "create chat session")
}
sessionID = sess.ID
autoCreated = true
}
if fopts != nil && fopts.Mode == cmdutil.FormatNDJSON {
return runAskNDJSON(ctx, opts, sessionID, svc)
}
if fopts != nil && fopts.Mode == cmdutil.FormatJSON {
return runAskJSON(ctx, opts, fopts, sessionID, svc)
}
// Surface auto-created session id up-front so a ^C mid-stream still
// leaves a recoverable pointer. Skipped in json/ndjson mode (session_id
// is in the output).
if autoCreated {
fmt.Fprintf(iostreams.IO.Err, "session: %s (use --session to continue)\n", sessionID)
}
return runAskText(ctx, opts, sessionID, autoCreated, svc)
}
// runAskNDJSON handles the --format ndjson path: emits a CLI init event at
// stream head, then passes every SDK agent event through verbatim as NDJSON
// lines. No buffering.
func runAskNDJSON(ctx context.Context, opts *AskOptions, sessionID string, svc AskService) error {
w := iostreams.IO.Out
// 1. Inject the CLI-managed init event at the head of the stream.
// Carries session pointer + agent id callers need for follow-up threading.
initEv := output.InitEvent{
SessionID: sessionID,
AgentID: opts.AgentID,
Profile: cmdutil.GetProfile(),
}
if err := output.EmitInit(w, initEv); err != nil {
return err
}
// 2. Open SDK stream and pass each agent event through as a bare NDJSON line.
req := &sdk.AgentQARequest{
Query: opts.Query,
AgentEnabled: true,
AgentID: opts.AgentID,
Channel: "api",
}
cb := func(r *sdk.AgentStreamResponse) error {
// NDJSON is the raw protocol/debug surface: do not filter events or
// mutate their payloads. JSON/text modes own presentation filtering.
return output.EmitSDKEvent(w, r)
}
if err := svc.AgentQAStreamWithRequest(ctx, sessionID, req, cb); err != nil {
if cmdutil.IsCancelled(ctx, err) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "session ask cancelled")
}
return cmdutil.WrapStream(err, "agent-chat stream")
}
return nil
}
// runAskText handles the --format text path. It renders the same
// projection as JSON immediately for both terminals and pipes.
func runAskText(ctx context.Context, opts *AskOptions, sessionID string, autoCreated bool, svc AskService) error {
req := &sdk.AgentQARequest{
Query: opts.Query,
AgentEnabled: true,
AgentID: opts.AgentID,
Channel: "api",
}
projector := sse.NewProjector(opts.Verbose, opts.Reference, "")
renderer := sse.NewTextRenderer(iostreams.IO.Out, opts.Verbose)
cb := func(r *sdk.AgentStreamResponse) error {
event, include := projector.Agent(r)
if !include {
return nil
}
return renderer.Write(event)
}
streamErr := svc.AgentQAStreamWithRequest(ctx, sessionID, req, cb)
if streamErr != nil {
if autoCreated {
fmt.Fprintf(iostreams.IO.Err, "session: %s (resume with --session %s)\n", sessionID, sessionID)
}
if cmdutil.IsCancelled(ctx, streamErr) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, streamErr, "session ask cancelled")
}
if projector.Seen() && !projector.Done() {
return cmdutil.Wrapf(cmdutil.CodeSSEStreamAborted, streamErr, "stream aborted before completion")
}
return cmdutil.WrapStream(streamErr, "agent-chat stream")
}
// Server closed cleanly but never sent a complete event — treat as aborted
// so agents don't silently emit a truncated answer as ok=true.
if !projector.Done() {
return cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")
}
return renderer.Close()
}
// runAskJSON handles the --format json path (the default): collect the
// projection and emit it in one normal success envelope.
func runAskJSON(ctx context.Context, opts *AskOptions, fopts *cmdutil.FormatOptions, sessionID string, svc AskService) error {
req := &sdk.AgentQARequest{
Query: opts.Query,
AgentEnabled: true,
AgentID: opts.AgentID,
Channel: "api",
}
projector := sse.NewProjector(opts.Verbose, opts.Reference, "")
events := make([]sse.ProjectedEvent, 0)
cb := func(r *sdk.AgentStreamResponse) error {
if event, include := projector.Agent(r); include {
events = append(events, event)
}
return nil
}
if err := svc.AgentQAStreamWithRequest(ctx, sessionID, req, cb); err != nil {
if cmdutil.IsCancelled(ctx, err) {
return askStreamError(cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "session ask cancelled"), sessionID)
}
return askStreamError(cmdutil.WrapStream(err, "agent-chat stream"), sessionID)
}
if !projector.Done() {
return askStreamError(
cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event"),
sessionID,
)
}
data := askResult{
Events: events,
SessionID: sessionID,
AgentID: opts.AgentID,
Query: opts.Query,
}
// Reaching here means fopts.Mode is FormatJSON (the only caller). Route
// through FormatOptions.Emit so --jq projection and the success-envelope
// contract apply. A nil fopts (direct-test entry) defaults to JSON.
if fopts == nil {
fopts = &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
}
return fopts.Emit(iostreams.IO.Out, data, nil)
}
func askStreamError(err *cmdutil.Error, sessionID string) *cmdutil.Error {
return err.WithDetail(map[string]any{"session_id": sessionID})
}
// askResult is the --format json data payload. The projector controls default
// versus verbose coverage.
type askResult struct {
Events []sse.ProjectedEvent `json:"events"`
SessionID string `json:"session_id"`
AgentID string `json:"agent_id"`
Query string `json:"query"`
}
// compile-time check: production SDK client satisfies AskService.
var _ AskService = (*sdk.Client)(nil)