@@ -8,12 +8,15 @@ import (
88 "fmt"
99 "os"
1010 "strings"
11+ "time"
1112
13+ "github.com/google/uuid"
1214 "github.com/rs/zerolog"
1315 "github.com/rs/zerolog/log"
1416 "github.com/xonecas/mysis/internal/config"
1517 "github.com/xonecas/mysis/internal/mcp"
1618 "github.com/xonecas/mysis/internal/provider"
19+ "github.com/xonecas/mysis/internal/store"
1720 "github.com/xonecas/mysis/internal/styles"
1821 )
1922
@@ -27,6 +30,8 @@ func main() {
2730 configPath = flag.String("config", "", "Path to config file")
2831 debug = flag.Bool("debug", false, "Enable debug logging")
2932 providerName = flag.String("p", "", "Provider name (overrides default from config)")
33+ sessionName = flag.String("session", "", "Session name (resume or create named session)")
34+ listSessions = flag.Bool("list-sessions", false, "List recent sessions and exit")
3035 )
3136 flag.Parse()
3237
@@ -75,6 +80,23 @@ func main() {
7580 os.Exit(1)
7681 }
7782
83+ // Open database
84+ db, err := store.Open()
85+ if err != nil {
86+ fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to open database: "+err.Error()))
87+ os.Exit(1)
88+ }
89+ defer db.Close()
90+
91+ // Handle --list-sessions flag
92+ if *listSessions {
93+ if err := listSessionsCmd(db); err != nil {
94+ fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error()))
95+ os.Exit(1)
96+ }
97+ return
98+ }
99+
78100 // Load credentials
79101 creds, err := config.LoadCredentials()
80102 if err != nil {
@@ -139,21 +161,69 @@ func main() {
139161 log.Info().Int("count", len(tools)).Msg("Tools available")
140162 }
141163
164+ // Initialize or resume session
165+ var sessionID string
166+ var sessionInfo string
167+ if *sessionName != "" {
168+ // Try to resume by name
169+ sess, err := db.GetSessionByName(*sessionName)
170+ if err != nil {
171+ fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to load session: "+err.Error()))
172+ os.Exit(1)
173+ }
174+ if sess != nil {
175+ sessionID = sess.ID
176+ sessionInfo = fmt.Sprintf("Resumed session: %s", *sessionName)
177+ log.Info().Str("session_id", sessionID).Str("name", *sessionName).Msg("Resumed session")
178+ } else {
179+ // Create new named session
180+ sessionID = uuid.New().String()
181+ if err := db.CreateSession(sessionID, selectedProvider, providerCfg.Model, sessionName); err != nil {
182+ fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to create session: "+err.Error()))
183+ os.Exit(1)
184+ }
185+ sessionInfo = fmt.Sprintf("New session: %s", *sessionName)
186+ log.Info().Str("session_id", sessionID).Str("name", *sessionName).Msg("Created named session")
187+ }
188+ } else {
189+ // Create anonymous session
190+ sessionID = uuid.New().String()
191+ if err := db.CreateSession(sessionID, selectedProvider, providerCfg.Model, nil); err != nil {
192+ fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to create session: "+err.Error()))
193+ os.Exit(1)
194+ }
195+ sessionInfo = fmt.Sprintf("Session: %s", sessionID[:8])
196+ log.Info().Str("session_id", sessionID).Msg("Created anonymous session")
197+ }
198+
199+ // Load message history
200+ history, err := db.LoadMessages(sessionID)
201+ if err != nil {
202+ fmt.Fprintln(os.Stderr, styles.Error.Render("Failed to load history: "+err.Error()))
203+ os.Exit(1)
204+ }
205+ if len(history) > 0 {
206+ log.Info().Int("count", len(history)).Msg("Loaded message history")
207+ }
208+
142209 // Print welcome message
143210 fmt.Println(styles.Brand.Render("╔══════════════════════════════════════╗"))
144- fmt.Println(styles.Brand.Render("║") + " " + styles.BrandBold.Render("Mysis") + " - SpaceMolt Agent CLI " + styles.Brand.Render("║"))
211+ fmt.Println(styles.Brand.Render("║") + " " + styles.BrandBold.Render("Mysis") + " - SpaceMolt Agent CLI " + styles.Brand.Render("║"))
145212 fmt.Println(styles.Brand.Render("╚══════════════════════════════════════╝"))
146213 fmt.Println()
147214 fmt.Println(styles.Muted.Render(fmt.Sprintf("Provider: %s (%s)", selectedProvider, providerCfg.Model)))
148215 fmt.Println(styles.Muted.Render(fmt.Sprintf("Tools: %d available", len(tools))))
216+ fmt.Println(styles.Muted.Render(sessionInfo))
149217 fmt.Println()
150218
151219 // Start conversation loop
152220 app := &App{
153- provider: prov,
154- proxy: proxy,
155- tools: tools,
156- history: []provider.Message{},
221+ provider: prov,
222+ proxy: proxy,
223+ tools: tools,
224+ history: history,
225+ db: db,
226+ sessionID: sessionID,
157227 }
158228
159229 if err := app.Run(ctx); err != nil {
@@ -164,10 +234,12 @@ func main() {
164234
165235 // App holds the application state
166236 type App struct {
167- provider provider.Provider
168- proxy *mcp.Proxy
169- tools []mcp.Tool
170- history []provider.Message
237+ provider provider.Provider
238+ proxy *mcp.Proxy
239+ tools []mcp.Tool
240+ history []provider.Message
241+ db *store.Store
242+ sessionID string
171243 }
172244
173245 // Run starts the conversation loop
@@ -195,10 +267,16 @@ func (app *App) Run(ctx context.Context) error {
195267 }
196268
197269 // Add user message to history
198- app.history = append(app.history, provider.Message{
270+ userMsg := provider.Message{
199271 Role: "user",
200272 Content: input,
201- })
273+ }
274+ app.history = append(app.history, userMsg)
275+
276+ // Save user message
277+ if err := app.db.SaveMessage(app.sessionID, userMsg); err != nil {
278+ log.Warn().Err(err).Msg("Failed to save user message")
279+ }
202280
203281 // Process turn (may involve multiple LLM calls if tools are used)
204282 if err := app.processTurn(ctx); err != nil {
@@ -214,7 +292,7 @@ func (app *App) Run(ctx context.Context) error {
214292
215293 // processTurn handles one conversation turn, which may involve tool calls
216294 func (app *App) processTurn(ctx context.Context) error {
217- maxToolRounds := 10 // Prevent infinite loops
295+ maxToolRounds := 20 // Prevent infinite loops
218296
219297 for round := 0; round < maxToolRounds; round++ {
220298 // Convert MCP tools to provider format
@@ -245,7 +323,7 @@ func (app *App) processTurn(ctx context.Context) error {
245323 }
246324
247325 // Add assistant response to history
248- app.history = append(app.history, provider.Message{
326+ app.addMessage(provider.Message{
249327 Role: "assistant",
250328 Content: resp.Content,
251329 })
@@ -254,7 +332,7 @@ func (app *App) processTurn(ctx context.Context) error {
254332 }
255333
256334 // Tool calls present - add assistant message with tool calls to history
257- app.history = append(app.history, provider.Message{
335+ app.addMessage(provider.Message{
258336 Role: "assistant",
259337 Content: resp.Content,
260338 ToolCalls: resp.ToolCalls,
@@ -283,7 +361,7 @@ func (app *App) processTurn(ctx context.Context) error {
283361 fmt.Println(styles.Error.Render(" Error: " + err.Error()))
284362
285363 // Add error result to history
286- app.history = append(app.history, provider.Message{
364+ app.addMessage(provider.Message{
287365 Role: "tool",
288366 Content: fmt.Sprintf("Error: %v", err),
289367 ToolCallID: toolCall.ID,
@@ -306,7 +384,7 @@ func (app *App) processTurn(ctx context.Context) error {
306384 }
307385
308386 // Add error result to history
309- app.history = append(app.history, provider.Message{
387+ app.addMessage(provider.Message{
310388 Role: "tool",
311389 Content: errText,
312390 ToolCallID: toolCall.ID,
@@ -334,7 +412,7 @@ func (app *App) processTurn(ctx context.Context) error {
334412 }
335413
336414 // Add tool result to history
337- app.history = append(app.history, provider.Message{
415+ app.addMessage(provider.Message{
338416 Role: "tool",
339417 Content: resultText,
340418 ToolCallID: toolCall.ID,
@@ -347,6 +425,74 @@ func (app *App) processTurn(ctx context.Context) error {
347425 return fmt.Errorf("too many tool call rounds (limit: %d)", maxToolRounds)
348426 }
349427
428+// addMessage adds a message to history and saves it to the database.
429+func (app *App) addMessage(msg provider.Message) {
430+ app.history = append(app.history, msg)
431+ if err := app.db.SaveMessage(app.sessionID, msg); err != nil {
432+ log.Warn().Err(err).Msg("Failed to save message to database")
433+ }
434+}
435+
436+// listSessionsCmd lists recent sessions.
437+func listSessionsCmd(db *store.Store) error {
438+ sessions, err := db.ListSessions(20)
439+ if err != nil {
440+ return fmt.Errorf("list sessions: %w", err)
441+ }
442+
443+ if len(sessions) == 0 {
444+ fmt.Println("No sessions found")
445+ return nil
446+ }
447+
448+ fmt.Println(styles.Brand.Render("Recent Sessions:"))
449+ fmt.Println()
450+
451+ for _, sess := range sessions {
452+ fmt.Printf("%s ", styles.Muted.Render(sess.ID[:8]))
453+
454+ if sess.Name != nil {
455+ fmt.Print(styles.BrandBold.Render(*sess.Name))
456+ } else {
457+ fmt.Print(styles.Muted.Render("(anonymous)"))
458+ }
459+
460+ fmt.Printf(" - %s (%s)\n", sess.Provider, sess.Model)
461+
462+ elapsed := time.Since(sess.LastActiveAt)
463+ fmt.Printf(" %s\n", styles.Muted.Render(formatDuration(elapsed)+" ago"))
464+ fmt.Println()
465+ }
466+
467+ return nil
468+}
469+
470+// formatDuration formats a duration in human-readable form.
471+func formatDuration(d time.Duration) string {
472+ if d < time.Minute {
473+ return "just now"
474+ }
475+ if d < time.Hour {
476+ mins := int(d.Minutes())
477+ if mins == 1 {
478+ return "1 minute"
479+ }
480+ return fmt.Sprintf("%d minutes", mins)
481+ }
482+ if d < 24*time.Hour {
483+ hours := int(d.Hours())
484+ if hours == 1 {
485+ return "1 hour"
486+ }
487+ return fmt.Sprintf("%d hours", hours)
488+ }
489+ days := int(d.Hours() / 24)
490+ if days == 1 {
491+ return "1 day"
492+ }
493+ return fmt.Sprintf("%d days", days)
494+}
495+
350496 // initializeProviders creates and registers all configured providers
351497 func initializeProviders(cfg *config.Config, creds *config.Credentials) *provider.Registry {
352498 registry := provider.NewRegistry()