Merge upstream/main and resolve conflicts in AgentLoop
This commit is contained in:
commit
819d37536d
13 changed files with 621 additions and 79 deletions
15
Makefile
15
Makefile
|
|
@ -39,8 +39,6 @@ ifeq ($(UNAME_S),Linux)
|
||||||
ARCH=amd64
|
ARCH=amd64
|
||||||
else ifeq ($(UNAME_M),aarch64)
|
else ifeq ($(UNAME_M),aarch64)
|
||||||
ARCH=arm64
|
ARCH=arm64
|
||||||
else ifeq ($(UNAME_M),loongarch64)
|
|
||||||
ARCH=loong64
|
|
||||||
else ifeq ($(UNAME_M),riscv64)
|
else ifeq ($(UNAME_M),riscv64)
|
||||||
ARCH=riscv64
|
ARCH=riscv64
|
||||||
else
|
else
|
||||||
|
|
@ -86,7 +84,6 @@ build-all: generate
|
||||||
@mkdir -p $(BUILD_DIR)
|
@mkdir -p $(BUILD_DIR)
|
||||||
GOOS=linux GOARCH=amd64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-amd64 ./$(CMD_DIR)
|
GOOS=linux GOARCH=amd64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-amd64 ./$(CMD_DIR)
|
||||||
GOOS=linux GOARCH=arm64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-arm64 ./$(CMD_DIR)
|
GOOS=linux GOARCH=arm64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-arm64 ./$(CMD_DIR)
|
||||||
GOOS=linux GOARCH=loong64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-loong64 ./$(CMD_DIR)
|
|
||||||
GOOS=linux GOARCH=riscv64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-riscv64 ./$(CMD_DIR)
|
GOOS=linux GOARCH=riscv64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux-riscv64 ./$(CMD_DIR)
|
||||||
GOOS=darwin GOARCH=arm64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-arm64 ./$(CMD_DIR)
|
GOOS=darwin GOARCH=arm64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-arm64 ./$(CMD_DIR)
|
||||||
GOOS=windows GOARCH=amd64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-windows-amd64.exe ./$(CMD_DIR)
|
GOOS=windows GOARCH=amd64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-windows-amd64.exe ./$(CMD_DIR)
|
||||||
|
|
@ -122,7 +119,7 @@ clean:
|
||||||
@rm -rf $(BUILD_DIR)
|
@rm -rf $(BUILD_DIR)
|
||||||
@echo "Clean complete"
|
@echo "Clean complete"
|
||||||
|
|
||||||
## fmt: Format Go code
|
## vet: Run go vet for static analysis
|
||||||
vet:
|
vet:
|
||||||
@$(GO) vet ./...
|
@$(GO) vet ./...
|
||||||
|
|
||||||
|
|
@ -134,11 +131,19 @@ test:
|
||||||
fmt:
|
fmt:
|
||||||
@$(GO) fmt ./...
|
@$(GO) fmt ./...
|
||||||
|
|
||||||
## deps: Update dependencies
|
## deps: Download dependencies
|
||||||
deps:
|
deps:
|
||||||
|
@$(GO) mod download
|
||||||
|
@$(GO) mod verify
|
||||||
|
|
||||||
|
## update-deps: Update dependencies
|
||||||
|
update-deps:
|
||||||
@$(GO) get -u ./...
|
@$(GO) get -u ./...
|
||||||
@$(GO) mod tidy
|
@$(GO) mod tidy
|
||||||
|
|
||||||
|
## check: Run vet, fmt, and verify dependencies
|
||||||
|
check: deps fmt vet test
|
||||||
|
|
||||||
## run: Build and run picoclaw
|
## run: Build and run picoclaw
|
||||||
run: build
|
run: build
|
||||||
@$(BUILD_DIR)/$(BINARY_NAME) $(ARGS)
|
@$(BUILD_DIR)/$(BINARY_NAME) $(ARGS)
|
||||||
|
|
|
||||||
|
|
@ -562,7 +562,7 @@ func gatewayCmd() {
|
||||||
})
|
})
|
||||||
|
|
||||||
// Setup cron tool and service
|
// Setup cron tool and service
|
||||||
cronService := setupCronTool(agentLoop, msgBus, cfg.WorkspacePath())
|
cronService := setupCronTool(agentLoop, msgBus, cfg.WorkspacePath(), cfg.Agents.Defaults.RestrictToWorkspace)
|
||||||
|
|
||||||
heartbeatService := heartbeat.NewHeartbeatService(
|
heartbeatService := heartbeat.NewHeartbeatService(
|
||||||
cfg.WorkspacePath(),
|
cfg.WorkspacePath(),
|
||||||
|
|
@ -594,6 +594,9 @@ func gatewayCmd() {
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Inject channel manager into agent loop for command handling
|
||||||
|
agentLoop.SetChannelManager(channelManager)
|
||||||
|
|
||||||
var transcriber *voice.GroqTranscriber
|
var transcriber *voice.GroqTranscriber
|
||||||
if cfg.Providers.Groq.APIKey != "" {
|
if cfg.Providers.Groq.APIKey != "" {
|
||||||
transcriber = voice.NewGroqTranscriber(cfg.Providers.Groq.APIKey)
|
transcriber = voice.NewGroqTranscriber(cfg.Providers.Groq.APIKey)
|
||||||
|
|
@ -984,14 +987,14 @@ func getConfigPath() string {
|
||||||
return filepath.Join(home, ".picoclaw", "config.json")
|
return filepath.Join(home, ".picoclaw", "config.json")
|
||||||
}
|
}
|
||||||
|
|
||||||
func setupCronTool(agentLoop *agent.AgentLoop, msgBus *bus.MessageBus, workspace string) *cron.CronService {
|
func setupCronTool(agentLoop *agent.AgentLoop, msgBus *bus.MessageBus, workspace string, restrict bool) *cron.CronService {
|
||||||
cronStorePath := filepath.Join(workspace, "cron", "jobs.json")
|
cronStorePath := filepath.Join(workspace, "cron", "jobs.json")
|
||||||
|
|
||||||
// Create cron service
|
// Create cron service
|
||||||
cronService := cron.NewCronService(cronStorePath, nil)
|
cronService := cron.NewCronService(cronStorePath, nil)
|
||||||
|
|
||||||
// Create and register CronTool
|
// Create and register CronTool
|
||||||
cronTool := tools.NewCronTool(cronService, agentLoop, msgBus, workspace)
|
cronTool := tools.NewCronTool(cronService, agentLoop, msgBus, workspace, restrict)
|
||||||
agentLoop.RegisterTool(cronTool)
|
agentLoop.RegisterTool(cronTool)
|
||||||
|
|
||||||
// Set the onJob handler
|
// Set the onJob handler
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,7 @@ import (
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
"github.com/sipeed/picoclaw/pkg/bus"
|
"github.com/sipeed/picoclaw/pkg/bus"
|
||||||
|
"github.com/sipeed/picoclaw/pkg/channels"
|
||||||
"github.com/sipeed/picoclaw/pkg/config"
|
"github.com/sipeed/picoclaw/pkg/config"
|
||||||
"github.com/sipeed/picoclaw/pkg/constants"
|
"github.com/sipeed/picoclaw/pkg/constants"
|
||||||
"github.com/sipeed/picoclaw/pkg/logger"
|
"github.com/sipeed/picoclaw/pkg/logger"
|
||||||
|
|
@ -45,6 +46,7 @@ type AgentLoop struct {
|
||||||
running atomic.Bool
|
running atomic.Bool
|
||||||
summarizing sync.Map // Tracks which sessions are currently being summarized
|
summarizing sync.Map // Tracks which sessions are currently being summarized
|
||||||
configPath string // Path to config.json for persistence
|
configPath string // Path to config.json for persistence
|
||||||
|
channelManager *channels.Manager
|
||||||
}
|
}
|
||||||
|
|
||||||
// processOptions configures how a message is processed
|
// processOptions configures how a message is processed
|
||||||
|
|
@ -272,6 +274,10 @@ func (al *AgentLoop) RegisterTool(tool tools.Tool) {
|
||||||
al.tools.Register(tool)
|
al.tools.Register(tool)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (al *AgentLoop) SetChannelManager(cm *channels.Manager) {
|
||||||
|
al.channelManager = cm
|
||||||
|
}
|
||||||
|
|
||||||
// RecordLastChannel records the last active channel for this workspace.
|
// RecordLastChannel records the last active channel for this workspace.
|
||||||
// This uses the atomic state save mechanism to prevent data loss on crash.
|
// This uses the atomic state save mechanism to prevent data loss on crash.
|
||||||
func (al *AgentLoop) RecordLastChannel(channel string) error {
|
func (al *AgentLoop) RecordLastChannel(channel string) error {
|
||||||
|
|
@ -336,43 +342,9 @@ func (al *AgentLoop) processMessage(ctx context.Context, msg bus.InboundMessage)
|
||||||
return al.processSystemMessage(ctx, msg)
|
return al.processSystemMessage(ctx, msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle Slash Commands
|
// Check for commands
|
||||||
if strings.HasPrefix(msg.Content, "/") {
|
if response, handled := al.handleCommand(ctx, msg); handled {
|
||||||
cmd := strings.Split(msg.Content, " ")[0]
|
return response, nil
|
||||||
switch cmd {
|
|
||||||
case "/model":
|
|
||||||
parts := strings.SplitN(msg.Content, " ", 2)
|
|
||||||
if len(parts) == 1 {
|
|
||||||
return fmt.Sprintf("Current model: `%s`\nCurrent provider: `%s`\n\n_Usage: `/model <name>` or `/model <provider>/<model>`_", al.model, al.cfg.Agents.Defaults.Provider), nil
|
|
||||||
}
|
|
||||||
input := strings.TrimSpace(parts[1])
|
|
||||||
|
|
||||||
// Check for provider/model format (e.g. "vllm/qwen3-coder-next:cloud")
|
|
||||||
if idx := strings.Index(input, "/"); idx > 0 {
|
|
||||||
newProvider := input[:idx]
|
|
||||||
newModel := input[idx+1:]
|
|
||||||
oldProvider := al.cfg.Agents.Defaults.Provider
|
|
||||||
oldModel := al.model
|
|
||||||
|
|
||||||
// Switch provider
|
|
||||||
al.cfg.Agents.Defaults.Provider = newProvider
|
|
||||||
newLLM, err := providers.CreateProvider(al.cfg)
|
|
||||||
if err != nil {
|
|
||||||
al.cfg.Agents.Defaults.Provider = oldProvider
|
|
||||||
return fmt.Sprintf("❌ Failed to switch to `%s`: %v", newProvider, err), nil
|
|
||||||
}
|
|
||||||
al.provider = newLLM
|
|
||||||
al.SetModel(newModel) // This also calls saveConfig()
|
|
||||||
return fmt.Sprintf("✅ Switched: `%s/%s` → `%s/%s`", oldProvider, oldModel, newProvider, newModel), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Model-only switch (keep current provider)
|
|
||||||
oldModel := al.model
|
|
||||||
al.SetModel(input)
|
|
||||||
return fmt.Sprintf("🔄 Switched model: `%s` → `%s` (provider: `%s`)", oldModel, input, al.cfg.Agents.Defaults.Provider), nil
|
|
||||||
case "/models":
|
|
||||||
return al.listModelsResponse(), nil
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Process as user message
|
// Process as user message
|
||||||
|
|
@ -495,7 +467,7 @@ func (al *AgentLoop) runAgentLoop(ctx context.Context, opts processOptions) (str
|
||||||
|
|
||||||
// 7. Optional: summarization
|
// 7. Optional: summarization
|
||||||
if opts.EnableSummary {
|
if opts.EnableSummary {
|
||||||
al.maybeSummarize(opts.SessionKey)
|
al.maybeSummarize(opts.SessionKey, opts.Channel, opts.ChatID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 8. Optional: send response via bus
|
// 8. Optional: send response via bus
|
||||||
|
|
@ -557,11 +529,131 @@ func (al *AgentLoop) runLLMIteration(ctx context.Context, messages []providers.M
|
||||||
"tools_json": formatToolsForLog(providerToolDefs),
|
"tools_json": formatToolsForLog(providerToolDefs),
|
||||||
})
|
})
|
||||||
|
|
||||||
// Call LLM
|
var response *providers.LLMResponse
|
||||||
response, err := al.provider.Chat(ctx, messages, providerToolDefs, al.model, map[string]interface{}{
|
var err error
|
||||||
"max_tokens": 8192,
|
|
||||||
"temperature": 0.7,
|
// Retry loop for context/token errors
|
||||||
})
|
maxRetries := 2
|
||||||
|
for retry := 0; retry <= maxRetries; retry++ {
|
||||||
|
response, err = al.provider.Chat(ctx, messages, providerToolDefs, al.model, map[string]interface{}{
|
||||||
|
"max_tokens": 8192,
|
||||||
|
"temperature": 0.7,
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
break // Success
|
||||||
|
}
|
||||||
|
|
||||||
|
errMsg := strings.ToLower(err.Error())
|
||||||
|
// Check for context window errors (provider specific, but usually contain "token" or "invalid")
|
||||||
|
isContextError := strings.Contains(errMsg, "token") ||
|
||||||
|
strings.Contains(errMsg, "context") ||
|
||||||
|
strings.Contains(errMsg, "invalidparameter") ||
|
||||||
|
strings.Contains(errMsg, "length")
|
||||||
|
|
||||||
|
if isContextError && retry < maxRetries {
|
||||||
|
logger.WarnCF("agent", "Context window error detected, attempting compression", map[string]interface{}{
|
||||||
|
"error": err.Error(),
|
||||||
|
"retry": retry,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Notify user on first retry only
|
||||||
|
if retry == 0 && !constants.IsInternalChannel(opts.Channel) && opts.SendResponse {
|
||||||
|
al.bus.PublishOutbound(bus.OutboundMessage{
|
||||||
|
Channel: opts.Channel,
|
||||||
|
ChatID: opts.ChatID,
|
||||||
|
Content: "⚠️ Context window exceeded. Compressing history and retrying...",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Force compression
|
||||||
|
al.forceCompression(opts.SessionKey)
|
||||||
|
|
||||||
|
// Rebuild messages with compressed history
|
||||||
|
// Note: We need to reload history from session manager because forceCompression changed it
|
||||||
|
newHistory := al.sessions.GetHistory(opts.SessionKey)
|
||||||
|
newSummary := al.sessions.GetSummary(opts.SessionKey)
|
||||||
|
|
||||||
|
// Re-create messages for the next attempt
|
||||||
|
// We keep the current user message (opts.UserMessage) effectively
|
||||||
|
messages = al.contextBuilder.BuildMessages(
|
||||||
|
newHistory,
|
||||||
|
newSummary,
|
||||||
|
opts.UserMessage,
|
||||||
|
nil,
|
||||||
|
opts.Channel,
|
||||||
|
opts.ChatID,
|
||||||
|
)
|
||||||
|
|
||||||
|
// Important: If we are in the middle of a tool loop (iteration > 1),
|
||||||
|
// rebuilding messages from session history might duplicate the flow or miss context
|
||||||
|
// if intermediate steps weren't saved correctly.
|
||||||
|
// However, al.sessions.AddFullMessage is called after every tool execution,
|
||||||
|
// so GetHistory should reflect the current state including partial tool execution.
|
||||||
|
// But we need to ensure we don't duplicate the user message which is appended in BuildMessages.
|
||||||
|
// BuildMessages(history...) takes the stored history and appends the *current* user message.
|
||||||
|
// If iteration > 1, the "current user message" was already added to history in step 3 of runAgentLoop.
|
||||||
|
// So if we pass opts.UserMessage again, we might duplicate it?
|
||||||
|
// Actually, step 3 is: al.sessions.AddMessage(opts.SessionKey, "user", opts.UserMessage)
|
||||||
|
// So GetHistory ALREADY contains the user message!
|
||||||
|
|
||||||
|
// CORRECTION:
|
||||||
|
// BuildMessages combines: [System] + [History] + [CurrentMessage]
|
||||||
|
// But Step 3 added CurrentMessage to History.
|
||||||
|
// So if we use GetHistory now, it has the user message.
|
||||||
|
// If we pass opts.UserMessage to BuildMessages, it adds it AGAIN.
|
||||||
|
|
||||||
|
// For retry in the middle of a loop, we should rely on what's in the session.
|
||||||
|
// BUT checking BuildMessages implementation:
|
||||||
|
// It appends history... then appends currentMessage.
|
||||||
|
|
||||||
|
// Logic fix for retry:
|
||||||
|
// If iteration == 1, opts.UserMessage corresponds to the user input.
|
||||||
|
// If iteration > 1, we are processing tool results. The "messages" passed to Chat
|
||||||
|
// already accumulated tool outputs.
|
||||||
|
// Rebuilding from session history is safest because it persists state.
|
||||||
|
// Start fresh with rebuilt history.
|
||||||
|
|
||||||
|
// Special case: standard BuildMessages appends "currentMessage".
|
||||||
|
// If we are strictly retrying the *LLM call*, we want the exact same state as before but compressed.
|
||||||
|
// However, the "messages" argument passed to runLLMIteration is constructed by the caller.
|
||||||
|
// If we rebuild from Session, we need to know if "currentMessage" should be appended or is already in history.
|
||||||
|
|
||||||
|
// In runAgentLoop:
|
||||||
|
// 3. sessions.AddMessage(userMsg)
|
||||||
|
// 4. runLLMIteration(..., UserMessage)
|
||||||
|
|
||||||
|
// So History contains the user message.
|
||||||
|
// BuildMessages typically appends the user message as a *new* pending message.
|
||||||
|
// Wait, standard BuildMessages usage in runAgentLoop:
|
||||||
|
// messages := BuildMessages(history (has old), UserMessage)
|
||||||
|
// THEN AddMessage(UserMessage).
|
||||||
|
// So "history" passed to BuildMessages does NOT contain the current UserMessage yet.
|
||||||
|
|
||||||
|
// But here, inside the loop, we have already saved it.
|
||||||
|
// So GetHistory() includes the current user message.
|
||||||
|
// If we call BuildMessages(GetHistory(), UserMessage), we get duplicates.
|
||||||
|
|
||||||
|
// Hack/Fix:
|
||||||
|
// If we are retrying, we rebuild from Session History ONLY.
|
||||||
|
// We pass empty string as "currentMessage" to BuildMessages
|
||||||
|
// because the "current message" is already saved in history (step 3).
|
||||||
|
|
||||||
|
messages = al.contextBuilder.BuildMessages(
|
||||||
|
newHistory,
|
||||||
|
newSummary,
|
||||||
|
"", // Empty because history already contains the relevant messages
|
||||||
|
nil,
|
||||||
|
opts.Channel,
|
||||||
|
opts.ChatID,
|
||||||
|
)
|
||||||
|
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Real error or success, break loop
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.ErrorCF("agent", "LLM call failed",
|
logger.ErrorCF("agent", "LLM call failed",
|
||||||
|
|
@ -569,7 +661,7 @@ func (al *AgentLoop) runLLMIteration(ctx context.Context, messages []providers.M
|
||||||
"iteration": iteration,
|
"iteration": iteration,
|
||||||
"error": err.Error(),
|
"error": err.Error(),
|
||||||
})
|
})
|
||||||
return "", iteration, fmt.Errorf("LLM call failed: %w", err)
|
return "", iteration, fmt.Errorf("LLM call failed after retries: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if no tool calls - we're done
|
// Check if no tool calls - we're done
|
||||||
|
|
@ -701,7 +793,7 @@ func (al *AgentLoop) updateToolContexts(channel, chatID string) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// maybeSummarize triggers summarization if the session history exceeds thresholds.
|
// maybeSummarize triggers summarization if the session history exceeds thresholds.
|
||||||
func (al *AgentLoop) maybeSummarize(sessionKey string) {
|
func (al *AgentLoop) maybeSummarize(sessionKey, channel, chatID string) {
|
||||||
newHistory := al.sessions.GetHistory(sessionKey)
|
newHistory := al.sessions.GetHistory(sessionKey)
|
||||||
tokenEstimate := al.estimateTokens(newHistory)
|
tokenEstimate := al.estimateTokens(newHistory)
|
||||||
threshold := al.contextWindow * 75 / 100
|
threshold := al.contextWindow * 75 / 100
|
||||||
|
|
@ -710,12 +802,80 @@ func (al *AgentLoop) maybeSummarize(sessionKey string) {
|
||||||
if _, loading := al.summarizing.LoadOrStore(sessionKey, true); !loading {
|
if _, loading := al.summarizing.LoadOrStore(sessionKey, true); !loading {
|
||||||
go func() {
|
go func() {
|
||||||
defer al.summarizing.Delete(sessionKey)
|
defer al.summarizing.Delete(sessionKey)
|
||||||
|
// Notify user about optimization if not an internal channel
|
||||||
|
if !constants.IsInternalChannel(channel) {
|
||||||
|
al.bus.PublishOutbound(bus.OutboundMessage{
|
||||||
|
Channel: channel,
|
||||||
|
ChatID: chatID,
|
||||||
|
Content: "⚠️ Memory threshold reached. Optimizing conversation history...",
|
||||||
|
})
|
||||||
|
}
|
||||||
al.summarizeSession(sessionKey)
|
al.summarizeSession(sessionKey)
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// forceCompression aggressively reduces context when the limit is hit.
|
||||||
|
// It drops the oldest 50% of messages (keeping system prompt and last user message).
|
||||||
|
func (al *AgentLoop) forceCompression(sessionKey string) {
|
||||||
|
history := al.sessions.GetHistory(sessionKey)
|
||||||
|
if len(history) <= 4 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep system prompt (usually [0]) and the very last message (user's trigger)
|
||||||
|
// We want to drop the oldest half of the *conversation*
|
||||||
|
// Assuming [0] is system, [1:] is conversation
|
||||||
|
conversation := history[1 : len(history)-1]
|
||||||
|
if len(conversation) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper to find the mid-point of the conversation
|
||||||
|
mid := len(conversation) / 2
|
||||||
|
|
||||||
|
// New history structure:
|
||||||
|
// 1. System Prompt
|
||||||
|
// 2. [Summary of dropped part] - synthesized
|
||||||
|
// 3. Second half of conversation
|
||||||
|
// 4. Last message
|
||||||
|
|
||||||
|
// Simplified approach for emergency: Drop first half of conversation
|
||||||
|
// and rely on existing summary if present, or create a placeholder.
|
||||||
|
|
||||||
|
droppedCount := mid
|
||||||
|
keptConversation := conversation[mid:]
|
||||||
|
|
||||||
|
newHistory := make([]providers.Message, 0)
|
||||||
|
newHistory = append(newHistory, history[0]) // System prompt
|
||||||
|
|
||||||
|
// Add a note about compression
|
||||||
|
compressionNote := fmt.Sprintf("[System: Emergency compression dropped %d oldest messages due to context limit]", droppedCount)
|
||||||
|
// If there was an existing summary, we might lose it if it was in the dropped part (which is just messages).
|
||||||
|
// The summary is stored separately in session.Summary, so it persists!
|
||||||
|
// We just need to ensure the user knows there's a gap.
|
||||||
|
|
||||||
|
// We only modify the messages list here
|
||||||
|
newHistory = append(newHistory, providers.Message{
|
||||||
|
Role: "system",
|
||||||
|
Content: compressionNote,
|
||||||
|
})
|
||||||
|
|
||||||
|
newHistory = append(newHistory, keptConversation...)
|
||||||
|
newHistory = append(newHistory, history[len(history)-1]) // Last message
|
||||||
|
|
||||||
|
// Update session
|
||||||
|
al.sessions.SetHistory(sessionKey, newHistory)
|
||||||
|
al.sessions.Save(sessionKey)
|
||||||
|
|
||||||
|
logger.WarnCF("agent", "Forced compression executed", map[string]interface{}{
|
||||||
|
"session_key": sessionKey,
|
||||||
|
"dropped_msgs": droppedCount,
|
||||||
|
"new_count": len(newHistory),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// GetStartupInfo returns information about loaded tools and skills for logging.
|
// GetStartupInfo returns information about loaded tools and skills for logging.
|
||||||
func (al *AgentLoop) GetStartupInfo() map[string]interface{} {
|
func (al *AgentLoop) GetStartupInfo() map[string]interface{} {
|
||||||
info := make(map[string]interface{})
|
info := make(map[string]interface{})
|
||||||
|
|
@ -743,7 +903,7 @@ func formatMessagesForLog(messages []providers.Message) string {
|
||||||
result += "[\n"
|
result += "[\n"
|
||||||
for i, msg := range messages {
|
for i, msg := range messages {
|
||||||
result += fmt.Sprintf(" [%d] Role: %s\n", i, msg.Role)
|
result += fmt.Sprintf(" [%d] Role: %s\n", i, msg.Role)
|
||||||
if msg.ToolCalls != nil && len(msg.ToolCalls) > 0 {
|
if len(msg.ToolCalls) > 0 {
|
||||||
result += " ToolCalls:\n"
|
result += " ToolCalls:\n"
|
||||||
for _, tc := range msg.ToolCalls {
|
for _, tc := range msg.ToolCalls {
|
||||||
result += fmt.Sprintf(" - ID: %s, Type: %s, Name: %s\n", tc.ID, tc.Type, tc.Name)
|
result += fmt.Sprintf(" - ID: %s, Type: %s, Name: %s\n", tc.ID, tc.Type, tc.Name)
|
||||||
|
|
@ -810,7 +970,7 @@ func (al *AgentLoop) summarizeSession(sessionKey string) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// Estimate tokens for this message
|
// Estimate tokens for this message
|
||||||
msgTokens := len(m.Content) / 4
|
msgTokens := len(m.Content) / 2 // Use safer estimate here too (2.5 -> 2 for integer division safety)
|
||||||
if msgTokens > maxMessageTokens {
|
if msgTokens > maxMessageTokens {
|
||||||
omitted = true
|
omitted = true
|
||||||
continue
|
continue
|
||||||
|
|
@ -881,13 +1041,122 @@ func (al *AgentLoop) summarizeBatch(ctx context.Context, batch []providers.Messa
|
||||||
}
|
}
|
||||||
|
|
||||||
// estimateTokens estimates the number of tokens in a message list.
|
// estimateTokens estimates the number of tokens in a message list.
|
||||||
// Uses rune count instead of byte length so that CJK and other multi-byte
|
// Uses a safe heuristic of 2.5 characters per token to account for CJK and other
|
||||||
// characters are not over-counted (a Chinese character is 3 bytes but roughly
|
// overheads better than the previous 3 chars/token.
|
||||||
// one token).
|
|
||||||
func (al *AgentLoop) estimateTokens(messages []providers.Message) int {
|
func (al *AgentLoop) estimateTokens(messages []providers.Message) int {
|
||||||
total := 0
|
totalChars := 0
|
||||||
for _, m := range messages {
|
for _, m := range messages {
|
||||||
total += utf8.RuneCountInString(m.Content) / 3
|
totalChars += utf8.RuneCountInString(m.Content)
|
||||||
}
|
}
|
||||||
return total
|
// 2.5 chars per token = totalChars * 2 / 5
|
||||||
|
return totalChars * 2 / 5
|
||||||
|
}
|
||||||
|
|
||||||
|
func (al *AgentLoop) handleCommand(ctx context.Context, msg bus.InboundMessage) (string, bool) {
|
||||||
|
content := strings.TrimSpace(msg.Content)
|
||||||
|
if !strings.HasPrefix(content, "/") {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
parts := strings.Fields(content)
|
||||||
|
if len(parts) == 0 {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd := parts[0]
|
||||||
|
args := parts[1:]
|
||||||
|
|
||||||
|
switch cmd {
|
||||||
|
case "/show":
|
||||||
|
if len(args) < 1 {
|
||||||
|
return "Usage: /show [model|channel]", true
|
||||||
|
}
|
||||||
|
switch args[0] {
|
||||||
|
case "model":
|
||||||
|
return fmt.Sprintf("Current model: `%s`\nCurrent provider: `%s`", al.model, al.cfg.Agents.Defaults.Provider), true
|
||||||
|
case "channel":
|
||||||
|
return fmt.Sprintf("Current channel: %s", msg.Channel), true
|
||||||
|
default:
|
||||||
|
return fmt.Sprintf("Unknown show target: %s", args[0]), true
|
||||||
|
}
|
||||||
|
|
||||||
|
case "/list":
|
||||||
|
if len(args) < 1 {
|
||||||
|
return "Usage: /list [models|channels]", true
|
||||||
|
}
|
||||||
|
switch args[0] {
|
||||||
|
case "models":
|
||||||
|
return al.listModelsResponse(), true
|
||||||
|
case "channels":
|
||||||
|
if al.channelManager == nil {
|
||||||
|
return "Channel manager not initialized", true
|
||||||
|
}
|
||||||
|
channels := al.channelManager.GetEnabledChannels()
|
||||||
|
if len(channels) == 0 {
|
||||||
|
return "No channels enabled", true
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("Enabled channels: %s", strings.Join(channels, ", ")), true
|
||||||
|
default:
|
||||||
|
return fmt.Sprintf("Unknown list target: %s", args[0]), true
|
||||||
|
}
|
||||||
|
|
||||||
|
case "/switch":
|
||||||
|
if len(args) < 3 || args[1] != "to" {
|
||||||
|
return "Usage: /switch [model|channel] to <name>", true
|
||||||
|
}
|
||||||
|
target := args[0]
|
||||||
|
value := args[2]
|
||||||
|
|
||||||
|
switch target {
|
||||||
|
case "model":
|
||||||
|
oldModel := al.model
|
||||||
|
al.SetModel(value)
|
||||||
|
return fmt.Sprintf("Switched model from %s to %s", oldModel, value), true
|
||||||
|
case "channel":
|
||||||
|
if al.channelManager == nil {
|
||||||
|
return "Channel manager not initialized", true
|
||||||
|
}
|
||||||
|
if _, exists := al.channelManager.GetChannel(value); !exists && value != "cli" {
|
||||||
|
return fmt.Sprintf("Channel '%s' not found or not enabled", value), true
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("Switched target channel to %s (Note: this currently only validates existence)", value), true
|
||||||
|
default:
|
||||||
|
return fmt.Sprintf("Unknown switch target: %s", target), true
|
||||||
|
}
|
||||||
|
|
||||||
|
case "/model":
|
||||||
|
if len(args) == 0 {
|
||||||
|
return fmt.Sprintf("Current model: `%s`\nCurrent provider: `%s`\n\n_Usage: `/model <name>` or `/model <provider>/<model>`_", al.model, al.cfg.Agents.Defaults.Provider), true
|
||||||
|
}
|
||||||
|
input := args[0]
|
||||||
|
|
||||||
|
// Check for provider/model format (e.g. "vllm/qwen3-coder-next:cloud")
|
||||||
|
if idx := strings.Index(input, "/"); idx > 0 {
|
||||||
|
newProvider := input[:idx]
|
||||||
|
newModel := input[idx+1:]
|
||||||
|
oldProvider := al.cfg.Agents.Defaults.Provider
|
||||||
|
oldModel := al.model
|
||||||
|
|
||||||
|
// Switch provider
|
||||||
|
al.cfg.Agents.Defaults.Provider = newProvider
|
||||||
|
newLLM, err := providers.CreateProvider(al.cfg)
|
||||||
|
if err != nil {
|
||||||
|
al.cfg.Agents.Defaults.Provider = oldProvider
|
||||||
|
return fmt.Sprintf("❌ Failed to switch to `%s`: %v", newProvider, err), true
|
||||||
|
}
|
||||||
|
al.provider = newLLM
|
||||||
|
al.SetModel(newModel) // This also calls saveConfig()
|
||||||
|
return fmt.Sprintf("✅ Switched: `%s/%s` → `%s/%s`", oldProvider, oldModel, newProvider, newModel), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Model-only switch (keep current provider)
|
||||||
|
oldModel := al.model
|
||||||
|
al.SetModel(input)
|
||||||
|
return fmt.Sprintf("🔄 Switched model: `%s` → `%s` (provider: `%s`)", oldModel, input, al.cfg.Agents.Defaults.Provider), true
|
||||||
|
|
||||||
|
case "/models":
|
||||||
|
return al.listModelsResponse(), true
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", false
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ package agent
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
@ -50,7 +51,7 @@ func TestRecordLastChannel(t *testing.T) {
|
||||||
// Create agent loop
|
// Create agent loop
|
||||||
msgBus := bus.NewMessageBus()
|
msgBus := bus.NewMessageBus()
|
||||||
provider := &mockProvider{}
|
provider := &mockProvider{}
|
||||||
al := NewAgentLoop(cfg, msgBus, provider)
|
al := NewAgentLoop(cfg, msgBus, provider, "")
|
||||||
|
|
||||||
// Test RecordLastChannel
|
// Test RecordLastChannel
|
||||||
testChannel := "test-channel"
|
testChannel := "test-channel"
|
||||||
|
|
@ -66,7 +67,7 @@ func TestRecordLastChannel(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify persistence by creating a new agent loop
|
// Verify persistence by creating a new agent loop
|
||||||
al2 := NewAgentLoop(cfg, msgBus, provider)
|
al2 := NewAgentLoop(cfg, msgBus, provider, "")
|
||||||
if al2.state.GetLastChannel() != testChannel {
|
if al2.state.GetLastChannel() != testChannel {
|
||||||
t.Errorf("Expected persistent channel '%s', got '%s'", testChannel, al2.state.GetLastChannel())
|
t.Errorf("Expected persistent channel '%s', got '%s'", testChannel, al2.state.GetLastChannel())
|
||||||
}
|
}
|
||||||
|
|
@ -95,7 +96,7 @@ func TestRecordLastChatID(t *testing.T) {
|
||||||
// Create agent loop
|
// Create agent loop
|
||||||
msgBus := bus.NewMessageBus()
|
msgBus := bus.NewMessageBus()
|
||||||
provider := &mockProvider{}
|
provider := &mockProvider{}
|
||||||
al := NewAgentLoop(cfg, msgBus, provider)
|
al := NewAgentLoop(cfg, msgBus, provider, "")
|
||||||
|
|
||||||
// Test RecordLastChatID
|
// Test RecordLastChatID
|
||||||
testChatID := "test-chat-id-123"
|
testChatID := "test-chat-id-123"
|
||||||
|
|
@ -111,7 +112,7 @@ func TestRecordLastChatID(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify persistence by creating a new agent loop
|
// Verify persistence by creating a new agent loop
|
||||||
al2 := NewAgentLoop(cfg, msgBus, provider)
|
al2 := NewAgentLoop(cfg, msgBus, provider, "")
|
||||||
if al2.state.GetLastChatID() != testChatID {
|
if al2.state.GetLastChatID() != testChatID {
|
||||||
t.Errorf("Expected persistent chat ID '%s', got '%s'", testChatID, al2.state.GetLastChatID())
|
t.Errorf("Expected persistent chat ID '%s', got '%s'", testChatID, al2.state.GetLastChatID())
|
||||||
}
|
}
|
||||||
|
|
@ -140,7 +141,7 @@ func TestNewAgentLoop_StateInitialized(t *testing.T) {
|
||||||
// Create agent loop
|
// Create agent loop
|
||||||
msgBus := bus.NewMessageBus()
|
msgBus := bus.NewMessageBus()
|
||||||
provider := &mockProvider{}
|
provider := &mockProvider{}
|
||||||
al := NewAgentLoop(cfg, msgBus, provider)
|
al := NewAgentLoop(cfg, msgBus, provider, "")
|
||||||
|
|
||||||
// Verify state manager is initialized
|
// Verify state manager is initialized
|
||||||
if al.state == nil {
|
if al.state == nil {
|
||||||
|
|
@ -175,7 +176,7 @@ func TestToolRegistry_ToolRegistration(t *testing.T) {
|
||||||
|
|
||||||
msgBus := bus.NewMessageBus()
|
msgBus := bus.NewMessageBus()
|
||||||
provider := &mockProvider{}
|
provider := &mockProvider{}
|
||||||
al := NewAgentLoop(cfg, msgBus, provider)
|
al := NewAgentLoop(cfg, msgBus, provider, "")
|
||||||
|
|
||||||
// Register a custom tool
|
// Register a custom tool
|
||||||
customTool := &mockCustomTool{}
|
customTool := &mockCustomTool{}
|
||||||
|
|
@ -221,7 +222,7 @@ func TestToolContext_Updates(t *testing.T) {
|
||||||
|
|
||||||
msgBus := bus.NewMessageBus()
|
msgBus := bus.NewMessageBus()
|
||||||
provider := &simpleMockProvider{response: "OK"}
|
provider := &simpleMockProvider{response: "OK"}
|
||||||
_ = NewAgentLoop(cfg, msgBus, provider)
|
_ = NewAgentLoop(cfg, msgBus, provider, "")
|
||||||
|
|
||||||
// Verify that ContextualTool interface is defined and can be implemented
|
// Verify that ContextualTool interface is defined and can be implemented
|
||||||
// This test validates the interface contract exists
|
// This test validates the interface contract exists
|
||||||
|
|
@ -252,7 +253,7 @@ func TestToolRegistry_GetDefinitions(t *testing.T) {
|
||||||
|
|
||||||
msgBus := bus.NewMessageBus()
|
msgBus := bus.NewMessageBus()
|
||||||
provider := &mockProvider{}
|
provider := &mockProvider{}
|
||||||
al := NewAgentLoop(cfg, msgBus, provider)
|
al := NewAgentLoop(cfg, msgBus, provider, "")
|
||||||
|
|
||||||
// Register a test tool and verify it shows up in startup info
|
// Register a test tool and verify it shows up in startup info
|
||||||
testTool := &mockCustomTool{}
|
testTool := &mockCustomTool{}
|
||||||
|
|
@ -296,7 +297,7 @@ func TestAgentLoop_GetStartupInfo(t *testing.T) {
|
||||||
|
|
||||||
msgBus := bus.NewMessageBus()
|
msgBus := bus.NewMessageBus()
|
||||||
provider := &mockProvider{}
|
provider := &mockProvider{}
|
||||||
al := NewAgentLoop(cfg, msgBus, provider)
|
al := NewAgentLoop(cfg, msgBus, provider, "")
|
||||||
|
|
||||||
info := al.GetStartupInfo()
|
info := al.GetStartupInfo()
|
||||||
|
|
||||||
|
|
@ -343,7 +344,7 @@ func TestAgentLoop_Stop(t *testing.T) {
|
||||||
|
|
||||||
msgBus := bus.NewMessageBus()
|
msgBus := bus.NewMessageBus()
|
||||||
provider := &mockProvider{}
|
provider := &mockProvider{}
|
||||||
al := NewAgentLoop(cfg, msgBus, provider)
|
al := NewAgentLoop(cfg, msgBus, provider, "")
|
||||||
|
|
||||||
// Note: running is only set to true when Run() is called
|
// Note: running is only set to true when Run() is called
|
||||||
// We can't test that without starting the event loop
|
// We can't test that without starting the event loop
|
||||||
|
|
@ -465,7 +466,7 @@ func TestToolResult_SilentToolDoesNotSendUserMessage(t *testing.T) {
|
||||||
|
|
||||||
msgBus := bus.NewMessageBus()
|
msgBus := bus.NewMessageBus()
|
||||||
provider := &simpleMockProvider{response: "File operation complete"}
|
provider := &simpleMockProvider{response: "File operation complete"}
|
||||||
al := NewAgentLoop(cfg, msgBus, provider)
|
al := NewAgentLoop(cfg, msgBus, provider, "")
|
||||||
helper := testHelper{al: al}
|
helper := testHelper{al: al}
|
||||||
|
|
||||||
// ReadFileTool returns SilentResult, which should not send user message
|
// ReadFileTool returns SilentResult, which should not send user message
|
||||||
|
|
@ -507,7 +508,7 @@ func TestToolResult_UserFacingToolDoesSendMessage(t *testing.T) {
|
||||||
|
|
||||||
msgBus := bus.NewMessageBus()
|
msgBus := bus.NewMessageBus()
|
||||||
provider := &simpleMockProvider{response: "Command output: hello world"}
|
provider := &simpleMockProvider{response: "Command output: hello world"}
|
||||||
al := NewAgentLoop(cfg, msgBus, provider)
|
al := NewAgentLoop(cfg, msgBus, provider, "")
|
||||||
helper := testHelper{al: al}
|
helper := testHelper{al: al}
|
||||||
|
|
||||||
// ExecTool returns UserResult, which should send user message
|
// ExecTool returns UserResult, which should send user message
|
||||||
|
|
@ -527,3 +528,99 @@ func TestToolResult_UserFacingToolDoesSendMessage(t *testing.T) {
|
||||||
t.Errorf("Expected 'Command output: hello world', got: %s", response)
|
t.Errorf("Expected 'Command output: hello world', got: %s", response)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// failFirstMockProvider fails on the first N calls with a specific error
|
||||||
|
type failFirstMockProvider struct {
|
||||||
|
failures int
|
||||||
|
currentCall int
|
||||||
|
failError error
|
||||||
|
successResp string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *failFirstMockProvider) Chat(ctx context.Context, messages []providers.Message, tools []providers.ToolDefinition, model string, opts map[string]interface{}) (*providers.LLMResponse, error) {
|
||||||
|
m.currentCall++
|
||||||
|
if m.currentCall <= m.failures {
|
||||||
|
return nil, m.failError
|
||||||
|
}
|
||||||
|
return &providers.LLMResponse{
|
||||||
|
Content: m.successResp,
|
||||||
|
ToolCalls: []providers.ToolCall{},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *failFirstMockProvider) GetDefaultModel() string {
|
||||||
|
return "mock-fail-model"
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAgentLoop_ContextExhaustionRetry verify that the agent retries on context errors
|
||||||
|
func TestAgentLoop_ContextExhaustionRetry(t *testing.T) {
|
||||||
|
tmpDir, err := os.MkdirTemp("", "agent-test-*")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to create temp dir: %v", err)
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(tmpDir)
|
||||||
|
|
||||||
|
cfg := &config.Config{
|
||||||
|
Agents: config.AgentsConfig{
|
||||||
|
Defaults: config.AgentDefaults{
|
||||||
|
Workspace: tmpDir,
|
||||||
|
Model: "test-model",
|
||||||
|
MaxTokens: 4096,
|
||||||
|
MaxToolIterations: 10,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
msgBus := bus.NewMessageBus()
|
||||||
|
|
||||||
|
// Create a provider that fails once with a context error
|
||||||
|
contextErr := fmt.Errorf("InvalidParameter: Total tokens of image and text exceed max message tokens")
|
||||||
|
provider := &failFirstMockProvider{
|
||||||
|
failures: 1,
|
||||||
|
failError: contextErr,
|
||||||
|
successResp: "Recovered from context error",
|
||||||
|
}
|
||||||
|
|
||||||
|
al := NewAgentLoop(cfg, msgBus, provider, "")
|
||||||
|
|
||||||
|
// Inject some history to simulate a full context
|
||||||
|
sessionKey := "test-session-context"
|
||||||
|
// Create dummy history
|
||||||
|
history := []providers.Message{
|
||||||
|
{Role: "system", Content: "System prompt"},
|
||||||
|
{Role: "user", Content: "Old message 1"},
|
||||||
|
{Role: "assistant", Content: "Old response 1"},
|
||||||
|
{Role: "user", Content: "Old message 2"},
|
||||||
|
{Role: "assistant", Content: "Old response 2"},
|
||||||
|
{Role: "user", Content: "Trigger message"},
|
||||||
|
}
|
||||||
|
al.sessions.SetHistory(sessionKey, history)
|
||||||
|
|
||||||
|
// Call ProcessDirectWithChannel
|
||||||
|
// Note: ProcessDirectWithChannel calls processMessage which will execute runLLMIteration
|
||||||
|
response, err := al.ProcessDirectWithChannel(context.Background(), "Trigger message", sessionKey, "test", "test-chat")
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Expected success after retry, got error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if response != "Recovered from context error" {
|
||||||
|
t.Errorf("Expected 'Recovered from context error', got '%s'", response)
|
||||||
|
}
|
||||||
|
|
||||||
|
// We expect 2 calls: 1st failed, 2nd succeeded
|
||||||
|
if provider.currentCall != 2 {
|
||||||
|
t.Errorf("Expected 2 calls (1 fail + 1 success), got %d", provider.currentCall)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check final history length
|
||||||
|
finalHistory := al.sessions.GetHistory(sessionKey)
|
||||||
|
// We verify that the history has been modified (compressed)
|
||||||
|
// Original length: 6
|
||||||
|
// Expected behavior: compression drops ~50% of history (mid slice)
|
||||||
|
// We can assert that the length is NOT what it would be without compression.
|
||||||
|
// Without compression: 6 + 1 (new user msg) + 1 (assistant msg) = 8
|
||||||
|
if len(finalHistory) >= 8 {
|
||||||
|
t.Errorf("Expected history to be compressed (len < 8), got %d", len(finalHistory))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -296,6 +296,13 @@ func (c *SlackChannel) handleAppMention(ev *slackevents.AppMentionEvent) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !c.IsAllowed(ev.User) {
|
||||||
|
logger.DebugCF("slack", "Mention rejected by allowlist", map[string]interface{}{
|
||||||
|
"user_id": ev.User,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
senderID := ev.User
|
senderID := ev.User
|
||||||
channelID := ev.Channel
|
channelID := ev.Channel
|
||||||
threadTS := ev.ThreadTimeStamp
|
threadTS := ev.ThreadTimeStamp
|
||||||
|
|
@ -345,6 +352,13 @@ func (c *SlackChannel) handleSlashCommand(event socketmode.Event) {
|
||||||
c.socketClient.Ack(*event.Request)
|
c.socketClient.Ack(*event.Request)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !c.IsAllowed(cmd.UserID) {
|
||||||
|
logger.DebugCF("slack", "Slash command rejected by allowlist", map[string]interface{}{
|
||||||
|
"user_id": cmd.UserID,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
senderID := cmd.UserID
|
senderID := cmd.UserID
|
||||||
channelID := cmd.ChannelID
|
channelID := cmd.ChannelID
|
||||||
chatID := channelID
|
chatID := channelID
|
||||||
|
|
|
||||||
|
|
@ -370,7 +370,7 @@ func SaveConfig(path string, cfg *Config) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return os.WriteFile(path, data, 0644)
|
return os.WriteFile(path, data, 0600)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Config) WorkspacePath() string {
|
func (c *Config) WorkspacePath() string {
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,9 @@
|
||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -147,6 +150,30 @@ func TestDefaultConfig_WebTools(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSaveConfig_FilePermissions(t *testing.T) {
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
t.Skip("file permission bits are not enforced on Windows")
|
||||||
|
}
|
||||||
|
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
path := filepath.Join(tmpDir, "config.json")
|
||||||
|
|
||||||
|
cfg := DefaultConfig()
|
||||||
|
if err := SaveConfig(path, cfg); err != nil {
|
||||||
|
t.Fatalf("SaveConfig failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Stat failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
perm := info.Mode().Perm()
|
||||||
|
if perm != 0600 {
|
||||||
|
t.Errorf("config file has permission %04o, want 0600", perm)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestConfig_Complete verifies all config fields are set
|
// TestConfig_Complete verifies all config fields are set
|
||||||
func TestConfig_Complete(t *testing.T) {
|
func TestConfig_Complete(t *testing.T) {
|
||||||
cfg := DefaultConfig()
|
cfg := DefaultConfig()
|
||||||
|
|
|
||||||
|
|
@ -340,7 +340,7 @@ func (cs *CronService) saveStoreUnsafe() error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return os.WriteFile(cs.storePath, data, 0644)
|
return os.WriteFile(cs.storePath, data, 0600)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cs *CronService) AddJob(name string, schedule CronSchedule, message string, deliver bool, channel, to string) (*CronJob, error) {
|
func (cs *CronService) AddJob(name string, schedule CronSchedule, message string, deliver bool, channel, to string) (*CronJob, error) {
|
||||||
|
|
|
||||||
38
pkg/cron/service_test.go
Normal file
38
pkg/cron/service_test.go
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
package cron
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSaveStore_FilePermissions(t *testing.T) {
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
t.Skip("file permission bits are not enforced on Windows")
|
||||||
|
}
|
||||||
|
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
storePath := filepath.Join(tmpDir, "cron", "jobs.json")
|
||||||
|
|
||||||
|
cs := NewCronService(storePath, nil)
|
||||||
|
|
||||||
|
_, err := cs.AddJob("test", CronSchedule{Kind: "every", EveryMS: int64Ptr(60000)}, "hello", false, "cli", "direct")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("AddJob failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
info, err := os.Stat(storePath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Stat failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
perm := info.Mode().Perm()
|
||||||
|
if perm != 0600 {
|
||||||
|
t.Errorf("cron store has permission %04o, want 0600", perm)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func int64Ptr(v int64) *int64 {
|
||||||
|
return &v
|
||||||
|
}
|
||||||
|
|
@ -264,3 +264,19 @@ func (sm *SessionManager) loadSessions() error {
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetHistory updates the messages of a session.
|
||||||
|
func (sm *SessionManager) SetHistory(key string, history []providers.Message) {
|
||||||
|
sm.mu.Lock()
|
||||||
|
defer sm.mu.Unlock()
|
||||||
|
|
||||||
|
session, ok := sm.sessions[key]
|
||||||
|
if ok {
|
||||||
|
// Create a deep copy to strictly isolate internal state
|
||||||
|
// from the caller's slice.
|
||||||
|
msgs := make([]providers.Message, len(history))
|
||||||
|
copy(msgs, history)
|
||||||
|
session.Messages = msgs
|
||||||
|
session.Updated = time.Now()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -28,12 +28,12 @@ type CronTool struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCronTool creates a new CronTool
|
// NewCronTool creates a new CronTool
|
||||||
func NewCronTool(cronService *cron.CronService, executor JobExecutor, msgBus *bus.MessageBus, workspace string) *CronTool {
|
func NewCronTool(cronService *cron.CronService, executor JobExecutor, msgBus *bus.MessageBus, workspace string, restrict bool) *CronTool {
|
||||||
return &CronTool{
|
return &CronTool{
|
||||||
cronService: cronService,
|
cronService: cronService,
|
||||||
executor: executor,
|
executor: executor,
|
||||||
msgBus: msgBus,
|
msgBus: msgBus,
|
||||||
execTool: NewExecTool(workspace, false),
|
execTool: NewExecTool(workspace, restrict),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -29,13 +29,54 @@ func validatePath(path, workspace string, restrict bool) (string, error) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if restrict && !strings.HasPrefix(absPath, absWorkspace) {
|
if restrict {
|
||||||
return "", fmt.Errorf("access denied: path is outside the workspace")
|
if !isWithinWorkspace(absPath, absWorkspace) {
|
||||||
|
return "", fmt.Errorf("access denied: path is outside the workspace")
|
||||||
|
}
|
||||||
|
|
||||||
|
workspaceReal := absWorkspace
|
||||||
|
if resolved, err := filepath.EvalSymlinks(absWorkspace); err == nil {
|
||||||
|
workspaceReal = resolved
|
||||||
|
}
|
||||||
|
|
||||||
|
if resolved, err := filepath.EvalSymlinks(absPath); err == nil {
|
||||||
|
if !isWithinWorkspace(resolved, workspaceReal) {
|
||||||
|
return "", fmt.Errorf("access denied: symlink resolves outside workspace")
|
||||||
|
}
|
||||||
|
} else if os.IsNotExist(err) {
|
||||||
|
if parentResolved, err := resolveExistingAncestor(filepath.Dir(absPath)); err == nil {
|
||||||
|
if !isWithinWorkspace(parentResolved, workspaceReal) {
|
||||||
|
return "", fmt.Errorf("access denied: symlink resolves outside workspace")
|
||||||
|
}
|
||||||
|
} else if !os.IsNotExist(err) {
|
||||||
|
return "", fmt.Errorf("failed to resolve path: %w", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return "", fmt.Errorf("failed to resolve path: %w", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return absPath, nil
|
return absPath, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func resolveExistingAncestor(path string) (string, error) {
|
||||||
|
for current := filepath.Clean(path); ; current = filepath.Dir(current) {
|
||||||
|
if resolved, err := filepath.EvalSymlinks(current); err == nil {
|
||||||
|
return resolved, nil
|
||||||
|
} else if !os.IsNotExist(err) {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if filepath.Dir(current) == current {
|
||||||
|
return "", os.ErrNotExist
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isWithinWorkspace(candidate, workspace string) bool {
|
||||||
|
rel, err := filepath.Rel(filepath.Clean(workspace), filepath.Clean(candidate))
|
||||||
|
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator))
|
||||||
|
}
|
||||||
|
|
||||||
type ReadFileTool struct {
|
type ReadFileTool struct {
|
||||||
workspace string
|
workspace string
|
||||||
restrict bool
|
restrict bool
|
||||||
|
|
|
||||||
|
|
@ -247,3 +247,35 @@ func TestFilesystemTool_ListDir_DefaultPath(t *testing.T) {
|
||||||
t.Errorf("Expected success with default path '.', got IsError=true: %s", result.ForLLM)
|
t.Errorf("Expected success with default path '.', got IsError=true: %s", result.ForLLM)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Block paths that look inside workspace but point outside via symlink.
|
||||||
|
func TestFilesystemTool_ReadFile_RejectsSymlinkEscape(t *testing.T) {
|
||||||
|
|
||||||
|
root := t.TempDir()
|
||||||
|
workspace := filepath.Join(root, "workspace")
|
||||||
|
if err := os.MkdirAll(workspace, 0755); err != nil {
|
||||||
|
t.Fatalf("failed to create workspace: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
secret := filepath.Join(root, "secret.txt")
|
||||||
|
if err := os.WriteFile(secret, []byte("top secret"), 0644); err != nil {
|
||||||
|
t.Fatalf("failed to write secret file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
link := filepath.Join(workspace, "leak.txt")
|
||||||
|
if err := os.Symlink(secret, link); err != nil {
|
||||||
|
t.Skipf("symlink not supported in this environment: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tool := NewReadFileTool(workspace, true)
|
||||||
|
result := tool.Execute(context.Background(), map[string]interface{}{
|
||||||
|
"path": link,
|
||||||
|
})
|
||||||
|
|
||||||
|
if !result.IsError {
|
||||||
|
t.Fatalf("expected symlink escape to be blocked")
|
||||||
|
}
|
||||||
|
if !strings.Contains(result.ForLLM, "symlink resolves outside workspace") {
|
||||||
|
t.Fatalf("expected symlink escape error, got: %s", result.ForLLM)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue