Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ Commands, approval prompts, live command output, and history remain literal. Onl
| `clai setup` | Run the configuration wizard. |
| `clai --setup` | Compatibility alias for `setup`. |
| `clai --question <question>` | Answer-only mode using `question_query`, with or without System One; proposed shell commands are not executed. |
| `clai --execute <request>` | Request a command directly, bypassing intent routing. Syntax checks, risk auditing, and approval still apply. |
| `clai --show-history` | Render persisted conversation history. |
| `clai --show-history --verbose` | Include full stored command stdout and stderr. |
| `clai --clear-history` | Remove persisted conversation history. |
Expand Down Expand Up @@ -393,6 +394,8 @@ If `system_one_key`, `system_one_api`, and `system_one_model` are configured, CL

Requests are interpreted by meaning rather than question marks. Questions needing live data, such as `what is the time?` or `how much disk space is free?`, should produce a command to obtain the answer and follow the usual risk and confirmation rules. General knowledge and how-to questions can be answered directly without execution. With `share_command_results=true`, CLAI also interprets the resulting command output. These decisions use System One when configured, or the main LLM otherwise.

For an action routed by System One or selected with `--execute`, CLAI retries once if the provider returns no command. If it still gets no command, CLAI says so and shows any clarification or blocker. For example, `clai --execute "diagnose and resolve the missing libvips dependency for Discourse"` requests a checked command proposal under your normal risk policy. When System One routes a shell how-to question, CLAI prepares the example without tool calls, shows it as instructions, and retries once if the example is missing. For example, `clai "how do I uninstall ImageMagick?"` asks for instructions you can review and run yourself.

## Providers

