12 Commits

Author SHA1 Message Date
Grail Finder
1f112259d2 Enha(tools.todo): always provide whole todo list 2026-03-01 07:01:13 +03:00
Grail Finder
a505ffaaa9 Fix (tool): handle subcommands 2026-02-28 16:16:32 +03:00
Grail Finder
32be271aa3 Feat (tools): file_edit 2026-02-28 15:40:52 +03:00
Grail Finder
133ec27938 Feat(shell): cd and pipes support 2026-02-28 13:59:54 +03:00
Grail Finder
d79760a289 Fix: do not delete tool calls or lose them on copy 2026-02-28 10:23:03 +03:00
Grail Finder
2580360f91 Fix: removed code that deletes tool calls 2026-02-28 09:13:05 +03:00
Grail Finder
fe4dd0c982 Enha: add go to allowed commands 2026-02-28 08:39:13 +03:00
Grail Finder
83f99d3577 Enha: first chat name convention 2026-02-28 08:09:56 +03:00
Grail Finder
e521434073 Refactor: move msg totext method to main package
logic requires reference to config
2026-02-28 07:57:49 +03:00
Grail Finder
916c5d3904 Enha: icon for collapsed tools 2026-02-27 21:25:26 +03:00
Grail Finder
5b1cbb46fa Chore: linter complaints 2026-02-27 20:03:47 +03:00
Grail Finder
1fcab8365e Enha: tool filter 2026-02-27 18:45:59 +03:00
15 changed files with 591 additions and 636 deletions

View File

@@ -1,4 +1,4 @@
.PHONY: setconfig run lint install-linters setup-whisper build-whisper download-whisper-model docker-up docker-down docker-logs noextra-run installdelve checkdelve
.PHONY: setconfig run lint lintall install-linters setup-whisper build-whisper download-whisper-model docker-up docker-down docker-logs noextra-run installdelve checkdelve
run: setconfig
go build -tags extra -o gf-lt && ./gf-lt
@@ -25,7 +25,10 @@ install-linters: ## Install additional linters (noblanks)
go install github.com/GrailFinder/noblanks-linter/cmd/noblanks@latest
lint: ## Run linters. Use make install-linters first.
golangci-lint run -c .golangci.yml ./...; noblanks ./...
golangci-lint run -c .golangci.yml ./...
lintall: lint
noblanks ./...
# Whisper STT Setup (in batteries directory)
setup-whisper: build-whisper download-whisper-model

View File

