current state
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"sidekick"
|
||||
|
||||
"github.com/mark3labs/mcp-go/mcp"
|
||||
"github.com/mark3labs/mcp-go/server"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg, err := sidekick.LoadConfig("config.toml")
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to load config: %v", err)
|
||||
}
|
||||
|
||||
// Disable standard logging to stdout if stdio transport is used,
|
||||
// so it doesn't corrupt the JSON-RPC stream.
|
||||
if cfg.MCPListener.Transport == "stdio" || cfg.MCPListener.Transport == "" {
|
||||
log.SetOutput(os.Stderr)
|
||||
}
|
||||
|
||||
tmpl, _ := sidekick.LoadPrompts("prompts.toml")
|
||||
|
||||
sidekick.InitMCPServers(cfg.MCPServers)
|
||||
pool := make(map[string]*sidekick.Sidekick)
|
||||
|
||||
for id, aCfg := range cfg.Agents {
|
||||
if tmpl != nil && tmpl.Lookup(id) != nil {
|
||||
rendered, rErr := sidekick.RenderPrompt(tmpl, id)
|
||||
if rErr == nil {
|
||||
aCfg.SystemPrompt = rendered
|
||||
}
|
||||
}
|
||||
mCfg := cfg.Models[aCfg.ModelID]
|
||||
pool[id] = sidekick.NewSidekick(aCfg, mCfg, nil)
|
||||
}
|
||||
|
||||
entryAgent := "coordinator"
|
||||
if _, ok := pool[entryAgent]; !ok {
|
||||
for id := range pool {
|
||||
entryAgent = id
|
||||
break
|
||||
}
|
||||
}
|
||||
agent := pool[entryAgent]
|
||||
|
||||
mcpServer := server.NewMCPServer("Sidekick MCP", "1.0.0")
|
||||
|
||||
mcpServer.AddTool(
|
||||
mcp.NewToolWithRawSchema(
|
||||
"query",
|
||||
"Ask Sidekick a question or provide a message, optionally with conversation history",
|
||||
json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"message": { "type": "string", "description": "The user's message" },
|
||||
"history": {
|
||||
"type": "array",
|
||||
"description": "Optional list of previous messages",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"role": { "type": "string" },
|
||||
"content": { "type": "string" }
|
||||
},
|
||||
"required": ["role", "content"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["message"]
|
||||
}`),
|
||||
),
|
||||
func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
msg, err := request.RequireString("message")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("message argument is required and must be a string: %v", err)
|
||||
}
|
||||
|
||||
var inCtx []sidekick.Message
|
||||
|
||||
args := request.GetArguments()
|
||||
if histInter, ok := args["history"]; ok {
|
||||
if histList, ok := histInter.([]interface{}); ok {
|
||||
for _, h := range histList {
|
||||
if hMap, ok := h.(map[string]interface{}); ok {
|
||||
roleInter, okRole := hMap["role"]
|
||||
contentInter, okContent := hMap["content"]
|
||||
if okRole && okContent {
|
||||
if roleStr, isStr := roleInter.(string); isStr {
|
||||
if contentStr, isStrContent := contentInter.(string); isStrContent {
|
||||
inCtx = append(inCtx, sidekick.Message{
|
||||
Role: sidekick.MessageRole(roleStr),
|
||||
Content: contentStr,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inCtx = append(inCtx, sidekick.Message{
|
||||
Role: sidekick.MessageRoleUser,
|
||||
Content: msg,
|
||||
})
|
||||
|
||||
responseStr, err := agent.Run(ctx, inCtx, pool)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("agent run failed: %w", err)
|
||||
}
|
||||
|
||||
// Add the final response to the history structure to be returned
|
||||
outHistory := append(inCtx, sidekick.Message{
|
||||
Role: sidekick.MessageRole("assistant"),
|
||||
Content: responseStr,
|
||||
})
|
||||
|
||||
resultObj := map[string]interface{}{
|
||||
"response": responseStr,
|
||||
"history": outHistory,
|
||||
}
|
||||
|
||||
resultBytes, err := json.Marshal(resultObj)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal result: %w", err)
|
||||
}
|
||||
|
||||
return &mcp.CallToolResult{
|
||||
Content: []mcp.Content{
|
||||
mcp.NewTextContent(string(resultBytes)),
|
||||
},
|
||||
}, nil
|
||||
},
|
||||
)
|
||||
|
||||
transport := cfg.MCPListener.Transport
|
||||
if transport == "stdio" || transport == "" {
|
||||
if err := server.ServeStdio(mcpServer); err != nil {
|
||||
log.Fatalf("MCP Server (stdio) error: %v", err)
|
||||
}
|
||||
} else if transport == "http" || transport == "sse" { // mcp-go supports SSE, which is Streamable HTTP
|
||||
port := cfg.MCPListener.Port
|
||||
if port == 0 {
|
||||
port = 8080
|
||||
}
|
||||
addr := fmt.Sprintf(":%d", port)
|
||||
log.Printf("Starting MCP Streamable HTTP server on %s", addr)
|
||||
srv := server.NewStreamableHTTPServer(mcpServer)
|
||||
if err := srv.Start(addr); err != nil {
|
||||
log.Fatalf("MCP Server (http) error: %v", err)
|
||||
}
|
||||
} else {
|
||||
log.Fatalf("Unsupported MCP listener transport: %s", transport)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/mark3labs/mcp-go/mcp"
|
||||
)
|
||||
|
||||
// Since we cannot easily test the main() function without significant refactoring
|
||||
// to split initialization from the server start, we test the tool handler logic.
|
||||
// This mirrors the logic in main.go but allows for unit testing.
|
||||
|
||||
func TestQueryToolHandler(t *testing.T) {
|
||||
// In a real scenario, we might want to refactor main.go to export a
|
||||
// function that creates the handler. For now, we'll verify the logic
|
||||
// we've implemented in the main.go file by testing the expected
|
||||
// behavior of a similar handler.
|
||||
|
||||
t.Run("ValidRequest", func(t *testing.T) {
|
||||
// Mock arguments
|
||||
args := map[string]interface{}{
|
||||
"message": "Hello Sidekick",
|
||||
"history": []interface{}{
|
||||
map[string]interface{}{"role": "user", "content": "Hi"},
|
||||
map[string]interface{}{"role": "assistant", "content": "Hello! How can I help?"},
|
||||
},
|
||||
}
|
||||
|
||||
req := mcp.CallToolRequest{}
|
||||
req.Params.Name = "query"
|
||||
req.Params.Arguments = args
|
||||
|
||||
// We verify the RequireString and GetArguments logic here
|
||||
msg, err := req.RequireString("message")
|
||||
if err != nil || msg != "Hello Sidekick" {
|
||||
t.Errorf("RequireString failed: %v", err)
|
||||
}
|
||||
|
||||
rawArgs := req.GetArguments()
|
||||
histInter, ok := rawArgs["history"]
|
||||
if !ok {
|
||||
t.Fatal("history missing from arguments")
|
||||
}
|
||||
|
||||
histList, ok := histInter.([]interface{})
|
||||
if !ok || len(histList) != 2 {
|
||||
t.Errorf("history list invalid: %v", histInter)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("MissingMessage", func(t *testing.T) {
|
||||
req := mcp.CallToolRequest{}
|
||||
req.Params.Name = "query"
|
||||
req.Params.Arguments = map[string]interface{}{}
|
||||
|
||||
_, err := req.RequireString("message")
|
||||
if err == nil {
|
||||
t.Error("expected error for missing message")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestResultMarshalling(t *testing.T) {
|
||||
// Verify the format of the response as requested: {"response", "history"}
|
||||
type msg struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
result := map[string]interface{}{
|
||||
"response": "Agent response",
|
||||
"history": []msg{
|
||||
{Role: "user", Content: "User message"},
|
||||
{Role: "assistant", Content: "Agent response"},
|
||||
},
|
||||
}
|
||||
|
||||
data, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal failed: %v", err)
|
||||
}
|
||||
|
||||
var decoded map[string]interface{}
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
t.Fatalf("unmarshal failed: %v", err)
|
||||
}
|
||||
|
||||
if _, ok := decoded["response"]; !ok {
|
||||
t.Error("response key missing")
|
||||
}
|
||||
if _, ok := decoded["history"]; !ok {
|
||||
t.Error("history key missing")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/bubbles/textarea"
|
||||
"github.com/charmbracelet/bubbles/viewport"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"sidekick"
|
||||
)
|
||||
|
||||
var (
|
||||
titleStyle = lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color("#FFFDF5")).
|
||||
Background(lipgloss.Color("#25A065")).
|
||||
Padding(0, 1).
|
||||
Bold(true)
|
||||
statusStyle = lipgloss.NewStyle().
|
||||
Foreground(lipgloss.Color("#FFFDF5")).
|
||||
Background(lipgloss.Color("#3C3C3C")).
|
||||
Padding(0, 1)
|
||||
viewportStyle = lipgloss.NewStyle().
|
||||
Border(lipgloss.RoundedBorder()).
|
||||
BorderForeground(lipgloss.Color("62")).
|
||||
Padding(0, 1)
|
||||
textareaStyle = lipgloss.NewStyle().
|
||||
Border(lipgloss.RoundedBorder()).
|
||||
BorderForeground(lipgloss.Color("240")).
|
||||
Padding(0, 1)
|
||||
textareaFocusStyle = lipgloss.NewStyle().
|
||||
Border(lipgloss.RoundedBorder()).
|
||||
BorderForeground(lipgloss.Color("62")).
|
||||
Padding(0, 1)
|
||||
userStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("6")).Bold(true)
|
||||
agentStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("5")).Bold(true)
|
||||
sysStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("8")).Italic(true)
|
||||
)
|
||||
|
||||
type model struct {
|
||||
viewport viewport.Model
|
||||
textarea textarea.Model
|
||||
agent *sidekick.Sidekick
|
||||
pool map[string]*sidekick.Sidekick
|
||||
messages []string
|
||||
isThinking bool
|
||||
err error
|
||||
ready bool
|
||||
width int
|
||||
height int
|
||||
}
|
||||
|
||||
type agentResponseMsg struct {
|
||||
response string
|
||||
err error
|
||||
}
|
||||
|
||||
func initialModel() model {
|
||||
ta := textarea.New()
|
||||
ta.Placeholder = "Type a message..."
|
||||
ta.Focus()
|
||||
ta.Prompt = "┃ "
|
||||
ta.CharLimit = 2000
|
||||
ta.SetHeight(3)
|
||||
|
||||
// Load TOML config
|
||||
cfg, err := sidekick.LoadConfig("config.toml")
|
||||
var agent *sidekick.Sidekick
|
||||
var pool map[string]*sidekick.Sidekick
|
||||
|
||||
if err != nil {
|
||||
ac := sidekick.AgentConfig{ID: "tui", Role: sidekick.RoleSpecialist, MaxIterations: 5}
|
||||
agent = sidekick.NewSidekick(ac, sidekick.ModelConfig{}, nil)
|
||||
} else {
|
||||
// Attempt to load and apply prompts
|
||||
tmpl, _ := sidekick.LoadPrompts("prompts.toml")
|
||||
|
||||
sidekick.InitMCPServers(cfg.MCPServers)
|
||||
pool = make(map[string]*sidekick.Sidekick)
|
||||
for id, aCfg := range cfg.Agents {
|
||||
if tmpl != nil && tmpl.Lookup(id) != nil {
|
||||
rendered, rErr := sidekick.RenderPrompt(tmpl, id)
|
||||
if rErr == nil {
|
||||
aCfg.SystemPrompt = rendered
|
||||
}
|
||||
}
|
||||
mCfg := cfg.Models[aCfg.ModelID]
|
||||
pool[id] = sidekick.NewSidekick(aCfg, mCfg, nil)
|
||||
}
|
||||
entryAgent := "coordinator"
|
||||
if _, ok := pool[entryAgent]; !ok {
|
||||
for id := range pool {
|
||||
entryAgent = id
|
||||
break
|
||||
}
|
||||
}
|
||||
agent = pool[entryAgent]
|
||||
}
|
||||
|
||||
return model{
|
||||
textarea: ta,
|
||||
agent: agent,
|
||||
pool: pool,
|
||||
messages: []string{sysStyle.Render("System: Sidekick initialized. Type a message below.")},
|
||||
}
|
||||
}
|
||||
|
||||
func (m model) Init() tea.Cmd { return textarea.Blink }
|
||||
|
||||
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
var (
|
||||
tiCmd tea.Cmd
|
||||
vpCmd tea.Cmd
|
||||
)
|
||||
|
||||
switch msg := msg.(type) {
|
||||
case tea.KeyMsg:
|
||||
switch msg.Type {
|
||||
case tea.KeyCtrlC, tea.KeyEsc:
|
||||
return m, tea.Quit
|
||||
case tea.KeyEnter:
|
||||
if msg.Alt {
|
||||
break
|
||||
}
|
||||
v := m.textarea.Value()
|
||||
if strings.TrimSpace(v) == "" || m.isThinking {
|
||||
return m, nil
|
||||
}
|
||||
m.messages = append(m.messages, userStyle.Render("You")+"\n"+v)
|
||||
m.textarea.Reset()
|
||||
m.viewport.SetContent(strings.Join(m.messages, "\n\n"))
|
||||
m.viewport.GotoBottom()
|
||||
m.isThinking = true
|
||||
return m, m.runAgent(v)
|
||||
}
|
||||
case agentResponseMsg:
|
||||
m.isThinking = false
|
||||
if msg.err != nil {
|
||||
m.messages = append(m.messages, sysStyle.Render(fmt.Sprintf("Error: %v", msg.err)))
|
||||
} else {
|
||||
m.messages = append(m.messages, agentStyle.Render("Sidekick")+"\n"+msg.response)
|
||||
}
|
||||
m.viewport.SetContent(strings.Join(m.messages, "\n\n"))
|
||||
m.viewport.GotoBottom()
|
||||
return m, nil
|
||||
case tea.WindowSizeMsg:
|
||||
m.width = msg.Width
|
||||
m.height = msg.Height
|
||||
|
||||
headerHeight := 1
|
||||
inputHeight := 5 // Textarea height(3) + border/padding
|
||||
|
||||
if !m.ready {
|
||||
m.viewport = viewport.New(msg.Width-2, msg.Height-headerHeight-inputHeight-2)
|
||||
m.viewport.SetContent(strings.Join(m.messages, "\n\n"))
|
||||
m.ready = true
|
||||
} else {
|
||||
m.viewport.Width = msg.Width - 2
|
||||
m.viewport.Height = msg.Height - headerHeight - inputHeight - 2
|
||||
}
|
||||
|
||||
m.textarea.SetWidth(msg.Width - 4)
|
||||
}
|
||||
|
||||
m.textarea, tiCmd = m.textarea.Update(msg)
|
||||
m.viewport, vpCmd = m.viewport.Update(msg)
|
||||
return m, tea.Batch(tiCmd, vpCmd)
|
||||
}
|
||||
|
||||
func (m model) runAgent(prompt string) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
res, err := m.agent.Run(context.Background(), []sidekick.Message{{Role: sidekick.MessageRoleUser, Content: prompt}}, m.pool)
|
||||
return agentResponseMsg{response: res, err: err}
|
||||
}
|
||||
}
|
||||
|
||||
func (m model) View() string {
|
||||
if !m.ready {
|
||||
return "\n Initializing..."
|
||||
}
|
||||
|
||||
status := "IDLE"
|
||||
if m.isThinking {
|
||||
status = "THINKING"
|
||||
}
|
||||
|
||||
header := lipgloss.JoinHorizontal(lipgloss.Top,
|
||||
titleStyle.Render(" SIDEKICK NG "),
|
||||
statusStyle.Render(" "+status+" "),
|
||||
)
|
||||
|
||||
vpView := viewportStyle.Width(m.width - 2).Height(m.height - 10).Render(m.viewport.View())
|
||||
|
||||
taStyle := textareaStyle
|
||||
if m.textarea.Focused() {
|
||||
taStyle = textareaFocusStyle
|
||||
}
|
||||
taView := taStyle.Width(m.width - 2).Render(m.textarea.View())
|
||||
|
||||
return lipgloss.JoinVertical(lipgloss.Left,
|
||||
header,
|
||||
vpView,
|
||||
taView,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
func main() {
|
||||
if _, err := tea.NewProgram(initialModel(), tea.WithAltScreen()).Run(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
)
|
||||
|
||||
// Since sidekick-tui/main.go uses global variables and is a tea.Model,
|
||||
// we test basic model behavior.
|
||||
|
||||
func TestInitialModel(t *testing.T) {
|
||||
// For testing, sidekick.LoadConfig would fail or look in its default dir.
|
||||
// This ensures that the model can be initialized even without a config.
|
||||
m := initialModel()
|
||||
|
||||
if m.agent == nil {
|
||||
t.Error("expected default agent to be initialized even without config")
|
||||
}
|
||||
|
||||
if m.textarea.Value() != "" {
|
||||
t.Errorf("expected empty textarea, got %s", m.textarea.Value())
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelUpdate(t *testing.T) {
|
||||
m := initialModel()
|
||||
m.ready = true
|
||||
m.width = 80
|
||||
m.height = 24
|
||||
|
||||
// Test a key message (Enter)
|
||||
m.textarea.SetValue("Hello")
|
||||
newModel, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
|
||||
|
||||
tm := newModel.(model)
|
||||
if tm.isThinking != true {
|
||||
t.Error("expected model to be in thinking state after Enter")
|
||||
}
|
||||
if tm.textarea.Value() != "" {
|
||||
t.Error("expected textarea to be reset after Enter")
|
||||
}
|
||||
if cmd == nil {
|
||||
t.Error("expected a command after Enter")
|
||||
}
|
||||
|
||||
// Test an agent response message
|
||||
respModel, _ := tm.Update(agentResponseMsg{response: "Hi"})
|
||||
rm := respModel.(model)
|
||||
if rm.isThinking != false {
|
||||
t.Error("expected model to stop thinking after response")
|
||||
}
|
||||
if len(rm.messages) < 2 {
|
||||
t.Error("expected message list to grow after response")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user