X-Git-Url: https://git.giacomolli.uk/onechat/blobdiff_plain/e737005f89c7c663e1636830001730ad79396bdc..f226928c3a074ac4856ba07e8fd7107aba5444a3:/daemon.go diff --git a/daemon.go b/daemon.go index 2d83017..e534aea 100644 --- a/daemon.go +++ b/daemon.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "io" - "log" "net" "os" "path/filepath" @@ -29,7 +28,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 -// 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 { @@ -64,7 +64,9 @@ func daemon(ctx context.Context, out io.Writer) (err error) { }() whatsappSetDeviceProps() - whatsapp, err := openWhatsApp(ctx, dir, time.Now, log.New(out, "whatsapp: ", log.LstdFlags), whatsappNewClient) + + logger := daemonLogger(out, "onechat: ") + whatsapp, err := openWhatsApp(ctx, dir, time.Now, daemonLogger(out, "whatsapp: "), whatsappNewClient) if err != nil { return err } @@ -84,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")) - 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 } @@ -93,7 +95,7 @@ func daemon(ctx context.Context, out io.Writer) (err error) { err = errors.Join(err, memory.Close()) }() - schedules, err := openSchedules(filepath.Join(agent.dir, scheduleFileName), time.Now) + schedules, err := openSchedules(filepath.Join(agent.dir, scheduleFileName), time.Now, logger) if err != nil { return err } @@ -108,22 +110,23 @@ func daemon(ctx context.Context, out io.Writer) (err error) { 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 := "not linked" + if whatsapp.isLinked() { + linked = "linked" } + logger.Info("ready", "version", version, "socket", listener.Addr(), "model", agent.config.Model, "effort", agent.config.Effort, "workdir", agent.config.Workdir, "whatsapp", linked, "schedules", 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.Info("Telegram bot started") } - return daemonServe(ctx, listener, telegram, whatsapp, func(notify func(Event)) (*TurnLoop, error) { - return newTurnLoop(agent, memory, subagents, whatsapp, schedules, 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) }) } @@ -153,10 +156,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) @@ -193,16 +198,30 @@ 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, h.whatsapp, request, func(text string) { - h.Send(client, Event{ - Kind: "notice", - Text: text, + if request.Type == "backup" { + var size int64 + + size, err = backupData(ctx, filepath.Dir(l.agent.dir), request.Text, h.whatsapp, l.runs.Snapshot) + if err == nil { + h.Send(client, Event{ + Kind: "backup", + Text: fmt.Sprintf("%s (%d bytes)", request.Text, size), + }) + } + } else { + err = daemonRunRequest(l, h.whatsapp, request, func(text string) { + h.Send(client, Event{ + Kind: "notice", + Text: text, + }) }) - }) + } } if err != nil { @@ -250,6 +269,7 @@ func (h *DaemonHub) remove(client *DaemonClient) { delete(h.clients, client) client.once.Do(func() { close(client.events) + _ = client.conn.Close() }) } @@ -267,9 +287,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() @@ -313,9 +335,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 -// 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() @@ -338,7 +361,9 @@ func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, w } var workers sync.WaitGroup + workers.Add(2) + go func() { defer workers.Done() @@ -346,20 +371,37 @@ func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, w }() 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, whatsapp) + cancel() }() } @@ -370,11 +412,13 @@ func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, w } cancel() + err = errors.Join(err, listener.Close()) + 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