]> git.giacomolli.uk - onechat/blob - daemon.go
Check operation context on returned errors
[onechat] / daemon.go
1 package main
2
3 import (
4         "bufio"
5         "context"
6         "encoding/json"
7         "errors"
8         "fmt"
9         "io"
10         "log"
11         "net"
12         "os"
13         "path/filepath"
14         "sync"
15         "time"
16 )
17
18 const (
19         // daemonAgentDirName is the directory of the root agent in the data
20         // directory.
21         daemonAgentDirName = "agent"
22
23         // daemonClientEvents is the number of events that can wait for a slow
24         // client before the daemon drops it.
25         daemonClientEvents = 1024
26 )
27
28 // daemon runs "onechat daemon": it owns the root agent and its files and serves
29 // the clients on the Unix socket in the data directory until ctx ends. When
30 // telegram.json exists, it also runs the Telegram bot. It also keeps a linked
31 // WhatsApp device connected. It holds the lock of the token file, so it is the
32 // only process that refreshes the tokens and opens the WhatsApp session. Its
33 // log lines go to out, through the loggers of daemonLogger.
34 func daemon(ctx context.Context, out io.Writer) (err error) {
35         dir, err := dataDir()
36         if err != nil {
37                 return err
38         }
39
40         // Check the socket path before the daemon writes a file, so that a data
41         // directory with a long path stays empty.
42         socket := filepath.Join(dir, socketFileName)
43         err = checkSocketPath(socket)
44         if err != nil {
45                 return err
46         }
47
48         config, err := loadConfig(dir)
49         if err != nil {
50                 return err
51         }
52
53         botSettings, hasBot, err := loadTelegramConfig(dir)
54         if err != nil {
55                 return err
56         }
57
58         tokens, err := lockTokens(dir)
59         if err != nil {
60                 return err
61         }
62
63         defer func() {
64                 err = errors.Join(err, tokens.Close())
65         }()
66
67         whatsappSetDeviceProps()
68         logger := daemonLogger(out, "onechat: ")
69         whatsapp, err := openWhatsApp(ctx, dir, time.Now, daemonLogger(out, "whatsapp: "), whatsappNewClient)
70         if err != nil {
71                 return err
72         }
73
74         defer func() {
75                 err = errors.Join(err, whatsapp.Close())
76         }()
77
78         address, auth, err := modelEndpoint(config, dir)
79         if err != nil {
80                 return err
81         }
82
83         agent, err := openAgent(filepath.Join(dir, daemonAgentDirName))
84         if err != nil {
85                 return err
86         }
87
88         client := newModelClient(address, auth, agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl"))
89         memory, err := openMemory(ctx, agent.dir, time.Now, newCompactor(client, agent.Prompt, config.Compactor), logger)
90         if err != nil {
91                 return err
92         }
93
94         defer func() {
95                 err = errors.Join(err, memory.Close())
96         }()
97
98         schedules, err := openSchedules(filepath.Join(agent.dir, scheduleFileName), time.Now, logger)
99         if err != nil {
100                 return err
101         }
102
103         subagents := newSubagents(filepath.Join(agent.dir, subagentDirName), time.Now, subagentNameRandom)
104         defer func() {
105                 err = errors.Join(err, subagents.Close())
106         }()
107
108         listener, err := daemonListenSocket(socket)
109         if err != nil {
110                 return err
111         }
112
113         linked := "WhatsApp not linked"
114         if whatsapp.isLinked() {
115                 linked = "WhatsApp linked"
116         }
117
118         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())
119
120         var telegram *TelegramBot
121         if hasBot {
122                 telegram = newTelegramBot(newTelegramAPI(telegramAPIURL, botSettings.Token), botSettings.Owner, filepath.Join(agent.dir, telegramOffsetFileName), daemonLogger(out, "telegram: "))
123                 logger.Print("Telegram bot started")
124         }
125
126         return daemonServe(ctx, listener, telegram, whatsapp, schedules, func(notify func(Event)) (*TurnLoop, error) {
127                 return newTurnLoop(agent, memory, subagents, whatsapp, schedules, client, time.Now, logger, notify)
128         })
129 }
130
131 // DaemonHub holds the connected clients and sends each event to all of them. It
132 // runs the WhatsApp commands of the clients on whatsapp.
133 type DaemonHub struct {
134         whatsapp *WhatsApp
135
136         mutex   sync.Mutex
137         clients map[*DaemonClient]bool
138         workers sync.WaitGroup
139 }
140
141 // Accept serves each client of listener until the listener closes. A new
142 // client gets a ready event with the name of the agent, and a busy event when a
143 // turn runs.
144 func (h *DaemonHub) Accept(ctx context.Context, listener net.Listener, l *TurnLoop) {
145         for {
146                 conn, err := listener.Accept()
147                 if err != nil {
148                         return
149                 }
150
151                 client := &DaemonClient{
152                         conn:   conn,
153                         events: make(chan Event, daemonClientEvents),
154                 }
155
156                 h.mutex.Lock()
157                 h.clients[client] = true
158                 h.mutex.Unlock()
159
160                 h.workers.Add(2)
161                 go h.write(client)
162                 go h.read(ctx, client, l)
163
164                 h.Send(client, Event{
165                         Kind: "ready",
166                         Text: l.agent.config.Name,
167                 })
168
169                 if l.Busy() {
170                         h.Send(client, Event{
171                                 Kind: "busy",
172                         })
173                 }
174         }
175 }
176
177 // write sends the events of client as JSON lines until its channel closes.
178 func (h *DaemonHub) write(client *DaemonClient) {
179         defer h.workers.Done()
180
181         encoder := json.NewEncoder(client.conn)
182         for event := range client.events {
183                 err := encoder.Encode(event)
184                 if err != nil {
185                         h.drop(client)
186                 }
187         }
188 }
189
190 // read runs the requests of client until it closes its connection.
191 func (h *DaemonHub) read(ctx context.Context, client *DaemonClient, l *TurnLoop) {
192         defer h.workers.Done()
193         defer h.drop(client)
194
195         scanner := bufio.NewScanner(client.conn)
196         scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
197         for ctx.Err() == nil && scanner.Scan() {
198                 var request SocketRequest
199                 err := json.Unmarshal(scanner.Bytes(), &request)
200                 if err == nil {
201                         err = daemonRunRequest(l, h.whatsapp, request, func(text string) {
202                                 h.Send(client, Event{
203                                         Kind: "notice",
204                                         Text: text,
205                                 })
206                         })
207                 }
208
209                 if err != nil {
210                         h.Send(client, Event{
211                                 Kind: "error",
212                                 Text: err.Error(),
213                         })
214                 }
215         }
216 }
217
218 // Send gives event to one client, or drops the client when its events do not
219 // fit.
220 func (h *DaemonHub) Send(client *DaemonClient, event Event) {
221         h.mutex.Lock()
222         defer h.mutex.Unlock()
223
224         h.send(client, event)
225 }
226
227 // drop removes client and closes its connection.
228 func (h *DaemonHub) drop(client *DaemonClient) {
229         h.mutex.Lock()
230         defer h.mutex.Unlock()
231
232         h.remove(client)
233 }
234
235 // send gives event to client. The caller holds the mutex.
236 func (h *DaemonHub) send(client *DaemonClient, event Event) {
237         if !h.clients[client] {
238                 return
239         }
240
241         select {
242         case client.events <- event:
243         default:
244                 h.remove(client)
245         }
246 }
247
248 // remove removes client, closes its connection, and ends its writer. The
249 // caller holds the mutex.
250 func (h *DaemonHub) remove(client *DaemonClient) {
251         delete(h.clients, client)
252         client.once.Do(func() {
253                 close(client.events)
254                 _ = client.conn.Close()
255         })
256 }
257
258 // Broadcast gives event to every client.
259 func (h *DaemonHub) Broadcast(event Event) {
260         h.mutex.Lock()
261         defer h.mutex.Unlock()
262
263         for client := range h.clients {
264                 h.send(client, event)
265         }
266 }
267
268 // CloseAll drops every client and waits for their readers and writers.
269 func (h *DaemonHub) CloseAll() {
270         h.mutex.Lock()
271         for client := range h.clients {
272                 h.remove(client)
273         }
274         h.mutex.Unlock()
275
276         h.workers.Wait()
277 }
278
279 // DaemonClient is one connected client. Its events wait in a channel for the
280 // writer, so a slow client does not stop the agent.
281 type DaemonClient struct {
282         conn   net.Conn
283         events chan Event
284         once   sync.Once
285 }
286
287 // daemonListenSocket listens on the Unix socket at path, with mode 0600. The
288 // caller owns the chat, so a socket file at path is left from a daemon that
289 // ended, and daemonListenSocket removes it.
290 func daemonListenSocket(path string) (net.Listener, error) {
291         err := checkSocketPath(path)
292         if err != nil {
293                 return nil, err
294         }
295
296         err = os.Remove(path)
297         if err != nil && !errors.Is(err, os.ErrNotExist) {
298                 return nil, fmt.Errorf("remove old socket: %w", err)
299         }
300
301         listener, err := net.Listen("unix", path)
302         if err != nil {
303                 return nil, fmt.Errorf("listen on socket: %w", err)
304         }
305
306         err = os.Chmod(path, 0o600)
307         if err != nil {
308                 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
309         }
310
311         return listener, nil
312 }
313
314 // daemonServe runs the loop that start makes and serves the clients of listener
315 // until ctx ends or the loop fails. It closes listener. It runs whatsapp, which
316 // logs its batches and notes in the loop and tells all clients its notices, and
317 // a failure of whatsapp stops the agent. It runs schedules, which log their
318 // runs in the loop, and a failure of schedules stops the agent too. When bot is
319 // not nil, it runs the bot too, and a failure of the bot stops the agent.
320 func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, whatsapp *WhatsApp, schedules *Schedules, start func(notify func(Event)) (*TurnLoop, error)) error {
321         ctx, cancel := context.WithCancel(ctx)
322         defer cancel()
323
324         hub := &DaemonHub{
325                 whatsapp: whatsapp,
326                 clients:  make(map[*DaemonClient]bool),
327         }
328
329         notify := hub.Broadcast
330         if bot != nil {
331                 notify = func(event Event) {
332                         hub.Broadcast(event)
333                         bot.Notify(event)
334                 }
335         }
336
337         l, err := start(notify)
338         if err != nil {
339                 return errors.Join(err, listener.Close())
340         }
341
342         var workers sync.WaitGroup
343         workers.Add(2)
344         go func() {
345                 defer workers.Done()
346
347                 hub.Accept(ctx, listener, l)
348         }()
349
350         var whatsappErr error
351         go func() {
352                 defer workers.Done()
353
354                 whatsappErr = whatsapp.Run(ctx, l, notify)
355                 cancel()
356         }()
357
358         var schedulesErr error
359         workers.Add(1)
360         go func() {
361                 defer workers.Done()
362
363                 schedulesErr = schedules.Run(ctx, l)
364                 cancel()
365         }()
366
367         var botErr error
368         if bot != nil {
369                 workers.Add(1)
370                 go func() {
371                         defer workers.Done()
372
373                         botErr = bot.Run(ctx, l, whatsapp)
374                         cancel()
375                 }()
376         }
377
378         err = l.Run(ctx)
379         if errors.Is(err, context.Canceled) {
380                 err = nil
381         }
382
383         cancel()
384         err = errors.Join(err, listener.Close())
385         hub.CloseAll()
386         workers.Wait()
387
388         return errors.Join(err, whatsappErr, schedulesErr, botErr)
389 }
390
391 // daemonRunRequest runs one request of a client. The answers of a WhatsApp
392 // command go to answer.
393 func daemonRunRequest(l *TurnLoop, whatsapp *WhatsApp, request SocketRequest, answer func(text string)) error {
394         switch request.Type {
395         case "send":
396                 if request.Text == "" {
397                         return errors.New("empty message")
398                 }
399
400                 _, err := l.Submit(terminalSource, request.Text)
401
402                 return err
403         case "interrupt":
404                 if !l.Interrupt() {
405                         return errors.New("no turn runs")
406                 }
407
408                 return nil
409         case "whatsapp":
410                 whatsapp.Command(request.Text, answer)
411
412                 return nil
413         case "stop":
414                 found, err := l.StopSubagent(request.Text)
415                 if err == nil && !found {
416                         err = fmt.Errorf("no subagent %s runs", request.Text)
417                 }
418
419                 return err
420         default:
421                 return fmt.Errorf("unknown request %q", request.Type)
422         }
423 }
424
425 // daemonLogger returns the logger of the part of the daemon with prefix, such
426 // as "telegram: ", on out. The journal adds the time to each line and sets
427 // JOURNAL_STREAM for a service, so then the lines have no time stamp. Otherwise
428 // each line has the standard time stamp.
429 func daemonLogger(out io.Writer, prefix string) *log.Logger {
430         if os.Getenv("JOURNAL_STREAM") != "" {
431                 return log.New(out, prefix, 0)
432         }
433
434         return log.New(out, prefix, log.LstdFlags)
435 }
436
437 // durationText returns d for a log line: rounded to the second, or to the
438 // millisecond when it is shorter than a second.
439 func durationText(d time.Duration) string {
440         if d < time.Second {
441                 return d.Round(time.Millisecond).String()
442         }
443
444         return d.Round(time.Second).String()
445 }