xonecas.io
6119
My

mysis / commit 2c0bac1

feat: add /autoplay command for autonomous gameplay

Implement autonomous turn execution with time-based intervals.

Commands:
- /autoplay <message> - Start autoplay (unlimited)
- /autoplay stop - Stop autoplay
- /autoplay - Show current status

Implementation:
- Sends message immediately, then every 200 seconds
- Interval: 200s = 20 tool rounds × 10s per game tick
- Gives agent time to complete multi-step tool sequences
- Runs in background goroutine (non-blocking)
- Thread-safe with mutex protecting shared state
- Errors don't stop autoplay (logs warning, continues)
- Cancelable via context for clean shutdown

Display:
- Shows autoplay message: "> <message>"
- Turn separator: "─── Autoplay Turn ───"
- Interval info on start
- Continuation on errors (doesn't abort)

Also:
- Truncate reasoning output (trim whitespace, collapse to single line, max 200 chars)
- Echo autoplay messages to stdout so user can see what's being sent

No tick polling needed - simple timer approach prevents rate limit issues.

xonecas2026-02-10 2c0bac1aeaeb9bc575cd3c76ccd3834e50b34992 parent d13964e

1 file changed

cmd/mysis/main.go+205−11
@@ -8,6 +8,7 @@ import (
88 "fmt"
99 "os"
1010 "strings"
11+ "sync"
1112 "time"
1213
1314 "github.com/google/uuid"
@@ -234,12 +235,16 @@ func main() {
234235
235236 // App holds the application state
236237 type App struct {
237- provider provider.Provider
238- proxy *mcp.Proxy
239- tools []mcp.Tool
240- history []provider.Message
241- db *store.Store
242- sessionID string
238+ provider provider.Provider
239+ proxy *mcp.Proxy
240+ tools []mcp.Tool
241+ history []provider.Message
242+ db *store.Store
243+ sessionID string
244+ autoplayEnabled bool
245+ autoplayMessage string
246+ autoplayCancel context.CancelFunc
247+ mu sync.Mutex // Protects autoplay state and history
243248 }
244249
245250 // Run starts the conversation loop
@@ -266,6 +271,14 @@ func (app *App) Run(ctx context.Context) error {
266271 break
267272 }
268273
274+ // Handle /autoplay commands
275+ if strings.HasPrefix(input, "/autoplay") {
276+ if err := app.handleAutoplayCommand(ctx, input); err != nil {
277+ fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error()))
278+ }
279+ continue
280+ }
281+
269282 // Add user message to history
270283 userMsg := provider.Message{
271284 Role: "user",
@@ -295,16 +308,22 @@ func (app *App) processTurn(ctx context.Context) error {
295308 maxToolRounds := 20 // Prevent infinite loops
296309
297310 for round := 0; round < maxToolRounds; round++ {
311+ // Get a snapshot of history for this round
312+ app.mu.Lock()
313+ historyCopy := make([]provider.Message, len(app.history))
314+ copy(historyCopy, app.history)
315+ app.mu.Unlock()
316+
298317 // Compress history before sending to LLM
299318 // Keep last 10 turns full, compress older state queries
300- compressedHistory := store.CompressHistory(app.history, 10)
319+ compressedHistory := store.CompressHistory(historyCopy, 10)
301320
302321 // Log compression stats
303- if len(compressedHistory) < len(app.history) {
304- originalTokens := store.EstimateTokenCount(app.history)
322+ if len(compressedHistory) < len(historyCopy) {
323+ originalTokens := store.EstimateTokenCount(historyCopy)
305324 compressedTokens := store.EstimateTokenCount(compressedHistory)
306325 log.Debug().
307- Int("original_msgs", len(app.history)).
326+ Int("original_msgs", len(historyCopy)).
308327 Int("compressed_msgs", len(compressedHistory)).
309328 Int("original_tokens", originalTokens).
310329 Int("compressed_tokens", compressedTokens).
@@ -330,7 +349,16 @@ func (app *App) processTurn(ctx context.Context) error {
330349
331350 // Display reasoning if present
332351 if resp.Reasoning != "" {
333- fmt.Println(styles.Muted.Render("∴ " + resp.Reasoning))
352+ // Trim excessive whitespace and collapse multiple spaces/newlines
353+ reasoning := strings.TrimSpace(resp.Reasoning)
354+ reasoning = strings.Join(strings.Fields(reasoning), " ")
355+
356+ // Truncate if too long
357+ if len(reasoning) > 200 {
358+ reasoning = reasoning[:197] + "..."
359+ }
360+
361+ fmt.Println(styles.Muted.Render("∴ " + reasoning))
334362 }
335363
336364 // If no tool calls, display text response and we're done
@@ -444,7 +472,10 @@ func (app *App) processTurn(ctx context.Context) error {
444472
445473 // addMessage adds a message to history and saves it to the database.
446474 func (app *App) addMessage(msg provider.Message) {
475+ app.mu.Lock()
447476 app.history = append(app.history, msg)
477+ app.mu.Unlock()
478+
448479 if err := app.db.SaveMessage(app.sessionID, msg); err != nil {
449480 log.Warn().Err(err).Msg("Failed to save message to database")
450481 }
@@ -542,3 +573,166 @@ func initializeProviders(cfg *config.Config, creds *config.Credentials) *provide
542573
543574 return registry
544575 }
576+
577+// handleAutoplayCommand handles /autoplay commands
578+func (app *App) handleAutoplayCommand(ctx context.Context, input string) error {
579+ parts := strings.Fields(input)
580+
581+ if len(parts) == 1 {
582+ // Just "/autoplay" - show status
583+ app.mu.Lock()
584+ enabled := app.autoplayEnabled
585+ message := app.autoplayMessage
586+ app.mu.Unlock()
587+
588+ if enabled {
589+ fmt.Println(styles.Secondary.Render(fmt.Sprintf("Autoplay active: \"%s\"", message)))
590+ } else {
591+ fmt.Println(styles.Muted.Render("Autoplay not active"))
592+ fmt.Println(styles.Muted.Render("Usage: /autoplay <message>"))
593+ }
594+ return nil
595+ }
596+
597+ // Check for "stop" subcommand
598+ if parts[1] == "stop" {
599+ app.mu.Lock()
600+ if app.autoplayEnabled {
601+ app.autoplayEnabled = false
602+ if app.autoplayCancel != nil {
603+ app.autoplayCancel()
604+ app.autoplayCancel = nil
605+ }
606+ app.mu.Unlock()
607+ fmt.Println(styles.Success.Render("Autoplay stopped"))
608+ } else {
609+ app.mu.Unlock()
610+ fmt.Println(styles.Muted.Render("Autoplay not active"))
611+ }
612+ return nil
613+ }
614+
615+ // Join all parts after /autoplay as the message
616+ message := strings.Join(parts[1:], " ")
617+
618+ if message == "" {
619+ return fmt.Errorf("missing message for autoplay")
620+ }
621+
622+ // Start autoplay
623+ app.mu.Lock()
624+ if app.autoplayEnabled {
625+ app.mu.Unlock()
626+ return fmt.Errorf("autoplay already running - use '/autoplay stop' first")
627+ }
628+
629+ app.autoplayEnabled = true
630+ app.autoplayMessage = message
631+
632+ // Create cancelable context for autoplay goroutine
633+ autoplayCtx, cancel := context.WithCancel(ctx)
634+ app.autoplayCancel = cancel
635+ app.mu.Unlock()
636+
637+ fmt.Println(styles.Secondary.Render(fmt.Sprintf("Autoplay started: \"%s\"", message)))
638+ fmt.Println(styles.Muted.Render("Interval: 200s (20 tool rounds × 10s/tick)"))
639+ fmt.Println(styles.Muted.Render("Type '/autoplay stop' to stop"))
640+
641+ // Start autoplay loop in background
642+ go app.runAutoplay(autoplayCtx)
643+
644+ return nil
645+}
646+
647+// runAutoplay sends the autoplay message every 200 seconds (20 tool rounds × 10s/tick)
648+func (app *App) runAutoplay(ctx context.Context) {
649+ log.Debug().Msg("Autoplay goroutine started")
650+
651+ // maxToolRounds (20) × game tick time (10s) = 200 seconds
652+ const autoplayInterval = 200 * time.Second
653+
654+ defer func() {
655+ app.mu.Lock()
656+ app.autoplayEnabled = false
657+ app.autoplayCancel = nil
658+ app.mu.Unlock()
659+ fmt.Println(styles.Muted.Render("Autoplay stopped"))
660+ log.Debug().Msg("Autoplay goroutine exiting")
661+ }()
662+
663+ // Send first message immediately
664+ log.Debug().Msg("Sending first autoplay message")
665+ if err := app.sendAutoplayMessage(ctx); err != nil {
666+ log.Error().Err(err).Msg("Autoplay failed to send first message")
667+ return
668+ }
669+ log.Debug().Msg("First autoplay message sent successfully")
670+
671+ // Then wait and send subsequent messages
672+ ticker := time.NewTicker(autoplayInterval)
673+ defer ticker.Stop()
674+
675+ for {
676+ select {
677+ case <-ctx.Done():
678+ return
679+ case <-ticker.C:
680+ app.mu.Lock()
681+ enabled := app.autoplayEnabled
682+ app.mu.Unlock()
683+
684+ if !enabled {
685+ return
686+ }
687+
688+ if err := app.sendAutoplayMessage(ctx); err != nil {
689+ return
690+ }
691+ }
692+ }
693+}
694+
695+// sendAutoplayMessage sends the autoplay message and processes the turn
696+func (app *App) sendAutoplayMessage(ctx context.Context) error {
697+ log.Debug().Msg("sendAutoplayMessage called")
698+
699+ app.mu.Lock()
700+ enabled := app.autoplayEnabled
701+ message := app.autoplayMessage
702+ app.mu.Unlock()
703+
704+ log.Debug().Bool("enabled", enabled).Str("message", message).Msg("Autoplay state")
705+
706+ if !enabled {
707+ return fmt.Errorf("autoplay disabled")
708+ }
709+
710+ fmt.Println(styles.Muted.Render("─── Autoplay Turn ───"))
711+ fmt.Println(styles.Brand.Render("> ") + message)
712+ log.Debug().Msg("About to process turn")
713+
714+ // Send autoplay message
715+ userMsg := provider.Message{
716+ Role: "user",
717+ Content: message,
718+ }
719+
720+ app.mu.Lock()
721+ app.history = append(app.history, userMsg)
722+ app.mu.Unlock()
723+
724+ if err := app.db.SaveMessage(app.sessionID, userMsg); err != nil {
725+ log.Warn().Err(err).Msg("Failed to save autoplay message")
726+ }
727+
728+ // Process turn
729+ if err := app.processTurn(ctx); err != nil {
730+ fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error()))
731+ // Don't stop autoplay on errors - just log and continue
732+ log.Warn().Err(err).Msg("Autoplay turn failed, continuing...")
733+ }
734+
735+ fmt.Println() // Blank line after response
736+ log.Debug().Msg("Autoplay message sent successfully")
737+ return nil
738+}