]> git.giacomolli.uk - onechat/blob - daemon.go
b6595c7624a12ef316f0c01a892584791a5b4637
[onechat] / daemon.go
1 package main
2
3 import (
4 "bufio"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "net"
11 "os"
12 "path/filepath"
13 "sync"
14 "time"
15 )
16
17 const (
18 // daemonAgentDirName is the directory of the root agent in the data
19 // directory.
20 daemonAgentDirName = "agent"
21
22 // daemonClientEvents is the number of events that can wait for a slow
23 // client before the daemon drops it.
24 daemonClientEvents = 1024
25 )
26
27 // DaemonHub holds the connected clients and sends each event to all of them. It
28 // runs the WhatsApp commands of the clients on whatsapp. snapshot locks all
29 // agents and subagents during a backup copy.
30 type DaemonHub struct {
31 whatsapp *WhatsApp
32 snapshot func(context.Context, func() error) error
33
34 mutex sync.Mutex
35 clients map[*DaemonClient]bool
36 workers sync.WaitGroup
37 }
38
39 // DaemonClient is one connected client. Its events wait in a channel for the
40 // writer, so a slow client does not stop the agent.
41 type DaemonClient struct {
42 conn net.Conn
43 events chan Event
44 once sync.Once
45 }
46
47 // Accept serves each client of listener until the listener closes. A new client
48 // gets a ready event with the name of the agent, and a busy event when a turn
49 // runs.
50 func (h *DaemonHub) Accept(ctx context.Context, listener net.Listener, l *TurnLoop) {
51 for {
52 conn, err := listener.Accept()
53 if err != nil {
54 return
55 }
56
57 client := &DaemonClient{
58 conn: conn,
59 events: make(chan Event, daemonClientEvents),
60 }
61
62 h.mutex.Lock()
63
64 h.clients[client] = true
65 h.mutex.Unlock()
66
67 h.workers.Add(2)
68
69 go h.write(client)
70 go h.read(ctx, client, l)
71
72 h.Send(client, Event{
73 Kind: "ready",
74 Text: l.agent.config.Name,
75 })
76
77 if l.Busy() {
78 h.Send(client, Event{
79 Kind: "busy",
80 })
81 }
82 }
83 }
84
85 // write sends the events of client as JSON lines until its channel closes.
86 func (h *DaemonHub) write(client *DaemonClient) {
87 defer h.workers.Done()
88
89 encoder := json.NewEncoder(client.conn)
90 for event := range client.events {
91 err := encoder.Encode(event)
92 if err != nil {
93 h.drop(client)
94 }
95 }
96 }
97
98 // read runs the requests of client until it closes its connection.
99 func (h *DaemonHub) read(ctx context.Context, client *DaemonClient, l *TurnLoop) {
100 defer h.workers.Done()
101 defer h.drop(client)
102
103 scanner := bufio.NewScanner(client.conn)
104 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
105
106 for ctx.Err() == nil && scanner.Scan() {
107 var request SocketRequest
108
109 err := json.Unmarshal(scanner.Bytes(), &request)
110 if err == nil {
111 if request.Type == "backup" {
112 var size int64
113
114 size, err = backupData(ctx, filepath.Dir(l.agent.dir), request.Text, h.whatsapp, h.snapshot)
115 if err == nil {
116 h.Send(client, Event{
117 Kind: "backup",
118 Text: fmt.Sprintf("%s (%d bytes)", request.Text, size),
119 })
120 }
121 } else {
122 err = daemonRunRequest(l, h.whatsapp, request, func(text string) {
123 h.Send(client, Event{
124 Kind: "notice",
125 Text: text,
126 })
127 })
128 }
129 }
130
131 if err != nil {
132 h.Send(client, Event{
133 Kind: "error",
134 Text: err.Error(),
135 })
136 }
137 }
138 }
139
140 // Send gives event to one client, or drops the client when its events do not
141 // fit.
142 func (h *DaemonHub) Send(client *DaemonClient, event Event) {
143 h.mutex.Lock()
144 defer h.mutex.Unlock()
145
146 h.send(client, event)
147 }
148
149 // drop removes client and closes its connection.
150 func (h *DaemonHub) drop(client *DaemonClient) {
151 h.mutex.Lock()
152 defer h.mutex.Unlock()
153
154 h.remove(client)
155 }
156
157 // send gives event to client. The caller holds the mutex.
158 func (h *DaemonHub) send(client *DaemonClient, event Event) {
159 if !h.clients[client] {
160 return
161 }
162
163 select {
164 case client.events <- event:
165 default:
166 h.remove(client)
167 }
168 }
169
170 // remove removes client, closes its connection, and ends its writer. The caller
171 // holds the mutex.
172 func (h *DaemonHub) remove(client *DaemonClient) {
173 delete(h.clients, client)
174 client.once.Do(func() {
175 close(client.events)
176
177 _ = client.conn.Close()
178 })
179 }
180
181 // Broadcast gives event to every client.
182 func (h *DaemonHub) Broadcast(event Event) {
183 h.mutex.Lock()
184 defer h.mutex.Unlock()
185
186 for client := range h.clients {
187 h.send(client, event)
188 }
189 }
190
191 // CloseAll drops every client and waits for their readers and writers.
192 func (h *DaemonHub) CloseAll() {
193 h.mutex.Lock()
194
195 for client := range h.clients {
196 h.remove(client)
197 }
198
199 h.mutex.Unlock()
200
201 h.workers.Wait()
202 }
203
204 // daemonRunRequest runs one request of a client. The answers of a WhatsApp
205 // command go to answer.
206 func daemonRunRequest(l *TurnLoop, whatsapp *WhatsApp, request SocketRequest, answer func(text string)) error {
207 switch request.Type {
208 case "send":
209 if request.Text == "" {
210 return errors.New("empty message")
211 }
212
213 _, err := l.Submit(terminalSource, request.Text)
214
215 return err
216 case "image":
217 if !filepath.IsAbs(request.Path) {
218 return errors.New("use /image PATH [caption]")
219 }
220
221 data, err := imageReadFile(request.Path)
222 if err != nil {
223 return fmt.Errorf("read terminal image: %w", err)
224 }
225
226 name, err := l.agent.Images().Save(data)
227 if err != nil {
228 return fmt.Errorf("store terminal image: %w", err)
229 }
230
231 _, err = l.Submit(terminalSource, imageText([]string{name}, request.Text))
232 if err != nil {
233 return fmt.Errorf("submit terminal image: %w", err)
234 }
235
236 return nil
237 case "interrupt":
238 if !l.Interrupt() {
239 return errors.New("no turn runs")
240 }
241
242 return nil
243 case "whatsapp":
244 whatsapp.Command(request.Text, answer)
245
246 return nil
247 case "stop":
248 found, err := l.StopSubagent(request.Text)
249 if err == nil && !found {
250 err = fmt.Errorf("no subagent %s runs", request.Text)
251 }
252
253 return err
254 default:
255 return fmt.Errorf("unknown request %q", request.Type)
256 }
257 }
258
259 // daemon runs "onechat daemon": it owns the root, its children, and their
260 // files, and serves the clients on the Unix socket in the data directory until
261 // ctx ends. When telegram.json exists, it also runs the Telegram bot. It also
262 // keeps a linked WhatsApp device connected. It holds the lock of the token
263 // file, so it is the only process that refreshes the tokens and opens the
264 // WhatsApp session. Its log lines go to out, through the loggers of
265 // daemonLogger.
266 func daemon(ctx context.Context, out io.Writer) (err error) {
267 dir, err := dataDir()
268 if err != nil {
269 return err
270 }
271
272 // Check the socket path before the daemon writes a file, so that a data
273 // directory with a long path stays empty.
274 socket := filepath.Join(dir, socketFileName)
275 err = checkSocketPath(socket)
276 if err != nil {
277 return err
278 }
279
280 config, err := loadConfig(dir)
281 if err != nil {
282 return err
283 }
284
285 botSettings, hasBot, err := loadTelegramConfig(dir)
286 if err != nil {
287 return err
288 }
289
290 tokens, err := lockTokens(dir)
291 if err != nil {
292 return err
293 }
294
295 defer func() {
296 err = errors.Join(err, tokens.Close())
297 }()
298
299 whatsappSetDeviceProps()
300
301 logger := daemonLogger(out, "onechat: ")
302 whatsapp, err := openWhatsApp(ctx, dir, time.Now, daemonLogger(out, "whatsapp: "), whatsappNewClient)
303 if err != nil {
304 return err
305 }
306
307 defer func() {
308 err = errors.Join(err, whatsapp.Close())
309 }()
310
311 address, auth, err := modelEndpoint(config, dir)
312 if err != nil {
313 return err
314 }
315
316 agents, err := openDaemonAgents(ctx, dir, address, auth, config.Compactor, time.Now, logger)
317 if err != nil {
318 return err
319 }
320
321 defer func() {
322 err = errors.Join(err, agents.Close())
323 }()
324
325 whatsapp.inbox.voice = &VoiceTranscriber{config: config.Voice}
326
327 root := agents[0]
328 agent := root.agent
329 schedules := root.schedules
330
331 listener, err := daemonListenSocket(socket)
332 if err != nil {
333 return err
334 }
335
336 linked := "not linked"
337 if whatsapp.isLinked() {
338 linked = "linked"
339 }
340
341 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(), "children", agents.ChildNames())
342
343 var telegram *TelegramBot
344
345 if hasBot {
346 telegram = newTelegramBot(newTelegramAPI(telegramAPIURL, botSettings.Token), botSettings.Owner, filepath.Join(agent.dir, telegramOffsetFileName), daemonLogger(out, "telegram: "))
347
348 telegram.voice = &VoiceTranscriber{config: config.Voice}
349
350 logger.Info("Telegram bot started")
351 }
352
353 return daemonServe(ctx, listener, telegram, whatsapp, schedules, func(notify func(Event)) (*TurnLoop, error) {
354 return root.Loop(whatsapp, notify)
355 }, agents[1:]...)
356 }
357
358 // daemonListenSocket listens on the Unix socket at path, with mode 0600. The
359 // caller owns the chat, so a socket file at path is left from a daemon that
360 // ended, and daemonListenSocket removes it.
361 func daemonListenSocket(path string) (net.Listener, error) {
362 err := checkSocketPath(path)
363 if err != nil {
364 return nil, err
365 }
366
367 err = os.Remove(path)
368 if err != nil && !errors.Is(err, os.ErrNotExist) {
369 return nil, fmt.Errorf("remove old socket: %w", err)
370 }
371
372 listener, err := net.Listen("unix", path)
373 if err != nil {
374 return nil, fmt.Errorf("listen on socket: %w", err)
375 }
376
377 err = os.Chmod(path, 0o600)
378 if err != nil {
379 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
380 }
381
382 return listener, nil
383 }
384
385 // daemonServe runs the loop that start makes and serves the clients of listener
386 // until ctx ends or the loop fails. It closes listener. It runs whatsapp, which
387 // logs its batches and notes in the loop and tells all clients its notices, and
388 // a failure of whatsapp stops the agent. It runs schedules, which log their
389 // runs in the loop, and a failure of schedules stops the agent too. When bot is
390 // not nil, it runs the bot too, and a failure of the bot stops the agent. Each
391 // child runs its own loop and schedules with no client events. A failed child
392 // stops the daemon, and backups lock all loops before they copy data.
393 func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, whatsapp *WhatsApp, schedules *Schedules, start func(notify func(Event)) (*TurnLoop, error), children ...*DaemonAgent) error {
394 ctx, cancel := context.WithCancel(ctx)
395 defer cancel()
396
397 hub := &DaemonHub{
398 whatsapp: whatsapp,
399 clients: make(map[*DaemonClient]bool),
400 }
401
402 notify := hub.Broadcast
403 if bot != nil {
404 notify = func(event Event) {
405 hub.Broadcast(event)
406 bot.Notify(event)
407 }
408 }
409
410 l, err := start(notify)
411 if err != nil {
412 return errors.Join(err, listener.Close())
413 }
414
415 if bot != nil {
416 l.tools.imageShow.bot = bot
417 }
418
419 loops := []*TurnLoop{l}
420 for _, child := range children {
421 loop, err := child.Loop(nil, func(Event) {
422 })
423 if err != nil {
424 return errors.Join(fmt.Errorf("start child %q: %w", child.agent.config.Name, err), listener.Close())
425 }
426
427 loops = append(loops, loop)
428 }
429
430 messages, err := openDaemonMessages(loops)
431 if err != nil {
432 return errors.Join(fmt.Errorf("open agent messages: %w", err), listener.Close())
433 }
434
435 hub.snapshot = func(ctx context.Context, snapshot func() error) error {
436 return messages.SnapshotAgents(ctx, snapshot)
437 }
438
439 runtime := &DaemonChildren{
440 ctx: ctx,
441 cancel: cancel,
442 root: l,
443 messages: messages,
444 }
445
446 l.tools.children = runtime
447
448 var workers sync.WaitGroup
449
450 childErrors := make([]error, len(children))
451 for i, child := range children {
452 workers.Add(1)
453
454 go func() {
455 defer workers.Done()
456
457 childErrors[i] = daemonRunChild(ctx, loops[i+1], child.schedules)
458 if childErrors[i] != nil {
459 child.logger.Error("child stopped", "err", childErrors[i])
460 }
461
462 cancel()
463 }()
464 }
465
466 workers.Add(2)
467
468 go func() {
469 defer workers.Done()
470
471 hub.Accept(ctx, listener, l)
472 }()
473
474 var whatsappErr error
475
476 go func() {
477 defer workers.Done()
478
479 whatsappErr = whatsapp.Run(ctx, l, notify)
480
481 cancel()
482 }()
483
484 var schedulesErr error
485
486 workers.Add(1)
487
488 go func() {
489 defer workers.Done()
490
491 schedulesErr = schedules.Run(ctx, l)
492
493 cancel()
494 }()
495
496 var botErr error
497
498 if bot != nil {
499 workers.Add(1)
500
501 go func() {
502 defer workers.Done()
503
504 botErr = bot.Run(ctx, l, whatsapp)
505
506 cancel()
507 }()
508 }
509
510 err = l.Run(ctx)
511 if errors.Is(err, context.Canceled) {
512 err = nil
513 }
514
515 cancel()
516
517 err = errors.Join(err, listener.Close())
518
519 hub.CloseAll()
520 workers.Wait()
521
522 return errors.Join(err, whatsappErr, schedulesErr, botErr, errors.Join(childErrors...), runtime.Close())
523 }
524
525 // daemonRunChild runs a child's turn loop and its schedules until either stops.
526 // Its events stay in its own log.
527 func daemonRunChild(ctx context.Context, loop *TurnLoop, schedules *Schedules) error {
528 ctx, cancel := context.WithCancel(ctx)
529 defer cancel()
530
531 done := make(chan error, 1)
532 go func() {
533 done <- schedules.Run(ctx, loop)
534
535 cancel()
536 }()
537
538 err := loop.Run(ctx)
539 if errors.Is(err, context.Canceled) {
540 err = nil
541 }
542
543 cancel()
544
545 return errors.Join(err, <-done)
546 }