@@ -71,8 +71,8 @@ func (ag *AgentClient) buildRequest(sysprompt, msg string) ([]byte, error) {
// Build prompt for completion endpoints
if isCompletion {
var sb strings.Builder
for _, m := range messages {
sb.WriteString(m.ToPrompt())
for i := range messages {
sb.WriteString(messages[i].ToPrompt())
sb.WriteString("\n")
}
prompt := strings.TrimSpace(sb.String())

247
bot.go
View File

@@ -66,6 +66,8 @@ var (
LocalModels = []string{}
)
var thinkBlockRE = regexp.MustCompile(`(?s)<think>.*?</think>`)
// parseKnownToTag extracts known_to list from content using configured tag.
// Returns cleaned content and list of character names.
func parseKnownToTag(content string) []string {
@@ -136,6 +138,9 @@ func processMessageTag(msg *models.RoleMsg) *models.RoleMsg {
// filterMessagesForCharacter returns messages visible to the specified character.
// If CharSpecificContextEnabled is false, returns all messages.
func filterMessagesForCharacter(messages []models.RoleMsg, character string) []models.RoleMsg {
if strings.Contains(cfg.CurrentAPI, "chat") {
return messages
}
if cfg == nil || !cfg.CharSpecificContextEnabled || character == "" {
return messages
}
@@ -143,97 +148,67 @@ func filterMessagesForCharacter(messages []models.RoleMsg, character string) []m
return messages
}
filtered := make([]models.RoleMsg, 0, len(messages))
for _, msg := range messages {
for i := range messages {
// If KnownTo is nil or empty, message is visible to all
// system msg cannot be filtered
if len(msg.KnownTo) == 0 || msg.Role == "system" {
filtered = append(filtered, msg)
if len(messages[i].KnownTo) == 0 || messages[i].Role == "system" {
filtered = append(filtered, messages[i])
continue
}
if slices.Contains(msg.KnownTo, character) {
if slices.Contains(messages[i].KnownTo, character) {
// Check if character is in KnownTo lis
filtered = append(filtered, msg)
filtered = append(filtered, messages[i])
}
}
return filtered
}
func cleanToolCalls(messages []models.RoleMsg) []models.RoleMsg {
// If AutoCleanToolCallsFromCtx is false, keep tool call messages in context
if cfg != nil && !cfg.AutoCleanToolCallsFromCtx {
return consolidateAssistantMessages(messages)
}
cleaned := make([]models.RoleMsg, 0, len(messages))
for i, msg := range messages {
// recognize the message as the tool call and remove it
// tool call in last msg should stay
if msg.ToolCallID == "" || i == len(messages)-1 {
cleaned = append(cleaned, msg)
}
}
return consolidateAssistantMessages(cleaned)
}
// consolidateAssistantMessages merges consecutive assistant messages into a single message
func consolidateAssistantMessages(messages []models.RoleMsg) []models.RoleMsg {
if len(messages) == 0 {
return messages
}
consolidated := make([]models.RoleMsg, 0, len(messages))
currentAssistantMsg := models.RoleMsg{}
isBuildingAssistantMsg := false
for i := 0; i < len(messages); i++ {
msg := messages[i]
// assistant role only
if msg.Role == cfg.AssistantRole {
// If this is an assistant message, start or continue building
if !isBuildingAssistantMsg {
// Start accumulating assistant message
currentAssistantMsg = msg.Copy()
isBuildingAssistantMsg = true
} else {
// Continue accumulating - append content to the current assistant message
if currentAssistantMsg.IsContentParts() || msg.IsContentParts() {
// Handle structured content
if !currentAssistantMsg.IsContentParts() {
// Preserve the original ToolCallID before conversion
originalToolCallID := currentAssistantMsg.ToolCallID
// Convert existing content to content parts
currentAssistantMsg = models.NewMultimodalMsg(currentAssistantMsg.Role, []interface{}{models.TextContentPart{Type: "text", Text: currentAssistantMsg.Content}})
// Restore the original ToolCallID to preserve tool call linking
currentAssistantMsg.ToolCallID = originalToolCallID
result := make([]models.RoleMsg, 0, len(messages))
for i := range messages {
// Non-assistant messages are appended as-is
if messages[i].Role != cfg.AssistantRole {
result = append(result, messages[i])
continue
}
if msg.IsContentParts() {
currentAssistantMsg.ContentParts = append(currentAssistantMsg.ContentParts, msg.GetContentParts()...)
} else if msg.Content != "" {
currentAssistantMsg.AddTextPart(msg.Content)
// Assistant message: start a new block or merge with the last one
if len(result) == 0 || result[len(result)-1].Role != cfg.AssistantRole {
// First assistant in a block: append a copy (avoid mutating input)
result = append(result, messages[i].Copy())
continue
}
// Merge with the last assistant message
last := &result[len(result)-1]
// If either message has structured content, unify to ContentParts
if last.IsContentParts() || messages[i].IsContentParts() {
// Convert last to ContentParts if needed, preserving ToolCallID
if !last.IsContentParts() {
toolCallID := last.ToolCallID
*last = models.NewMultimodalMsg(last.Role, []interface{}{
models.TextContentPart{Type: "text", Text: last.Content},
})
last.ToolCallID = toolCallID
}
// Add current message's content to last
if messages[i].IsContentParts() {
last.ContentParts = append(last.ContentParts, messages[i].GetContentParts()...)
} else if messages[i].Content != "" {
last.AddTextPart(messages[i].Content)
}
} else {
// Simple string content
if currentAssistantMsg.Content != "" {
currentAssistantMsg.Content += "\n" + msg.Content
} else {
currentAssistantMsg.Content = msg.Content
// Both simple strings: concatenate with newline
if last.Content != "" && messages[i].Content != "" {
last.Content += "\n" + messages[i].Content
} else if messages[i].Content != "" {
last.Content = messages[i].Content
}
// ToolCallID is already preserved since we're not creating a new message object when just concatenating content
// ToolCallID is already preserved in last
}
}
} else {
// This is not an assistant message
// If we were building an assistant message, add it to the result
if isBuildingAssistantMsg {
consolidated = append(consolidated, currentAssistantMsg)
isBuildingAssistantMsg = false
}
// Add the non-assistant message
consolidated = append(consolidated, msg)
}
}
// Don't forget the last assistant message if we were building one
if isBuildingAssistantMsg {
consolidated = append(consolidated, currentAssistantMsg)
}
return consolidated
return result
}
// GetLogLevel returns the current log level as a string
@@ -777,7 +752,7 @@ func showSpinner() {
botPersona = cfg.WriteNextMsgAsCompletionAgent
}
for botRespMode || toolRunningMode {
time.Sleep(100 * time.Millisecond)
time.Sleep(400 * time.Millisecond)
spin := i % len(spinners)
app.QueueUpdateDraw(func() {
switch {
@@ -960,7 +935,9 @@ out:
if err := updateStorageChat(activeChatName, chatBody.Messages); err != nil {
logger.Warn("failed to update storage", "error", err, "name", activeChatName)
}
if findCall(respText.String(), toolResp.String()) {
// Strip think blocks before parsing for tool calls
respTextNoThink := thinkBlockRE.ReplaceAllString(respText.String(), "")
if findCall(respTextNoThink, toolResp.String()) {
return nil
}
// Check if this message was sent privately to specific characters
@@ -982,7 +959,7 @@ func cleanChatBody() {
}
// Tool request cleaning is now configurable via AutoCleanToolCallsFromCtx (default false)
// /completion msg where part meant for user and other part tool call
chatBody.Messages = cleanToolCalls(chatBody.Messages)
// chatBody.Messages = cleanToolCalls(chatBody.Messages)
chatBody.Messages = consolidateAssistantMessages(chatBody.Messages)
}
@@ -1096,22 +1073,38 @@ func findCall(msg, toolCall string) bool {
}
lastToolCall.Args = openAIToolMap
fc = lastToolCall
// Set lastToolCall.ID from parsed tool call ID if available
if len(openAIToolMap) > 0 {
if id, exists := openAIToolMap["id"]; exists {
lastToolCall.ID = id
}
}
// NOTE: We do NOT override lastToolCall.ID from arguments.
// The ID should come from the streaming response (chunk.ToolID) set earlier.
// Some tools like todo_create have "id" in their arguments which is NOT the tool call ID.
} else {
jsStr := toolCallRE.FindString(msg)
if jsStr == "" { // no tool call case
return false
}
prefix := "__tool_call__\n"
suffix := "\n__tool_call__"
jsStr = strings.TrimSuffix(strings.TrimPrefix(jsStr, prefix), suffix)
// Remove prefix/suffix with flexible whitespace handling
jsStr = strings.TrimSpace(jsStr)
jsStr = strings.TrimPrefix(jsStr, "__tool_call__")
jsStr = strings.TrimSuffix(jsStr, "__tool_call__")
jsStr = strings.TrimSpace(jsStr)
// HTML-decode the JSON string to handle encoded characters like &lt; -> <=
decodedJsStr := html.UnescapeString(jsStr)
// Try to find valid JSON bounds (first { to last })
start := strings.Index(decodedJsStr, "{")
end := strings.LastIndex(decodedJsStr, "}")
if start == -1 || end == -1 || end <= start {
logger.Error("failed to find valid JSON in tool call", "json_string", decodedJsStr)
toolResponseMsg := models.RoleMsg{
Role: cfg.ToolRole,
Content: "Error processing tool call: no valid JSON found. Please check the JSON format.",
}
chatBody.Messages = append(chatBody.Messages, toolResponseMsg)
crr := &models.ChatRoundReq{
Role: cfg.AssistantRole,
}
chatRoundChan <- crr
return true
}
decodedJsStr = decodedJsStr[start : end+1]
var err error
fc, err = unmarshalFuncCall(decodedJsStr)
if err != nil {
@@ -1138,14 +1131,18 @@ func findCall(msg, toolCall string) bool {
lastToolCall.Args = fc.Args
}
// we got here => last msg recognized as a tool call (correct or not)
// make sure it has ToolCallID
if chatBody.Messages[len(chatBody.Messages)-1].ToolCallID == "" {
// Tool call IDs should be alphanumeric strings with length 9!
chatBody.Messages[len(chatBody.Messages)-1].ToolCallID = randString(9)
// Use the tool call ID from streaming response (lastToolCall.ID)
// Don't generate random ID - the ID should match between assistant message and tool response
lastMsgIdx := len(chatBody.Messages) - 1
if lastToolCall.ID != "" {
chatBody.Messages[lastMsgIdx].ToolCallID = lastToolCall.ID
}
// Ensure lastToolCall.ID is set, fallback to assistant message's ToolCallID
if lastToolCall.ID == "" {
lastToolCall.ID = chatBody.Messages[len(chatBody.Messages)-1].ToolCallID
// Store tool call info in the assistant message
// Convert Args map to JSON string for storage
chatBody.Messages[lastMsgIdx].ToolCall = &models.ToolCall{
ID: lastToolCall.ID,
Name: lastToolCall.Name,
Args: mapToString(lastToolCall.Args),
}
// call a func
_, ok := fnMap[fc.Name]
@@ -1175,15 +1172,18 @@ func findCall(msg, toolCall string) bool {
toolRunningMode = true
resp := callToolWithAgent(fc.Name, fc.Args)
toolRunningMode = false
toolMsg := string(resp) // Remove the "tool response: " prefix and %+v formatting
toolMsg := string(resp)
logger.Info("llm used a tool call", "tool_name", fc.Name, "too_args", fc.Args, "id", fc.ID, "tool_resp", toolMsg)
fmt.Fprintf(textView, "%s[-:-:b](%d) <%s>: [-:-:-]\n%s\n",
"\n\n", len(chatBody.Messages), cfg.ToolRole, toolMsg)
// Create tool response message with the proper tool_call_id
// Mark shell commands as always visible
isShellCommand := fc.Name == "execute_command"
toolResponseMsg := models.RoleMsg{
Role: cfg.ToolRole,
Content: toolMsg,
ToolCallID: lastToolCall.ID, // Use the stored tool call ID
ToolCallID: lastToolCall.ID,
IsShellCommand: isShellCommand,
}
chatBody.Messages = append(chatBody.Messages, toolResponseMsg)
logger.Debug("findCall: added actual tool response", "role", toolResponseMsg.Role, "content_len", len(toolResponseMsg.Content), "tool_call_id", toolResponseMsg.ToolCallID, "message_count_after_add", len(chatBody.Messages))
@@ -1200,12 +1200,42 @@ func findCall(msg, toolCall string) bool {
func chatToTextSlice(messages []models.RoleMsg, showSys bool) []string {
resp := make([]string, len(messages))
for i, msg := range messages {
// INFO: skips system msg and tool msg
if !showSys && (msg.Role == cfg.ToolRole || msg.Role == "system") {
for i := range messages {
icon := fmt.Sprintf("[-:-:b](%d) <%s>:[-:-:-]", i, messages[i].Role)
// Handle tool call indicators (assistant messages with tool call but empty content)
if messages[i].Role == cfg.AssistantRole && messages[i].ToolCall != nil && messages[i].ToolCall.ID != "" {
// This is a tool call indicator - show collapsed
if toolCollapsed {
toolName := messages[i].ToolCall.Name
resp[i] = fmt.Sprintf("%s\n[yellow::i][tool call: %s (press Ctrl+T to expand)][-:-:-]\n", icon, toolName)
} else {
// Show full tool call info
toolName := messages[i].ToolCall.Name
resp[i] = fmt.Sprintf("%s\n%s\n[yellow::i][tool call: %s][-:-:-]\nargs: %s\nid: %s\n", icon, messages[i].GetText(), toolName, messages[i].ToolCall.Args, messages[i].ToolCall.ID)
}
continue
}
resp[i] = msg.ToText(i)
// Handle tool responses
if messages[i].Role == cfg.ToolRole || messages[i].Role == "tool" {
// Always show shell commands
if messages[i].IsShellCommand {
resp[i] = MsgToText(i, &messages[i])
continue
}
// Hide non-shell tool responses when collapsed
if toolCollapsed {
resp[i] = icon + "\n[yellow::i][tool resp (press Ctrl+T to expand)][-:-:-]\n"
continue
}
// When expanded, show tool responses
resp[i] = MsgToText(i, &messages[i])
continue
}
// INFO: skips system msg when showSys is false
if !showSys && messages[i].Role == "system" {
continue
}
resp[i] = MsgToText(i, &messages[i])
}
return resp
}
@@ -1239,20 +1269,6 @@ func chatToText(messages []models.RoleMsg, showSys bool) string {
return text
}
func removeThinking(chatBody *models.ChatBody) {
msgs := []models.RoleMsg{}
for _, msg := range chatBody.Messages {
// Filter out tool messages and thinking markers
if msg.Role == cfg.ToolRole {
continue
}
// find thinking and remove it - use SetText to preserve ContentParts
msg.SetText(thinkRE.ReplaceAllString(msg.GetText(), ""))
msgs = append(msgs, msg)
}
chatBody.Messages = msgs
}
func addNewChat(chatName string) {
id, err := store.ChatGetMaxID()
if err != nil {
@@ -1374,15 +1390,6 @@ func init() {
os.Exit(1)
return
}
// Set image base directory for path display
baseDir := cfg.FilePickerDir
if baseDir == "" || baseDir == "." {
// Resolve "." to current working directory
if wd, err := os.Getwd(); err == nil {
baseDir = wd
}
}
models.SetImageBaseDir(baseDir)
defaultStarter = []models.RoleMsg{
{Role: "system", Content: basicSysMsg},
{Role: cfg.AssistantRole, Content: defaultFirstMsg},
@@ -1397,8 +1404,6 @@ func init() {
}
// load cards
basicCard.Role = cfg.AssistantRole
// toolCard.Role = cfg.AssistantRole
//
logLevel.Set(slog.LevelInfo)
logger = slog.New(slog.NewTextHandler(logfile, &slog.HandlerOptions{Level: logLevel}))
store = storage.NewProviderSQL(cfg.DBPATH, logger)

View File

@@ -27,7 +27,6 @@ AutoCleanToolCallsFromCtx = false
RAGEnabled = false
RAGBatchSize = 1
RAGWordLimit = 80
RAGWorkers = 2
RAGDir = "ragimport"
# extra tts
TTS_ENABLED = false

View File

@@ -39,7 +39,6 @@ type Config struct {
// rag settings
RAGEnabled bool `toml:"RAGEnabled"`
RAGDir string `toml:"RAGDir"`
RAGWorkers uint32 `toml:"RAGWorkers"`
RAGBatchSize int `toml:"RAGBatchSize"`
RAGWordLimit uint32 `toml:"RAGWordLimit"`
// deepseek

View File

@@ -80,9 +80,6 @@ This document explains how to set up and configure the application using the `co
#### RAGWordLimit (`80`)
- Maximum number of words in a batch to tokenize and store.
#### RAGWorkers (`2`)
- Number of concurrent workers for RAG processing.
#### RAGDir (`"ragimport"`)
- Directory containing documents for RAG processing.

View File

@@ -15,8 +15,6 @@ import (
"time"
"unicode"
"math/rand/v2"
"github.com/rivo/tview"
)
@@ -68,6 +66,14 @@ func isASCII(s string) bool {
return true
}
func mapToString[V any](m map[string]V) string {
rs := strings.Builder{}
for k, v := range m {
fmt.Fprintf(&rs, "%v: %v\n", k, v)
}
return rs.String()
}
// stripThinkingFromMsg removes thinking blocks from assistant messages.
// Skips user, tool, and system messages as they may contain thinking examples.
func stripThinkingFromMsg(msg *models.RoleMsg) *models.RoleMsg {
@@ -375,16 +381,6 @@ func makeStatusLine() string {
return statusLine + imageInfo + shellModeInfo
}
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func randString(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.IntN(len(letters))]
}
return string(b)
}
// set of roles within card definition and mention in chat history
func listChatRoles() []string {
currentChat, ok := chatMap[activeChatName]
@@ -465,9 +461,8 @@ func updateFlexLayout() {
}
func executeCommandAndDisplay(cmdText string) {
// Parse the command (split by spaces, but handle quoted arguments)
cmdParts := parseCommand(cmdText)
if len(cmdParts) == 0 {
cmdText = strings.TrimSpace(cmdText)
if cmdText == "" {
fmt.Fprintf(textView, "\n[red]Error: No command provided[-:-:-]\n")
if scrollToEndEnabled {
textView.ScrollToEnd()
@@ -475,14 +470,58 @@ func executeCommandAndDisplay(cmdText string) {
colorText()
return
}
command := cmdParts[0]
args := []string{}
if len(cmdParts) > 1 {
args = cmdParts[1:]
workingDir := cfg.FilePickerDir
// Handle cd command specially to update working directory
if strings.HasPrefix(cmdText, "cd ") {
newDir := strings.TrimPrefix(cmdText, "cd ")
newDir = strings.TrimSpace(newDir)
// Handle cd ~ or cdHOME
if strings.HasPrefix(newDir, "~") {
home := os.Getenv("HOME")
newDir = strings.Replace(newDir, "~", home, 1)
}
// Create the command execution
cmd := exec.Command(command, args...)
cmd.Dir = cfg.FilePickerDir
// Check if directory exists
if _, err := os.Stat(newDir); err == nil {
workingDir = newDir
cfg.FilePickerDir = workingDir
// Update shell input label with new directory
shellInput.SetLabel(fmt.Sprintf("[%s]$ ", cfg.FilePickerDir))
outputContent := workingDir
// Add the command being executed to the chat
fmt.Fprintf(textView, "\n[-:-:b](%d) <%s>: [-:-:-]\n$ %s\n",
len(chatBody.Messages), cfg.ToolRole, cmdText)
fmt.Fprintf(textView, "%s\n", outputContent)
combinedMsg := models.RoleMsg{
Role: cfg.ToolRole,
Content: "$ " + cmdText + "\n\n" + outputContent,
}
chatBody.Messages = append(chatBody.Messages, combinedMsg)
if scrollToEndEnabled {
textView.ScrollToEnd()
}
colorText()
return
} else {
outputContent := "cd: " + newDir + ": No such file or directory"
fmt.Fprintf(textView, "\n[-:-:b](%d) <%s>: [-:-:-]\n$ %s\n",
len(chatBody.Messages), cfg.ToolRole, cmdText)
fmt.Fprintf(textView, "[red]%s[-:-:-]\n", outputContent)
combinedMsg := models.RoleMsg{
Role: cfg.ToolRole,
Content: "$ " + cmdText + "\n\n" + outputContent,
}
chatBody.Messages = append(chatBody.Messages, combinedMsg)
if scrollToEndEnabled {
textView.ScrollToEnd()
}
colorText()
return
}
}
// Use /bin/sh to support pipes, redirects, etc.
cmd := exec.Command("/bin/sh", "-c", cmdText)
cmd.Dir = workingDir
// Execute the command and get output
output, err := cmd.CombinedOutput()
// Add the command being executed to the chat
@@ -531,42 +570,6 @@ func executeCommandAndDisplay(cmdText string) {
shellHistoryPos = -1
}
// parseCommand splits command string handling quotes properly
func parseCommand(cmd string) []string {
var args []string
var current string
var inQuotes bool
var quoteChar rune
for _, r := range cmd {
switch r {
case '"', '\'':
if inQuotes {
if r == quoteChar {
inQuotes = false
} else {
current += string(r)
}
} else {
inQuotes = true
quoteChar = r
}
case ' ', '\t':
if inQuotes {
current += string(r)
} else if current != "" {
args = append(args, current)
current = ""
}
default:
current += string(r)
}
}
if current != "" {
args = append(args, current)
}
return args
}
// == search ==
// Global variables for search state
@@ -806,3 +809,91 @@ func scanFiles(dir, filter string) []string {
scanRecursive(dir, 0, "")
return files
}
// models logic that is too complex for models package
func MsgToText(i int, m *models.RoleMsg) string {
var contentStr string
var imageIndicators []string
if !m.HasContentParts {
contentStr = m.Content
} else {
var textParts []string
for _, part := range m.ContentParts {
switch p := part.(type) {
case models.TextContentPart:
if p.Type == "text" {
textParts = append(textParts, p.Text)
}
case models.ImageContentPart:
displayPath := p.Path
if displayPath == "" {
displayPath = "image"
} else {
displayPath = extractDisplayPath(displayPath, cfg.FilePickerDir)
}
imageIndicators = append(imageIndicators, fmt.Sprintf("[orange::i][image: %s][-:-:-]", displayPath))
case map[string]any:
if partType, exists := p["type"]; exists {
switch partType {
case "text":
if textVal, textExists := p["text"]; textExists {
if textStr, isStr := textVal.(string); isStr {
textParts = append(textParts, textStr)
}
}
case "image_url":
var displayPath string
if pathVal, pathExists := p["path"]; pathExists {
if pathStr, isStr := pathVal.(string); isStr && pathStr != "" {
displayPath = extractDisplayPath(pathStr, cfg.FilePickerDir)
}
}
if displayPath == "" {
displayPath = "image"
}
imageIndicators = append(imageIndicators, fmt.Sprintf("[orange::i][image: %s][-:-:-]", displayPath))
}
}
}
}
contentStr = strings.Join(textParts, " ") + " "
}
contentStr, _ = strings.CutPrefix(contentStr, m.Role+":")
icon := fmt.Sprintf("(%d) <%s>: ", i, m.Role)
var finalContent strings.Builder
if len(imageIndicators) > 0 {
for _, indicator := range imageIndicators {
finalContent.WriteString(indicator)
finalContent.WriteString("\n")
}
}
finalContent.WriteString(contentStr)
if m.Stats != nil {
fmt.Fprintf(&finalContent, "\n[gray::i][%d tok, %.1fs, %.1f t/s][-:-:-]", m.Stats.Tokens, m.Stats.Duration, m.Stats.TokensPerSec)
}
textMsg := fmt.Sprintf("[-:-:b]%s[-:-:-]\n%s\n", icon, finalContent.String())
return strings.ReplaceAll(textMsg, "\n\n", "\n")
}
// extractDisplayPath returns a path suitable for display, potentially relative to imageBaseDir
func extractDisplayPath(p, bp string) string {
if p == "" {
return ""
}
// If base directory is set, try to make path relative to it
if bp != "" {
if rel, err := filepath.Rel(bp, p); err == nil {
// Check if relative path doesn't start with ".." (meaning it's within base dir)
// If it starts with "..", we might still want to show it as relative
// but for now we show full path if it goes outside base dir
if !strings.HasPrefix(rel, "..") {
p = rel
}
}
}
// Truncate long paths to last 60 characters if needed
if len(p) > 60 {
return "..." + p[len(p)-60:]
}
return p
}

72
llm.go
View File

@@ -14,8 +14,8 @@ var lastImg string // for ctrl+j
// containsToolSysMsg checks if the toolSysMsg already exists in the chat body
func containsToolSysMsg() bool {
for _, msg := range chatBody.Messages {
if msg.Role == cfg.ToolRole && msg.Content == toolSysMsg {
for i := range chatBody.Messages {
if chatBody.Messages[i].Role == cfg.ToolRole && chatBody.Messages[i].Content == toolSysMsg {
return true
}
}
@@ -147,8 +147,8 @@ func (lcp LCPCompletion) FormMsg(msg, role string, resume bool) (io.Reader, erro
}
filteredMessages, botPersona := filterMessagesForCurrentCharacter(chatBody.Messages)
messages := make([]string, len(filteredMessages))
for i, m := range filteredMessages {
messages[i] = stripThinkingFromMsg(&m).ToPrompt()
for i := range filteredMessages {
messages[i] = stripThinkingFromMsg(&filteredMessages[i]).ToPrompt()
}
prompt := strings.Join(messages, "\n")
// Add multimodal media markers to the prompt text when multimodal data is present
@@ -289,14 +289,23 @@ func (op LCPChat) FormMsg(msg, role string, resume bool) (io.Reader, error) {
Model: chatBody.Model,
Stream: chatBody.Stream,
}
for i, msg := range filteredMessages {
strippedMsg := *stripThinkingFromMsg(&msg)
if strippedMsg.Role == cfg.UserRole {
for i := range filteredMessages {
strippedMsg := *stripThinkingFromMsg(&filteredMessages[i])
switch strippedMsg.Role {
case cfg.UserRole:
bodyCopy.Messages[i] = strippedMsg
bodyCopy.Messages[i].Role = "user"
} else {
case cfg.AssistantRole:
bodyCopy.Messages[i] = strippedMsg
bodyCopy.Messages[i].Role = "assistant"
case cfg.ToolRole:
bodyCopy.Messages[i] = strippedMsg
bodyCopy.Messages[i].Role = "tool"
default:
bodyCopy.Messages[i] = strippedMsg
}
// Clear ToolCalls - they're stored in chat history for display but not sent to LLM
// bodyCopy.Messages[i].ToolCall = nil
}
// Clean null/empty messages to prevent API issues
bodyCopy.Messages = consolidateAssistantMessages(bodyCopy.Messages)
@@ -358,8 +367,8 @@ func (ds DeepSeekerCompletion) FormMsg(msg, role string, resume bool) (io.Reader
}
filteredMessages, botPersona := filterMessagesForCurrentCharacter(chatBody.Messages)
messages := make([]string, len(filteredMessages))
for i, m := range filteredMessages {
messages[i] = stripThinkingFromMsg(&m).ToPrompt()
for i := range filteredMessages {
messages[i] = stripThinkingFromMsg(&filteredMessages[i]).ToPrompt()
}
prompt := strings.Join(messages, "\n")
// strings builder?
@@ -429,14 +438,27 @@ func (ds DeepSeekerChat) FormMsg(msg, role string, resume bool) (io.Reader, erro
Model: chatBody.Model,
Stream: chatBody.Stream,
}
for i, msg := range filteredMessages {
strippedMsg := *stripThinkingFromMsg(&msg)
if strippedMsg.Role == cfg.UserRole || i == 1 {
for i := range filteredMessages {
strippedMsg := *stripThinkingFromMsg(&filteredMessages[i])
switch strippedMsg.Role {
case cfg.UserRole:
if i == 1 {
bodyCopy.Messages[i] = strippedMsg
bodyCopy.Messages[i].Role = "user"
} else {
bodyCopy.Messages[i] = strippedMsg
}
case cfg.AssistantRole:
bodyCopy.Messages[i] = strippedMsg
bodyCopy.Messages[i].Role = "assistant"
case cfg.ToolRole:
bodyCopy.Messages[i] = strippedMsg
bodyCopy.Messages[i].Role = "tool"
default:
bodyCopy.Messages[i] = strippedMsg
}
// Clear ToolCalls - they're stored in chat history for display but not sent to LLM
// bodyCopy.Messages[i].ToolCall = nil
}
// Clean null/empty messages to prevent API issues
bodyCopy.Messages = consolidateAssistantMessages(bodyCopy.Messages)
@@ -489,8 +511,8 @@ func (or OpenRouterCompletion) FormMsg(msg, role string, resume bool) (io.Reader
}
filteredMessages, botPersona := filterMessagesForCurrentCharacter(chatBody.Messages)
messages := make([]string, len(filteredMessages))
for i, m := range filteredMessages {
messages[i] = stripThinkingFromMsg(&m).ToPrompt()
for i := range filteredMessages {
messages[i] = stripThinkingFromMsg(&filteredMessages[i]).ToPrompt()
}
prompt := strings.Join(messages, "\n")
// strings builder?
@@ -593,14 +615,24 @@ func (or OpenRouterChat) FormMsg(msg, role string, resume bool) (io.Reader, erro
Model: chatBody.Model,
Stream: chatBody.Stream,
}
for i, msg := range filteredMessages {
strippedMsg := *stripThinkingFromMsg(&msg)
bodyCopy.Messages[i] = strippedMsg
// Standardize role if it's a user role
if bodyCopy.Messages[i].Role == cfg.UserRole {
for i := range filteredMessages {
strippedMsg := *stripThinkingFromMsg(&filteredMessages[i])
switch strippedMsg.Role {
case cfg.UserRole:
bodyCopy.Messages[i] = strippedMsg
bodyCopy.Messages[i].Role = "user"
case cfg.AssistantRole:
bodyCopy.Messages[i] = strippedMsg
bodyCopy.Messages[i].Role = "assistant"
case cfg.ToolRole:
bodyCopy.Messages[i] = strippedMsg
bodyCopy.Messages[i].Role = "tool"
default:
bodyCopy.Messages[i] = strippedMsg
}
// Clear ToolCalls - they're stored in chat history for display but not sent to LLM
// literally deletes data that we need
// bodyCopy.Messages[i].ToolCall = nil
}
// Clean null/empty messages to prevent API issues
bodyCopy.Messages = consolidateAssistantMessages(bodyCopy.Messages)

View File

@@ -16,6 +16,7 @@ var (
shellHistory []string
shellHistoryPos int = -1
thinkingCollapsed = false
toolCollapsed = true
statusLineTempl = "help (F12) | chat: [orange:-:b]%s[-:-:-] (F1) | [%s:-:b]tool use[-:-:-] (ctrl+k) | model: [%s:-:b]%s[-:-:-] (ctrl+l) | [%s:-:b]skip LLM resp[-:-:-] (F10)\nAPI: [orange:-:b]%s[-:-:-] (ctrl+v) | writing as: [orange:-:b]%s[-:-:-] (ctrl+q) | bot will write as [orange:-:b]%s[-:-:-] (ctrl+x)"
focusSwitcher = map[tview.Primitive]tview.Primitive{}
)

View File

@@ -1,42 +0,0 @@
package main
import (
"fmt"
"gf-lt/config"
"gf-lt/models"
"strings"
"testing"
)
func TestRemoveThinking(t *testing.T) {
cases := []struct {
cb *models.ChatBody
toolMsgs uint8
}{
{cb: &models.ChatBody{
Stream: true,
Messages: []models.RoleMsg{
{Role: "tool", Content: "should be ommited"},
{Role: "system", Content: "should stay"},
{Role: "user", Content: "hello, how are you?"},
{Role: "assistant", Content: "Oh, hi. <think>I should thank user and continue the conversation</think> I am geat, thank you! How are you?"},
},
},
toolMsgs: uint8(1),
},
}
for i, tc := range cases {
t.Run(fmt.Sprintf("run_%d", i), func(t *testing.T) {
cfg = &config.Config{ToolRole: "tool"} // Initialize cfg.ToolRole for test
mNum := len(tc.cb.Messages)
removeThinking(tc.cb)
if len(tc.cb.Messages) != mNum-int(tc.toolMsgs) {
t.Errorf("failed to delete tools msg %v; expected %d, got %d", tc.cb.Messages, mNum-int(tc.toolMsgs), len(tc.cb.Messages))
}
for _, msg := range tc.cb.Messages {
if strings.Contains(msg.Content, "<think>") {
t.Errorf("msg contains think tag; msg: %s\n", msg.Content)
}
}
}) }
}

View File

@@ -5,28 +5,21 @@ import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
)
var (
// imageBaseDir is the base directory for displaying image paths.
// If set, image paths will be shown relative to this directory.
imageBaseDir = ""
)
// SetImageBaseDir sets the base directory for displaying image paths.
// If dir is empty, full paths will be shown.
func SetImageBaseDir(dir string) {
imageBaseDir = dir
}
type FuncCall struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Args map[string]string `json:"args"`
}
type ToolCall struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Args string `json:"arguments"`
}
type LLMResp struct {
Choices []struct {
FinishReason string `json:"finish_reason"`
@@ -109,27 +102,33 @@ type RoleMsg struct {
Content string `json:"-"`
ContentParts []any `json:"-"`
ToolCallID string `json:"tool_call_id,omitempty"` // For tool response messages
ToolCall *ToolCall `json:"tool_call,omitempty"` // For assistant messages with tool calls
IsShellCommand bool `json:"is_shell_command,omitempty"` // True for shell command outputs (always shown)
KnownTo []string `json:"known_to,omitempty"`
Stats *ResponseStats `json:"stats"`
hasContentParts bool // Flag to indicate which content type to marshal
HasContentParts bool // Flag to indicate which content type to marshal
}
// MarshalJSON implements custom JSON marshaling for RoleMsg
//
//nolint:gocritic
func (m RoleMsg) MarshalJSON() ([]byte, error) {
if m.hasContentParts {
if m.HasContentParts {
// Use structured content format
aux := struct {
Role string `json:"role"`
Content []any `json:"content"`
ToolCallID string `json:"tool_call_id,omitempty"`
ToolCall *ToolCall `json:"tool_call,omitempty"`
IsShellCommand bool `json:"is_shell_command,omitempty"`
KnownTo []string `json:"known_to,omitempty"`
Stats *ResponseStats `json:"stats,omitempty"`
}{
Role: m.Role,
Content: m.ContentParts,
ToolCallID: m.ToolCallID,
ToolCall: m.ToolCall,
IsShellCommand: m.IsShellCommand,
KnownTo: m.KnownTo,
Stats: m.Stats,
}
@@ -140,12 +139,16 @@ func (m RoleMsg) MarshalJSON() ([]byte, error) {
Role string `json:"role"`
Content string `json:"content"`
ToolCallID string `json:"tool_call_id,omitempty"`
ToolCall *ToolCall `json:"tool_call,omitempty"`
IsShellCommand bool `json:"is_shell_command,omitempty"`
KnownTo []string `json:"known_to,omitempty"`
Stats *ResponseStats `json:"stats,omitempty"`
}{
Role: m.Role,
Content: m.Content,
ToolCallID: m.ToolCallID,
ToolCall: m.ToolCall,
IsShellCommand: m.IsShellCommand,
KnownTo: m.KnownTo,
Stats: m.Stats,
}
@@ -160,6 +163,8 @@ func (m *RoleMsg) UnmarshalJSON(data []byte) error {
Role string `json:"role"`
Content []any `json:"content"`
ToolCallID string `json:"tool_call_id,omitempty"`
ToolCall *ToolCall `json:"tool_call,omitempty"`
IsShellCommand bool `json:"is_shell_command,omitempty"`
KnownTo []string `json:"known_to,omitempty"`
Stats *ResponseStats `json:"stats,omitempty"`
}
@@ -167,9 +172,11 @@ func (m *RoleMsg) UnmarshalJSON(data []byte) error {
m.Role = structured.Role
m.ContentParts = structured.Content
m.ToolCallID = structured.ToolCallID
m.ToolCall = structured.ToolCall
m.IsShellCommand = structured.IsShellCommand
m.KnownTo = structured.KnownTo
m.Stats = structured.Stats
m.hasContentParts = true
m.HasContentParts = true
return nil
}
@@ -178,6 +185,8 @@ func (m *RoleMsg) UnmarshalJSON(data []byte) error {
Role string `json:"role"`
Content string `json:"content"`
ToolCallID string `json:"tool_call_id,omitempty"`
ToolCall *ToolCall `json:"tool_call,omitempty"`
IsShellCommand bool `json:"is_shell_command,omitempty"`
KnownTo []string `json:"known_to,omitempty"`
Stats *ResponseStats `json:"stats,omitempty"`
}
@@ -187,79 +196,17 @@ func (m *RoleMsg) UnmarshalJSON(data []byte) error {
m.Role = simple.Role
m.Content = simple.Content
m.ToolCallID = simple.ToolCallID
m.ToolCall = simple.ToolCall
m.IsShellCommand = simple.IsShellCommand
m.KnownTo = simple.KnownTo
m.Stats = simple.Stats
m.hasContentParts = false
m.HasContentParts = false
return nil
}
func (m *RoleMsg) ToText(i int) string {
var contentStr string
var imageIndicators []string
if !m.hasContentParts {
contentStr = m.Content
} else {
var textParts []string
for _, part := range m.ContentParts {
switch p := part.(type) {
case TextContentPart:
if p.Type == "text" {
textParts = append(textParts, p.Text)
}
case ImageContentPart:
displayPath := p.Path
if displayPath == "" {
displayPath = "image"
} else {
displayPath = extractDisplayPath(displayPath)
}
imageIndicators = append(imageIndicators, fmt.Sprintf("[orange::i][image: %s][-:-:-]", displayPath))
case map[string]any:
if partType, exists := p["type"]; exists {
switch partType {
case "text":
if textVal, textExists := p["text"]; textExists {
if textStr, isStr := textVal.(string); isStr {
textParts = append(textParts, textStr)
}
}
case "image_url":
var displayPath string
if pathVal, pathExists := p["path"]; pathExists {
if pathStr, isStr := pathVal.(string); isStr && pathStr != "" {
displayPath = extractDisplayPath(pathStr)
}
}
if displayPath == "" {
displayPath = "image"
}
imageIndicators = append(imageIndicators, fmt.Sprintf("[orange::i][image: %s][-:-:-]", displayPath))
}
}
}
}
contentStr = strings.Join(textParts, " ") + " "
}
contentStr, _ = strings.CutPrefix(contentStr, m.Role+":")
icon := fmt.Sprintf("(%d) <%s>: ", i, m.Role)
var finalContent strings.Builder
if len(imageIndicators) > 0 {
for _, indicator := range imageIndicators {
finalContent.WriteString(indicator)
finalContent.WriteString("\n")
}
}
finalContent.WriteString(contentStr)
if m.Stats != nil {
fmt.Fprintf(&finalContent, "\n[gray::i][%d tok, %.1fs, %.1f t/s][-:-:-]", m.Stats.Tokens, m.Stats.Duration, m.Stats.TokensPerSec)
}
textMsg := fmt.Sprintf("[-:-:b]%s[-:-:-]\n%s\n", icon, finalContent.String())
return strings.ReplaceAll(textMsg, "\n\n", "\n")
}
func (m *RoleMsg) ToPrompt() string {
var contentStr string
if !m.hasContentParts {
if !m.HasContentParts {
contentStr = m.Content
} else {
// For structured content, just take the text parts
@@ -292,7 +239,7 @@ func NewRoleMsg(role, content string) RoleMsg {
return RoleMsg{
Role: role,
Content: content,
hasContentParts: false,
HasContentParts: false,
}
}
@@ -301,7 +248,7 @@ func NewMultimodalMsg(role string, contentParts []any) RoleMsg {
return RoleMsg{
Role: role,
ContentParts: contentParts,
hasContentParts: true,
HasContentParts: true,
}
}
@@ -310,7 +257,7 @@ func (m *RoleMsg) HasContent() bool {
if m.Content != "" {
return true
}
if m.hasContentParts && len(m.ContentParts) > 0 {
if m.HasContentParts && len(m.ContentParts) > 0 {
return true
}
return false
@@ -318,7 +265,7 @@ func (m *RoleMsg) HasContent() bool {
// IsContentParts returns true if the message uses structured content parts
func (m *RoleMsg) IsContentParts() bool {
return m.hasContentParts
return m.HasContentParts
}
// GetContentParts returns the content parts of the message
@@ -335,14 +282,16 @@ func (m *RoleMsg) Copy() RoleMsg {
ToolCallID: m.ToolCallID,
KnownTo: m.KnownTo,
Stats: m.Stats,
hasContentParts: m.hasContentParts,
HasContentParts: m.HasContentParts,
ToolCall: m.ToolCall,
IsShellCommand: m.IsShellCommand,
}
}
// GetText returns the text content of the message, handling both
// simple Content and multimodal ContentParts formats.
func (m *RoleMsg) GetText() string {
if !m.hasContentParts {
if !m.HasContentParts {
return m.Content
}
var textParts []string
@@ -371,7 +320,7 @@ func (m *RoleMsg) GetText() string {
// ContentParts (multimodal), it updates the text parts while preserving
// images. If not, it sets the simple Content field.
func (m *RoleMsg) SetText(text string) {
if !m.hasContentParts {
if !m.HasContentParts {
m.Content = text
return
}
@@ -401,14 +350,14 @@ func (m *RoleMsg) SetText(text string) {
// AddTextPart adds a text content part to the message
func (m *RoleMsg) AddTextPart(text string) {
if !m.hasContentParts {
if !m.HasContentParts {
// Convert to content parts format
if m.Content != "" {
m.ContentParts = []any{TextContentPart{Type: "text", Text: m.Content}}
} else {
m.ContentParts = []any{}
}
m.hasContentParts = true
m.HasContentParts = true
}
textPart := TextContentPart{Type: "text", Text: text}
m.ContentParts = append(m.ContentParts, textPart)
@@ -416,14 +365,14 @@ func (m *RoleMsg) AddTextPart(text string) {
// AddImagePart adds an image content part to the message
func (m *RoleMsg) AddImagePart(imageURL, imagePath string) {
if !m.hasContentParts {
if !m.HasContentParts {
// Convert to content parts format
if m.Content != "" {
m.ContentParts = []any{TextContentPart{Type: "text", Text: m.Content}}
} else {
m.ContentParts = []any{}
}
m.hasContentParts = true
m.HasContentParts = true
}
imagePart := ImageContentPart{
Type: "image_url",
@@ -467,31 +416,6 @@ func CreateImageURLFromPath(imagePath string) (string, error) {
return fmt.Sprintf("data:%s;base64,%s", mimeType, encoded), nil
}
// extractDisplayPath returns a path suitable for display, potentially relative to imageBaseDir
func extractDisplayPath(p string) string {
if p == "" {
return ""
}
// If base directory is set, try to make path relative to it
if imageBaseDir != "" {
if rel, err := filepath.Rel(imageBaseDir, p); err == nil {
// Check if relative path doesn't start with ".." (meaning it's within base dir)
// If it starts with "..", we might still want to show it as relative
// but for now we show full path if it goes outside base dir
if !strings.HasPrefix(rel, "..") {
p = rel
}
}
}
// Truncate long paths to last 60 characters if needed
if len(p) > 60 {
return "..." + p[len(p)-60:]
}
return p
}
type ChatBody struct {
Model string `json:"model"`
Stream bool `json:"stream"`
@@ -499,16 +423,16 @@ type ChatBody struct {
}
func (cb *ChatBody) Rename(oldname, newname string) {
for i, m := range cb.Messages {
cb.Messages[i].Content = strings.ReplaceAll(m.Content, oldname, newname)
cb.Messages[i].Role = strings.ReplaceAll(m.Role, oldname, newname)
for i := range cb.Messages {
cb.Messages[i].Content = strings.ReplaceAll(cb.Messages[i].Content, oldname, newname)
cb.Messages[i].Role = strings.ReplaceAll(cb.Messages[i].Role, oldname, newname)
}
}
func (cb *ChatBody) ListRoles() []string {
namesMap := make(map[string]struct{})
for _, m := range cb.Messages {
namesMap[m.Role] = struct{}{}
for i := range cb.Messages {
namesMap[cb.Messages[i].Role] = struct{}{}
}
resp := make([]string, len(namesMap))
i := 0

View File

@@ -1,161 +0,0 @@
package models
import (
"strings"
"testing"
)
func TestRoleMsgToTextWithImages(t *testing.T) {
tests := []struct {
name string
msg RoleMsg
index int
expected string // substring to check
}{
{
name: "text and image",
index: 0,
msg: func() RoleMsg {
msg := NewMultimodalMsg("user", []interface{}{})
msg.AddTextPart("Look at this picture")
msg.AddImagePart("data:image/jpeg;base64,abc123", "/home/user/Pictures/cat.jpg")
return msg
}(),
expected: "[orange::i][image: /home/user/Pictures/cat.jpg][-:-:-]",
},
{
name: "image only",
index: 1,
msg: func() RoleMsg {
msg := NewMultimodalMsg("user", []interface{}{})
msg.AddImagePart("data:image/png;base64,xyz789", "/tmp/screenshot_20250217_123456.png")
return msg
}(),
expected: "[orange::i][image: /tmp/screenshot_20250217_123456.png][-:-:-]",
},
{
name: "long filename truncated",
index: 2,
msg: func() RoleMsg {
msg := NewMultimodalMsg("user", []interface{}{})
msg.AddTextPart("Check this")
msg.AddImagePart("data:image/jpeg;base64,foo", "/very/long/path/to/a/really_long_filename_that_exceeds_forty_characters.jpg")
return msg
}(),
expected: "[orange::i][image: .../to/a/really_long_filename_that_exceeds_forty_characters.jpg][-:-:-]",
},
{
name: "multiple images",
index: 3,
msg: func() RoleMsg {
msg := NewMultimodalMsg("user", []interface{}{})
msg.AddTextPart("Multiple images")
msg.AddImagePart("data:image/jpeg;base64,a", "/path/img1.jpg")
msg.AddImagePart("data:image/png;base64,b", "/path/img2.png")
return msg
}(),
expected: "[orange::i][image: /path/img1.jpg][-:-:-]\n[orange::i][image: /path/img2.png][-:-:-]",
},
{
name: "old format without path",
index: 4,
msg: RoleMsg{
Role: "user",
hasContentParts: true,
ContentParts: []interface{}{
map[string]interface{}{
"type": "image_url",
"image_url": map[string]interface{}{
"url": "data:image/jpeg;base64,old",
},
},
},
},
expected: "[orange::i][image: image][-:-:-]",
},
{
name: "old format with path",
index: 5,
msg: RoleMsg{
Role: "user",
hasContentParts: true,
ContentParts: []interface{}{
map[string]interface{}{
"type": "image_url",
"path": "/old/path/photo.jpg",
"image_url": map[string]interface{}{
"url": "data:image/jpeg;base64,old",
},
},
},
},
expected: "[orange::i][image: /old/path/photo.jpg][-:-:-]",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := tt.msg.ToText(tt.index)
if !strings.Contains(result, tt.expected) {
t.Errorf("ToText() result does not contain expected indicator\ngot: %s\nwant substring: %s", result, tt.expected)
}
// Ensure the indicator appears before text content
if strings.Contains(tt.expected, "cat.jpg") && strings.Contains(result, "Look at this picture") {
indicatorPos := strings.Index(result, "[orange::i][image: /home/user/Pictures/cat.jpg][-:-:-]")
textPos := strings.Index(result, "Look at this picture")
if indicatorPos == -1 || textPos == -1 || indicatorPos >= textPos {
t.Errorf("image indicator should appear before text")
}
}
})
}
}
func TestExtractDisplayPath(t *testing.T) {
// Save original base dir
originalBaseDir := imageBaseDir
defer func() { imageBaseDir = originalBaseDir }()
tests := []struct {
name string
baseDir string
path string
expected string
}{
{
name: "no base dir shows full path",
baseDir: "",
path: "/home/user/images/cat.jpg",
expected: "/home/user/images/cat.jpg",
},
{
name: "relative path within base dir",
baseDir: "/home/user",
path: "/home/user/images/cat.jpg",
expected: "images/cat.jpg",
},
{
name: "path outside base dir shows full path",
baseDir: "/home/user",
path: "/tmp/test.jpg",
expected: "/tmp/test.jpg",
},
{
name: "same directory",
baseDir: "/home/user/images",
path: "/home/user/images/cat.jpg",
expected: "cat.jpg",
},
{
name: "long path truncated",
baseDir: "",
path: "/very/long/path/to/a/really_long_filename_that_exceeds_sixty_characters_limit_yes_it_is_very_long.jpg",
expected: "..._that_exceeds_sixty_characters_limit_yes_it_is_very_long.jpg",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
imageBaseDir = tt.baseDir
result := extractDisplayPath(tt.path)
if result != tt.expected {
t.Errorf("extractDisplayPath(%q) with baseDir=%q = %q, want %q",
tt.path, tt.baseDir, result, tt.expected)
}
})
}
}

View File

@@ -131,13 +131,18 @@ func loadOldChatOrGetNew() []models.RoleMsg {
chat, err := store.GetLastChat()
if err != nil {
logger.Warn("failed to load history chat", "error", err)
maxID, err := store.ChatGetMaxID()
if err != nil {
logger.Error("failed to fetch max chat id", "error", err)
}
maxID++
chat := &models.Chat{
ID: 0,
ID: maxID,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Agent: cfg.AssistantRole,
}
chat.Name = fmt.Sprintf("%s_%v", chat.Agent, chat.CreatedAt.Unix())
chat.Name = fmt.Sprintf("%s_%v", chat.Agent, chat.ID)
activeChatName = chat.Name
chatMap[chat.Name] = chat
return defaultStarter
@@ -149,10 +154,6 @@ func loadOldChatOrGetNew() []models.RoleMsg {
chatMap[chat.Name] = chat
return defaultStarter
}
// if chat.Name == "" {
// logger.Warn("empty chat name", "id", chat.ID)
// chat.Name = fmt.Sprintf("%s_%v", chat.Agent, chat.CreatedAt.Unix())
// }
chatMap[chat.Name] = chat
activeChatName = chat.Name
cfg.AssistantRole = chat.Agent

199
tools.go
View File

@@ -95,6 +95,11 @@ Your current tools:
"when_to_use": "when asked to append content to a file; use sed to edit content"
},
{
"name":"file_edit",
"args": ["path", "oldString", "newString", "lineNumber"],
"when_to_use": "when you need to make targeted changes to a specific section of a file without rewriting the entire file; lineNumber is optional - if provided, only edits that specific line; if not provided, replaces all occurrences of oldString"
},
{
"name":"file_delete",
"args": ["path"],
"when_to_use": "when asked to delete a file"
@@ -117,7 +122,7 @@ Your current tools:
{
"name":"execute_command",
"args": ["command", "args"],
"when_to_use": "when asked to execute a system command; args is optional; allowed commands: grep, sed, awk, find, cat, head, tail, sort, uniq, wc, ls, echo, cut, tr, cp, mv, rm, mkdir, rmdir, pwd, df, free, ps, top, du, whoami, date, uname"
"when_to_use": "when asked to execute a system command; args is optional; allowed commands: grep, sed, awk, find, cat, head, tail, sort, uniq, wc, ls, echo, cut, tr, cp, mv, rm, mkdir, rmdir, pwd, df, free, ps, top, du, whoami, date, uname, go"
}
]
</tools>
@@ -506,6 +511,85 @@ func fileWriteAppend(args map[string]string) []byte {
return []byte(msg)
}
func fileEdit(args map[string]string) []byte {
path, ok := args["path"]
if !ok || path == "" {
msg := "path not provided to file_edit tool"
logger.Error(msg)
return []byte(msg)
}
path = resolvePath(path)
oldString, ok := args["oldString"]
if !ok || oldString == "" {
msg := "oldString not provided to file_edit tool"
logger.Error(msg)
return []byte(msg)
}
newString, ok := args["newString"]
if !ok {
newString = ""
}
lineNumberStr, hasLineNumber := args["lineNumber"]
// Read file content
content, err := os.ReadFile(path)
if err != nil {
msg := "failed to read file: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
fileContent := string(content)
var replacementCount int
if hasLineNumber && lineNumberStr != "" {
// Line-number based edit
lineNum, err := strconv.Atoi(lineNumberStr)
if err != nil {
msg := "invalid lineNumber: must be a valid integer"
logger.Error(msg)
return []byte(msg)
}
lines := strings.Split(fileContent, "\n")
if lineNum < 1 || lineNum > len(lines) {
msg := fmt.Sprintf("lineNumber %d out of range (file has %d lines)", lineNum, len(lines))
logger.Error(msg)
return []byte(msg)
}
// Find oldString in the specific line
targetLine := lines[lineNum-1]
if !strings.Contains(targetLine, oldString) {
msg := fmt.Sprintf("oldString not found on line %d", lineNum)
logger.Error(msg)
return []byte(msg)
}
lines[lineNum-1] = strings.Replace(targetLine, oldString, newString, 1)
replacementCount = 1
fileContent = strings.Join(lines, "\n")
} else {
// Replace all occurrences
if !strings.Contains(fileContent, oldString) {
msg := "oldString not found in file"
logger.Error(msg)
return []byte(msg)
}
fileContent = strings.ReplaceAll(fileContent, oldString, newString)
replacementCount = strings.Count(fileContent, newString)
}
if err := os.WriteFile(path, []byte(fileContent), 0644); err != nil {
msg := "failed to write file: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
msg := fmt.Sprintf("file edited successfully at %s (%d replacement(s))", path, replacementCount)
return []byte(msg)
}
func fileDelete(args map[string]string) []byte {
path, ok := args["path"]
if !ok || path == "" {
@@ -705,6 +789,16 @@ func executeCommand(args map[string]string) []byte {
argNum++
}
}
// Handle commands passed as single string with spaces (e.g., "go run main.go")
// Split into base command and arguments
if strings.Contains(command, " ") {
parts := strings.Fields(command)
baseCmd := parts[0]
extraArgs := parts[1:]
// Prepend extra args to cmdArgs
cmdArgs = append(extraArgs, cmdArgs...)
command = baseCmd
}
if !isCommandAllowed(command, cmdArgs...) {
msg := fmt.Sprintf("command '%s' is not allowed", command)
logger.Error(msg)
@@ -740,6 +834,14 @@ type TodoList struct {
Items []TodoItem `json:"items"`
}
func (t TodoList) ToString() string {
sb := strings.Builder{}
for i := range t.Items {
fmt.Fprintf(&sb, "\n[%s] %s. %s\n", t.Items[i].Status, t.Items[i].ID, t.Items[i].Task)
}
return sb.String()
}
// Global todo list storage
var globalTodoList = TodoList{
Items: []TodoItem{},
@@ -766,6 +868,7 @@ func todoCreate(args map[string]string) []byte {
"id": id,
"task": task,
"status": "pending",
"todos": globalTodoList.ToString(),
}
jsonResult, err := json.Marshal(result)
if err != nil {
@@ -777,38 +880,9 @@ func todoCreate(args map[string]string) []byte {
}
func todoRead(args map[string]string) []byte {
id, ok := args["id"]
if ok && id != "" {
// Find specific todo by ID
for _, item := range globalTodoList.Items {
if item.ID == id {
result := map[string]interface{}{
"todo": item,
}
jsonResult, err := json.Marshal(result)
if err != nil {
msg := "failed to marshal result; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return jsonResult
}
}
// ID not found
result := map[string]string{
"error": fmt.Sprintf("todo with id %s not found", id),
}
jsonResult, err := json.Marshal(result)
if err != nil {
msg := "failed to marshal result; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return jsonResult
}
// Return all todos if no ID specified
result := map[string]interface{}{
"todos": globalTodoList.Items,
"todos": globalTodoList.ToString(),
}
jsonResult, err := json.Marshal(result)
if err != nil {
@@ -859,6 +933,7 @@ func todoUpdate(args map[string]string) []byte {
result := map[string]string{
"message": "todo updated successfully",
"id": id,
"todos": globalTodoList.ToString(),
}
jsonResult, err := json.Marshal(result)
if err != nil {
@@ -897,6 +972,7 @@ func todoDelete(args map[string]string) []byte {
result := map[string]string{
"message": "todo deleted successfully",
"id": id,
"todos": globalTodoList.ToString(),
}
jsonResult, err := json.Marshal(result)
if err != nil {
@@ -963,13 +1039,18 @@ func isCommandAllowed(command string, args ...string) bool {
"date": true,
"uname": true,
"git": true,
"go": true,
}
if !allowedCommands[command] {
return false
// Allow all go subcommands (go run, go mod tidy, go test, etc.)
if strings.HasPrefix(command, "go ") && allowedCommands["go"] {
return true
}
if command == "git" && len(args) > 0 {
return gitReadSubcommands[args[0]]
}
if !allowedCommands[command] {
return false
}
return true
}
@@ -997,6 +1078,7 @@ var fnMap = map[string]fnSig{
"file_read": fileRead,
"file_write": fileWrite,
"file_write_append": fileWriteAppend,
"file_edit": fileEdit,
"file_delete": fileDelete,
"file_move": fileMove,
"file_copy": fileCopy,
@@ -1264,6 +1346,36 @@ var baseTools = []models.Tool{
},
},
},
// file_edit
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "file_edit",
Description: "Edit a specific section of a file by replacing oldString with newString. Use for targeted changes without rewriting the entire file.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"path", "oldString", "newString"},
Properties: map[string]models.ToolArgProps{
"path": models.ToolArgProps{
Type: "string",
Description: "path of the file to edit",
},
"oldString": models.ToolArgProps{
Type: "string",
Description: "the exact string to find and replace",
},
"newString": models.ToolArgProps{
Type: "string",
Description: "the string to replace oldString with",
},
"lineNumber": models.ToolArgProps{
Type: "string",
Description: "optional line number (1-indexed) to edit - if provided, only that line is edited",
},
},
},
},
},
// file_delete
models.Tool{
Type: "function",
@@ -1349,14 +1461,14 @@ var baseTools = []models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "execute_command",
Description: "Execute a shell command safely. Use when you need to run system commands like grep sed awk find cat head tail sort uniq wc ls echo cut tr cp mv rm mkdir rmdir pwd df free ps top du whoami date uname. Git is allowed for read-only operations: status, log, diff, show, branch, reflog, rev-parse, shortlog, describe.",
Description: "Execute a shell command safely. Use when you need to run system commands like grep sed awk find cat head tail sort uniq wc ls echo cut tr cp mv rm mkdir rmdir pwd df free ps top du whoami date uname go. Git is allowed for read-only operations: status, log, diff, show, branch, reflog, rev-parse, shortlog, describe.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"command"},
Properties: map[string]models.ToolArgProps{
"command": models.ToolArgProps{
Type: "string",
Description: "command to execute (only commands from whitelist are allowed: grep sed awk find cat head tail sort uniq wc ls echo cut tr cp mv rm mkdir rmdir pwd df free ps top du whoami date uname; git allowed for reads: status log diff show branch reflog rev-parse shortlog describe)",
Description: "command to execute (only commands from whitelist are allowed: grep sed awk find cat head tail sort uniq wc ls echo cut tr cp mv rm mkdir rmdir pwd df free ps top du whoami date uname go; git allowed for reads: status log diff show branch reflog rev-parse shortlog describe)",
},
"args": models.ToolArgProps{
Type: "string",
@@ -1410,21 +1522,8 @@ var baseTools = []models.Tool{
Description: "Update a todo item by ID with new task or status. Status must be one of: pending, in_progress, completed.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"id"},
Properties: map[string]models.ToolArgProps{
"id": models.ToolArgProps{
Type: "string",
Description: "id of the todo item to update",
},
"task": models.ToolArgProps{
Type: "string",
Description: "new task description (optional)",
},
"status": models.ToolArgProps{
Type: "string",
Description: "new status for the todo: pending, in_progress, or completed (optional)",
},
},
Required: []string{},
Properties: map[string]models.ToolArgProps{},
},
},
},

25
tui.go
View File

@@ -80,7 +80,7 @@ var (
[yellow]Ctrl+p[white]: props edit form (min-p, dry, etc.)
[yellow]Ctrl+v[white]: show API link selection popup to choose current API
[yellow]Ctrl+r[white]: start/stop recording from your microphone (needs stt server or whisper binary)
[yellow]Ctrl+t[white]: remove thinking (<think>) and tool messages from context (delete from chat)
[yellow]Ctrl+t[white]: (un)collapse tool messages
[yellow]Ctrl+l[white]: show model selection popup to choose current model
[yellow]Ctrl+k[white]: switch tool use (recommend tool use to llm after user msg)
[yellow]Ctrl+a[white]: interrupt tts (needs tts server)
@@ -99,6 +99,7 @@ var (
[yellow]Alt+8[white]: show char img or last picked img
[yellow]Alt+9[white]: warm up (load) selected llama.cpp model
[yellow]Alt+t[white]: toggle thinking blocks visibility (collapse/expand <think> blocks)
[yellow]Ctrl+t[white]: toggle tool call/response visibility (collapse/expand tool calls and non-shell tool responses)
[yellow]Alt+i[white]: show colorscheme selection popup
=== scrolling chat window (some keys similar to vim) ===
@@ -563,6 +564,20 @@ func init() {
}
return nil
}
// Handle Ctrl+T to toggle tool call/response visibility
if event.Key() == tcell.KeyCtrlT {
toolCollapsed = !toolCollapsed
textView.SetText(chatToText(chatBody.Messages, cfg.ShowSys))
colorText()
status := "expanded"
if toolCollapsed {
status = "collapsed"
}
if err := notifyUser("tools", "Tool calls/responses "+status); err != nil {
logger.Error("failed to send notification", "error", err)
}
return nil
}
if event.Key() == tcell.KeyRune && event.Rune() == 'i' && event.Modifiers()&tcell.ModAlt != 0 {
if isFullScreenPageActive() {
return event
@@ -781,14 +796,6 @@ func init() {
showModelSelectionPopup()
return nil
}
if event.Key() == tcell.KeyCtrlT {
// clear context
// remove tools and thinking
removeThinking(chatBody)
textView.SetText(chatToText(chatBody.Messages, cfg.ShowSys))
colorText()
return nil
}
if event.Key() == tcell.KeyCtrlV {
if isFullScreenPageActive() {
return event