WeKnora/cli/internal/cmdutil/agenthelp.go

105 lines
3.5 KiB
Go
Raw Normal View History

feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
// Package-level note:
//
// SetAgentHelp wires structured agent-targeted help onto a cobra command.
feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING) D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
2026-05-21 10:43:18 +00:00
// Current coverage: chat, kb list, and destructive commands. Adding it to
// another command requires touching only that command's NewCmd (a 5-line
// copy of the existing call sites).
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
package cmdutil
import (
"encoding/json"
feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING) D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
2026-05-21 10:43:18 +00:00
"fmt"
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
"io"
"os"
"github.com/spf13/cobra"
)
// AgentHelp is the structured help blob emitted when an agent invokes
// `weknora <command> --help` with WEKNORA_AGENT_HELP=1. Distinct from
// cobra's human help text — agent-readable JSON keyed by stable fields
// so an LLM doesn't need to scrape the human help table.
feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING) D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
2026-05-21 10:43:18 +00:00
//
// Warnings surface both as a JSON field (agent introspection) and as an
// "AI agents:" block appended to human help. The two channels share a
// single source list so they cannot drift.
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
type AgentHelp struct {
UsedFor string `json:"used_for"`
RequiredFlags []string `json:"required_flags,omitempty"`
Examples []string `json:"examples,omitempty"`
Output string `json:"output,omitempty"`
feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING) D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
2026-05-21 10:43:18 +00:00
Warnings []string `json:"warnings,omitempty"`
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
}
// agentHelpAnnotation stores the marshaled AgentHelp on the command so the
// `weknora schema` command can introspect any command's contract without
// invoking its help func (and toggling WEKNORA_AGENT_HELP). Shares the
// annotations map with SetRisk (distinct keys).
const agentHelpAnnotation = "weknora.agent_help"
feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING) D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
2026-05-21 10:43:18 +00:00
// SetAgentHelp attaches agent-targeted help metadata to a command.
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
//
feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING) D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
2026-05-21 10:43:18 +00:00
// Routing:
// - WEKNORA_AGENT_HELP=1: emit the AgentHelp JSON blob to stdout and
// return — agents get clean parseable JSON, no trailing prose.
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
// - Otherwise (human help path): if cmd has risk annotations from SetRisk,
// prepend "Risk: <action> (<level>)" line; then render the normal human
// help via origHelp; then append the "AI agents:" Warnings block.
//
// The AgentHelp is also recorded as a JSON annotation so `weknora schema` can
// surface it as a first-class, discoverable command (not only via the
// WEKNORA_AGENT_HELP env toggle on --help).
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
func SetAgentHelp(cmd *cobra.Command, ah AgentHelp) {
if b, err := json.Marshal(ah); err == nil {
if cmd.Annotations == nil {
cmd.Annotations = make(map[string]string)
}
cmd.Annotations[agentHelpAnnotation] = string(b)
}
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
origHelp := cmd.HelpFunc()
cmd.SetHelpFunc(func(c *cobra.Command, args []string) {
if os.Getenv("WEKNORA_AGENT_HELP") == "1" {
emitAgentHelp(c.OutOrStdout(), ah)
return
}
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
// Prepend Risk: line in the default (human) branch only; the
// JSON branch above already carries warnings[]. Skip silently if
// the command has no risk annotations.
if level, action, ok := GetRisk(c); ok {
fmt.Fprintf(c.OutOrStdout(), "Risk: %s (%s)\n\n", action, level)
}
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
origHelp(c, args)
feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING) D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
2026-05-21 10:43:18 +00:00
if len(ah.Warnings) > 0 {
w := c.OutOrStdout()
fmt.Fprintln(w)
fmt.Fprintln(w, "AI agents:")
for _, msg := range ah.Warnings {
fmt.Fprintln(w, "- "+msg)
}
}
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
})
}
// AgentHelpFor returns the AgentHelp registered on cmd via SetAgentHelp.
// ok is false when the command carries none (e.g. cobra-generated subtrees).
func AgentHelpFor(cmd *cobra.Command) (ah AgentHelp, ok bool) {
if cmd.Annotations == nil {
return ah, false
}
raw, present := cmd.Annotations[agentHelpAnnotation]
if !present {
return ah, false
}
if err := json.Unmarshal([]byte(raw), &ah); err != nil {
return ah, false
}
return ah, true
}
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
func emitAgentHelp(w io.Writer, ah AgentHelp) {
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
_ = enc.Encode(ah)
}