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
15 changes: 13 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ Commands, approval prompts, live command output, and history remain literal. Onl
| `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 copy` | Copy the command or shell example from the latest recorded request. |
| `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 @@ -320,10 +321,11 @@ Suggested commands are displayed by risk:
| `reversible change` | Amber | A change that is normally undoable. |
| `danger zone` | Red | Deletion, overwrite, reset, force, or another hard-to-reverse action. |

When confirmation is required, CLAI prompts with `execute command? [y/e/t/N]`:
When confirmation is required, CLAI offers `execute command? [y/e/c/t/N]`.

- `y` runs the command.
- `e` lets you replace the proposed command before it runs.
- `c` copies the command to the clipboard and shows the same prompt again.
- `t` exits CLAI and prepares the command for review in your shell, without executing it.
- Enter or any other answer cancels.

Expand All @@ -335,14 +337,22 @@ When confirmation is required, CLAI prompts with `execute command? [y/e/t/N]`:
| `1` | Automatically run green commands; confirm amber and red commands. |
| `2` | Automatically run green and amber commands; confirm red commands. |

Danger-zone commands always receive the normal confirmation. When `confirm_dangerous_commands=true`, accepting one produces a second `danger zone command, are you sure? [y/N]:` prompt.
Danger-zone commands always receive the normal confirmation. When `confirm_dangerous_commands=true`, accepting one produces a second `danger zone command, are you sure? [y/c/N]` prompt.

Approved commands run through `bash -o errexit -o pipefail -c`. Stdout and stderr stream to the terminal without truncation, while CLAI retains only the most recent 256 KiB of each stream. Cancellation terminates the command's process group, and detached descendants cannot keep CLAI blocked on inherited output pipes. After a failed command in an interactive terminal, CLAI can send the command and its stderr back to the provider to request an explanation and possible repair.

Approved commands inherit terminal input, so prompts from tools such as `apt-get` can be answered normally after CLAI's own confirmations. On Unix, CLAI hands foreground terminal ownership to the command and restores it and the terminal settings afterward, including on cancellation. Redirected file input is also passed through; when no input file is available, commands receive EOF. Output still streams and is captured as described above; this is not a full pseudo-terminal wrapper for screen-oriented applications.

Risk is model-generated guidance, not a security boundary. Read every proposed or edited command before approving it.

### Copying commands

Use `c` at an execution or shell-handoff prompt. After a one-shot request, run `clai copy`. In an interactive CLAI session, enter `/copy`. Copying works locally without an API key.

Copy uses the latest recorded request, including an edited command, a command that ran with result sharing off, a declined proposal, or a shell example from an advice-only reply. For Markdown advice with several tagged shell code blocks, it uses the last shell block. A prose-only request leaves nothing to copy.

CLAI uses the local clipboard when available through `pbcopy` on macOS, PowerShell on Windows or WSL, `wl-copy` on Wayland, and `xclip` or `xsel` on X11. Over SSH, or when a local helper is unavailable, it can send an OSC 52 clipboard request to the visible terminal. Terminal and tmux settings determine whether that request reaches your clipboard.

### Commands that need a full terminal

CLAI captures command output through pipes. It supports ordinary input prompts, but it cannot provide the full terminal interface required by applications such as `tmux attach`, screen editors and interactive process monitors.
Expand All @@ -354,6 +364,7 @@ Recognized interactive command ────────────────
▼
Other command → run once → terminal error → offer shell handoff
│
c: copy and offer handoff again
t: exit CLAI with the command
N: cancel handoff
```
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 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.",
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 clai copy to copy the latest command. 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
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
github.com/charmbracelet/x/ansi v0.11.9
github.com/modelcontextprotocol/go-sdk v1.8.0
github.com/spf13/cobra v1.10.2
github.com/yuin/goldmark v1.8.7
go.yaml.in/yaml/v3 v3.0.6
golang.org/x/sys v0.50.0
golang.org/x/term v0.48.0
Expand Down Expand Up @@ -38,7 +39,6 @@ require (
github.com/spf13/pflag v1.1.0 // indirect
github.com/xo/terminfo v1.3.1 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
github.com/yuin/goldmark v1.8.7 // indirect
github.com/yuin/goldmark-emoji v1.0.6 // indirect
golang.org/x/net v0.62.0 // indirect
golang.org/x/oauth2 v0.38.0 // indirect
Expand Down
29 changes: 24 additions & 5 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ type Application struct {
selectedSkills []string
skillsOff bool
exitToShell bool
copyClipboard func(context.Context, string, io.Writer) (bool, error)
}

func New(_ context.Context, in io.Reader, out, errOut io.Writer) (*Application, error) {
Expand Down Expand Up @@ -139,6 +140,12 @@ func (a *Application) Run(ctx context.Context, args []string) error {
if query == "" {
continue
}
if query == "/copy" {
if err := a.copyLastCommand(ctx); err != nil {
a.UI.Error(err.Error())
}
continue
}
if strings.HasPrefix(query, "/tools") || strings.HasPrefix(query, "/skills") || strings.HasPrefix(query, "/context") {
arguments := strings.Fields(strings.TrimPrefix(query, "/"))
if handled, err := a.handleBuiltIn(ctx, arguments); handled {
Expand Down Expand Up @@ -167,6 +174,9 @@ func (a *Application) Run(ctx context.Context, args []string) error {
}

func (a *Application) handleBuiltIn(ctx context.Context, args []string) (bool, error) {
if len(args) == 1 && args[0] == "copy" {
return true, a.copyLastCommand(ctx)
}
if len(args) > 0 && (args[0] == "skills" || args[0] == "context") {
return true, a.handleContextCommand(args)
}
Expand Down Expand Up @@ -362,7 +372,9 @@ func (a *Application) process(ctx context.Context, query, requestedKind string)
return err
}
}
var example string
if kind == "how_to" && reply.Command != "" {
example = 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
Expand Down Expand Up @@ -392,8 +404,12 @@ func (a *Application) process(ctx context.Context, query, requestedKind string)
if err := a.History.AppendReply(reply); err != nil {
return err
}
a.History.RecordCommand(example)
a.UI.Reply(reply)
if reply.Command == "" {
if a.UI.Interactive() && a.History.LatestCommand() != "" {
a.UI.Info("Copy with clai copy after CLAI exits, or /copy at the CLAI prompt.")
}
return nil
}
return a.confirmAndRun(ctx, query, reply, forceConfirm)
Expand Down Expand Up @@ -609,10 +625,10 @@ func (a *Application) confirmAndRun(ctx context.Context, originalQuery string, r
command := reply.Command
edited := false
if runner.TerminalCommand(command) {
return a.offerTerminal(command, false)
return a.offerTerminal(ctx, command, false)
}
if forceConfirm || RequiresConfirmation(reply.Risk, a.Config.RiskAppetite) {
choice, err := a.UI.Choice("execute command? [y/e/t/N] (t: return to shell): ")
choice, err := a.commandChoice(ctx, "execute command? [y/e/c/t/N] (c: copy, t: return to shell): ", command)
if errors.Is(err, io.EOF) {
a.UI.Cancel()
return nil
Expand Down Expand Up @@ -642,6 +658,9 @@ func (a *Application) confirmAndRun(ctx context.Context, originalQuery string, r
return fmt.Errorf("edited command has invalid Bash syntax")
}
command = value
if a.History != nil {
a.History.RecordCommand(command)
}
}
edited = true
case "y":
Expand All @@ -650,7 +669,7 @@ func (a *Application) confirmAndRun(ctx context.Context, originalQuery string, r
return nil
}
if (reply.Risk == model.RiskDanger || (forceConfirm && edited)) && a.Config.ConfirmDangerousCommands {
confirm, err := a.UI.Choice("danger zone command, are you sure? [y/N]: ")
confirm, err := a.commandChoice(ctx, "danger zone command, are you sure? [y/c/N] (c: copy): ", command)
if errors.Is(err, io.EOF) {
a.UI.Cancel()
return nil
Expand All @@ -665,7 +684,7 @@ func (a *Application) confirmAndRun(ctx context.Context, originalQuery string, r
}
}
if runner.TerminalCommand(command) {
return a.offerTerminal(command, false)
return a.offerTerminal(ctx, command, false)
}
a.UI.BlankLine()
result := a.Runner.Run(ctx, command, edited)
Expand All @@ -689,7 +708,7 @@ func (a *Application) confirmAndRun(ctx context.Context, originalQuery string, r
}
}
if terminalFailure {
return a.offerTerminal(command, true)
return a.offerTerminal(ctx, command, true)
}
if result.ExitCode == 0 {
return nil
Expand Down
45 changes: 45 additions & 0 deletions internal/app/clipboard.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package app

import (
"context"
"fmt"

"github.com/merefield/clai/internal/clipboard"
)

func (a *Application) copyLastCommand(ctx context.Context) error {
command := a.History.LatestCommand()
if command == "" {
return fmt.Errorf("the latest CLAI request has no command to copy")
}
return a.copyCommand(ctx, command)
}

func (a *Application) copyCommand(ctx context.Context, command string) error {
copyText := a.copyClipboard
if copyText == nil {
copyText = clipboard.Copy
}
terminal, err := copyText(ctx, command, a.UI.Out)
if err != nil {
return err
}
if terminal {
a.UI.Info("Sent the command to the terminal clipboard.")
} else {
a.UI.OK("Copied command to clipboard.")
}
return nil
}

func (a *Application) commandChoice(ctx context.Context, prompt, command string) (string, error) {
for {
choice, err := a.UI.Choice(prompt)
if err != nil || choice != "c" {
return choice, err
}
if err := a.copyCommand(ctx, command); err != nil {
a.UI.Error(err.Error())
}
}
}
126 changes: 126 additions & 0 deletions internal/app/clipboard_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package app

import (
"context"
"errors"
"io"
"os"
"strings"
"testing"

"github.com/merefield/clai/internal/history"
"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 TestCopyAtCommandPrompts(t *testing.T) {
for _, tc := range []struct {
name, command, prompt, input string
copyError error
wantRuns int
}{
{name: "execute", command: "printf 'café'\nprintf '%s' '$HOME'", prompt: "[y/e/c/t/N]", input: "c\ny\n", wantRuns: 1},
{name: "handoff", command: "tmux attach", prompt: "[c/t/N]", input: "c\nn\n"},
{name: "failed copy", command: "printf hello", prompt: "[y/e/c/t/N]", input: "c\nn\n", copyError: errors.New("clipboard unavailable")},
} {
t.Run(tc.name, func(t *testing.T) {
a, runner, out, handoff := handoffFixture(t, tc.input)
var copied []string
a.copyClipboard = func(_ context.Context, text string, _ io.Writer) (bool, error) {
if len(runner.calls) != 0 {
t.Fatal("copy ran the command before approval")
}
copied = append(copied, text)
return false, tc.copyError
}
if err := a.confirmAndRun(t.Context(), "request", model.Reply{Command: tc.command, Risk: model.RiskNone}, false); err != nil {
t.Fatal(err)
}
if len(copied) != 1 || copied[0] != tc.command || len(runner.calls) != tc.wantRuns || strings.Count(out.String(), tc.prompt) != 2 {
t.Fatalf("copied %q, ran %q, output %q", copied, runner.calls, out)
}
if _, err := os.Stat(handoff); !os.IsNotExist(err) {
t.Fatalf("copy created a handoff: %v", err)
}
})
}
}

func TestCopyFromLatestSavedRequest(t *testing.T) {
const shellAdvice = `{"cmd":"","info":"List files:\n\n~~~bash\nls -a\n~~~","risk":"none","variables":[]}`
for _, tc := range []struct {
name, input, response, want string
args []string
howTo bool
wantRuns int
}{
{
name: "executed edit with result sharing off", input: "e\nprintf 'new command'\n",
response: `{"cmd":"printf old","info":"Prints.","risk":"none","variables":[]}`,
args: []string{"print something"}, want: "printf 'new command'", wantRuns: 1,
},
{
name: "declined proposal", input: "n\n",
response: `{"cmd":"printf proposed","info":"Prints.","risk":"none","variables":[]}`,
args: []string{"print something"}, want: "printf proposed",
},
{
name: "structured how-to example", howTo: true,
response: `{"cmd":"tmux attach-session","info":"Attaches to a session.","risk":"none","variables":[]}`,
args: []string{"what about last session?"}, want: "tmux attach-session",
},
{
name: "Markdown advice", response: shellAdvice,
args: []string{"--question", "how to list files?"}, want: "ls -a",
},
{
name: "prose only does not pick an older command",
response: `{"cmd":"","info":"The -t option specifies the target session.","risk":"none","variables":[]}`,
args: []string{"what is -t for?"},
},
} {
t.Run(tc.name, func(t *testing.T) {
a, out, _ := contextFixture(t)
a.UI = ui.New(strings.NewReader(tc.input), out, out, true)
a.History.AppendText("user", "previous request")
if err := a.History.AppendReply(model.Reply{Command: "printf stale"}); err != nil {
t.Fatal(err)
}
if tc.howTo {
a.SystemOne = &fakeSystemOne{intent: systemone.IntentDecision{Intent: systemone.IntentHowTo, Confidence: 1}}
}
client := &fakeClient{responses: []provider.Response{{Text: tc.response}}}
a.Client = client
if err := a.Run(t.Context(), tc.args); err != nil {
t.Fatal(err)
}
if err := a.Close(); err != nil {
t.Fatal(err)
}
reloaded, err := history.Load(a.History.Path)
if err != nil {
t.Fatal(err)
}
a.History = reloaded
a.Config.Set("key", "")
var copied []string
a.copyClipboard = func(_ context.Context, text string, _ io.Writer) (bool, error) {
copied = append(copied, text)
return false, nil
}
err = a.Run(t.Context(), []string{"copy"})
if tc.want == "" {
if err == nil || !strings.Contains(err.Error(), "no command to copy") || len(copied) != 0 {
t.Fatalf("copied %q with error %v", copied, err)
}
} else if err != nil || len(copied) != 1 || copied[0] != tc.want {
t.Fatalf("copied %q, want %q, error %v", copied, tc.want, err)
}
if len(a.Runner.(*fakeRunner).calls) != tc.wantRuns || len(client.requests) != 1 {
t.Fatal("copy triggered execution or made a model request")
}
})
}
}
Loading
Loading