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 // daemon runs "onechat daemon": it owns the root, its children, and their
28 // files, and serves the clients on the Unix socket in the data directory until
29 // ctx ends. When telegram.json exists, it also runs the Telegram bot. It also
30 // keeps a linked WhatsApp device connected. It holds the lock of the token
31 // file, so it is the only process that refreshes the tokens and opens the
32 // WhatsApp session. Its log lines go to out, through the loggers of
34 func daemon(ctx context.Context, out io.Writer) (err error) {
40 // Check the socket path before the daemon writes a file, so that a data
41 // directory with a long path stays empty.
42 socket := filepath.Join(dir, socketFileName)
43 err = checkSocketPath(socket)
48 config, err := loadConfig(dir)
53 botSettings, hasBot, err := loadTelegramConfig(dir)
58 tokens, err := lockTokens(dir)
64 err = errors.Join(err, tokens.Close())
67 whatsappSetDeviceProps()
69 logger := daemonLogger(out, "onechat: ")
70 whatsapp, err := openWhatsApp(ctx, dir, time.Now, daemonLogger(out, "whatsapp: "), whatsappNewClient)
76 err = errors.Join(err, whatsapp.Close())
79 address, auth, err := modelEndpoint(config, dir)
84 agents, err := openDaemonAgents(ctx, dir, address, auth, config.Compactor, time.Now, logger)
90 err = errors.Join(err, agents.Close())
93 whatsapp.inbox.voice = &VoiceTranscriber{config: config.Voice}
97 schedules := root.schedules
99 listener, err := daemonListenSocket(socket)
104 linked := "not linked"
105 if whatsapp.isLinked() {
109 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())
111 var telegram *TelegramBot
114 telegram = newTelegramBot(newTelegramAPI(telegramAPIURL, botSettings.Token), botSettings.Owner, filepath.Join(agent.dir, telegramOffsetFileName), daemonLogger(out, "telegram: "))
116 telegram.voice = &VoiceTranscriber{config: config.Voice}
118 logger.Info("Telegram bot started")
121 return daemonServe(ctx, listener, telegram, whatsapp, schedules, func(notify func(Event)) (*TurnLoop, error) {
122 return root.Loop(whatsapp, notify)
126 // DaemonHub holds the connected clients and sends each event to all of them. It
127 // runs the WhatsApp commands of the clients on whatsapp. snapshot locks all
128 // agents and subagents during a backup copy.
129 type DaemonHub struct {
131 snapshot func(context.Context, func() error) error
134 clients map[*DaemonClient]bool
135 workers sync.WaitGroup
138 // Accept serves each client of listener until the listener closes. A new
139 // client gets a ready event with the name of the agent, and a busy event when a
141 func (h *DaemonHub) Accept(ctx context.Context, listener net.Listener, l *TurnLoop) {
143 conn, err := listener.Accept()
148 client := &DaemonClient{
150 events: make(chan Event, daemonClientEvents),
155 h.clients[client] = true
161 go h.read(ctx, client, l)
163 h.Send(client, Event{
165 Text: l.agent.config.Name,
169 h.Send(client, Event{
176 // write sends the events of client as JSON lines until its channel closes.
177 func (h *DaemonHub) write(client *DaemonClient) {
178 defer h.workers.Done()
180 encoder := json.NewEncoder(client.conn)
181 for event := range client.events {
182 err := encoder.Encode(event)
189 // read runs the requests of client until it closes its connection.
190 func (h *DaemonHub) read(ctx context.Context, client *DaemonClient, l *TurnLoop) {
191 defer h.workers.Done()
194 scanner := bufio.NewScanner(client.conn)
195 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
197 for ctx.Err() == nil && scanner.Scan() {
198 var request SocketRequest
200 err := json.Unmarshal(scanner.Bytes(), &request)
202 if request.Type == "backup" {
205 size, err = backupData(ctx, filepath.Dir(l.agent.dir), request.Text, h.whatsapp, h.snapshot)
207 h.Send(client, Event{
209 Text: fmt.Sprintf("%s (%d bytes)", request.Text, size),
213 err = daemonRunRequest(l, h.whatsapp, request, func(text string) {
214 h.Send(client, Event{
223 h.Send(client, Event{
231 // Send gives event to one client, or drops the client when its events do not
233 func (h *DaemonHub) Send(client *DaemonClient, event Event) {
235 defer h.mutex.Unlock()
237 h.send(client, event)
240 // drop removes client and closes its connection.
241 func (h *DaemonHub) drop(client *DaemonClient) {
243 defer h.mutex.Unlock()
248 // send gives event to client. The caller holds the mutex.
249 func (h *DaemonHub) send(client *DaemonClient, event Event) {
250 if !h.clients[client] {
255 case client.events <- event:
261 // remove removes client, closes its connection, and ends its writer. The
262 // caller holds the mutex.
263 func (h *DaemonHub) remove(client *DaemonClient) {
264 delete(h.clients, client)
265 client.once.Do(func() {
268 _ = client.conn.Close()
272 // Broadcast gives event to every client.
273 func (h *DaemonHub) Broadcast(event Event) {
275 defer h.mutex.Unlock()
277 for client := range h.clients {
278 h.send(client, event)
282 // CloseAll drops every client and waits for their readers and writers.
283 func (h *DaemonHub) CloseAll() {
286 for client := range h.clients {
295 // DaemonClient is one connected client. Its events wait in a channel for the
296 // writer, so a slow client does not stop the agent.
297 type DaemonClient struct {
303 // daemonListenSocket listens on the Unix socket at path, with mode 0600. The
304 // caller owns the chat, so a socket file at path is left from a daemon that
305 // ended, and daemonListenSocket removes it.
306 func daemonListenSocket(path string) (net.Listener, error) {
307 err := checkSocketPath(path)
312 err = os.Remove(path)
313 if err != nil && !errors.Is(err, os.ErrNotExist) {
314 return nil, fmt.Errorf("remove old socket: %w", err)
317 listener, err := net.Listen("unix", path)
319 return nil, fmt.Errorf("listen on socket: %w", err)
322 err = os.Chmod(path, 0o600)
324 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
330 // daemonServe runs the loop that start makes and serves the clients of listener
331 // until ctx ends or the loop fails. It closes listener. It runs whatsapp, which
332 // logs its batches and notes in the loop and tells all clients its notices, and
333 // a failure of whatsapp stops the agent. It runs schedules, which log their
334 // runs in the loop, and a failure of schedules stops the agent too. When bot is
335 // not nil, it runs the bot too, and a failure of the bot stops the agent. Each
336 // child runs its own loop and schedules with no client events. A failed child
337 // stops the daemon, and backups lock all loops before they copy data.
338 func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, whatsapp *WhatsApp, schedules *Schedules, start func(notify func(Event)) (*TurnLoop, error), children ...*DaemonAgent) error {
339 ctx, cancel := context.WithCancel(ctx)
344 clients: make(map[*DaemonClient]bool),
347 notify := hub.Broadcast
349 notify = func(event Event) {
355 l, err := start(notify)
357 return errors.Join(err, listener.Close())
361 l.tools.imageShow.bot = bot
364 loops := []*TurnLoop{l}
365 for _, child := range children {
366 loop, err := child.Loop(nil, func(Event) {
369 return errors.Join(fmt.Errorf("start child %q: %w", child.agent.config.Name, err), listener.Close())
372 loops = append(loops, loop)
375 messages, err := openDaemonMessages(loops)
377 return errors.Join(fmt.Errorf("open agent messages: %w", err), listener.Close())
380 hub.snapshot = func(ctx context.Context, snapshot func() error) error {
381 return messages.SnapshotAgents(ctx, snapshot)
384 runtime := &DaemonChildren{
390 l.tools.children = runtime
392 var workers sync.WaitGroup
394 childErrors := make([]error, len(children))
395 for i, child := range children {
401 childErrors[i] = daemonRunChild(ctx, loops[i+1], child.schedules)
402 if childErrors[i] != nil {
403 child.logger.Error("child stopped", "err", childErrors[i])
415 hub.Accept(ctx, listener, l)
418 var whatsappErr error
423 whatsappErr = whatsapp.Run(ctx, l, notify)
428 var schedulesErr error
435 schedulesErr = schedules.Run(ctx, l)
448 botErr = bot.Run(ctx, l, whatsapp)
455 if errors.Is(err, context.Canceled) {
461 err = errors.Join(err, listener.Close())
466 return errors.Join(err, whatsappErr, schedulesErr, botErr, errors.Join(childErrors...), runtime.Close())
469 // daemonRunChild runs a child's turn loop and its schedules until either stops.
470 // Its events stay in its own log.
471 func daemonRunChild(ctx context.Context, loop *TurnLoop, schedules *Schedules) error {
472 ctx, cancel := context.WithCancel(ctx)
475 done := make(chan error, 1)
477 done <- schedules.Run(ctx, loop)
483 if errors.Is(err, context.Canceled) {
489 return errors.Join(err, <-done)
492 // daemonRunRequest runs one request of a client. The answers of a WhatsApp
493 // command go to answer.
494 func daemonRunRequest(l *TurnLoop, whatsapp *WhatsApp, request SocketRequest, answer func(text string)) error {
495 switch request.Type {
497 if request.Text == "" {
498 return errors.New("empty message")
501 _, err := l.Submit(terminalSource, request.Text)
505 if !filepath.IsAbs(request.Path) {
506 return errors.New("use /image PATH [caption]")
509 data, err := imageReadFile(request.Path)
511 return fmt.Errorf("read terminal image: %w", err)
514 name, err := l.agent.Images().Save(data)
516 return fmt.Errorf("store terminal image: %w", err)
519 _, err = l.Submit(terminalSource, imageText([]string{name}, request.Text))
521 return fmt.Errorf("submit terminal image: %w", err)
527 return errors.New("no turn runs")
532 whatsapp.Command(request.Text, answer)
536 found, err := l.StopSubagent(request.Text)
537 if err == nil && !found {
538 err = fmt.Errorf("no subagent %s runs", request.Text)
543 return fmt.Errorf("unknown request %q", request.Type)