]> git.giacomolli.uk - onechat/blobdiff - daemon.go
Log the start and the length of each subagent run
[onechat] / daemon.go
index 991edfaa2a444fd6802f90d4ae859bd75f611f20..a2893387ec3240423d6497b22bfcc4c8830e73f3 100644 (file)
--- a/daemon.go
+++ b/daemon.go
@@ -29,7 +29,8 @@ const (
 // the clients on the Unix socket in the data directory until ctx ends. When
 // telegram.json exists, it also runs the Telegram bot. It also keeps a linked
 // WhatsApp device connected. It holds the lock of the token file, so it is the
 // the clients on the Unix socket in the data directory until ctx ends. When
 // telegram.json exists, it also runs the Telegram bot. It also keeps a linked
 // WhatsApp device connected. It holds the lock of the token file, so it is the
-// only process that refreshes the tokens and opens the WhatsApp session.
+// only process that refreshes the tokens and opens the WhatsApp session. Its
+// log lines go to out, through the loggers of daemonLogger.
 func daemon(ctx context.Context, out io.Writer) (err error) {
        dir, err := dataDir()
        if err != nil {
 func daemon(ctx context.Context, out io.Writer) (err error) {
        dir, err := dataDir()
        if err != nil {
@@ -63,7 +64,9 @@ func daemon(ctx context.Context, out io.Writer) (err error) {
                err = errors.Join(err, tokens.Close())
        }()
 
                err = errors.Join(err, tokens.Close())
        }()
 
-       whatsapp, err := openWhatsApp(ctx, dir, time.Now, log.New(out, "whatsapp: ", log.LstdFlags), whatsappNewClient)
+       whatsappSetDeviceProps()
+       logger := daemonLogger(out, "onechat: ")
+       whatsapp, err := openWhatsApp(ctx, dir, time.Now, daemonLogger(out, "whatsapp: "), whatsappNewClient)
        if err != nil {
                return err
        }
        if err != nil {
                return err
        }
@@ -83,7 +86,7 @@ func daemon(ctx context.Context, out io.Writer) (err error) {
        }
 
        client := newModelClient(address, auth, agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl"))
        }
 
        client := newModelClient(address, auth, agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl"))
-       memory, err := openMemory(ctx, agent.dir, time.Now, newCompactor(client, agent.Prompt, config.Compactor))
+       memory, err := openMemory(ctx, agent.dir, time.Now, newCompactor(client, agent.Prompt, config.Compactor), logger)
        if err != nil {
                return err
        }
        if err != nil {
                return err
        }
@@ -92,6 +95,11 @@ func daemon(ctx context.Context, out io.Writer) (err error) {
                err = errors.Join(err, memory.Close())
        }()
 
                err = errors.Join(err, memory.Close())
        }()
 
+       schedules, err := openSchedules(filepath.Join(agent.dir, scheduleFileName), time.Now, logger)
+       if err != nil {
+               return err
+       }
+
        subagents := newSubagents(filepath.Join(agent.dir, subagentDirName), time.Now, subagentNameRandom)
        defer func() {
                err = errors.Join(err, subagents.Close())
        subagents := newSubagents(filepath.Join(agent.dir, subagentDirName), time.Now, subagentNameRandom)
        defer func() {
                err = errors.Join(err, subagents.Close())
@@ -102,22 +110,21 @@ func daemon(ctx context.Context, out io.Writer) (err error) {
                return err
        }
 
                return err
        }
 
-       _, err = fmt.Fprintf(out, "onechat: %s on %s, %s at %s effort, in %s\n", agent.config.Name, listener.Addr(), agent.config.Model, agent.config.Effort, agent.config.Workdir)
-       if err != nil {
-               return errors.Join(err, listener.Close())
+       linked := "WhatsApp not linked"
+       if whatsapp.isLinked() {
+               linked = "WhatsApp linked"
        }
 
        }
 
+       logger.Printf("ready: socket %s, model %s (%s), workdir %s, %s, %d schedules", listener.Addr(), agent.config.Model, agent.config.Effort, agent.config.Workdir, linked, schedules.Len())
+
        var telegram *TelegramBot
        if hasBot {
        var telegram *TelegramBot
        if hasBot {
-               telegram = newTelegramBot(newTelegramAPI(telegramAPIURL, botSettings.Token), botSettings.Owner, filepath.Join(agent.dir, telegramOffsetFileName), log.New(out, "telegram: ", log.LstdFlags))
-               _, err = fmt.Fprintln(out, "onechat: the Telegram bot waits for messages of its owner")
-               if err != nil {
-                       return errors.Join(err, listener.Close())
-               }
+               telegram = newTelegramBot(newTelegramAPI(telegramAPIURL, botSettings.Token), botSettings.Owner, filepath.Join(agent.dir, telegramOffsetFileName), daemonLogger(out, "telegram: "))
+               logger.Print("Telegram bot started")
        }
 
        }
 
-       return daemonServe(ctx, listener, telegram, whatsapp, func(notify func(Event)) (*TurnLoop, error) {
-               return newTurnLoop(agent, memory, subagents, client, time.Now, notify)
+       return daemonServe(ctx, listener, telegram, whatsapp, schedules, func(notify func(Event)) (*TurnLoop, error) {
+               return newTurnLoop(agent, memory, subagents, whatsapp, schedules, client, time.Now, logger, notify)
        })
 }
 
        })
 }
 
@@ -307,9 +314,10 @@ func daemonListenSocket(path string) (net.Listener, error) {
 // daemonServe runs the loop that start makes and serves the clients of listener
 // until ctx ends or the loop fails. It closes listener. It runs whatsapp, which
 // logs its batches and notes in the loop and tells all clients its notices, and
 // daemonServe runs the loop that start makes and serves the clients of listener
 // until ctx ends or the loop fails. It closes listener. It runs whatsapp, which
 // logs its batches and notes in the loop and tells all clients its notices, and
-// a failure of whatsapp stops the agent. When bot is not nil, it runs the bot
-// too, and a failure of the bot stops the agent.
-func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, whatsapp *WhatsApp, start func(notify func(Event)) (*TurnLoop, error)) error {
+// a failure of whatsapp stops the agent. It runs schedules, which log their
+// runs in the loop, and a failure of schedules stops the agent too. When bot is
+// not nil, it runs the bot too, and a failure of the bot stops the agent.
+func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, whatsapp *WhatsApp, schedules *Schedules, start func(notify func(Event)) (*TurnLoop, error)) error {
        ctx, cancel := context.WithCancel(ctx)
        defer cancel()
 
        ctx, cancel := context.WithCancel(ctx)
        defer cancel()
 
@@ -347,6 +355,15 @@ func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, w
                cancel()
        }()
 
                cancel()
        }()
 
+       var schedulesErr error
+       workers.Add(1)
+       go func() {
+               defer workers.Done()
+
+               schedulesErr = schedules.Run(ctx, l)
+               cancel()
+       }()
+
        var botErr error
        if bot != nil {
                workers.Add(1)
        var botErr error
        if bot != nil {
                workers.Add(1)
@@ -368,7 +385,7 @@ func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, w
        hub.CloseAll()
        workers.Wait()
 
        hub.CloseAll()
        workers.Wait()
 
-       return errors.Join(err, whatsappErr, botErr)
+       return errors.Join(err, whatsappErr, schedulesErr, botErr)
 }
 
 // daemonRunRequest runs one request of a client. The answers of a WhatsApp
 }
 
 // daemonRunRequest runs one request of a client. The answers of a WhatsApp
@@ -404,3 +421,25 @@ func daemonRunRequest(l *TurnLoop, whatsapp *WhatsApp, request SocketRequest, an
                return fmt.Errorf("unknown request %q", request.Type)
        }
 }
                return fmt.Errorf("unknown request %q", request.Type)
        }
 }
+
+// daemonLogger returns the logger of the part of the daemon with prefix, such
+// as "telegram: ", on out. The journal adds the time to each line and sets
+// JOURNAL_STREAM for a service, so then the lines have no time stamp. Otherwise
+// each line has the standard time stamp.
+func daemonLogger(out io.Writer, prefix string) *log.Logger {
+       if os.Getenv("JOURNAL_STREAM") != "" {
+               return log.New(out, prefix, 0)
+       }
+
+       return log.New(out, prefix, log.LstdFlags)
+}
+
+// durationText returns d for a log line: rounded to the second, or to the
+// millisecond when it is shorter than a second.
+func durationText(d time.Duration) string {
+       if d < time.Second {
+               return d.Round(time.Millisecond).String()
+       }
+
+       return d.Round(time.Second).String()
+}