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