diff --git a/README.md b/README.md index e4f9860..010c268 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,7 @@ Commands, approval prompts, live command output, and history remain literal. Onl | `clai --setup` | Compatibility alias for `setup`. | | `clai --question ` | Answer-only mode using `question_query`, with or without System One; proposed shell commands are not executed. | | `clai --execute ` | 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. | @@ -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. @@ -335,7 +337,7 @@ 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. @@ -343,6 +345,14 @@ Approved commands inherit terminal input, so prompts from tools such as `apt-get 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. @@ -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 ``` diff --git a/cmd/clai/main.go b/cmd/clai/main.go index a28e22f..b1e41dc 100644 --- a/cmd/clai/main.go +++ b/cmd/clai/main.go @@ -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 for an answer or clai --execute 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 for an answer or clai --execute 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, diff --git a/go.mod b/go.mod index c1a4d49..d285ee1 100644 --- a/go.mod +++ b/go.mod @@ -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 @@ -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 diff --git a/internal/app/app.go b/internal/app/app.go index 53dcac5..a1d3cd1 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -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) { @@ -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 { @@ -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) } @@ -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 @@ -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) @@ -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 @@ -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": @@ -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 @@ -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) @@ -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 diff --git a/internal/app/clipboard.go b/internal/app/clipboard.go new file mode 100644 index 0000000..7fd42a2 --- /dev/null +++ b/internal/app/clipboard.go @@ -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()) + } + } +} diff --git a/internal/app/clipboard_test.go b/internal/app/clipboard_test.go new file mode 100644 index 0000000..16c641b --- /dev/null +++ b/internal/app/clipboard_test.go @@ -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") + } + }) + } +} diff --git a/internal/app/prompts.go b/internal/app/prompts.go index 74839af..4cf6207 100644 --- a/internal/app/prompts.go +++ b/internal/app/prompts.go @@ -29,15 +29,15 @@ func CurrentVersion() string { 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 shellFollowUpGuidance = shellFollowUpContext + " Put the example in a fenced Markdown code block tagged bash 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 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 examples in fenced Markdown code blocks tagged bash 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. " + shellFollowUpGuidance +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 examples in fenced Markdown code blocks tagged bash 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. " + 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." @@ -95,12 +95,13 @@ func queryGuidance(kind, configured string) string { func templateMessages(kind, system string) []model.Message { messages := []model.Message{model.TextMessage("system", system)} + const listFilesAdvice = `{ "cmd": "", "info": "List all files, including hidden ones:\n\n~~~bash\nls -a\n~~~", "risk": "none", "variables": [] }` add := func(user, assistant string) { messages = append(messages, model.TextMessage("user", user), model.TextMessage("assistant", assistant)) } switch kind { case "question": - add("how do I list all files?", `{ "cmd": "", "info": "List all files, including hidden ones:\n\n ls -a", "risk": "none", "variables": [] }`) + add("how do I list all files?", listFilesAdvice) add("how do I autocomplete commands?", `{ "cmd": "", "info": "Press Tab to autocomplete commands, file names, and directories.", "risk": "none", "variables": [] }`) case "how_to": add("how do I list all files?", `{ "cmd": "ls -a", "info": "Lists all files, including hidden ones.", "risk": "none", "variables": [] }`) @@ -112,7 +113,7 @@ func templateMessages(kind, system string) []model.Message { default: add("what is the time?", `{ "cmd": "date", "info": "shows the current system date and time", "risk": "none", "variables": [] }`) if kind != "execute" { - add("how do I list all files", `{ "cmd": "", "info": "List all files, including hidden ones:\n\n ls -a", "risk": "none", "variables": [] }`) + add("how do I list all files", listFilesAdvice) } add("list all files", `{ "cmd": "ls -a", "info": "lists all files, including hidden ones", "risk": "none", "variables": [] }`) add("remove the hello world folder", `{ "cmd": "rm -r \"hello world\"", "info": "recursively removes the folder and its contents", "risk": "danger zone", "variables": [] }`) diff --git a/internal/app/terminal_handoff.go b/internal/app/terminal_handoff.go index 6825615..cf34b88 100644 --- a/internal/app/terminal_handoff.go +++ b/internal/app/terminal_handoff.go @@ -1,6 +1,7 @@ package app import ( + "context" "errors" "io" "os" @@ -12,14 +13,14 @@ import ( // successfully written handoff to its parent wrapper instead of normal success. var ErrShellHandoff = errors.New("shell handoff prepared") -func (a *Application) offerTerminal(command string, failed bool) error { +func (a *Application) offerTerminal(ctx context.Context, command string, failed bool) error { a.UI.Info("This command appears to need a full terminal. CLAI captures output through pipes and cannot provide that interface.") if failed { a.UI.Info("The command may have partially completed. Review it before running it again; CLAI will not retry it automatically.") } - choice, err := a.UI.Choice("return to your shell with this command? [t/N]: ") + choice, err := a.commandChoice(ctx, "return to your shell with this command? [c/t/N] (c: copy): ", command) if errors.Is(err, io.EOF) && choice == "" { - return a.copyTerminalCommand(command) + return a.displayTerminalCommand(command) } if err != nil && !errors.Is(err, io.EOF) { return err @@ -44,10 +45,10 @@ func (a *Application) handoffCommand(command string) error { a.UI.Error("Could not prepare shell handoff: " + err.Error()) } } - return a.copyTerminalCommand(command) + return a.displayTerminalCommand(command) } -func (a *Application) copyTerminalCommand(command string) error { +func (a *Application) displayTerminalCommand(command string) error { a.UI.Info("Without Bash/zsh handoff integration, copy this command and run it directly in Bash after CLAI exits.") a.UI.Plain(command + "\n") a.exitToShell = true diff --git a/internal/app/terminal_handoff_test.go b/internal/app/terminal_handoff_test.go index 03f4924..4a41c17 100644 --- a/internal/app/terminal_handoff_test.go +++ b/internal/app/terminal_handoff_test.go @@ -112,7 +112,7 @@ func TestInteractiveSessionExitsAfterHandoff(t *testing.T) { func TestHandoffEOFDisplaysCommandWithoutQueuing(t *testing.T) { app, runner, output, path := handoffFixture(t, "") - if err := app.offerTerminal("tmux attach -t work", true); err != nil { + if err := app.offerTerminal(t.Context(), "tmux attach -t work", true); err != nil { t.Fatal(err) } if !app.exitToShell || len(runner.calls) != 0 || !strings.Contains(output.String(), "\ntmux attach -t work\n") { @@ -125,7 +125,7 @@ func TestHandoffEOFDisplaysCommandWithoutQueuing(t *testing.T) { func TestHandoffChoiceWithoutTrailingNewline(t *testing.T) { app, _, _, path := handoffFixture(t, "t") - if err := app.offerTerminal("tmux attach", false); !errors.Is(err, ErrShellHandoff) { + if err := app.offerTerminal(t.Context(), "tmux attach", false); !errors.Is(err, ErrShellHandoff) { t.Fatalf("explicit choice at EOF was ignored: %v", err) } if _, err := os.Stat(path); err != nil { @@ -138,7 +138,7 @@ func TestExistingHandoffFileNeverSignalsSuccess(t *testing.T) { if err := os.WriteFile(path, []byte("stale command"), 0o600); err != nil { t.Fatal(err) } - if err := app.offerTerminal("tmux attach", false); err != nil { + if err := app.offerTerminal(t.Context(), "tmux attach", false); err != nil { t.Fatalf("failed exclusive write must use copy fallback, not a handoff status: %v", err) } data, err := os.ReadFile(path) diff --git a/internal/clipboard/clipboard.go b/internal/clipboard/clipboard.go new file mode 100644 index 0000000..1fc236f --- /dev/null +++ b/internal/clipboard/clipboard.go @@ -0,0 +1,67 @@ +package clipboard + +import ( + "context" + "encoding/base64" + "fmt" + "io" + "os" + "os/exec" + "runtime" + "strings" + + "golang.org/x/term" +) + +// Copy sends text to a local clipboard helper or to the visible terminal. +// terminal reports whether we sent an OSC 52 request without an acknowledgement. +func Copy(ctx context.Context, text string, output io.Writer) (terminal bool, err error) { + var localErr error + if os.Getenv("SSH_CONNECTION") == "" { + for _, helper := range localHelpers() { + process := exec.CommandContext(ctx, helper[0], helper[1:]...) + process.Stdin = strings.NewReader(text) + if err := process.Run(); err != nil { + localErr = fmt.Errorf("%s: %w", helper[0], err) + continue + } + return false, nil + } + } + if err := ctx.Err(); err != nil { + return false, err + } + if file, ok := output.(*os.File); ok && term.IsTerminal(int(file.Fd())) && os.Getenv("TERM") != "dumb" { + encoded := base64.StdEncoding.EncodeToString([]byte(text)) + _, err := io.WriteString(output, "\x1b]52;c;"+encoded+"\x1b\\") + return true, err + } + if localErr != nil { + return false, fmt.Errorf("clipboard unavailable: %w", localErr) + } + return false, fmt.Errorf("clipboard unavailable in this session") +} + +const windowsClipboard = `$ErrorActionPreference = 'Stop'; $reader = [IO.StreamReader]::new([Console]::OpenStandardInput(), [Text.Encoding]::UTF8, $false); Set-Clipboard -Value ($reader.ReadToEnd())` + +func localHelpers() [][]string { + windows := []string{"powershell.exe", "-NoProfile", "-NonInteractive", "-Command", windowsClipboard} + switch runtime.GOOS { + case "darwin": + return [][]string{{"pbcopy"}} + case "windows": + return [][]string{windows, {"pwsh.exe", "-NoProfile", "-NonInteractive", "-Command", windowsClipboard}} + default: + var helpers [][]string + if os.Getenv("WSL_INTEROP") != "" || os.Getenv("WSL_DISTRO_NAME") != "" { + helpers = append(helpers, windows) + } + if os.Getenv("WAYLAND_DISPLAY") != "" || os.Getenv("WAYLAND_SOCKET") != "" { + helpers = append(helpers, []string{"wl-copy"}) + } + if os.Getenv("DISPLAY") != "" { + helpers = append(helpers, []string{"xclip", "-selection", "clipboard", "-in"}, []string{"xsel", "--clipboard", "--input"}) + } + return helpers + } +} diff --git a/internal/history/commands.go b/internal/history/commands.go new file mode 100644 index 0000000..24e2914 --- /dev/null +++ b/internal/history/commands.go @@ -0,0 +1,94 @@ +package history + +import ( + "encoding/json" + "strings" + + "github.com/merefield/clai/internal/model" + "github.com/yuin/goldmark" + "github.com/yuin/goldmark/ast" + "github.com/yuin/goldmark/text" +) + +// RecordCommand attaches an example or edited command to the current reply. +func (s *Store) RecordCommand(command string) { + if command != "" && len(s.Messages) > 0 && s.Messages[len(s.Messages)-1].Role == "assistant" { + s.Messages[len(s.Messages)-1].CopyCommand = command + s.dirty = true + } +} + +// LatestCommand uses only the latest recorded turn and prefers the command +// run or proposed in that turn over any examples in its prose. +func (s *Store) LatestCommand() string { + var example string + for i := len(s.Messages) - 1; i >= 0; i-- { + message := s.Messages[i] + if message.Role == "user" { + break + } + if message.Role != "assistant" || len(message.ToolCalls) > 0 { + continue + } + if message.CopyCommand != "" { + return message.CopyCommand + } + var reply struct { + model.Reply + Result *model.CommandResult `json:"command_result"` + } + if json.Unmarshal([]byte(message.ContentText()), &reply) != nil { + continue + } + if reply.Result != nil && reply.Result.Command != "" { + return reply.Result.Command + } + if reply.Command != "" { + return reply.Command + } + if example == "" { + example = shellExample(reply.Info) + } + } + return example +} + +func shellExample(info string) string { + if !strings.Contains(info, "```") && !strings.Contains(info, "~~~") && !strings.HasPrefix(info, " ") { + return "" + } + source := []byte(info) + document := goldmark.DefaultParser().Parse(text.NewReader(source)) + var example string + _ = ast.Walk(document, func(node ast.Node, entering bool) (ast.WalkStatus, error) { + if !entering { + return ast.WalkContinue, nil + } + switch block := node.(type) { + case *ast.FencedCodeBlock: + switch strings.ToLower(string(block.Language(source))) { + case "bash", "sh", "shell", "zsh": + default: + return ast.WalkSkipChildren, nil + } + case *ast.CodeBlock: + // Releases before copy support stored how-to commands this way. + if node != document.FirstChild() || !strings.HasPrefix(info, " ") { + return ast.WalkSkipChildren, nil + } + default: + return ast.WalkContinue, nil + } + var command strings.Builder + lines := node.Lines() + for i := 0; i < lines.Len(); i++ { + line := lines.At(i) + command.Write(line.Value(source)) + } + if snippet := strings.TrimSuffix(command.String(), "\n"); strings.TrimSpace(snippet) != "" { + example = snippet + } + return ast.WalkSkipChildren, nil + }) + return example +} diff --git a/internal/history/store.go b/internal/history/store.go index 8120f71..8158efa 100644 --- a/internal/history/store.go +++ b/internal/history/store.go @@ -17,6 +17,11 @@ type Store struct { dirty bool } +type storedMessage struct { + model.Message + CopyCommand string `json:"copy_command,omitempty"` +} + func DefaultPath() (string, error) { if path := os.Getenv("CLAI_HISTORY"); path != "" { return path, nil @@ -41,9 +46,14 @@ func Load(path string) (*Store, error) { if err != nil { return nil, err } - if err := json.Unmarshal(b, &s.Messages); err != nil { + var records []storedMessage + if err := json.Unmarshal(b, &records); err != nil { return s, fmt.Errorf("parse history: %w", err) } + for _, record := range records { + record.Message.CopyCommand = record.CopyCommand + s.Messages = append(s.Messages, record.Message) + } s.dropSystemMessages() return s, nil } @@ -122,7 +132,11 @@ func (s *Store) Save(maxTurns int) error { start = len(s.Messages) - maxTurns } s.Messages = append([]model.Message(nil), s.Messages[start:]...) - b, err := json.Marshal(s.Messages) + records := make([]storedMessage, 0, len(s.Messages)) + for _, message := range s.Messages { + records = append(records, storedMessage{Message: message, CopyCommand: message.CopyCommand}) + } + b, err := json.Marshal(records) if err != nil { return err } diff --git a/internal/history/store_test.go b/internal/history/store_test.go index 73dc734..808f2c2 100644 --- a/internal/history/store_test.go +++ b/internal/history/store_test.go @@ -1,6 +1,7 @@ package history import ( + "encoding/json" "path/filepath" "strings" "testing" @@ -38,3 +39,37 @@ func TestRenderCommandResult(t *testing.T) { t.Fatalf("rendered = %s", rendered) } } + +func TestLatestCommandFromExistingHistory(t *testing.T) { + store := &Store{} + store.AppendText("user", "previous") + if err := store.AppendReply(model.Reply{Info: " tmux attach\n\nAttaches to a session."}); err != nil { + t.Fatal(err) + } + if command := store.LatestCommand(); command != "tmux attach" { + t.Fatalf("previous how-to example = %q", command) + } + store.AppendText("user", "execute") + if err := store.AppendReply(model.Reply{Command: "printf original"}); err != nil { + t.Fatal(err) + } + if err := store.AppendCommandResult(model.CommandResult{Command: "printf edited", Edited: true}); err != nil { + t.Fatal(err) + } + if err := store.AppendReply(model.Reply{Info: "Shows the output."}); err != nil { + t.Fatal(err) + } + if command := store.LatestCommand(); command != "printf edited" { + t.Fatalf("previous command result = %q", command) + } +} + +func TestCopyCommandIsExcludedFromProviderMessages(t *testing.T) { + store := &Store{} + store.AppendText("assistant", "{}") + store.RecordCommand("local edit") + payload, err := json.Marshal(store.Messages) + if err != nil || strings.Contains(string(payload), "local edit") { + t.Fatalf("provider messages include local clipboard metadata: %s, %v", payload, err) + } +} diff --git a/internal/model/model.go b/internal/model/model.go index 0d7908c..21a07c4 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -36,6 +36,8 @@ type Message struct { Content json.RawMessage `json:"content"` ToolCallID string `json:"tool_call_id,omitempty"` ToolCalls []ToolCall `json:"tool_calls,omitempty"` + // CopyCommand is local history metadata, never part of a provider message. + CopyCommand string `json:"-"` } func TextMessage(role, content string) Message {