]> git.giacomolli.uk - onechat/blob - daemon.go
d6aa6aaa8cf247cb2ec4a613fab3344cf0b7eaaf
[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 // The client is removed already, so a close failure cannot
178 // restore it.
179 client.conn.Close() // nolint: errcheck
180 })
181 }
182
183 // Broadcast gives event to every client.
184 func (h *DaemonHub) Broadcast(event Event) {
185 h.mutex.Lock()
186 defer h.mutex.Unlock()
187
188 for client := range h.clients {
189 h.send(client, event)
190 }
191 }
192
193 // CloseAll drops every client and waits for their readers and writers.
194 func (h *DaemonHub) CloseAll() {
195 h.mutex.Lock()
196
197 for client := range h.clients {
198 h.remove(client)
199 }
200
201 h.mutex.Unlock()
202
203 h.workers.Wait()
204 }
205
206 // daemonRunRequest runs one request of a client. The answers of a WhatsApp
207 // command go to answer.
208 func daemonRunRequest(l *TurnLoop, whatsapp *WhatsApp, request SocketRequest, answer func(text string)) error {
209 switch request.Type {
210 case "send":
211 if request.Text == "" {
212 return errors.New("empty message")
213 }
214
215 _, err := l.Submit(terminalSource, request.Text)
216
217 return err
218 case "image":
219 if !filepath.IsAbs(request.Path) {
220 return errors.New("use /image PATH [caption]")
221 }
222
223 data, err := imageReadFile(request.Path)
224 if err != nil {
225 return fmt.Errorf("read terminal image: %w", err)
226 }
227
228 name, err := l.agent.Images().Save(data)
229 if err != nil {
230 return fmt.Errorf("store terminal image: %w", err)
231 }
232
233 _, err = l.Submit(terminalSource, imageText([]string{name}, request.Text))
234 if err != nil {
235 return fmt.Errorf("submit terminal image: %w", err)
236 }
237
238 return nil
239 case "interrupt":
240 if !l.Interrupt() {
241 return errors.New("no turn runs")
242 }
243
244 return nil
245 case "whatsapp":
246 whatsapp.Command(request.Text, answer)
247
248 return nil
249 case "stop":
250 found, err := l.StopSubagent(request.Text)
251 if err == nil && !found {
252 err = fmt.Errorf("no subagent %s runs", request.Text)
253 }
254
255 return err
256 default:
257 return fmt.Errorf("unknown request %q", request.Type)
258 }
259 }
260
261 // daemon runs "onechat daemon": it owns the root, its children, and their
262 // files, and serves the clients on the Unix socket in the data directory until
263 // ctx ends. When telegram.json exists, it also runs the Telegram bot. It also
264 // keeps a linked WhatsApp device connected. It holds the lock of the token
265 // file, so it is the only process that refreshes the tokens and opens the
266 // WhatsApp session. Its log lines go to out, through the loggers of
267 // daemonLogger.
268 func daemon(ctx context.Context, out io.Writer) (err error) {
269 dir, err := dataDir()
270 if err != nil {
271 return err
272 }
273
274 // Check the socket path before the daemon writes a file, so that a data
275 // directory with a long path stays empty.
276 socket := filepath.Join(dir, socketFileName)
277 err = checkSocketPath(socket)
278 if err != nil {
279 return err
280 }
281
282 config, err := loadConfig(dir)
283 if err != nil {
284 return err
285 }
286
287 botSettings, hasBot, err := loadTelegramConfig(dir)
288 if err != nil {
289 return err
290 }
291
292 tokens, err := lockTokens(dir)
293 if err != nil {
294 return err
295 }
296
297 defer func() {
298 err = errors.Join(err, tokens.Close())
299 }()
300
301 whatsappSetDeviceProps()
302
303 logger := daemonLogger(out, "onechat: ")
304 whatsapp, err := openWhatsApp(ctx, dir, time.Now, daemonLogger(out, "whatsapp: "), whatsappNewClient)
305 if err != nil {
306 return err
307 }
308
309 defer func() {
310 err = errors.Join(err, whatsapp.Close())
311 }()
312
313 address, auth, err := modelEndpoint(config, dir)
314 if err != nil {
315 return err
316 }
317
318 agents, err := openDaemonAgents(ctx, dir, address, auth, config.Compactor, time.Now, logger)
319 if err != nil {
320 return err
321 }
322
323 defer func() {
324 err = errors.Join(err, agents.Close())
325 }()
326
327 whatsapp.inbox.voice = &VoiceTranscriber{config: config.Voice}
328
329 root := agents[0]
330 agent := root.agent
331 schedules := root.schedules
332
333 listener, err := daemonListenSocket(socket)
334 if err != nil {
335 return err
336 }
337
338 linked := "not linked"
339 if whatsapp.isLinked() {
340 linked = "linked"
341 }
342
343 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())
344
345 var telegram *TelegramBot
346
347 if hasBot {
348 telegram = newTelegramBot(newTelegramAPI(telegramAPIURL, botSettings.Token), botSettings.Owner, filepath.Join(agent.dir, telegramOffsetFileName), daemonLogger(out, "telegram: "))
349
350 telegram.voice = &VoiceTranscriber{config: config.Voice}
351
352 logger.Info("Telegram bot started")
353 }
354
355 return daemonServe(ctx, listener, telegram, whatsapp, schedules, func(notify func(Event)) (*TurnLoop, error) {
356 return root.Loop(whatsapp, notify)
357 }, agents[1:]...)
358 }
359
360 // daemonListenSocket listens on the Unix socket at path, with mode 0600. The
361 // caller owns the chat, so a socket file at path is left from a daemon that
362 // ended, and daemonListenSocket removes it.
363 func daemonListenSocket(path string) (net.Listener, error) {
364 err := checkSocketPath(path)
365 if err != nil {
366 return nil, err
367 }
368
369 err = os.Remove(path)
370 if err != nil && !errors.Is(err, os.ErrNotExist) {
371 return nil, fmt.Errorf("remove old socket: %w", err)
372 }
373
374 listener, err := net.Listen("unix", path)
375 if err != nil {
376 return nil, fmt.Errorf("listen on socket: %w", err)
377 }
378
379 err = os.Chmod(path, 0o600)
380 if err != nil {
381 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
382 }
383
384 return listener, nil
385 }
386
387 // daemonServe runs the loop that start makes and serves the clients of listener
388 // until ctx ends or the loop fails. It closes listener. It runs whatsapp, which
389 // logs its batches and notes in the loop and tells all clients its notices, and
390 // a failure of whatsapp stops the agent. It runs schedules, which log their
391 // runs in the loop, and a failure of schedules stops the agent too. When bot is
392 // not nil, it runs the bot too, and a failure of the bot stops the agent. Each
393 // child runs its own loop and schedules with no client events. A failed child
394 // stops the daemon, and backups lock all loops before they copy data.
395 func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, whatsapp *WhatsApp, schedules *Schedules, start func(notify func(Event)) (*TurnLoop, error), children ...*DaemonAgent) error {
396 ctx, cancel := context.WithCancel(ctx)
397 defer cancel()
398
399 hub := &DaemonHub{
400 whatsapp: whatsapp,
401 clients: make(map[*DaemonClient]bool),
402 }
403
404 notify := hub.Broadcast
405 if bot != nil {
406 notify = func(event Event) {
407 hub.Broadcast(event)
408 bot.Notify(event)
409 }
410 }
411
412 l, err := start(notify)
413 if err != nil {
414 return errors.Join(err, listener.Close())
415 }
416
417 if bot != nil {
418 l.tools.imageShow.bot = bot
419 }
420
421 loops := []*TurnLoop{l}
422 for _, child := range children {
423 loop, err := child.Loop(nil, func(Event) {
424 })
425 if err != nil {
426 return errors.Join(fmt.Errorf("start child %q: %w", child.agent.config.Name, err), listener.Close())
427 }
428
429 loops = append(loops, loop)
430 }
431
432 messages, err := openDaemonMessages(loops)
433 if err != nil {
434 return errors.Join(fmt.Errorf("open agent messages: %w", err), listener.Close())
435 }
436
437 hub.snapshot = func(ctx context.Context, snapshot func() error) error {
438 return messages.SnapshotAgents(ctx, snapshot)
439 }
440
441 runtime := &DaemonChildren{
442 ctx: ctx,
443 cancel: cancel,
444 root: l,
445 messages: messages,
446 }
447
448 l.tools.children = runtime
449
450 var workers sync.WaitGroup
451
452 childErrors := make([]error, len(children))
453 for i, child := range children {
454 workers.Add(1)
455
456 go func() {
457 defer workers.Done()
458
459 childErrors[i] = daemonRunChild(ctx, loops[i+1], child.schedules)
460 if childErrors[i] != nil {
461 child.logger.Error("child stopped", "err", childErrors[i])
462 }
463
464 cancel()
465 }()
466 }
467
468 workers.Add(2)
469
470 go func() {
471 defer workers.Done()
472
473 hub.Accept(ctx, listener, l)
474 }()
475
476 var whatsappErr error
477
478 go func() {
479 defer workers.Done()
480
481 whatsappErr = whatsapp.Run(ctx, l, notify)
482
483 cancel()
484 }()
485
486 var schedulesErr error
487
488 workers.Add(1)
489
490 go func() {
491 defer workers.Done()
492
493 schedulesErr = schedules.Run(ctx, l)
494
495 cancel()
496 }()
497
498 var botErr error
499
500 if bot != nil {
501 workers.Add(1)
502
503 go func() {
504 defer workers.Done()
505
506 botErr = bot.Run(ctx, l, whatsapp)
507
508 cancel()
509 }()
510 }
511
512 err = l.Run(ctx)
513 if errors.Is(err, context.Canceled) {
514 err = nil
515 }
516
517 cancel()
518
519 err = errors.Join(err, listener.Close())
520
521 hub.CloseAll()
522 workers.Wait()
523
524 return errors.Join(err, whatsappErr, schedulesErr, botErr, errors.Join(childErrors...), runtime.Close())
525 }
526
527 // daemonRunChild runs a child's turn loop and its schedules until either stops.
528 // Its events stay in its own log.
529 func daemonRunChild(ctx context.Context, loop *TurnLoop, schedules *Schedules) error {
530 ctx, cancel := context.WithCancel(ctx)
531 defer cancel()
532
533 done := make(chan error, 1)
534 go func() {
535 done <- schedules.Run(ctx, loop)
536
537 cancel()
538 }()
539
540 err := loop.Run(ctx)
541 if errors.Is(err, context.Canceled) {
542 err = nil
543 }
544
545 cancel()
546
547 return errors.Join(err, <-done)
548 }