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 // daemon runs "onechat daemon": it owns the root agent and its files and serves
29 // the clients on the Unix socket in the data directory until ctx ends. When
30 // telegram.json exists, it also runs the Telegram bot. It also keeps a linked
31 // WhatsApp device connected. It holds the lock of the token file, so it is the
32 // only process that refreshes the tokens and opens the WhatsApp session. Its
33 // log lines go to out, through the loggers of daemonLogger.
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()
68 logger := daemonLogger(out, "onechat: ")
69 whatsapp, err := openWhatsApp(ctx, dir, time.Now, daemonLogger(out, "whatsapp: "), whatsappNewClient)
75 err = errors.Join(err, whatsapp.Close())
78 address, auth, err := modelEndpoint(config, dir)
83 agent, err := openAgent(filepath.Join(dir, daemonAgentDirName))
88 client := newModelClient(address, auth, agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl"))
89 memory, err := openMemory(ctx, agent.dir, time.Now, newCompactor(client, agent.Prompt, config.Compactor))
95 err = errors.Join(err, memory.Close())
98 schedules, err := openSchedules(filepath.Join(agent.dir, scheduleFileName), time.Now)
103 subagents := newSubagents(filepath.Join(agent.dir, subagentDirName), time.Now, subagentNameRandom)
105 err = errors.Join(err, subagents.Close())
108 listener, err := daemonListenSocket(socket)
113 linked := "WhatsApp is not linked"
114 if whatsapp.isLinked() {
115 linked = "WhatsApp is linked"
118 logger.Printf("%s is ready: socket %s, model %s at %s effort, commands run in %s, %s, active schedules: %d", agent.config.Name, listener.Addr(), agent.config.Model, agent.config.Effort, agent.config.Workdir, linked, schedules.Len())
120 var telegram *TelegramBot
122 telegram = newTelegramBot(newTelegramAPI(telegramAPIURL, botSettings.Token), botSettings.Owner, filepath.Join(agent.dir, telegramOffsetFileName), daemonLogger(out, "telegram: "))
123 logger.Print("the Telegram bot waits for messages of its owner")
126 return daemonServe(ctx, listener, telegram, whatsapp, schedules, func(notify func(Event)) (*TurnLoop, error) {
127 return newTurnLoop(agent, memory, subagents, whatsapp, schedules, client, time.Now, notify)
131 // DaemonHub holds the connected clients and sends each event to all of them. It
132 // runs the WhatsApp commands of the clients on whatsapp.
133 type DaemonHub struct {
137 clients map[*DaemonClient]bool
138 workers sync.WaitGroup
141 // Accept serves each client of listener until the listener closes. A new
142 // client gets a ready event with the name of the agent, and a busy event when a
144 func (h *DaemonHub) Accept(ctx context.Context, listener net.Listener, l *TurnLoop) {
146 conn, err := listener.Accept()
151 client := &DaemonClient{
153 events: make(chan Event, daemonClientEvents),
157 h.clients[client] = true
162 go h.read(ctx, client, l)
164 h.Send(client, Event{
166 Text: l.agent.config.Name,
170 h.Send(client, Event{
177 // write sends the events of client as JSON lines until its channel closes.
178 func (h *DaemonHub) write(client *DaemonClient) {
179 defer h.workers.Done()
181 encoder := json.NewEncoder(client.conn)
182 for event := range client.events {
183 err := encoder.Encode(event)
190 // read runs the requests of client until it closes its connection.
191 func (h *DaemonHub) read(ctx context.Context, client *DaemonClient, l *TurnLoop) {
192 defer h.workers.Done()
195 scanner := bufio.NewScanner(client.conn)
196 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
197 for ctx.Err() == nil && scanner.Scan() {
198 var request SocketRequest
199 err := json.Unmarshal(scanner.Bytes(), &request)
201 err = daemonRunRequest(l, h.whatsapp, request, func(text string) {
202 h.Send(client, Event{
210 h.Send(client, Event{
218 // Send gives event to one client, or drops the client when its events do not
220 func (h *DaemonHub) Send(client *DaemonClient, event Event) {
222 defer h.mutex.Unlock()
224 h.send(client, event)
227 // drop removes client and closes its connection.
228 func (h *DaemonHub) drop(client *DaemonClient) {
230 defer h.mutex.Unlock()
235 // send gives event to client. The caller holds the mutex.
236 func (h *DaemonHub) send(client *DaemonClient, event Event) {
237 if !h.clients[client] {
242 case client.events <- event:
248 // remove removes client, closes its connection, and ends its writer. The
249 // caller holds the mutex.
250 func (h *DaemonHub) remove(client *DaemonClient) {
251 delete(h.clients, client)
252 client.once.Do(func() {
254 _ = client.conn.Close()
258 // Broadcast gives event to every client.
259 func (h *DaemonHub) Broadcast(event Event) {
261 defer h.mutex.Unlock()
263 for client := range h.clients {
264 h.send(client, event)
268 // CloseAll drops every client and waits for their readers and writers.
269 func (h *DaemonHub) CloseAll() {
271 for client := range h.clients {
279 // DaemonClient is one connected client. Its events wait in a channel for the
280 // writer, so a slow client does not stop the agent.
281 type DaemonClient struct {
287 // daemonListenSocket listens on the Unix socket at path, with mode 0600. The
288 // caller owns the chat, so a socket file at path is left from a daemon that
289 // ended, and daemonListenSocket removes it.
290 func daemonListenSocket(path string) (net.Listener, error) {
291 err := checkSocketPath(path)
296 err = os.Remove(path)
297 if err != nil && !errors.Is(err, os.ErrNotExist) {
298 return nil, fmt.Errorf("remove old socket: %w", err)
301 listener, err := net.Listen("unix", path)
303 return nil, fmt.Errorf("listen on socket: %w", err)
306 err = os.Chmod(path, 0o600)
308 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
314 // daemonServe runs the loop that start makes and serves the clients of listener
315 // until ctx ends or the loop fails. It closes listener. It runs whatsapp, which
316 // logs its batches and notes in the loop and tells all clients its notices, and
317 // a failure of whatsapp stops the agent. It runs schedules, which log their
318 // runs in the loop, and a failure of schedules stops the agent too. When bot is
319 // not nil, it runs the bot too, and a failure of the bot stops the agent.
320 func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, whatsapp *WhatsApp, schedules *Schedules, start func(notify func(Event)) (*TurnLoop, error)) error {
321 ctx, cancel := context.WithCancel(ctx)
326 clients: make(map[*DaemonClient]bool),
329 notify := hub.Broadcast
331 notify = func(event Event) {
337 l, err := start(notify)
339 return errors.Join(err, listener.Close())
342 var workers sync.WaitGroup
347 hub.Accept(ctx, listener, l)
350 var whatsappErr error
354 whatsappErr = whatsapp.Run(ctx, l, notify)
358 var schedulesErr error
363 schedulesErr = schedules.Run(ctx, l)
373 botErr = bot.Run(ctx, l, whatsapp)
379 if errors.Is(err, context.Canceled) {
384 err = errors.Join(err, listener.Close())
388 return errors.Join(err, whatsappErr, schedulesErr, botErr)
391 // daemonRunRequest runs one request of a client. The answers of a WhatsApp
392 // command go to answer.
393 func daemonRunRequest(l *TurnLoop, whatsapp *WhatsApp, request SocketRequest, answer func(text string)) error {
394 switch request.Type {
396 if request.Text == "" {
397 return errors.New("empty message")
400 _, err := l.Submit(terminalSource, request.Text)
405 return errors.New("no turn runs")
410 whatsapp.Command(request.Text, answer)
414 found, err := l.StopSubagent(request.Text)
415 if err == nil && !found {
416 err = fmt.Errorf("no subagent %s runs", request.Text)
421 return fmt.Errorf("unknown request %q", request.Type)
425 // daemonLogger returns the logger of the part of the daemon with prefix, such
426 // as "telegram: ", on out. The journal adds the time to each line and sets
427 // JOURNAL_STREAM for a service, so then the lines have no time stamp. Otherwise
428 // each line has the standard time stamp.
429 func daemonLogger(out io.Writer, prefix string) *log.Logger {
430 if os.Getenv("JOURNAL_STREAM") != "" {
431 return log.New(out, prefix, 0)
434 return log.New(out, prefix, log.LstdFlags)
437 // durationText returns d for a log line: rounded to the second, or to the
438 // millisecond when it is shorter than a second.
439 func durationText(d time.Duration) string {
441 return d.Round(time.Millisecond).String()
444 return d.Round(time.Second).String()