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())
95 schedules := root.schedules
97 listener, err := daemonListenSocket(socket)
102 linked := "not linked"
103 if whatsapp.isLinked() {
107 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())
109 var telegram *TelegramBot
112 telegram = newTelegramBot(newTelegramAPI(telegramAPIURL, botSettings.Token), botSettings.Owner, filepath.Join(agent.dir, telegramOffsetFileName), daemonLogger(out, "telegram: "))
114 logger.Info("Telegram bot started")
117 return daemonServe(ctx, listener, telegram, whatsapp, schedules, func(notify func(Event)) (*TurnLoop, error) {
118 return root.Loop(whatsapp, notify)
122 // DaemonHub holds the connected clients and sends each event to all of them. It
123 // runs the WhatsApp commands of the clients on whatsapp. snapshot locks all
124 // agents and subagents during a backup copy.
125 type DaemonHub struct {
127 snapshot func(context.Context, func() error) error
130 clients map[*DaemonClient]bool
131 workers sync.WaitGroup
134 // Accept serves each client of listener until the listener closes. A new
135 // client gets a ready event with the name of the agent, and a busy event when a
137 func (h *DaemonHub) Accept(ctx context.Context, listener net.Listener, l *TurnLoop) {
139 conn, err := listener.Accept()
144 client := &DaemonClient{
146 events: make(chan Event, daemonClientEvents),
151 h.clients[client] = true
157 go h.read(ctx, client, l)
159 h.Send(client, Event{
161 Text: l.agent.config.Name,
165 h.Send(client, Event{
172 // write sends the events of client as JSON lines until its channel closes.
173 func (h *DaemonHub) write(client *DaemonClient) {
174 defer h.workers.Done()
176 encoder := json.NewEncoder(client.conn)
177 for event := range client.events {
178 err := encoder.Encode(event)
185 // read runs the requests of client until it closes its connection.
186 func (h *DaemonHub) read(ctx context.Context, client *DaemonClient, l *TurnLoop) {
187 defer h.workers.Done()
190 scanner := bufio.NewScanner(client.conn)
191 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
193 for ctx.Err() == nil && scanner.Scan() {
194 var request SocketRequest
196 err := json.Unmarshal(scanner.Bytes(), &request)
198 if request.Type == "backup" {
201 size, err = backupData(ctx, filepath.Dir(l.agent.dir), request.Text, h.whatsapp, h.snapshot)
203 h.Send(client, Event{
205 Text: fmt.Sprintf("%s (%d bytes)", request.Text, size),
209 err = daemonRunRequest(l, h.whatsapp, request, func(text string) {
210 h.Send(client, Event{
219 h.Send(client, Event{
227 // Send gives event to one client, or drops the client when its events do not
229 func (h *DaemonHub) Send(client *DaemonClient, event Event) {
231 defer h.mutex.Unlock()
233 h.send(client, event)
236 // drop removes client and closes its connection.
237 func (h *DaemonHub) drop(client *DaemonClient) {
239 defer h.mutex.Unlock()
244 // send gives event to client. The caller holds the mutex.
245 func (h *DaemonHub) send(client *DaemonClient, event Event) {
246 if !h.clients[client] {
251 case client.events <- event:
257 // remove removes client, closes its connection, and ends its writer. The
258 // caller holds the mutex.
259 func (h *DaemonHub) remove(client *DaemonClient) {
260 delete(h.clients, client)
261 client.once.Do(func() {
264 _ = client.conn.Close()
268 // Broadcast gives event to every client.
269 func (h *DaemonHub) Broadcast(event Event) {
271 defer h.mutex.Unlock()
273 for client := range h.clients {
274 h.send(client, event)
278 // CloseAll drops every client and waits for their readers and writers.
279 func (h *DaemonHub) CloseAll() {
282 for client := range h.clients {
291 // DaemonClient is one connected client. Its events wait in a channel for the
292 // writer, so a slow client does not stop the agent.
293 type DaemonClient struct {
299 // daemonListenSocket listens on the Unix socket at path, with mode 0600. The
300 // caller owns the chat, so a socket file at path is left from a daemon that
301 // ended, and daemonListenSocket removes it.
302 func daemonListenSocket(path string) (net.Listener, error) {
303 err := checkSocketPath(path)
308 err = os.Remove(path)
309 if err != nil && !errors.Is(err, os.ErrNotExist) {
310 return nil, fmt.Errorf("remove old socket: %w", err)
313 listener, err := net.Listen("unix", path)
315 return nil, fmt.Errorf("listen on socket: %w", err)
318 err = os.Chmod(path, 0o600)
320 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
326 // daemonServe runs the loop that start makes and serves the clients of listener
327 // until ctx ends or the loop fails. It closes listener. It runs whatsapp, which
328 // logs its batches and notes in the loop and tells all clients its notices, and
329 // a failure of whatsapp stops the agent. It runs schedules, which log their
330 // runs in the loop, and a failure of schedules stops the agent too. When bot is
331 // not nil, it runs the bot too, and a failure of the bot stops the agent. Each
332 // child runs its own loop and schedules with no client events. A failed child
333 // stops the daemon, and backups lock all loops before they copy data.
334 func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, whatsapp *WhatsApp, schedules *Schedules, start func(notify func(Event)) (*TurnLoop, error), children ...*DaemonAgent) error {
335 ctx, cancel := context.WithCancel(ctx)
340 clients: make(map[*DaemonClient]bool),
343 notify := hub.Broadcast
345 notify = func(event Event) {
351 l, err := start(notify)
353 return errors.Join(err, listener.Close())
356 loops := []*TurnLoop{l}
357 for _, child := range children {
358 loop, err := child.Loop(nil, func(Event) {
361 return errors.Join(fmt.Errorf("start child %q: %w", child.agent.config.Name, err), listener.Close())
364 loops = append(loops, loop)
367 messages, err := openDaemonMessages(loops)
369 return errors.Join(fmt.Errorf("open agent messages: %w", err), listener.Close())
372 hub.snapshot = func(ctx context.Context, snapshot func() error) error {
373 return messages.SnapshotAgents(ctx, snapshot)
376 runtime := &DaemonChildren{
382 l.tools.children = runtime
384 var workers sync.WaitGroup
386 childErrors := make([]error, len(children))
387 for i, child := range children {
393 childErrors[i] = daemonRunChild(ctx, loops[i+1], child.schedules)
394 if childErrors[i] != nil {
395 child.logger.Error("child stopped", "err", childErrors[i])
407 hub.Accept(ctx, listener, l)
410 var whatsappErr error
415 whatsappErr = whatsapp.Run(ctx, l, notify)
420 var schedulesErr error
427 schedulesErr = schedules.Run(ctx, l)
440 botErr = bot.Run(ctx, l, whatsapp)
447 if errors.Is(err, context.Canceled) {
453 err = errors.Join(err, listener.Close())
458 return errors.Join(err, whatsappErr, schedulesErr, botErr, errors.Join(childErrors...), runtime.Close())
461 // daemonRunChild runs a child's turn loop and its schedules until either stops.
462 // Its events stay in its own log.
463 func daemonRunChild(ctx context.Context, loop *TurnLoop, schedules *Schedules) error {
464 ctx, cancel := context.WithCancel(ctx)
467 done := make(chan error, 1)
469 done <- schedules.Run(ctx, loop)
475 if errors.Is(err, context.Canceled) {
481 return errors.Join(err, <-done)
484 // daemonRunRequest runs one request of a client. The answers of a WhatsApp
485 // command go to answer.
486 func daemonRunRequest(l *TurnLoop, whatsapp *WhatsApp, request SocketRequest, answer func(text string)) error {
487 switch request.Type {
489 if request.Text == "" {
490 return errors.New("empty message")
493 _, err := l.Submit(terminalSource, request.Text)
497 if !filepath.IsAbs(request.Path) {
498 return errors.New("use /image PATH [caption]")
501 data, err := imageReadFile(request.Path)
503 return fmt.Errorf("read terminal image: %w", err)
506 name, err := l.agent.Images().Save(data)
508 return fmt.Errorf("store terminal image: %w", err)
511 _, err = l.Submit(terminalSource, imageText([]string{name}, request.Text))
513 return fmt.Errorf("submit terminal image: %w", err)
519 return errors.New("no turn runs")
524 whatsapp.Command(request.Text, answer)
528 found, err := l.StopSubagent(request.Text)
529 if err == nil && !found {
530 err = fmt.Errorf("no subagent %s runs", request.Text)
535 return fmt.Errorf("unknown request %q", request.Type)