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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,8 @@ Requests are interpreted by meaning rather than question marks. Questions needin

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.

Follow-up questions can refer to a command discussed earlier. After discussing `ls`, ask `clai "what about including hidden files?"` to get a complete command example such as `ls -a`. For intent routing, System One receives the current request and whether history is available. The main response model uses that history to resolve the reference.

## Providers

CLAI selects its native adapter from the configured `api` URL:
Expand Down
5 changes: 4 additions & 1 deletion internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,10 @@ func (a *Application) routeIntent(ctx context.Context, query, requestedKind stri
return requestedKind, nil
}
if a.SystemOne != nil {
decision, err := a.SystemOne.RouteIntent(ctx, systemone.IntentRequest{UserRequest: query})
decision, err := a.SystemOne.RouteIntent(ctx, systemone.IntentRequest{
UserRequest: query,
HasHistory: len(a.History.Messages) > 0,
})
if err != nil {
return "", fmt.Errorf("route intent with system one: %w", err)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/app/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,7 @@ func TestSystemOneRoutesQuestionWithoutQuestionMark(t *testing.T) {
if err := application.process(context.Background(), "how much is 3 times pi", ""); err != nil {
t.Fatal(err)
}
if len(router.intentRequests) != 1 || router.intentRequests[0].UserRequest != "how much is 3 times pi" {
if len(router.intentRequests) != 1 || router.intentRequests[0] != (systemone.IntentRequest{UserRequest: "how much is 3 times pi"}) {
t.Fatalf("intent requests = %#v", router.intentRequests)
}
if len(commandRunner.calls) != 0 {
Expand Down
49 changes: 49 additions & 0 deletions internal/app/command_retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"strings"
"testing"

"github.com/merefield/clai/internal/history"
"github.com/merefield/clai/internal/mcptools"
"github.com/merefield/clai/internal/model"
"github.com/merefield/clai/internal/provider"
Expand Down Expand Up @@ -138,6 +139,54 @@ func TestHowToRejectsUnexpectedToolCallsBeforeDispatch(t *testing.T) {
}
}

func TestFollowUpCommandExampleUsesSavedConversation(t *testing.T) {
a, out, _ := contextFixture(t)
a.Config.Set("risk_appetite", "2")
a.History.AppendText("user", "attach to tmux session builder")
if err := a.History.AppendReply(model.Reply{Command: "tmux attach-session -t builder", Info: "Attaches to builder.", Risk: model.RiskNone}); err != nil {
t.Fatal(err)
}
router := &fakeSystemOne{intent: systemone.IntentDecision{Intent: systemone.IntentQuestion, Confidence: 1}}
a.SystemOne = router
client := &fakeClient{responses: []provider.Response{
{Text: `{"cmd":"","info":"The -t option specifies the target session.","risk":"none","variables":[]}`},
{Text: `{"cmd":"","info":"Attaches to the last tmux session.","risk":"none","variables":[]}`},
{Text: `{"cmd":"tmux attach-session","info":"From outside tmux, attaches with no explicit target. tmux prefers the most recently used unattached session.","risk":"none","variables":[]}`},
}}
a.Client = client
if err := a.Run(t.Context(), []string{"what is the -t for?"}); err != nil {
t.Fatal(err)
}
if len(client.requests) != 1 || !strings.Contains(out.String(), "specifies the target session") {
t.Fatalf("option explanation should need only one response: %s", out)
}
if err := a.History.Save(a.Config.MaxHistoryTurns); err != nil {
t.Fatal(err)
}
saved, err := history.Load(a.History.Path)
if err != nil {
t.Fatal(err)
}
a.History = saved
out.Reset()

const followUp = "what about last session?"
router.intent.Intent = systemone.IntentHowTo
if err := a.Run(t.Context(), []string{followUp}); err != nil {
t.Fatal(err)
}
if len(router.intentRequests) != 2 || router.intentRequests[1] != (systemone.IntentRequest{UserRequest: followUp, HasHistory: true}) {
t.Fatalf("follow-up routing input = %#v", router.intentRequests)
}
if len(client.requests) != 3 || !strings.Contains(requestText(client.requests[2]), "tmux attach-session -t builder") || !strings.Contains(requestText(client.requests[2]), "specifies the target session") {
t.Fatal("expected one retry with the tmux proposal and the option explanation in context")
}
reply, err := ParseReply(saved.Messages[len(saved.Messages)-1].ContentText())
if err != nil || reply.Command != "" || !strings.Contains(out.String(), "tmux attach-session") || len(router.riskRequests) != 0 || len(a.Runner.(*fakeRunner).calls) != 0 {
t.Fatalf("expected a display-only example, got reply=%+v, error=%v, output=%s", reply, err, out)
}
}

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 {
Expand Down
10 changes: 7 additions & 3 deletions internal/app/prompts.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,19 @@ func CurrentVersion() string {
return strings.TrimSpace(sourceVersion)
}

const autoRequestGuidance = "Interpret the user's intent regardless of question marks. Requests to fix a concrete failure, install a dependency, or perform a terminal task call for a command. For requests needing current system or external state, propose a command to obtain it and avoid inventing live facts. For general knowledge, explanations, or how-to questions that need no live data, answer directly in info with empty cmd and variables and risk 'none'. For shell how-to questions, put copyable Bash examples in Markdown code blocks in info when the user's target is clear. Ask for any missing detail that would change the command."
const shellFollowUpContext = "Use the conversation history to resolve references. If a follow-up asks for a different target or option for a previously discussed command, give the complete revised Bash command. Prefer built-in target selection where it matches the requested behavior. For example, from outside tmux, 'tmux attach-session' without '-t' chooses by recency and prefers an unattached session. If choosing by recency from a list, sort by the relevant timestamp."

const shellFollowUpGuidance = shellFollowUpContext + " Put the example in a Markdown code block in info. If the user asks what an option means, explain that option."

const autoRequestGuidance = "Interpret the user's intent regardless of question marks. Requests to fix a concrete failure, install a dependency, or perform a terminal task call for a command. For requests needing current system or external state, propose a command to obtain it and avoid inventing live facts. For general knowledge, explanations, or how-to questions that need no live data, answer directly in info with empty cmd and variables and risk 'none'. For shell how-to questions, put copyable Bash examples in Markdown code blocks in info when the user's target is clear. Ask for any missing detail that would change the command. " + shellFollowUpGuidance

const actionRequestGuidance = "The user wants a shell action or live inspection. Put a runnable Bash command in cmd and its explanation in info. If more evidence is needed, propose a read-only diagnostic command. If no suitable command can be proposed, leave cmd empty and explain the blocker or ask for the missing detail. Avoid describing an action as if it were proposed when cmd is empty."

const executionReplyContract = "Return only a single compact JSON object containing 'cmd', 'info', 'risk' and 'variables' fields. 'info' must be a concise answer or command explanation. 'risk' must be exactly 'none', 'reversible change', or 'danger zone'. Use 'none' only for read-only inspection. Use 'reversible change' for changes that are normally undoable. Use 'danger zone' for deletion, overwrite, reset, force, or hard-to-reverse changes. 'variables' must be an array. Represent missing user values as {{variable_name}} in cmd and info and include matching objects with name and prompt. Do not quote placeholders in cmd; CLAI shell-escapes substitutions."

const defaultQuestionQuery = "Return only a single compact JSON object with cmd, info, risk and variables. For questions, cmd must be empty, risk must be 'none', variables must be empty, and info must be a concise terminal-related answer. When the user asks how to do a shell task, include actual Bash examples in Markdown code blocks in info. If the target or environment is unclear and would change the command, ask for the missing detail."
const defaultQuestionQuery = "Return only a single compact JSON object with cmd, info, risk and variables. For questions, cmd must be empty, risk must be 'none', variables must be empty, and info must be a concise terminal-related answer. When the user asks how to do a shell task, include actual Bash examples in Markdown code blocks in info. If the target or environment is unclear and would change the command, ask for the missing detail. " + shellFollowUpGuidance

const commandExampleGuidance = "The user wants shell instructions. Put the actual Bash example in cmd and explain what it does in info. CLAI displays the example as text for the user to read. If an essential detail is missing, leave cmd empty and ask for that detail in info. Keep risk 'none' and variables empty. Return one CLAI JSON object."
const commandExampleGuidance = "The user wants shell instructions. " + shellFollowUpContext + " Put the actual Bash example in cmd and explain what it does in info. CLAI displays the example as text for the user to read. If an essential detail is missing, leave cmd empty and ask for that detail in info. Keep risk 'none' and variables empty. Return one CLAI JSON object."

const defaultErrorQuery = "Return only a single compact JSON object with cmd, info, risk and variables. Explain what the error means and why the suggested repair may work. Classify the repair risk using none, reversible change, or danger zone."

Expand Down
7 changes: 4 additions & 3 deletions internal/systemone/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ type HTTPClient struct {

type IntentRequest struct {
UserRequest string `json:"user_request"`
HasHistory bool `json:"has_history"`
}

type IntentDecision struct {
Expand Down Expand Up @@ -128,11 +129,11 @@ func (c *HTTPClient) RouteIntent(ctx context.Context, input IntentRequest) (Inte
Questions: map[string]question{
"intent": {
"type": "choice",
"instructions": "Which CLAI workflow should handle the request in `user_request`? Decide from the outcome the user asks for. A request to fix a concrete failure needs action or diagnosis even if the user has not specified the command.",
"instructions": "Which CLAI workflow should handle the request in `user_request`? Decide from the outcome the user asks for. A request to fix a concrete failure needs action or diagnosis even if the user has not specified the command. When `has_history` is true, the response model can resolve references to earlier turns. A short follow-up asking for a variation on a previous command's target or options can request an example even if it omits the command verb and tool name. Such a follow-up alone does not authorize execution.",
"criteria": map[string]string{
IntentExecute: "The user wants CLAI to perform a terminal task, diagnose or fix a local failure, or look up live system or external state. Examples: resolve this LoadError, install a missing dependency, check available disk space, show git status.",
IntentHowTo: "The user wants shell instructions or a command example to run themselves. Examples: how to uninstall this, how do I normally install a dependency, what command would list hidden files. The request is about the steps, with no need for CLAI to run the command.",
IntentQuestion: "The user wants general knowledge or an explanation without live inspection, changes, or a shell command example. Examples: what does LoadError mean, explain git status, how do I autocomplete a filename using the keyboard.",
IntentHowTo: "The user wants shell instructions or a command example to run themselves. Examples: how to uninstall this, how do I normally install a dependency, what command would list hidden files. With history, examples of implied variations include 'what about last session?', 'what about including hidden files?' and 'what if I want to use a different branch?'.",
IntentQuestion: "The user wants general knowledge or an explanation without live inspection, changes, or a shell command example. Examples: what does LoadError mean, explain git status, how do I autocomplete a filename using the keyboard, what is the -t for?",
IntentClearHistory: "The user wants to clear, reset, forget, or flush CLAI conversation history.",
},
},
Expand Down
6 changes: 5 additions & 1 deletion internal/systemone/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func TestRouteIntentUsesChoiceQuestion(t *testing.T) {
if err != nil {
t.Fatal(err)
}
decision, err := client.RouteIntent(context.Background(), IntentRequest{UserRequest: "how to uninstall this?"})
decision, err := client.RouteIntent(context.Background(), IntentRequest{UserRequest: "what about last session?", HasHistory: true})
if err != nil {
t.Fatal(err)
}
Expand All @@ -137,6 +137,10 @@ func TestRouteIntentUsesChoiceQuestion(t *testing.T) {
if request["model"] != "jev-test" {
t.Fatalf("request = %#v", request)
}
state := request["state"].(map[string]any)
if len(state) != 2 || state["user_request"] != "what about last session?" || state["has_history"] != true {
t.Fatalf("intent state = %#v", state)
}
questions := request["questions"].(map[string]any)
intent := questions["intent"].(map[string]any)
if intent["type"] != "choice" {
Expand Down
Loading