19 // daemonAgentDirName is the directory of the root agent in the data
21 daemonAgentDirName = "agent"
23 // daemonClientEvents is the number of events that can wait for a slow
24 // client before the daemon drops it.
25 daemonClientEvents = 1024
28 // DaemonHub holds the connected clients and sends each event to all of them. It
29 // runs the WhatsApp commands of the clients on whatsapp. snapshot locks all
30 // agents and subagents during a backup copy.
31 type DaemonHub struct {
33 snapshot func(context.Context, func() error) error
36 clients map[*DaemonClient]bool
37 workers sync.WaitGroup
40 // DaemonClient is one connected client. Its events wait in a channel for the
41 // writer, so a slow client does not stop the agent.
42 type DaemonClient struct {
48 // Accept serves each client of listener until the listener closes. A new client
49 // gets a ready event with the name of the agent, and a busy event when a turn
51 func (h *DaemonHub) Accept(ctx context.Context, listener net.Listener, l *TurnLoop) {
53 conn, err := listener.Accept()
58 client := &DaemonClient{
60 events: make(chan Event, daemonClientEvents),
65 h.clients[client] = true
71 go h.read(ctx, client, l)
75 Text: l.agent.config.Name,
86 // write sends the events of client as JSON lines until its channel closes.
87 func (h *DaemonHub) write(client *DaemonClient) {
88 defer h.workers.Done()
90 encoder := json.NewEncoder(client.conn)
91 for event := range client.events {
92 err := encoder.Encode(event)
99 // read runs the requests of client until it closes its connection.
100 func (h *DaemonHub) read(ctx context.Context, client *DaemonClient, l *TurnLoop) {
101 defer h.workers.Done()
104 scanner := bufio.NewScanner(client.conn)
105 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
107 for ctx.Err() == nil && scanner.Scan() {
108 var request SocketRequest
110 err := json.Unmarshal(scanner.Bytes(), &request)
112 switch request.Type {
116 decoder := json.NewDecoder(bytes.NewReader(scanner.Bytes()))
117 decoder.DisallowUnknownFields()
119 err = decoder.Decode(&request)
121 receipt, err = l.messages.Notify(request.Notify)
125 h.Send(client, receipt)
130 size, err = backupData(ctx, filepath.Dir(l.agent.dir), request.Text, h.whatsapp, h.snapshot)
132 h.Send(client, Event{
134 Text: fmt.Sprintf("%s (%d bytes)", request.Text, size),
138 err = daemonRunRequest(l, h.whatsapp, request, func(text string) {
139 h.Send(client, Event{
148 h.Send(client, Event{
156 // Send gives event to one client, or drops the client when its events do not
158 func (h *DaemonHub) Send(client *DaemonClient, event Event) {
160 defer h.mutex.Unlock()
162 h.send(client, event)
165 // drop removes client and closes its connection.
166 func (h *DaemonHub) drop(client *DaemonClient) {
168 defer h.mutex.Unlock()
173 // send gives event to client. The caller holds the mutex.
174 func (h *DaemonHub) send(client *DaemonClient, event Event) {
175 if !h.clients[client] {
180 case client.events <- event:
186 // remove removes client, closes its connection, and ends its writer. The caller
188 func (h *DaemonHub) remove(client *DaemonClient) {
189 delete(h.clients, client)
190 client.once.Do(func() {
193 // The client is removed already, so a close failure cannot
195 client.conn.Close() // nolint: errcheck
199 // Broadcast gives event to every client.
200 func (h *DaemonHub) Broadcast(event Event) {
202 defer h.mutex.Unlock()
204 for client := range h.clients {
205 h.send(client, event)
209 // CloseAll drops every client and waits for their readers and writers.
210 func (h *DaemonHub) CloseAll() {
213 for client := range h.clients {
222 // daemonRunRequest runs one request of a client. The answers of a WhatsApp
223 // command go to answer.
224 func daemonRunRequest(l *TurnLoop, whatsapp *WhatsApp, request SocketRequest, answer func(text string)) error {
225 switch request.Type {
227 if request.Text == "" {
228 return errors.New("empty message")
231 _, err := l.Submit(terminalSource, request.Text)
233 return fmt.Errorf("submit terminal message: %w", err)
238 if !filepath.IsAbs(request.Path) {
239 return errors.New("use /image PATH [caption]")
242 data, err := imageReadFile(request.Path)
244 return fmt.Errorf("read terminal image: %w", err)
247 name, err := l.agent.Images().Save(data)
249 return fmt.Errorf("store terminal image: %w", err)
252 _, err = l.Submit(terminalSource, imageText([]string{name}, request.Text))
254 return fmt.Errorf("submit terminal image: %w", err)
260 return errors.New("no turn runs")
265 whatsapp.Command(request.Text, answer)
269 found, err := l.StopSubagent(request.Text)
270 if err == nil && !found {
271 err = fmt.Errorf("no subagent %s runs", request.Text)
275 return fmt.Errorf("stop subagent: %w", err)
280 return fmt.Errorf("unknown request %q", request.Type)
284 // daemon runs "onechat daemon": it owns the root, its children, and their
285 // files, and serves the clients on the Unix socket in the data directory until
286 // ctx ends. When telegram.json exists, it also runs the Telegram bot. It also
287 // keeps a linked WhatsApp device connected. It holds the lock of the token
288 // file, so it is the only process that refreshes the tokens and opens the
289 // WhatsApp session. Its log lines go to out, through the loggers of
291 func daemon(ctx context.Context, out io.Writer) (err error) {
292 dir, err := dataDir()
294 return fmt.Errorf("find data directory: %w", err)
297 // Check the socket path before the daemon writes a file, so that a data
298 // directory with a long path stays empty.
299 socket := filepath.Join(dir, socketFileName)
300 err = checkSocketPath(socket)
302 return fmt.Errorf("check daemon socket path: %w", err)
305 config, err := loadConfig(dir)
307 return fmt.Errorf("load daemon config: %w", err)
310 botSettings, hasBot, err := loadTelegramConfig(dir)
312 return fmt.Errorf("load Telegram config: %w", err)
315 tokens, err := lockTokens(dir)
317 return fmt.Errorf("lock login tokens: %w", err)
321 err = errors.Join(err, tokens.Close())
324 whatsappSetDeviceProps()
326 logger := daemonLogger(out, "onechat: ")
327 whatsapp, err := openWhatsApp(ctx, dir, time.Now, daemonLogger(out, "whatsapp: "), whatsappNewClient)
329 return fmt.Errorf("open WhatsApp: %w", err)
333 err = errors.Join(err, whatsapp.Close())
336 address, auth, err := modelEndpoint(config, dir)
338 return fmt.Errorf("configure model endpoint: %w", err)
341 agents, err := openDaemonAgents(ctx, dir, address, auth, config.Compactor, time.Now, logger)
343 return fmt.Errorf("open daemon agents: %w", err)
347 err = errors.Join(err, agents.Close())
350 whatsapp.inbox.voice = &VoiceTranscriber{config: config.Voice}
354 schedules := root.schedules
356 listener, err := daemonListenSocket(socket)
358 return fmt.Errorf("listen for daemon clients: %w", err)
361 linked := "not linked"
362 if whatsapp.isLinked() {
366 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())
368 var telegram *TelegramBot
371 telegram = newTelegramBot(newTelegramAPI(telegramAPIURL, botSettings.Token), botSettings.Owner, filepath.Join(agent.dir, telegramOffsetFileName), daemonLogger(out, "telegram: "))
373 telegram.voice = &VoiceTranscriber{config: config.Voice}
375 logger.Info("Telegram bot started")
378 err = daemonServe(ctx, listener, telegram, whatsapp, schedules, func(notify func(Event)) (*TurnLoop, error) {
379 return root.Loop(whatsapp, notify)
382 return fmt.Errorf("serve daemon: %w", err)
388 // daemonListenSocket listens on the Unix socket at path, with mode 0600. The
389 // caller owns the chat, so a socket file at path is left from a daemon that
390 // ended, and daemonListenSocket removes it.
391 func daemonListenSocket(path string) (net.Listener, error) {
392 err := checkSocketPath(path)
394 return nil, fmt.Errorf("check daemon socket path: %w", err)
397 err = os.Remove(path)
398 if err != nil && !errors.Is(err, os.ErrNotExist) {
399 return nil, fmt.Errorf("remove old socket: %w", err)
402 listener, err := net.Listen("unix", path)
404 return nil, fmt.Errorf("listen on socket: %w", err)
407 err = os.Chmod(path, 0o600)
409 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
415 // daemonServe runs the loop that start makes and serves the clients of listener
416 // until ctx ends or the loop fails. It closes listener. It runs whatsapp, which
417 // logs its batches and notes in the loop and tells all clients its notices, and
418 // a failure of whatsapp stops the agent. It runs schedules, which log their
419 // runs in the loop, and a failure of schedules stops the agent too. When bot is
420 // not nil, it runs the bot too, and a failure of the bot stops the agent. Each
421 // child runs its own loop and schedules with no client events. A failed child
422 // stops the daemon, and backups lock all loops before they copy data.
423 func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, whatsapp *WhatsApp, schedules *Schedules, start func(notify func(Event)) (*TurnLoop, error), children ...*DaemonAgent) error {
424 ctx, cancel := context.WithCancel(ctx)
429 clients: make(map[*DaemonClient]bool),
432 notify := hub.Broadcast
434 notify = func(event Event) {
440 l, err := start(notify)
442 return errors.Join(err, listener.Close())
446 l.tools.imageShow.bot = bot
449 loops := []*TurnLoop{l}
450 for _, child := range children {
451 loop, err := child.Loop(nil, func(Event) {
454 return errors.Join(fmt.Errorf("start child %q: %w", child.agent.config.Name, err), listener.Close())
457 loops = append(loops, loop)
460 messages, err := openDaemonMessages(loops)
462 return errors.Join(fmt.Errorf("open agent messages: %w", err), listener.Close())
465 hub.snapshot = func(ctx context.Context, snapshot func() error) error {
466 return messages.SnapshotAgents(ctx, snapshot)
469 runtime := &DaemonChildren{
476 l.tools.children = runtime
478 var workers sync.WaitGroup
480 childErrors := make([]error, len(children))
481 for i, child := range children {
487 childErrors[i] = daemonRunChild(ctx, loops[i+1], child.schedules)
488 if childErrors[i] != nil {
489 child.logger.Error("child stopped", "err", childErrors[i])
501 hub.Accept(ctx, listener, l)
504 var whatsappErr error
509 whatsappErr = whatsapp.Run(ctx, l, notify)
514 var schedulesErr error
521 schedulesErr = schedules.Run(ctx, l)
534 botErr = bot.Run(ctx, l, whatsapp)
541 if errors.Is(err, context.Canceled) {
547 err = errors.Join(err, listener.Close())
552 return errors.Join(err, whatsappErr, schedulesErr, botErr, errors.Join(childErrors...), runtime.Close())
555 // daemonRunChild runs a child's turn loop and its schedules until either stops.
556 // Its events stay in its own log.
557 func daemonRunChild(ctx context.Context, loop *TurnLoop, schedules *Schedules) error {
558 ctx, cancel := context.WithCancel(ctx)
561 done := make(chan error, 1)
563 done <- schedules.Run(ctx, loop)
569 if errors.Is(err, context.Canceled) {
575 return errors.Join(err, <-done)