CLAI selects its native adapter from the configured `api` URL:
Expand Down
2 changes: 1 addition & 1 deletion cmd/clai/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func newRootCommand(ctx context.Context) *cobra.Command {
return &cobra.Command{
Use: "clai [request...]",
Short: "AI-powered terminal assistant",
Long: "AI-powered terminal assistant. Use clai --question <question> for answer-only requests; --skill NAME selects a local Agent Skill. Inspect context with clai context show or clai skills --help without an API key.",
Long: "AI-powered terminal assistant. Use clai --question <question> for an answer or clai --execute <request> for a command proposal governed by your risk policy. Use --skill NAME to select a local Agent Skill. Inspect context with clai context show or clai skills --help without an API key.",
Version: app.CurrentVersion(),
DisableFlagParsing: true,
SilenceErrors: true,
Expand Down
58 changes: 42 additions & 16 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,9 @@ func (a *Application) Run(ctx context.Context, args []string) error {
}
}
if requestedKind != "" && strings.TrimSpace(strings.Join(args, " ")) == "" {
if requestedKind == "execute" {
return fmt.Errorf("usage: clai --execute <request>")
}
return fmt.Errorf("usage: clai --question <question>")
}
if a.Config.Key == "" {
Expand Down Expand Up @@ -285,21 +288,24 @@ func (a *Application) clearHistory() error {
}

func (a *Application) process(ctx context.Context, query, requestedKind string) error {
if err := a.ensureToolsLoaded(ctx); err != nil {
return err
}
if a.ToolManager != nil && a.Config.UseTools && a.Client.SupportsTools() && a.ToolManager.Dirty() {
if err := a.loadTools(ctx); err != nil {
return err
}
}
kind, err := a.routeIntent(ctx, query, requestedKind)
if err != nil {
return err
}
if kind == "clear_history" {
return a.clearHistory()
}
allowTools := kind != "how_to"
if allowTools {
if err := a.ensureToolsLoaded(ctx); err != nil {
return err
}
if a.ToolManager != nil && a.Config.UseTools && a.Client.SupportsTools() && a.ToolManager.Dirty() {
if err := a.loadTools(ctx); err != nil {
return err
}
}
}
snapshot, err := a.resolveContext(query)
if err != nil {
return err
Expand All @@ -312,16 +318,23 @@ func (a *Application) process(ctx context.Context, query, requestedKind string)
a.requestContext = previousContext
}()
a.History.AppendText("user", query)
var definitions []model.ToolDefinition
if allowTools {
definitions = a.toolDefinitions()
}
previousResponseID := ""
for round := 0; round < 9; round++ {
messages := a.messages(kind)
stop := a.UI.Spinner(ctx, "Thinking...")
response, err := a.Client.Complete(ctx, provider.Request{Messages: messages, Tools: a.toolDefinitions(), PreviousResponseID: previousResponseID})
response, err := a.Client.Complete(ctx, provider.Request{Messages: messages, Tools: definitions, PreviousResponseID: previousResponseID})
stop()
if err != nil {
return err
}
if len(response.ToolCalls) > 0 || response.FinishReason == "tool_calls" {
if !allowTools {
return fmt.Errorf("provider requested a tool while preparing shell instructions")
}
if len(response.ToolCalls) == 0 {
return fmt.Errorf("API requested tools without supplying tool calls")
}
Expand All @@ -342,11 +355,19 @@ func (a *Application) process(ctx context.Context, query, requestedKind string)
if strings.TrimSpace(response.Text) == "" {
return fmt.Errorf("API returned an empty assistant message")
}
reply, err := ParseReply(response.Text)
if err != nil {
reply = model.Reply{Info: strings.TrimSpace(response.Text), Risk: model.RiskNone, Variables: []model.Variable{}}
reply := parseReplyOrText(response.Text)
if (kind == "execute" || kind == "how_to") && reply.Command == "" {
reply, err = a.retryMissingCommand(ctx, kind)
if err != nil {
return err
}
}
if kind == "question" {
if kind == "how_to" && reply.Command != "" {
// Starting with an indented code block keeps the example literal,
// even if the command itself contains Markdown fences.
reply.Info = " " + strings.ReplaceAll(reply.Command, "\n", "\n ") + "\n\n" + reply.Info
}
if kind == "question" || kind == "how_to" {
reply.Command = ""
reply.Risk = model.RiskNone
reply.Variables = []model.Variable{}
Comment thread
merefield marked this conversation as resolved.
Resolved
Expand All @@ -356,7 +377,7 @@ func (a *Application) process(ctx context.Context, query, requestedKind string)
a.UI.Cancel()
return nil
}
if HasPlaceholders(reply.Command) || HasPlaceholders(reply.Info) {
if kind != "how_to" && (HasPlaceholders(reply.Command) || HasPlaceholders(reply.Info)) {
reply = model.Reply{Info: "CLAI returned unresolved placeholders. Rephrase the request or specify missing values.", Risk: model.RiskNone, Variables: []model.Variable{}}
}
if reply.Command != "" {
Expand Down Expand Up @@ -392,6 +413,8 @@ func (a *Application) routeIntent(ctx context.Context, query, requestedKind stri
switch decision.Intent {
case systemone.IntentQuestion:
return "question", nil
case systemone.IntentHowTo:
return "how_to", nil
case systemone.IntentClearHistory:
if !systemone.ValidConfidence(decision.Confidence) || decision.Confidence < 0.65 {
return "", fmt.Errorf("system one history-clear intent is uncertain; use the explicit clear command to clear history")
Expand All @@ -403,7 +426,7 @@ func (a *Application) routeIntent(ctx context.Context, query, requestedKind stri
return "", fmt.Errorf("system one returned unknown intent %q", decision.Intent)
}
}
return "execute", nil
return "auto", nil
}

func (a *Application) auditRisk(ctx context.Context, query string, reply *model.Reply) (bool, error) {
Expand Down Expand Up @@ -492,6 +515,9 @@ func (a *Application) messages(kind string) []model.Message {
if kind == "result" {
capability = "External CLAI tools are unavailable during command-result interpretation."
}
if kind == "how_to" {
capability = "CLAI tools are unavailable while preparing shell instructions."
}
system := systemPrompt(a.Config.Path, a.History.Path, capability) + " " + queryGuidance(kind, configuredQuery(a.Config, kind))
local := a.requestContext.message(kind)
if local != "" {
Expand All @@ -512,7 +538,7 @@ func (a *Application) messages(kind string) []model.Message {

func configuredQuery(cfg *config.Config, kind string) string {
switch kind {
case "question":
case "question", "how_to":
return cfg.QuestionQuery
case "error":
return cfg.ErrorQuery
Expand Down
43 changes: 43 additions & 0 deletions internal/app/command_retry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package app

import (
"context"
"fmt"
"strings"

"github.com/merefield/clai/internal/model"
"github.com/merefield/clai/internal/provider"
)

func (a *Application) retryMissingCommand(ctx context.Context, kind string) (model.Reply, error) {
feedback := "The previous reply did not provide a usable command. Revisit the original request and put a suitable action or diagnostic command in cmd."
noCommand := "No command was proposed."
if kind == "how_to" {
feedback = "The previous reply did not provide a command example. Put the actual Bash example in cmd for the user to read. CLAI will display it as instructions."
noCommand = "No command example was provided."
}
text, err := a.requestCommandRetry(ctx, kind, feedback+" If you cannot provide one, explain the blocker or ask for the missing detail in info. Return one CLAI JSON reply without calling tools.")
if err != nil {
return model.Reply{}, fmt.Errorf("retry missing command: %w", err)
}
reply := parseReplyOrText(text)
if reply.Command == "" {
if detail := strings.TrimSpace(reply.Info); detail != "" {
noCommand += "\n\n" + detail
}
return model.Reply{Info: noCommand, Risk: model.RiskNone, Variables: []model.Variable{}}, nil
}
return reply, nil
}

func (a *Application) requestCommandRetry(ctx context.Context, kind, feedback string) (string, error) {
messages := append(a.messages(kind), model.TextMessage("user", feedback))
response, err := a.Client.Complete(ctx, provider.Request{Messages: messages})
if err != nil {
return "", err
}
if len(response.ToolCalls) > 0 || response.FinishReason == "tool_calls" {
return "", fmt.Errorf("provider requested a tool during command retry")
}
return response.Text, nil
}
147 changes: 147 additions & 0 deletions internal/app/command_retry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
package app

import (
"strings"
"testing"

"github.com/merefield/clai/internal/mcptools"
"github.com/merefield/clai/internal/model"
"github.com/merefield/clai/internal/provider"
"github.com/merefield/clai/internal/systemone"
"github.com/merefield/clai/internal/ui"
)

func TestActionWithoutCommandRetriesBeforeNormalReview(t *testing.T) {
const query = "resolve LoadError Discourse requires libvips for image processing"
const diagnostic = "pkg-config --modversion vips"
for _, mode := range []string{"routed", "explicit"} {
t.Run(mode, func(t *testing.T) {
a, out, _ := contextFixture(t)
a.UI = ui.New(strings.NewReader("n\n"), out, out, true)
router := &fakeSystemOne{intent: systemone.IntentDecision{Intent: systemone.IntentExecute, Confidence: 1}, risk: systemone.RiskDecision{Risk: "none", Confidence: 1}}
a.SystemOne = router
args := []string{query}
if mode == "explicit" {
router.intent.Intent = systemone.IntentQuestion
args = []string{"--execute", query}
}
client := &fakeClient{responses: []provider.Response{
{Text: `{"cmd":"","info":"Installs the libvips development package.","risk":"none","variables":[]}`},
{Text: `{"cmd":"pkg-config --modversion vips","info":"Checks whether pkg-config can find libvips.","risk":"none","variables":[]}`},
}}
a.Client = client
r := &fakeRunner{}
var checked string
r.check = func(command string) (string, error) { checked = command; return "", nil }
a.Runner = r
if err := a.Run(t.Context(), args); err != nil {
t.Fatal(err)
}
if (len(router.intentRequests) == 0) != (mode == "explicit") || len(router.riskRequests) != 1 || router.riskRequests[0].Command != diagnostic {
t.Fatalf("intent=%v audit=%v", router.intentRequests, router.riskRequests)
}
if len(client.requests) != 2 || len(client.requests[1].Tools) != 0 || !strings.Contains(requestText(client.requests[1]), "did not provide a usable command") {
t.Fatalf("unexpected retry: %+v", client.requests)
}
if checked != diagnostic || len(r.calls) != 0 || !strings.Contains(out.String(), diagnostic) || !strings.Contains(out.String(), "execute command?") || strings.Contains(out.String(), "Installs the libvips") {
t.Fatalf("expected a checked proposal at the approval prompt: checked=%q ran=%v output=%s", checked, r.calls, out)
}
})
}
}

func TestActionStillWithoutCommandShowsBlockerAndStops(t *testing.T) {
for name, blocker := range map[string]string{
"json": `{"cmd":"","info":"Which environment needs the dependency?","risk":"none","variables":[]}`,
"plain text": "Which environment needs the dependency?",
} {
t.Run(name, func(t *testing.T) {
a, out, _ := contextFixture(t)
client := &fakeClient{responses: []provider.Response{{Text: "Installs the dependency."}, {Text: blocker}}}
a.Client = client
if err := a.Run(t.Context(), []string{"--execute", "fix the dependency"}); err != nil {
t.Fatal(err)
}
if len(client.requests) != 2 || len(a.Runner.(*fakeRunner).calls) != 0 || !strings.Contains(out.String(), "No command was proposed.") || !strings.Contains(out.String(), "Which environment needs the dependency?") {
t.Fatalf("expected one retry and a visible blocker: %s", out)
}
})
}
}

func TestHowToRetryDisplaysCommandExampleWithoutApprovingOrRunningIt(t *testing.T) {
a, out, _ := contextFixture(t)
a.Config.Set("risk_appetite", "2")
a.Config.Set("share_command_results", "true")
a.Config.Set("use_tools", "true")
a.Tools = testTools(t, fakeTool{})
const query = "how to uninstall this?"
const command = "sudo apt remove imagemagick"
a.History.AppendText("user", "I installed ImageMagick using apt.")
router := &fakeSystemOne{intent: systemone.IntentDecision{Intent: systemone.IntentHowTo, Confidence: 1}}
a.SystemOne = router
client := &fakeClient{tools: true, responses: []provider.Response{
{Text: `{"cmd":"","info":"Uninstalls ImageMagick and removes unused dependencies.","risk":"none","variables":[]}`},
{Text: `{"cmd":"sudo apt remove imagemagick","info":"Removes the package. Review apt's proposed changes before confirming.","risk":"reversible change","variables":[]}`},
}}
a.Client = client
r := &fakeRunner{check: func(command string) (string, error) {
t.Fatalf("how-to example entered the syntax check: %s", command)
return "", nil
}}
a.Runner = r
if err := a.Run(t.Context(), []string{query}); err != nil {
t.Fatal(err)
}
if len(router.intentRequests) != 1 || len(router.riskRequests) != 0 || len(r.calls) != 0 || strings.Contains(out.String(), "execute command?") {
t.Fatalf("how-to example entered the execution flow: %v / %s", r.calls, out)
}
if len(client.requests) != 2 || !strings.Contains(requestText(client.requests[1]), "did not provide a command example") || !strings.Contains(requestText(client.requests[1]), "installed ImageMagick using apt") {
t.Fatalf("how-to retry lost the reason or conversation context: %+v", client.requests)
}
for _, request := range client.requests {
if len(request.Tools) != 0 || !strings.Contains(request.Messages[0].ContentText(), "tools are unavailable while preparing shell instructions") {
t.Fatalf("how-to request advertised tools: %+v", request)
}
}
if !strings.Contains(out.String(), command) || strings.Contains(out.String(), "removes unused dependencies") {
t.Fatalf("missing example or stale explanation: %s", out)
}
saved, err := ParseReply(a.History.Messages[len(a.History.Messages)-1].ContentText())
if err != nil || saved.Command != "" || !strings.Contains(saved.Info, " "+command) {
t.Fatalf("example was not saved as inert instructions: %+v, %v", saved, err)
}
}

func TestHowToRejectsUnexpectedToolCallsBeforeDispatch(t *testing.T) {
a, out, _ := contextFixture(t)
a.Config.Set("use_tools", "true")
a.Tools = testTools(t, fakeTool{})
manager, err := mcptools.New(t.TempDir(), out)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = manager.Close() })
a.ToolManager = manager
a.SystemOne = &fakeSystemOne{intent: systemone.IntentDecision{Intent: systemone.IntentHowTo, Confidence: 1}}
client := &fakeClient{tools: true, responses: []provider.Response{
{ToolCalls: []model.ToolCall{{ID: "unexpected", Function: model.FunctionCall{Name: "lookup", Arguments: `{}`}}}},
{Text: `{"cmd":"printf later","info":"An example.","risk":"none","variables":[]}`},
}}
a.Client = client
err = a.Run(t.Context(), []string{"how do I uninstall this?"})
if err == nil || !strings.Contains(err.Error(), "provider requested a tool while preparing shell instructions") {
t.Fatalf("expected a rejected tool call, got %v", err)
}
if a.toolsLoaded || len(client.requests) != 1 || len(a.History.Messages) != 1 || len(a.History.Messages[0].ToolCalls) != 0 {
t.Fatalf("how-to request entered the tool workflow: loaded=%v requests=%d history=%+v", a.toolsLoaded, len(client.requests), a.History.Messages)
}
}

func TestExecuteOptionRequiresRequestAndConflictsWithQuestion(t *testing.T) {
for _, args := range [][]string{{"--execute"}, {"--question", "--execute", "test"}, {"--execute", "--question", "test"}} {
if err := (&Application{}).Run(t.Context(), args); err == nil {
t.Errorf("accepted invalid options: %v", args)
}
}
}
11 changes: 10 additions & 1 deletion internal/app/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,13 +136,22 @@ func parseRequestOptions(args []string) ([]string, []string, string, error) {
switch args[0] {
case "--skill":
if len(args) < 2 || strings.HasPrefix(args[1], "--") || len(selected) >= 8 {
return nil, nil, "", fmt.Errorf("usage: clai [--skill NAME] [--question] <request>; at most eight skills")
return nil, nil, "", fmt.Errorf("usage: clai [--skill NAME] [--question|--execute] <request>; at most eight skills")
}
selected = append(selected, args[1])
args = args[2:]
case "--question":
if kind == "execute" {
return nil, nil, "", fmt.Errorf("use either --question or --execute")
}
kind = "question"
args = args[1:]
case "--execute":
if kind == "question" {
return nil, nil, "", fmt.Errorf("use either --question or --execute")
}
kind = "execute"
args = args[1:]
case "--":
return args[1:], selected, kind, nil
default:
Expand Down
2 changes: 1 addition & 1 deletion internal/app/context_commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const contextHelp = `Local context commands (no API key required):
clai skills show NAME [--body]
clai skills validate PATH
clai skills reload
clai --skill NAME [--skill NAME] [--question] <request>
clai --skill NAME [--skill NAME] [--question|--execute] <request>
Interactive: /skills list, /skills use NAME, /skills off, /context show
Local documents are untrusted guidance, sent to the configured response provider.
`
Expand Down
Loading
Loading