2026-05-15 18:35:30 +00:00
package agentcmd
import (
"context"
"fmt"
"io"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// CreateService is the narrow SDK surface this command depends on.
// *sdk.Client satisfies it via duck typing.
type CreateService interface {
CreateAgent ( ctx context . Context , req * sdk . CreateAgentRequest ) ( * sdk . Agent , error )
CopyAgent ( ctx context . Context , id string ) ( * sdk . Agent , error )
UpdateAgent ( ctx context . Context , id string , req * sdk . UpdateAgentRequest ) ( * sdk . Agent , error )
}
// CreateOptions captures flag state. SystemPromptReader and ConfigFileBody
// are populated from --system-prompt-file and --config-file respectively
// (or stdin when the value is "-"). The embedded flags struct tracks "was
// set" bits so MergeAgentConfig can distinguish "user passed --foo zero"
// from "user did not pass --foo".
type CreateOptions struct {
Name string
Model string
Description string
SystemPrompt string
SystemPromptReader io . Reader
AgentMode string
KBs [ ] string
KBSelectionMode string
RerankModel string
Temperature float64
From string
ConfigFileBody io . Reader
ConfigFileKind string // "yaml" or "json"
GenerateSkeleton bool
feat(cli): --dry-run + risk metadata + validation parity on 19 mutations
Two intertwined agent safety nets that share the same files:
1. --dry-run flag for offline preview of mutation commands
2. Risk: metadata + SetRisk helper for destructive command surfaces
Coverage (19 mutation commands with --dry-run):
kb.create/edit/delete agent.create/edit/delete
doc.create/upload/fetch/delete doc.delete_all (special variant)
session.delete chunk.delete profile.add/remove
auth.refresh/logout link unlink
api.{post,put,patch,delete} (api.get + --dry-run rejected, exit 2)
Envelope additions (omitempty in non-dry-run paths):
meta.dry_run: bool true when --dry-run was used
meta.plan: map {action, args} per the per-command taxonomy
Risk: metadata
--------------
cmdutil.SetRisk(cmd, action) stamps cobra.Annotations with
risk.level=destructive + risk.action=<action> on the 9 destructive
commands. The SetAgentHelp wrapper prepends a "Risk: <action>
(destructive)" line in the default text help path so agents see a clear
warning before parsing Usage. WEKNORA_AGENT_HELP=1 JSON path stays
unchanged — structured agent-help already carries warnings[].
Validation parity with the live path
------------------------------------
Every pure-local validation (flag presence, mutual exclusion, enum
bounds, URL/regex format, ResolveKBLocal for KB resolution that does not
require an SDK call) runs BEFORE the dry-run gate. This matches the
industry-standard "preview shows what live would do" contract:
--dry-run accepts exactly the same invocations the live path accepts and
rejects exactly the same invocations the live path rejects, modulo the
side-effecting work itself.
The side-effecting work (SDK calls, file writes, keyring writes, server-
side name → id resolution) is what --dry-run actually gates. Each
mutation file pairs its RunE validation block with a regression test
under *_dry_run_test.go / dryrun_validation_test.go so future refactors
don't reintroduce the gap.
Helper surface
--------------
- HandleDryRun(cmd, dryRun, plan) extracts the early-return so the
19 RunE call sites stay 3 lines each.
- EmitDryRun routes through FormatOptions.Emit, inheriting _notice /
TTY indent / --jq filtering for free.
- ResolveKBLocal mirrors ResolveKB but never calls the SDK; dry-run
paths use it so the plan reports the raw --kb value (UUID or name)
without a name → id lookup.
Streaming commands (chat, session ask, session continue-stream) are
deliberately excluded: a buffered plan makes no sense for an event
stream.
Lock semantics in the dry-run path:
- destructive + --dry-run: exit 0, no exit-10 confirmation prompt
- --dry-run + -y: byte-identical envelope to --dry-run alone
- --dry-run + --jq: filter applies to the preview envelope normally
2026-05-27 20:28:48 +00:00
DryRun bool
2026-05-15 18:35:30 +00:00
flags createFlagSet // populated in PreRunE for *Set bits
}
// createFlagSet records which hot-path flags the user explicitly passed so
// MergeAgentConfig knows which fields to overlay onto the base config.
type createFlagSet struct {
agentModeSet bool
systemPromptSet bool
rerankModelSet bool
temperatureSet bool
kbSelectionModeSet bool
kbsSet bool
}
2026-05-15 18:42:18 +00:00
const agentCreateExample = ` weknora agent create "Support Bot" -- model < model - id >
2026-05-29 12:06:30 +00:00
weknora agent create "Code Reviewer" -- model < model - id > -- system - prompt - file . / prompt . md -- attach - kb kb_eng -- attach - kb kb_arch
2026-05-15 18:42:18 +00:00
weknora agent create "From Template" -- model < model - id > -- from ag_existing
2026-05-15 18:35:30 +00:00
weknora agent create -- generate - skeleton > my - agent . yaml
2026-05-15 18:42:18 +00:00
weknora agent create "Tuned" -- model < model - id > -- config - file . / my - agent . yaml `
2026-05-15 18:35:30 +00:00
const agentCreateLong = ` Create a new custom agent .
2026-06-26 12:40:59 +00:00
-- model is required ( an agent without a model cannot invoke ) ; discover a
valid model id with ' weknora model list ' . The 7
2026-05-15 18:35:30 +00:00
optional hot - path flags cover the most frequently set AgentConfig fields ;
for the remaining 27 use -- config - file with a YAML or JSON document
matching the AgentConfig schema ( run -- generate - skeleton to get a
ready - to - edit template ) .
Precedence when both a config file and hot - path flags are supplied :
hot - path flag > config - file value > server default
-- from < id > copies an existing agent ( SDK CopyAgent ) then applies any
2026-05-29 12:06:30 +00:00
hot - path overrides via UpdateAgent . -- attach - kb on -- from REPLACES the copied
2026-05-15 18:35:30 +00:00
agent ' s KB list ( not merge ) — matches surgical - flag semantics .
AI agents : writes a new resource server - side . Failure surfaces as a
typed code on stderr : input . invalid_argument ( bad flags , bad file , or
bad model ) , resource . not_found ( -- from < missing > ) , auth . unauthenticated . `
// NewCmdCreate builds `weknora agent create <name> --model <id>`.
func NewCmdCreate ( f * cmdutil . Factory ) * cobra . Command {
opts := & CreateOptions { }
var systemPromptFile , configFile string
cmd := & cobra . Command {
Use : "create <name>" ,
Short : "Create a new custom agent" ,
Long : agentCreateLong ,
Example : agentCreateExample ,
// Allow 0 args for --generate-skeleton; PreRunE enforces the real
// arity rule once it knows whether skeleton mode is active.
Args : cobra . MaximumNArgs ( 1 ) ,
PreRunE : func ( cmd * cobra . Command , args [ ] string ) error {
if opts . GenerateSkeleton {
return nil
}
if len ( args ) != 1 {
return cmdutil . NewFlagError ( fmt . Errorf ( "accepts 1 arg, received %d" , len ( args ) ) )
}
opts . Name = args [ 0 ]
if opts . Model == "" {
return cmdutil . NewFlagError ( fmt . Errorf ( ` required flag(s) "model" not set ` ) )
}
opts . flags . agentModeSet = cmd . Flags ( ) . Changed ( "agent-mode" )
opts . flags . systemPromptSet = cmd . Flags ( ) . Changed ( "system-prompt" ) || cmd . Flags ( ) . Changed ( "system-prompt-file" )
opts . flags . rerankModelSet = cmd . Flags ( ) . Changed ( "rerank-model" )
opts . flags . temperatureSet = cmd . Flags ( ) . Changed ( "temperature" )
opts . flags . kbSelectionModeSet = cmd . Flags ( ) . Changed ( "kb-selection-mode" )
2026-05-29 12:06:30 +00:00
opts . flags . kbsSet = cmd . Flags ( ) . Changed ( "attach-kb" )
2026-05-15 18:35:30 +00:00
2026-05-15 18:42:18 +00:00
// --temperature is bounded 0.0..2.0. Reject out-of-range
// early with a typed input.invalid_argument so users don't
// burn a roundtrip on a value the server would also reject.
2026-05-15 18:35:30 +00:00
if opts . flags . temperatureSet && ( opts . Temperature < 0.0 || opts . Temperature > 2.0 ) {
return cmdutil . NewError ( cmdutil . CodeInputInvalidArgument ,
fmt . Sprintf ( "--temperature must be in 0.0..2.0, got %g" , opts . Temperature ) )
}
2026-06-26 12:40:59 +00:00
// Reject an unknown --agent-mode / --kb-selection-mode up front
// (typed exit 5) rather than letting the server fail the create.
if err := validateAgentModeFlags ( & opts . AgentMode , & opts . KBSelectionMode ) ; err != nil {
return err
}
2026-05-15 18:35:30 +00:00
if systemPromptFile != "" {
2026-05-15 18:42:18 +00:00
r , err := cmdutil . OpenInput ( systemPromptFile )
2026-05-15 18:35:30 +00:00
if err != nil {
return cmdutil . NewError ( cmdutil . CodeInputInvalidArgument , fmt . Sprintf ( "--system-prompt-file: %v" , err ) )
}
opts . SystemPromptReader = r
}
if configFile != "" {
r , kind , err := openConfigFile ( configFile )
if err != nil {
return cmdutil . NewError ( cmdutil . CodeInputInvalidArgument , fmt . Sprintf ( "--config-file: %v" , err ) )
}
opts . ConfigFileBody = r
opts . ConfigFileKind = kind
}
return nil
} ,
RunE : func ( cmd * cobra . Command , args [ ] string ) error {
2026-05-17 17:38:16 +00:00
fopts , err := cmdutil . CheckFormatFlag ( cmd )
2026-05-15 18:35:30 +00:00
if err != nil {
return err
}
2026-05-17 17:38:16 +00:00
fopts . ResolveDefault ( iostreams . IO . IsStdoutTTY ( ) )
feat(cli): --dry-run + risk metadata + validation parity on 19 mutations
Two intertwined agent safety nets that share the same files:
1. --dry-run flag for offline preview of mutation commands
2. Risk: metadata + SetRisk helper for destructive command surfaces
Coverage (19 mutation commands with --dry-run):
kb.create/edit/delete agent.create/edit/delete
doc.create/upload/fetch/delete doc.delete_all (special variant)
session.delete chunk.delete profile.add/remove
auth.refresh/logout link unlink
api.{post,put,patch,delete} (api.get + --dry-run rejected, exit 2)
Envelope additions (omitempty in non-dry-run paths):
meta.dry_run: bool true when --dry-run was used
meta.plan: map {action, args} per the per-command taxonomy
Risk: metadata
--------------
cmdutil.SetRisk(cmd, action) stamps cobra.Annotations with
risk.level=destructive + risk.action=<action> on the 9 destructive
commands. The SetAgentHelp wrapper prepends a "Risk: <action>
(destructive)" line in the default text help path so agents see a clear
warning before parsing Usage. WEKNORA_AGENT_HELP=1 JSON path stays
unchanged — structured agent-help already carries warnings[].
Validation parity with the live path
------------------------------------
Every pure-local validation (flag presence, mutual exclusion, enum
bounds, URL/regex format, ResolveKBLocal for KB resolution that does not
require an SDK call) runs BEFORE the dry-run gate. This matches the
industry-standard "preview shows what live would do" contract:
--dry-run accepts exactly the same invocations the live path accepts and
rejects exactly the same invocations the live path rejects, modulo the
side-effecting work itself.
The side-effecting work (SDK calls, file writes, keyring writes, server-
side name → id resolution) is what --dry-run actually gates. Each
mutation file pairs its RunE validation block with a regression test
under *_dry_run_test.go / dryrun_validation_test.go so future refactors
don't reintroduce the gap.
Helper surface
--------------
- HandleDryRun(cmd, dryRun, plan) extracts the early-return so the
19 RunE call sites stay 3 lines each.
- EmitDryRun routes through FormatOptions.Emit, inheriting _notice /
TTY indent / --jq filtering for free.
- ResolveKBLocal mirrors ResolveKB but never calls the SDK; dry-run
paths use it so the plan reports the raw --kb value (UUID or name)
without a name → id lookup.
Streaming commands (chat, session ask, session continue-stream) are
deliberately excluded: a buffered plan makes no sense for an event
stream.
Lock semantics in the dry-run path:
- destructive + --dry-run: exit 0, no exit-10 confirmation prompt
- --dry-run + -y: byte-identical envelope to --dry-run alone
- --dry-run + --jq: filter applies to the preview envelope normally
2026-05-27 20:28:48 +00:00
planArgs := map [ string ] any { "name" : opts . Name }
if configFile != "" {
planArgs [ "config" ] = configFile
}
if handled , err := cmdutil . HandleDryRun ( cmd , opts . DryRun , cmdutil . DryRunPlan {
Action : "agent.create" ,
Args : planArgs ,
} ) ; handled {
return err
}
2026-05-15 18:35:30 +00:00
cli , err := f . Client ( )
if err != nil {
return err
}
2026-06-26 12:40:59 +00:00
// Resolve --model / --rerank-model (id or name) and validate they
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-02 07:53:51 +00:00
// exist, matching the id-or-name policy of `kb config set`. A bogus name
2026-06-26 12:40:59 +00:00
// fails fast here instead of creating an agent whose model never
// resolves at run time.
if opts . Model , err = cmdutil . ResolveModelRef ( cmd . Context ( ) , cli , opts . Model , "KnowledgeQA" ) ; err != nil {
return err
}
if opts . RerankModel , err = cmdutil . ResolveModelRef ( cmd . Context ( ) , cli , opts . RerankModel , "Rerank" ) ; err != nil {
return err
}
// Resolve --attach-kb values (id or name) to canonical ids,
// matching the --kb flag's id-or-name policy. Without this a raw
// name is stored verbatim as a kb_id, silently creating an agent
// whose KB reference never resolves at run time.
if len ( opts . KBs ) > 0 {
resolved := make ( [ ] string , 0 , len ( opts . KBs ) )
for _ , raw := range opts . KBs {
id , rerr := cmdutil . ResolveKBFlag ( cmd . Context ( ) , cli , raw )
if rerr != nil {
return rerr
}
resolved = append ( resolved , id )
}
opts . KBs = resolved
}
2026-05-17 17:38:16 +00:00
return runCreate ( cmd . Context ( ) , opts , fopts , cli )
2026-05-15 18:35:30 +00:00
} ,
}
// Required (enforced in PreRunE rather than cmd.MarkFlagRequired so
// --generate-skeleton can bypass it — cobra's MarkFlagRequired runs
// before PreRunE and would otherwise block the skeleton path).
2026-06-26 12:40:59 +00:00
cmd . Flags ( ) . StringVar ( & opts . Model , "model" , "" , "LLM model id or name (required, except with --generate-skeleton)" )
2026-05-15 18:35:30 +00:00
// Hot-path (8 flag names, 7 distinct config fields)
cmd . Flags ( ) . StringVar ( & opts . Description , "description" , "" , "Agent description" )
cmd . Flags ( ) . StringVar ( & opts . SystemPrompt , "system-prompt" , "" , "System prompt text (mutex with --system-prompt-file)" )
cmd . Flags ( ) . StringVar ( & systemPromptFile , "system-prompt-file" , "" , "Read system prompt from FILE, or '-' for stdin" )
cmd . MarkFlagsMutuallyExclusive ( "system-prompt" , "system-prompt-file" )
2026-06-26 12:40:59 +00:00
cmd . Flags ( ) . StringVar ( & opts . AgentMode , "agent-mode" , "" , "Agent operating mode: " + strings . Join ( agentModeValues , " | " ) )
cmd . Flags ( ) . StringSliceVar ( & opts . KBs , "attach-kb" , nil , "Attach a knowledge base id (repeatable); aligns with 'agent update --add-kb'" )
cmd . Flags ( ) . StringVar ( & opts . KBSelectionMode , "kb-selection-mode" , "" , "KB selection mode: " + strings . Join ( kbSelectionModeValues , " | " ) )
cmd . Flags ( ) . StringVar ( & opts . RerankModel , "rerank-model" , "" , "Rerank model id or name" )
2026-05-15 18:35:30 +00:00
cmd . Flags ( ) . Float64Var ( & opts . Temperature , "temperature" , 0.0 , "Generation temperature (0.0..2.0)" )
// Power-user / utility
cmd . Flags ( ) . StringVar ( & opts . From , "from" , "" , "Copy from existing agent id (then apply other flags)" )
cmd . Flags ( ) . StringVar ( & configFile , "config-file" , "" , "Full AgentConfig YAML or JSON (use '-' for stdin)" )
cmd . Flags ( ) . BoolVar ( & opts . GenerateSkeleton , "generate-skeleton" , false , "Emit blank AgentConfig YAML to stdout and exit" )
2026-05-17 17:38:16 +00:00
cmdutil . AddFormatFlag ( cmd , agentViewFields ... )
feat(cli): --dry-run + risk metadata + validation parity on 19 mutations
Two intertwined agent safety nets that share the same files:
1. --dry-run flag for offline preview of mutation commands
2. Risk: metadata + SetRisk helper for destructive command surfaces
Coverage (19 mutation commands with --dry-run):
kb.create/edit/delete agent.create/edit/delete
doc.create/upload/fetch/delete doc.delete_all (special variant)
session.delete chunk.delete profile.add/remove
auth.refresh/logout link unlink
api.{post,put,patch,delete} (api.get + --dry-run rejected, exit 2)
Envelope additions (omitempty in non-dry-run paths):
meta.dry_run: bool true when --dry-run was used
meta.plan: map {action, args} per the per-command taxonomy
Risk: metadata
--------------
cmdutil.SetRisk(cmd, action) stamps cobra.Annotations with
risk.level=destructive + risk.action=<action> on the 9 destructive
commands. The SetAgentHelp wrapper prepends a "Risk: <action>
(destructive)" line in the default text help path so agents see a clear
warning before parsing Usage. WEKNORA_AGENT_HELP=1 JSON path stays
unchanged — structured agent-help already carries warnings[].
Validation parity with the live path
------------------------------------
Every pure-local validation (flag presence, mutual exclusion, enum
bounds, URL/regex format, ResolveKBLocal for KB resolution that does not
require an SDK call) runs BEFORE the dry-run gate. This matches the
industry-standard "preview shows what live would do" contract:
--dry-run accepts exactly the same invocations the live path accepts and
rejects exactly the same invocations the live path rejects, modulo the
side-effecting work itself.
The side-effecting work (SDK calls, file writes, keyring writes, server-
side name → id resolution) is what --dry-run actually gates. Each
mutation file pairs its RunE validation block with a regression test
under *_dry_run_test.go / dryrun_validation_test.go so future refactors
don't reintroduce the gap.
Helper surface
--------------
- HandleDryRun(cmd, dryRun, plan) extracts the early-return so the
19 RunE call sites stay 3 lines each.
- EmitDryRun routes through FormatOptions.Emit, inheriting _notice /
TTY indent / --jq filtering for free.
- ResolveKBLocal mirrors ResolveKB but never calls the SDK; dry-run
paths use it so the plan reports the raw --kb value (UUID or name)
without a name → id lookup.
Streaming commands (chat, session ask, session continue-stream) are
deliberately excluded: a buffered plan makes no sense for an event
stream.
Lock semantics in the dry-run path:
- destructive + --dry-run: exit 0, no exit-10 confirmation prompt
- --dry-run + -y: byte-identical envelope to --dry-run alone
- --dry-run + --jq: filter applies to the preview envelope normally
2026-05-27 20:28:48 +00:00
cmdutil . AddDryRunFlag ( cmd , & opts . DryRun )
2026-05-29 12:06:30 +00:00
cmdutil . SetAgentHelp ( cmd , cmdutil . AgentHelp {
2026-06-26 12:40:59 +00:00
UsedFor : "Create a new custom agent. --model is required and accepts a model id or name; --attach-kb (repeatable) accepts KB ids or names. Emits the created Agent object." ,
2026-05-29 12:06:30 +00:00
RequiredFlags : [ ] string { "<name> (positional)" , "--model" } ,
2026-06-26 12:40:59 +00:00
Examples : [ ] string {
` weknora agent create "Support Bot" --model gpt-4o ` ,
` weknora agent create "Support Bot" --model gpt-4o --attach-kb kb_eng --system-prompt "You are a support assistant." ` ,
` weknora agent create --generate-skeleton # print a blank config to fill in (no --model needed) ` ,
} ,
Output : "envelope.data is the created Agent object with id, name, config" ,
2026-05-29 12:06:30 +00:00
} )
2026-05-15 18:35:30 +00:00
return cmd
}
2026-05-17 17:38:16 +00:00
func runCreate ( ctx context . Context , opts * CreateOptions , fopts * cmdutil . FormatOptions , svc CreateService ) error {
2026-05-15 18:35:30 +00:00
if opts . GenerateSkeleton {
return cmdutil . GenerateAgentSkeleton ( iostreams . IO . Out )
}
// 1. Build base AgentConfig from --config-file (if any), else zero.
// (For --from, the copied agent's existing config becomes the base
// instead — set after CopyAgent below, before MergeAgentConfig.)
var base sdk . AgentConfig
if opts . ConfigFileBody != nil {
parsed , err := cmdutil . LoadAgentConfig ( opts . ConfigFileBody , opts . ConfigFileKind )
if err != nil {
return cmdutil . NewError ( cmdutil . CodeInputInvalidArgument , err . Error ( ) )
}
base = * parsed
}
// 2. Resolve system prompt (file/stdin > flag string)
if opts . SystemPromptReader != nil {
body , err := io . ReadAll ( opts . SystemPromptReader )
if err != nil {
return cmdutil . NewError ( cmdutil . CodeInputInvalidArgument , fmt . Sprintf ( "--system-prompt-file read: %v" , err ) )
}
opts . SystemPrompt = strings . TrimSpace ( string ( body ) )
}
// 3. Either copy-then-update, or create from scratch. For --from we
// must seed `base` from the copied agent's existing config FIRST so
// MergeAgentConfig preserves source fields the user did not override
// (e.g. SystemPrompt, AgentMode, KB list). Without this seeding the
// surgical overrides would ship UpdateAgent with the other 33 fields
// zeroed, clobbering source state.
if opts . From != "" {
copied , err := svc . CopyAgent ( ctx , opts . From )
if err != nil {
return cmdutil . WrapHTTP ( err , "copy agent %s" , opts . From )
}
if copied . Config != nil {
base = * copied . Config
}
2026-05-29 12:06:30 +00:00
// --attach-kb on --from REPLACES the copied KB list; when --attach-kb
2026-05-15 18:35:30 +00:00
// is not set, KnowledgeBasesSet stays false inside applyCreateOverrides
// and the copy's KB list passes through unchanged.
cfg := applyCreateOverrides ( & base , opts )
// Apply overrides on top of copied state via UpdateAgent (no
// server-side template-parameters route, so we do two roundtrips).
updateReq := & sdk . UpdateAgentRequest {
Name : opts . Name ,
Description : opts . Description ,
Config : cfg ,
}
updated , err := svc . UpdateAgent ( ctx , copied . ID , updateReq )
if err != nil {
return cmdutil . WrapHTTP ( err , "update copied agent %s" , copied . ID )
}
2026-05-17 17:38:16 +00:00
return emitAgent ( fopts , updated )
2026-05-15 18:35:30 +00:00
}
// 4. Plain create path: apply hot-path flag overrides onto base
// (zero-valued unless --config-file supplied content).
cfg := applyCreateOverrides ( & base , opts )
req := & sdk . CreateAgentRequest {
Name : opts . Name ,
Description : opts . Description ,
Config : cfg ,
}
created , err := svc . CreateAgent ( ctx , req )
if err != nil {
return cmdutil . WrapHTTP ( err , "create agent" )
}
2026-05-17 17:38:16 +00:00
return emitAgent ( fopts , created )
2026-05-15 18:35:30 +00:00
}
2026-06-26 12:40:59 +00:00
// agentModeValues / kbSelectionModeValues are the closed server enums for the
// --agent-mode / --kb-selection-mode flags, sourced from the SDK enumerators so
// the CLI can't drift from the server vocabulary.
var (
agentModeValues = cmdutil . EnumStrings ( sdk . AllAgentModes ( ) )
kbSelectionModeValues = cmdutil . EnumStrings ( sdk . AllKBSelectionModes ( ) )
)
// validateAgentModeFlags validates and canonicalises --agent-mode and
// --kb-selection-mode in place against the SDK enums. An empty value passes
// through (flag unset → no override). Rejecting a typo here gives a fast,
// typed input.invalid_argument instead of a confusing server-side failure.
// Shared by `agent create` and `agent update`.
func validateAgentModeFlags ( agentMode , kbSelectionMode * string ) error {
v , err := cmdutil . ValidateEnum ( "agent-mode" , * agentMode , agentModeValues )
if err != nil {
return err
}
* agentMode = v
v , err = cmdutil . ValidateEnum ( "kb-selection-mode" , * kbSelectionMode , kbSelectionModeValues )
if err != nil {
return err
}
* kbSelectionMode = v
return nil
}
2026-05-15 18:35:30 +00:00
// applyCreateOverrides merges hot-path flag overrides into the base config,
2026-05-29 12:06:30 +00:00
// then applies the "--attach-kb implies --kb-selection-mode=selected" fallback.
2026-05-15 18:35:30 +00:00
// Shared by the --from path (base=copied agent's config) and the plain
// create path (base=zero or --config-file). Keeping both paths on one
// helper prevents silent divergence when future flags are added.
func applyCreateOverrides ( base * sdk . AgentConfig , opts * CreateOptions ) * sdk . AgentConfig {
overrides := cmdutil . AgentConfigFlags {
AgentMode : opts . AgentMode , AgentModeSet : opts . flags . agentModeSet ,
SystemPrompt : opts . SystemPrompt , SystemPromptSet : opts . flags . systemPromptSet ,
ModelID : opts . Model , ModelIDSet : true , // --model is required
RerankModelID : opts . RerankModel , RerankModelIDSet : opts . flags . rerankModelSet ,
Temperature : opts . Temperature , TemperatureSet : opts . flags . temperatureSet ,
KBSelectionMode : opts . KBSelectionMode , KBSelectionModeSet : opts . flags . kbSelectionModeSet ,
KnowledgeBases : opts . KBs , KnowledgeBasesSet : opts . flags . kbsSet ,
}
cfg := cmdutil . MergeAgentConfig ( base , overrides )
2026-05-29 12:06:30 +00:00
// --attach-kb without explicit --kb-selection-mode implies "selected".
2026-05-15 18:35:30 +00:00
if opts . flags . kbsSet && ! opts . flags . kbSelectionModeSet && cfg . KBSelectionMode == "" {
cfg . KBSelectionMode = "selected"
}
return cfg
}
// openConfigFile returns a Reader, the detected kind ("yaml"/"json"), or
// an error. Format is inferred from file extension; "-" defaults to YAML.
func openConfigFile ( path string ) ( io . Reader , string , error ) {
2026-05-15 18:42:18 +00:00
r , err := cmdutil . OpenInput ( path )
2026-05-15 18:35:30 +00:00
if err != nil {
return nil , "" , err
}
kind := "yaml"
if strings . EqualFold ( filepath . Ext ( path ) , ".json" ) {
kind = "json"
}
return r , kind , nil
}
refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup
Sweep every CLI output path through the v0.7 envelope contract.
FormatOptions.Emit signature changes to (w, data, meta *output.Meta)
so list commands surface meta.count / has_more in the wire envelope.
TTY indent decision plumbed via FormatOptions.TTY (set by
ResolveDefault). --format and --jq promoted to persistent root flags
so unknown-subcommand paths still reach the typed-envelope guard
(per-command registration would have rejected --format on unknown
commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback
honored before TTY-resolved default. AddFormatFlag retained for the
per-command --jq field-hint Long-text addendum.
~55 production Emit call sites swept across cli/cmd/**: list paths
populate meta.count; mutation paths pass nil meta; envelope.profile
threaded via globalProfile. Existing JSON-shape tests migrated to
decode the envelope wrapper.
Multi-target batch operations get a unified shape via new helpers:
- output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok
pattern; data:[{id, ok, result?|error?}], meta:{count, successes*,
failures*}; Successes/Failures *int so explicit zero survives
omitempty in all-fail case).
- cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow +
cmdutil.ClassifyContextErr collapse the three previously-duplicated
multi-delete pipelines (doc / chunk / session) into one call site
pattern. doc upload --recursive uses the same helpers with a per-
file resultFn. Summary error sets Silent:true so the stderr
envelope path doesn't duplicate the stdout batch detail (exit 1
preserved via Code → ExitCode).
ConfirmDestructive / ConfirmDestructiveBatch extended with action +
retryCmd parameters. Every destructive command (kb delete, kb edit,
doc delete, doc delete --all, agent delete, agent edit, session
delete, chunk delete, auth logout, api -X DELETE) now attaches
error.risk.{level:"destructive", action:"<noun.verb>"} +
error.retry_command on the exit-10 envelope. kb edit / agent edit
also gain the destructive guard wiring (CHANGELOG listed them as
gated but they were silently executing without -y).
MCP tool handlers' 31 error paths return CallToolResult with
IsError + Content text fallback + StructuredContent (envelope.error
shape via cmdutil.ErrorToDetail). Handler Out type changed from
typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite
StructuredContent with a zero-struct on error returns. Success path
manually populates CallToolResult.StructuredContent via successResult
helper.
weknora api cleanup:
- -d/--data flag removed; body via --input <file> or --input -
(stdin) only. Aligns with gh / curl convention.
- HTTP method whitelist removed; any non-empty method accepted.
- HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds →
envelope.error.retry_after_seconds.
- runAPIPaginated raw-passthrough fallback now wraps response in
envelope so --paginate never emits bare JSON to stdout.
Test sweep: ~60 cmd/** tests migrated to decode envelope shape.
9 wire-contract goldens updated under cli/acceptance/testdata/wire/.
Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
2026-05-21 10:41:56 +00:00
// emitAgent writes the Agent to stdout (bare SDK shape for --format json,
2026-05-21 10:43:18 +00:00
// text KV otherwise). Shared by create and edit; defined here for proximity
refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup
Sweep every CLI output path through the v0.7 envelope contract.
FormatOptions.Emit signature changes to (w, data, meta *output.Meta)
so list commands surface meta.count / has_more in the wire envelope.
TTY indent decision plumbed via FormatOptions.TTY (set by
ResolveDefault). --format and --jq promoted to persistent root flags
so unknown-subcommand paths still reach the typed-envelope guard
(per-command registration would have rejected --format on unknown
commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback
honored before TTY-resolved default. AddFormatFlag retained for the
per-command --jq field-hint Long-text addendum.
~55 production Emit call sites swept across cli/cmd/**: list paths
populate meta.count; mutation paths pass nil meta; envelope.profile
threaded via globalProfile. Existing JSON-shape tests migrated to
decode the envelope wrapper.
Multi-target batch operations get a unified shape via new helpers:
- output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok
pattern; data:[{id, ok, result?|error?}], meta:{count, successes*,
failures*}; Successes/Failures *int so explicit zero survives
omitempty in all-fail case).
- cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow +
cmdutil.ClassifyContextErr collapse the three previously-duplicated
multi-delete pipelines (doc / chunk / session) into one call site
pattern. doc upload --recursive uses the same helpers with a per-
file resultFn. Summary error sets Silent:true so the stderr
envelope path doesn't duplicate the stdout batch detail (exit 1
preserved via Code → ExitCode).
ConfirmDestructive / ConfirmDestructiveBatch extended with action +
retryCmd parameters. Every destructive command (kb delete, kb edit,
doc delete, doc delete --all, agent delete, agent edit, session
delete, chunk delete, auth logout, api -X DELETE) now attaches
error.risk.{level:"destructive", action:"<noun.verb>"} +
error.retry_command on the exit-10 envelope. kb edit / agent edit
also gain the destructive guard wiring (CHANGELOG listed them as
gated but they were silently executing without -y).
MCP tool handlers' 31 error paths return CallToolResult with
IsError + Content text fallback + StructuredContent (envelope.error
shape via cmdutil.ErrorToDetail). Handler Out type changed from
typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite
StructuredContent with a zero-struct on error returns. Success path
manually populates CallToolResult.StructuredContent via successResult
helper.
weknora api cleanup:
- -d/--data flag removed; body via --input <file> or --input -
(stdin) only. Aligns with gh / curl convention.
- HTTP method whitelist removed; any non-empty method accepted.
- HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds →
envelope.error.retry_after_seconds.
- runAPIPaginated raw-passthrough fallback now wraps response in
envelope so --paginate never emits bare JSON to stdout.
Test sweep: ~60 cmd/** tests migrated to decode envelope shape.
9 wire-contract goldens updated under cli/acceptance/testdata/wire/.
Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
2026-05-21 10:41:56 +00:00
// to the create flow.
2026-05-17 17:38:16 +00:00
func emitAgent ( fopts * cmdutil . FormatOptions , ag * sdk . Agent ) error {
if fopts . WantsJSON ( ) {
refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup
Sweep every CLI output path through the v0.7 envelope contract.
FormatOptions.Emit signature changes to (w, data, meta *output.Meta)
so list commands surface meta.count / has_more in the wire envelope.
TTY indent decision plumbed via FormatOptions.TTY (set by
ResolveDefault). --format and --jq promoted to persistent root flags
so unknown-subcommand paths still reach the typed-envelope guard
(per-command registration would have rejected --format on unknown
commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback
honored before TTY-resolved default. AddFormatFlag retained for the
per-command --jq field-hint Long-text addendum.
~55 production Emit call sites swept across cli/cmd/**: list paths
populate meta.count; mutation paths pass nil meta; envelope.profile
threaded via globalProfile. Existing JSON-shape tests migrated to
decode the envelope wrapper.
Multi-target batch operations get a unified shape via new helpers:
- output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok
pattern; data:[{id, ok, result?|error?}], meta:{count, successes*,
failures*}; Successes/Failures *int so explicit zero survives
omitempty in all-fail case).
- cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow +
cmdutil.ClassifyContextErr collapse the three previously-duplicated
multi-delete pipelines (doc / chunk / session) into one call site
pattern. doc upload --recursive uses the same helpers with a per-
file resultFn. Summary error sets Silent:true so the stderr
envelope path doesn't duplicate the stdout batch detail (exit 1
preserved via Code → ExitCode).
ConfirmDestructive / ConfirmDestructiveBatch extended with action +
retryCmd parameters. Every destructive command (kb delete, kb edit,
doc delete, doc delete --all, agent delete, agent edit, session
delete, chunk delete, auth logout, api -X DELETE) now attaches
error.risk.{level:"destructive", action:"<noun.verb>"} +
error.retry_command on the exit-10 envelope. kb edit / agent edit
also gain the destructive guard wiring (CHANGELOG listed them as
gated but they were silently executing without -y).
MCP tool handlers' 31 error paths return CallToolResult with
IsError + Content text fallback + StructuredContent (envelope.error
shape via cmdutil.ErrorToDetail). Handler Out type changed from
typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite
StructuredContent with a zero-struct on error returns. Success path
manually populates CallToolResult.StructuredContent via successResult
helper.
weknora api cleanup:
- -d/--data flag removed; body via --input <file> or --input -
(stdin) only. Aligns with gh / curl convention.
- HTTP method whitelist removed; any non-empty method accepted.
- HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds →
envelope.error.retry_after_seconds.
- runAPIPaginated raw-passthrough fallback now wraps response in
envelope so --paginate never emits bare JSON to stdout.
Test sweep: ~60 cmd/** tests migrated to decode envelope shape.
9 wire-contract goldens updated under cli/acceptance/testdata/wire/.
Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
2026-05-21 10:41:56 +00:00
return fopts . Emit ( iostreams . IO . Out , ag , nil )
2026-05-15 18:35:30 +00:00
}
renderAgent ( iostreams . IO . Out , ag )
return nil
}