18 // daemonAgentDirName is the directory of the root agent in the data
20 daemonAgentDirName = "agent"
22 // daemonClientEvents is the number of events that can wait for a slow
23 // client before the daemon drops it.
24 daemonClientEvents = 1024
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 {
32 snapshot func(context.Context, func() error) error
35 clients map[*DaemonClient]bool
36 workers sync.WaitGroup
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 {
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
50 func (h *DaemonHub) Accept(ctx context.Context, listener net.Listener, l *TurnLoop) {
52 conn, err := listener.Accept()
57 client := &DaemonClient{
59 events: make(chan Event, daemonClientEvents),
64 h.clients[client] = true
70 go h.read(ctx, client, l)
74 Text: l.agent.config.Name,
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()
89 encoder := json.NewEncoder(client.conn)
90 for event := range client.events {
91 err := encoder.Encode(event)
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()
103 scanner := bufio.NewScanner(client.conn)
104 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
106 for ctx.Err() == nil && scanner.Scan() {
107 var request SocketRequest
109 err := json.Unmarshal(scanner.Bytes(), &request)
111 if request.Type == "backup" {
114 size, err = backupData(ctx, filepath.Dir(l.agent.dir), request.Text, h.whatsapp, h.snapshot)
116 h.Send(client, Event{
118 Text: fmt.Sprintf("%s (%d bytes)", request.Text, size),
122 err = daemonRunRequest(l, h.whatsapp, request, func(text string) {
123 h.Send(client, Event{
132 h.Send(client, Event{
140 // Send gives event to one client, or drops the client when its events do not
142 func (h *DaemonHub) Send(client *DaemonClient, event Event) {
144 defer h.mutex.Unlock()
146 h.send(client, event)
149 // drop removes client and closes its connection.
150 func (h *DaemonHub) drop(client *DaemonClient) {
152 defer h.mutex.Unlock()
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] {
164 case client.events <- event:
170 // remove removes client, closes its connection, and ends its writer. The caller
172 func (h *DaemonHub) remove(client *DaemonClient) {
173 delete(h.clients, client)
174 client.once.Do(func() {
177 // The client is removed already, so a close failure cannot
179 client.conn.Close() // nolint: errcheck
183 // Broadcast gives event to every client.
184 func (h *DaemonHub) Broadcast(event Event) {
186 defer h.mutex.Unlock()
188 for client := range h.clients {
189 h.send(client, event)
193 // CloseAll drops every client and waits for their readers and writers.
194 func (h *DaemonHub) CloseAll() {
197 for client := range h.clients {
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 {
211 if request.Text == "" {
212 return errors.New("empty message")
215 _, err := l.Submit(terminalSource, request.Text)
217 return fmt.Errorf("submit terminal message: %w", err)
222 if !filepath.IsAbs(request.Path) {
223 return errors.New("use /image PATH [caption]")
226 data, err := imageReadFile(request.Path)
228 return fmt.Errorf("read terminal image: %w", err)
231 name, err := l.agent.Images().Save(data)
233 return fmt.Errorf("store terminal image: %w", err)
236 _, err = l.Submit(terminalSource, imageText([]string{name}, request.Text))
238 return fmt.Errorf("submit terminal image: %w", err)
244 return errors.New("no turn runs")
249 whatsapp.Command(request.Text, answer)
253 found, err := l.StopSubagent(request.Text)
254 if err == nil && !found {
255 err = fmt.Errorf("no subagent %s runs", request.Text)
259 return fmt.Errorf("stop subagent: %w", err)
264 return fmt.Errorf("unknown request %q", request.Type)
268 // daemon runs "onechat daemon": it owns the root, its children, and their
269 // files, and serves the clients on the Unix socket in the data directory until
270 // ctx ends. When telegram.json exists, it also runs the Telegram bot. It also
271 // keeps a linked WhatsApp device connected. It holds the lock of the token
272 // file, so it is the only process that refreshes the tokens and opens the
273 // WhatsApp session. Its log lines go to out, through the loggers of
275 func daemon(ctx context.Context, out io.Writer) (err error) {
276 dir, err := dataDir()
278 return fmt.Errorf("find data directory: %w", err)
281 // Check the socket path before the daemon writes a file, so that a data
282 // directory with a long path stays empty.
283 socket := filepath.Join(dir, socketFileName)
284 err = checkSocketPath(socket)
286 return fmt.Errorf("check daemon socket path: %w", err)
289 config, err := loadConfig(dir)
291 return fmt.Errorf("load daemon config: %w", err)
294 botSettings, hasBot, err := loadTelegramConfig(dir)
296 return fmt.Errorf("load Telegram config: %w", err)
299 tokens, err := lockTokens(dir)
301 return fmt.Errorf("lock login tokens: %w", err)
305 err = errors.Join(err, tokens.Close())
308 whatsappSetDeviceProps()
310 logger := daemonLogger(out, "onechat: ")
311 whatsapp, err := openWhatsApp(ctx, dir, time.Now, daemonLogger(out, "whatsapp: "), whatsappNewClient)
313 return fmt.Errorf("open WhatsApp: %w", err)
317 err = errors.Join(err, whatsapp.Close())
320 address, auth, err := modelEndpoint(config, dir)
322 return fmt.Errorf("configure model endpoint: %w", err)
325 agents, err := openDaemonAgents(ctx, dir, address, auth, config.Compactor, time.Now, logger)
327 return fmt.Errorf("open daemon agents: %w", err)
331 err = errors.Join(err, agents.Close())
334 whatsapp.inbox.voice = &VoiceTranscriber{config: config.Voice}
338 schedules := root.schedules
340 listener, err := daemonListenSocket(socket)
342 return fmt.Errorf("listen for daemon clients: %w", err)
345 linked := "not linked"
346 if whatsapp.isLinked() {
350 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())
352 var telegram *TelegramBot
355 telegram = newTelegramBot(newTelegramAPI(telegramAPIURL, botSettings.Token), botSettings.Owner, filepath.Join(agent.dir, telegramOffsetFileName), daemonLogger(out, "telegram: "))
357 telegram.voice = &VoiceTranscriber{config: config.Voice}
359 logger.Info("Telegram bot started")
362 err = daemonServe(ctx, listener, telegram, whatsapp, schedules, func(notify func(Event)) (*TurnLoop, error) {
363 return root.Loop(whatsapp, notify)
366 return fmt.Errorf("serve daemon: %w", err)
372 // daemonListenSocket listens on the Unix socket at path, with mode 0600. The
373 // caller owns the chat, so a socket file at path is left from a daemon that
374 // ended, and daemonListenSocket removes it.
375 func daemonListenSocket(path string) (net.Listener, error) {
376 err := checkSocketPath(path)
378 return nil, fmt.Errorf("check daemon socket path: %w", err)
381 err = os.Remove(path)
382 if err != nil && !errors.Is(err, os.ErrNotExist) {
383 return nil, fmt.Errorf("remove old socket: %w", err)
386 listener, err := net.Listen("unix", path)
388 return nil, fmt.Errorf("listen on socket: %w", err)
391 err = os.Chmod(path, 0o600)
393 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
399 // daemonServe runs the loop that start makes and serves the clients of listener
400 // until ctx ends or the loop fails. It closes listener. It runs whatsapp, which
401 // logs its batches and notes in the loop and tells all clients its notices, and
402 // a failure of whatsapp stops the agent. It runs schedules, which log their
403 // runs in the loop, and a failure of schedules stops the agent too. When bot is
404 // not nil, it runs the bot too, and a failure of the bot stops the agent. Each
405 // child runs its own loop and schedules with no client events. A failed child
406 // stops the daemon, and backups lock all loops before they copy data.
407 func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, whatsapp *WhatsApp, schedules *Schedules, start func(notify func(Event)) (*TurnLoop, error), children ...*DaemonAgent) error {
408 ctx, cancel := context.WithCancel(ctx)
413 clients: make(map[*DaemonClient]bool),
416 notify := hub.Broadcast
418 notify = func(event Event) {
424 l, err := start(notify)
426 return errors.Join(err, listener.Close())
430 l.tools.imageShow.bot = bot
433 loops := []*TurnLoop{l}
434 for _, child := range children {
435 loop, err := child.Loop(nil, func(Event) {
438 return errors.Join(fmt.Errorf("start child %q: %w", child.agent.config.Name, err), listener.Close())
441 loops = append(loops, loop)
444 messages, err := openDaemonMessages(loops)
446 return errors.Join(fmt.Errorf("open agent messages: %w", err), listener.Close())
449 hub.snapshot = func(ctx context.Context, snapshot func() error) error {
450 return messages.SnapshotAgents(ctx, snapshot)
453 runtime := &DaemonChildren{
460 l.tools.children = runtime
462 var workers sync.WaitGroup
464 childErrors := make([]error, len(children))
465 for i, child := range children {
471 childErrors[i] = daemonRunChild(ctx, loops[i+1], child.schedules)
472 if childErrors[i] != nil {
473 child.logger.Error("child stopped", "err", childErrors[i])
485 hub.Accept(ctx, listener, l)
488 var whatsappErr error
493 whatsappErr = whatsapp.Run(ctx, l, notify)
498 var schedulesErr error
505 schedulesErr = schedules.Run(ctx, l)
518 botErr = bot.Run(ctx, l, whatsapp)
525 if errors.Is(err, context.Canceled) {
531 err = errors.Join(err, listener.Close())
536 return errors.Join(err, whatsappErr, schedulesErr, botErr, errors.Join(childErrors...), runtime.Close())
539 // daemonRunChild runs a child's turn loop and its schedules until either stops.
540 // Its events stay in its own log.
541 func daemonRunChild(ctx context.Context, loop *TurnLoop, schedules *Schedules) error {
542 ctx, cancel := context.WithCancel(ctx)
545 done := make(chan error, 1)
547 done <- schedules.Run(ctx, loop)
553 if errors.Is(err, context.Canceled) {
559 return errors.Join(err, <-done)