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.
This commit is contained in:
nullkey
2026-07-02 15:53:51 +08:00
committed by lyingbug
parent 040a734766
commit d3c03b2f34
95 changed files with 1711 additions and 436 deletions
+32 -41
View File
@@ -36,12 +36,10 @@ fields are `omitempty` — they only appear when populated:
```
`data` is omitted on mutation-only success (no payload). `meta` carries list
counters (`count`, `has_more`) and batch successes/failures, and is omitted
when empty. `meta.next_cursor`, `meta.total_count`, and `meta.request_id` are
counters (`count`, `has_more`, `total_count`) and batch successes/failures, and is omitted
when empty. `meta.next_cursor` and `meta.request_id` are
reserved — not currently populated; planned for v0.8 when the SDK exposes
pagination cursors and response headers. `_notice` is reserved — open-map
infrastructure is in place for deprecation / version_skew / security notices;
the field is omitted until a producer is wired in v0.8. `profile` echoes the
pagination cursors and response headers. `profile` echoes the
resolved profile name and is omitted when no profile is configured.
### Stderr (error path)
@@ -55,27 +53,29 @@ Errors emit an error envelope on stderr (`--format json`) or prose
"error": {
"type": "auth.unauthenticated",
"message": "fetch current user: HTTP error 401",
"exit_code": 3,
"hint": "run `weknora auth login`",
"retry_command": "weknora auth login",
"retry_argv": ["weknora", "auth", "login"],
"retry_after_seconds": 0,
"risk": {"level": "destructive", "action": "noun.verb"},
"detail": {}
},
"_notice": {}
}
}
```
`type` is the typed code (see [Error code reference](#error-code-reference)
below). `hint` is prose; `retry_command` is the suggested next argv (single
shell-escaped string). For non-destructive errors agents may execute it; on
exit-10 (`input.confirmation_required`) it is informational only — the human
must approve the destructive write explicitly. See "Exit-10 anti-patterns" for
details. Note: tokens in `retry_command` are built via `fmt.Sprintf` with
user-supplied IDs unquoted — callers that auto-execute must shell-quote each
token (emitting as a JSON array is planned for v0.8).
`retry_after_seconds` mirrors HTTP `Retry-After`. `risk` tags high-risk writes.
`detail` carries structured per-error context (e.g. `unknown_subcommand`'s
`available[]` list).
below). `hint` is prose; `retry_argv` is the suggested next command as a JSON
array of argv tokens — exec it directly (no shell-splitting or quoting needed).
For non-destructive errors agents may execute it; on exit-10
(`input.confirmation_required`) it is informational only — the human must
approve the destructive write explicitly. See "Exit-10 anti-patterns" for
details.
`exit_code` embeds the process exit code (§2) so a single JSON read is
authoritative without observing `$?` — it also disambiguates the two
`input.invalid_argument` cases (a cobra parse error is exit 2, a typed-value
error is exit 5). `retry_after_seconds` mirrors HTTP `Retry-After`. `risk` tags
high-risk writes. `detail` carries structured per-error context (e.g.
`unknown_subcommand`'s `available[]` list).
### Buffered JSON and NDJSON streams (chat / session ask)
@@ -88,7 +88,7 @@ text` renders the same projection live.
`init` event at the head and passes all subsequent SDK events through verbatim:
```
{"type":"init","session_id":"...","kb_id":"...","profile":"...","agent_id":"..."}
{"type":"init","session_id":"...","kb_id":"...","profile":"..."} // chat: kb_id ; session ask: agent_id instead
{"response_type":"thinking","content":"..."}
{"response_type":"answer","content":"Hello"}
{"response_type":"tool_call","tool_calls":[...]}
@@ -99,15 +99,6 @@ MCP `chat` / `session_ask` return the same `events` shape and accept
`reference` / `verbose` booleans. NDJSON ignores both presentation flags and
always stays raw.
### `_notice` evolution policy
`_notice` is an open map. New keys are **additive non-breaking**; agents MUST
ignore unknown keys. v0.7 reserves three keys: `deprecation` / `version_skew` /
`security`. New keys follow snake_case convention. The `_notice` field is
currently always empty — producer wiring is planned for v0.8 when the SDK
exposes version metadata. The wire infrastructure is in place so adding a
producer in v0.8 will not change the envelope shape.
### CLI vs server SDK contract boundary
CLI 1.0 contract covers:
@@ -165,12 +156,12 @@ is or isn't aligned with.
| **WeKnora** | DELETE triggers exit-10 (`input.confirmation_required`); user bypasses with `-y/--yes` |
| **Rationale** | DELETE is irreversible. Most raw-API CLI commands rely on restricted credentials for safety, but self-hosted deployments may not have restricted-credential infrastructure available. Defensive default because agents are common consumers. |
### 3. `retry_command` distinct from `hint`
### 3. `retry_argv` distinct from `hint`
| | |
|---|---|
| **WeKnora** | two separate fields: `retry_command` (suggested next argv, directly-executable for non-destructive errors; informational only on exit-10) + `hint` (prose) |
| **Rationale** | Agents don't regex-extract argv from prose — known fragility. Trade-off: one extra envelope field. On exit-10, the user must approve the destructive write; agents surface `retry_command` for human review, not auto-execution. |
| **WeKnora** | two separate fields: `retry_argv` (suggested next command as a JSON argv array, directly-executable for non-destructive errors; informational only on exit-10) + `hint` (prose) |
| **Rationale** | Agents don't regex-extract argv from prose — known fragility. An argv array is exec-ready with no shell-splitting or quoting. Trade-off: one extra envelope field. On exit-10, the user must approve the destructive write; agents surface `retry_argv` for human review, not auto-execution. |
### 4. NDJSON event stream has no envelope wrapping
@@ -438,7 +429,7 @@ For common retry patterns, AI agents can hardcode:
Exit code 10 (`input.confirmation_required`) marks a destructive write where the
CLI refused to proceed without explicit user approval. The retry envelope includes
`retry_command` showing the exact argv that would proceed. AI agents must NEVER
`retry_argv` showing the exact argv that would proceed. AI agents must NEVER
auto-retry this exit code — every exit 10 is a user-in-the-loop decision.
**Don't do these:**
@@ -446,7 +437,7 @@ auto-retry this exit code — every exit 10 is a user-in-the-loop decision.
1. **Auto-add `-y/--yes` and retry.** The flag exists for the user, not the agent.
Surface the exit-10 envelope to the user verbatim and wait for explicit go-ahead.
2. **Parse the retry_command and run it.** The retry_command is *informational* --
2. **Parse the retry_argv and run it.** The retry_argv is *informational* --
showing what *would* execute. Running it without user input collapses two steps
the user is supposed to see.
@@ -465,7 +456,7 @@ auto-retry this exit code — every exit 10 is a user-in-the-loop decision.
## Stream recovery
The `weknora session continue-stream <session-id> --message <msg-id>` command resumes an SSE event stream for an existing assistant message. Use cases: network-blip recovery, long-running agent invocation polling, completed-stream inspection.
The `weknora session resume <session-id> --message <msg-id>` command resumes an SSE event stream for an existing assistant message. Use cases: network-blip recovery, long-running agent invocation polling, completed-stream inspection.
### Server semantics: replay-from-0, not cursor-resume
@@ -474,7 +465,7 @@ The server **replays all stored events from the start** of the assistant message
### Agent contract
1. **Dedupe by message_id** (or maintain a per-message event hash set). Naively processing all received events causes duplicate side effects (re-running tool calls, re-rendering answers).
2. **Capture message_id from the init event** of the original `chat` or `session ask` invocation — the CLI injects `{"event":"init", "session_id":"...", "message_id":"..."}` as the first NDJSON line.
2. **Get the assistant `message_id` from `weknora message list --session <id>`** (a live stream's `assistant_message_id` is not resumable once the message persists). `session resume` then injects `{"type":"init", "session_id":"...", "message_id":"...", "profile":"..."}` as the first NDJSON line.
3. **Handle `local.sse_stream_aborted` typed error**: server-side buffer expired (TTL exceeded) or process restarted (memory mode). The message is no longer recoverable; restart the original query.
### Server-side buffer TTL
@@ -484,11 +475,11 @@ The server **replays all stored events from the start** of the assistant message
| `STREAM_MANAGER_TYPE=redis` | **1 hour** (server-side; not configurable from the CLI) |
| `STREAM_MANAGER_TYPE=memory` (default) | **Process lifetime** (server restart = data loss; no explicit cleanup logic) |
After TTL, `weknora session continue-stream` returns the typed error `local.sse_stream_aborted`, which maps to exit code 1 per the Error code reference.
After TTL, `weknora session resume` returns the typed error `local.sse_stream_aborted`, which maps to exit code 1 per the Error code reference.
## Dry-run contract
The `--dry-run` flag is available on every mutation cobra command (`kb create/edit/delete`, `agent create/edit/delete`, `doc create/upload/fetch/delete`, `chunk delete`, `session delete`, `auth refresh/logout`, `link/unlink`, `profile add/remove`) and on `weknora api` (POST/PUT/PATCH/DELETE only; GET rejected with FlagError exit 2).
The `--dry-run` flag is available on every mutation cobra command (`kb create/update/delete`, `agent create/update/delete`, `doc create/upload/fetch/delete`, `chunk delete`, `session delete`, `auth refresh/logout`, `link/unlink`, `profile add/remove`) and on `weknora api` (POST/PUT/PATCH/DELETE only; GET rejected with FlagError exit 2).
### Envelope shape on dry-run
@@ -516,8 +507,8 @@ The dry-run path is **offline** — no SDK calls, no Factory.Client() init, no R
| `--dry-run` + `-y` | Equivalent to single `--dry-run`; `-y` is no-op (dry-run early-exits before ConfirmDestructive) |
| `--dry-run` + `api -X GET` (or default GET) | FlagError exit 2: "--dry-run requires explicit -X POST/PUT/PATCH/DELETE; default GET is read-only with no side effect to preview" |
| `--dry-run` + `--jq <expr>` | jq applied to envelope output normally |
| `--dry-run` + `kb edit my-kb` | plan.args contains user raw input (NOT ResolveKB-resolved); agent verifies kb name correctness |
| `--dry-run` + fetch-then-update (`kb edit / agent edit`) | plan.args contains user-explicit fields ONLY; agent infers server-side fetch-then-update preserves unmentioned fields |
| `--dry-run` + `kb update my-kb` | plan.args contains user raw input (NOT ResolveKB-resolved); agent verifies kb name correctness |
| `--dry-run` + fetch-then-update (`kb update / agent update`) | plan.args contains user-explicit fields ONLY; agent infers server-side fetch-then-update preserves unmentioned fields |
| `--dry-run` + body containing secrets (`--input` payload) | **plan.body echoes the full body to stdout** so the agent can verify what would be sent; avoid piping secret-bearing bodies through dry-run for inspection |
### Streaming commands explicitly excluded
@@ -532,7 +523,7 @@ echo '{"query":"...","kb":"..."}' | weknora api -X POST /api/v1/sessions/<id>/ag
Agents see the same `risk.action` string (in the form `noun.verb`) on three independent surfaces:
1. **Error envelope** — `envelope.error.risk.action` on an exit-10 confirmation-required error, so the agent can decide whether to escalate to the user. 11 unique values: `kb.delete`, `kb.edit`, `agent.delete`, `agent.edit`, `doc.delete`, `doc.delete_all`, `session.delete`, `chunk.delete`, `profile.remove`, `auth.logout`, `api.delete`.
1. **Error envelope** — `envelope.error.risk.action` on an exit-10 confirmation-required error, so the agent can decide whether to escalate to the user. 11 unique values: `kb.delete`, `kb.update`, `agent.delete`, `agent.update`, `doc.delete`, `doc.delete_all`, `session.delete`, `chunk.delete`, `profile.remove`, `auth.logout`, `api.delete`.
2. **Help text** — a `Risk: <action> (destructive)` line prepended to the top of `--help` output on the 9 destructive cobra commands. `weknora api` is intentionally excluded: it is a generic HTTP passthrough whose risk depends on the method, so a static Risk: line would mislead for non-DELETE methods.
@@ -582,7 +573,7 @@ Required-input idioms in this codebase:
- Positional required: `cobra.ExactArgs(N)` or `cobra.MinimumNArgs(1)`
- Flag required: `cmd.MarkFlagRequired("flag")`
- Custom required (e.g., `agent edit` needs at-least-one-edit-flag): RunE-level validation that returns `input.invalid_argument`
- Custom required (e.g., `agent update` needs at-least-one-edit-flag): RunE-level validation that returns `input.invalid_argument`
- Mutex: `cmd.MarkFlagsMutuallyExclusive("a", "b")`
Reasons hard-required-flags is the v0.5+ default: