package bot import ( "encoding/json" "path" "regexp" "strings" "slackerbot/internal/acp" ) const toolLineMax = 80 // runes of a command shown in the reply // Prefixes that say little about what a command does. Each match is removed // from the start, repeatedly, so `cd x && timeout 60 nix develop -c go test` // shows as `go test`. var ( cdPrefix = regexp.MustCompile(`^cd\s+("[^"]*"|'[^']*'|\S+)\s*(&&|;)\s*`) timeoutPrefix = regexp.MustCompile(`^timeout\s+(-\S+\s+(\d\S*\s+)?)*\d+[smhd]?\s+`) developPrefix = regexp.MustCompile(`^nix\s+develop\b[^&|;]*?\s(-c|--command)\s+`) envPrefix = regexp.MustCompile(`^(env\s+)?([A-Za-z_]\w*=("[^"]*"|'[^']*'|\S*)\s+)+`) spaces = regexp.MustCompile(`\s+`) ) // toolLine is how a tool call shows in the reply. Goose's titles for shell // calls are the command cut at ~40 characters, mostly spent on `cd …`, so // those use the full command from rawInput with the noise stripped. func toolLine(u acp.Update) string { if cmd, ok := shellCommand(u); ok { cmd, dir := trimCommand(cmd) line := "`" + clip(strings.ReplaceAll(cmd, "`", "'"), toolLineMax) + "`" if dir != "" && dir != "/root" && dir != "~" { line += " (" + path.Base(dir) + ")" } return line } // "todo: todo write" → "todo write" if name, rest, ok := strings.Cut(u.Title, ": "); ok && strings.HasPrefix(rest, name+" ") { return rest } return u.Title } func shellCommand(u acp.Update) (string, bool) { if !strings.HasSuffix(u.ToolName, "shell") && !strings.HasPrefix(u.Title, "shell") { return "", false } var in struct { Command string `json:"command"` } if json.Unmarshal(u.RawInput, &in) != nil || strings.TrimSpace(in.Command) == "" { return "", false } return in.Command, true } // trimCommand strips the prefixes above and returns the last directory cd'd into. func trimCommand(cmd string) (string, string) { cmd = strings.TrimSpace(spaces.ReplaceAllString(cmd, " ")) orig, dir := cmd, "" for { if cmd == "" { return orig, "" } if m := cdPrefix.FindStringSubmatch(cmd); m != nil { dir = strings.Trim(m[1], `"'`) cmd = cmd[len(m[0]):] continue } rest := cmd for _, re := range []*regexp.Regexp{timeoutPrefix, developPrefix, envPrefix} { if m := re.FindString(rest); m != "" { rest = rest[len(m):] break } } if rest == cmd || strings.TrimSpace(rest) == "" { return cmd, dir } cmd = rest } } func clip(s string, max int) string { r := []rune(s) if len(r) <= max { return s } return strings.TrimSpace(string(r[:max-1])) + "…" }