]> git.giacomolli.uk - onechat/blobdiff - daemon.go
Format short daemon events with slog
[onechat] / daemon.go
index 2a23dc28a4405380137213b21f9c25566c575844..5ec220ed6d3f144db0805b2f3beb8a06da22ac96 100644 (file)
--- a/daemon.go
+++ b/daemon.go
@@ -27,8 +27,10 @@ const (
 
 // daemon runs "onechat daemon": it owns the root agent and its files and serves
 // the clients on the Unix socket in the data directory until ctx ends. When
-// telegram.json exists, it also runs the Telegram bot. It holds the lock of the
-// token file, so it is the only process that refreshes the tokens.
+// 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. 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 {
@@ -62,6 +64,18 @@ func daemon(ctx context.Context, out io.Writer) (err error) {
                err = errors.Join(err, tokens.Close())
        }()
 
+       whatsappSetDeviceProps()
+
+       logger := daemonLogger(out, "onechat: ")
+       whatsapp, err := openWhatsApp(ctx, dir, time.Now, daemonLogger(out, "whatsapp: "), whatsappNewClient)
+       if err != nil {
+               return err
+       }
+
+       defer func() {
+               err = errors.Join(err, whatsapp.Close())
+       }()
+
        address, auth, err := modelEndpoint(config, dir)
        if err != nil {
                return err
@@ -73,7 +87,7 @@ func daemon(ctx context.Context, out io.Writer) (err error) {
        }
 
        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
        }
@@ -82,32 +96,46 @@ func daemon(ctx context.Context, out io.Writer) (err error) {
                err = errors.Join(err, memory.Close())
        }()
 
-       listener, err := daemonListenSocket(socket)
+       schedules, err := openSchedules(filepath.Join(agent.dir, scheduleFileName), time.Now, logger)
        if err != nil {
                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)
+       subagents := newSubagents(filepath.Join(agent.dir, subagentDirName), time.Now, subagentNameRandom)
+       defer func() {
+               err = errors.Join(err, subagents.Close())
+       }()
+
+       listener, err := daemonListenSocket(socket)
        if err != nil {
-               return errors.Join(err, listener.Close())
+               return err
+       }
+
+       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 {
-               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, func(notify func(Event)) (*TurnLoop, error) {
-               return newTurnLoop(agent, memory, 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)
        })
 }
 
-// DaemonHub holds the connected clients and sends each event to all of them.
+// DaemonHub holds the connected clients and sends each event to all of them. It
+// runs the WhatsApp commands of the clients on whatsapp.
 type DaemonHub struct {
+       whatsapp *WhatsApp
+
        mutex   sync.Mutex
        clients map[*DaemonClient]bool
        workers sync.WaitGroup
@@ -129,10 +157,12 @@ func (h *DaemonHub) Accept(ctx context.Context, listener net.Listener, l *TurnLo
                }
 
                h.mutex.Lock()
+
                h.clients[client] = true
                h.mutex.Unlock()
 
                h.workers.Add(2)
+
                go h.write(client)
                go h.read(ctx, client, l)
 
@@ -169,11 +199,18 @@ func (h *DaemonHub) read(ctx context.Context, client *DaemonClient, l *TurnLoop)
 
        scanner := bufio.NewScanner(client.conn)
        scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
+
        for ctx.Err() == nil && scanner.Scan() {
                var request SocketRequest
+
                err := json.Unmarshal(scanner.Bytes(), &request)
                if err == nil {
-                       err = daemonRunRequest(l, request)
+                       err = daemonRunRequest(l, h.whatsapp, request, func(text string) {
+                               h.Send(client, Event{
+                                       Kind: "notice",
+                                       Text: text,
+                               })
+                       })
                }
 
                if err != nil {
@@ -221,6 +258,7 @@ func (h *DaemonHub) remove(client *DaemonClient) {
        delete(h.clients, client)
        client.once.Do(func() {
                close(client.events)
+
                _ = client.conn.Close()
        })
 }
@@ -238,9 +276,11 @@ func (h *DaemonHub) Broadcast(event Event) {
 // CloseAll drops every client and waits for their readers and writers.
 func (h *DaemonHub) CloseAll() {
        h.mutex.Lock()
+
        for client := range h.clients {
                h.remove(client)
        }
+
        h.mutex.Unlock()
 
        h.workers.Wait()
@@ -282,14 +322,18 @@ 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. 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, start func(notify func(Event)) (*TurnLoop, error)) error {
+// 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. 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()
 
        hub := &DaemonHub{
-               clients: make(map[*DaemonClient]bool),
+               whatsapp: whatsapp,
+               clients:  make(map[*DaemonClient]bool),
        }
 
        notify := hub.Broadcast
@@ -306,20 +350,47 @@ func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, s
        }
 
        var workers sync.WaitGroup
-       workers.Add(1)
+
+       workers.Add(2)
+
        go func() {
                defer workers.Done()
 
                hub.Accept(ctx, listener, l)
        }()
 
+       var whatsappErr error
+
+       go func() {
+               defer workers.Done()
+
+               whatsappErr = whatsapp.Run(ctx, l, notify)
+
+               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)
+
                go func() {
                        defer workers.Done()
 
-                       botErr = bot.Run(ctx, l)
+                       botErr = bot.Run(ctx, l, whatsapp)
+
                        cancel()
                }()
        }
@@ -330,15 +401,18 @@ func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, s
        }
 
        cancel()
+
        err = errors.Join(err, listener.Close())
+
        hub.CloseAll()
        workers.Wait()
 
-       return errors.Join(err, botErr)
+       return errors.Join(err, whatsappErr, schedulesErr, botErr)
 }
 
-// daemonRunRequest runs one request of a client.
-func daemonRunRequest(l *TurnLoop, request SocketRequest) error {
+// daemonRunRequest runs one request of a client. The answers of a WhatsApp
+// command go to answer.
+func daemonRunRequest(l *TurnLoop, whatsapp *WhatsApp, request SocketRequest, answer func(text string)) error {
        switch request.Type {
        case "send":
                if request.Text == "" {
@@ -354,7 +428,40 @@ func daemonRunRequest(l *TurnLoop, request SocketRequest) error {
                }
 
                return nil
+       case "whatsapp":
+               whatsapp.Command(request.Text, answer)
+
+               return nil
+       case "stop":
+               found, err := l.StopSubagent(request.Text)
+               if err == nil && !found {
+                       err = fmt.Errorf("no subagent %s runs", request.Text)
+               }
+
+               return err
        default:
                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()
+}