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 agent and its files and serves
28 // the clients on the Unix socket in the data directory until ctx ends. When
29 // telegram.json exists, it also runs the Telegram bot. It also keeps a linked
30 // WhatsApp device connected. It holds the lock of the token file, so it is the
31 // only process that refreshes the tokens and opens the WhatsApp session. Its
32 // log lines go to out, through the loggers of daemonLogger.
33 func daemon(ctx context.Context, out io.Writer) (err error) {
39 // Check the socket path before the daemon writes a file, so that a data
40 // directory with a long path stays empty.
41 socket := filepath.Join(dir, socketFileName)
42 err = checkSocketPath(socket)
47 config, err := loadConfig(dir)
52 botSettings, hasBot, err := loadTelegramConfig(dir)
57 tokens, err := lockTokens(dir)
63 err = errors.Join(err, tokens.Close())
66 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), logger)
95 err = errors.Join(err, memory.Close())
98 schedules, err := openSchedules(filepath.Join(agent.dir, scheduleFileName), time.Now, logger)
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 := "not linked"
114 if whatsapp.isLinked() {
118 logger.Info("ready", "socket", listener.Addr(), "model", agent.config.Model, "effort", agent.config.Effort, "workdir", agent.config.Workdir, "whatsapp", linked, "schedules", schedules.Len())
120 var telegram *TelegramBot
123 telegram = newTelegramBot(newTelegramAPI(telegramAPIURL, botSettings.Token), botSettings.Owner, filepath.Join(agent.dir, telegramOffsetFileName), daemonLogger(out, "telegram: "))
125 logger.Info("Telegram bot started")
128 return daemonServe(ctx, listener, telegram, whatsapp, schedules, func(notify func(Event)) (*TurnLoop, error) {
129 return newTurnLoop(agent, memory, subagents, whatsapp, schedules, client, time.Now, logger, notify)
133 // DaemonHub holds the connected clients and sends each event to all of them. It
134 // runs the WhatsApp commands of the clients on whatsapp.
135 type DaemonHub struct {
139 clients map[*DaemonClient]bool
140 workers sync.WaitGroup
143 // Accept serves each client of listener until the listener closes. A new
144 // client gets a ready event with the name of the agent, and a busy event when a
146 func (h *DaemonHub) Accept(ctx context.Context, listener net.Listener, l *TurnLoop) {
148 conn, err := listener.Accept()
153 client := &DaemonClient{
155 events: make(chan Event, daemonClientEvents),
160 h.clients[client] = true
166 go h.read(ctx, client, l)
168 h.Send(client, Event{
170 Text: l.agent.config.Name,
174 h.Send(client, Event{
181 // write sends the events of client as JSON lines until its channel closes.
182 func (h *DaemonHub) write(client *DaemonClient) {
183 defer h.workers.Done()
185 encoder := json.NewEncoder(client.conn)
186 for event := range client.events {
187 err := encoder.Encode(event)
194 // read runs the requests of client until it closes its connection.
195 func (h *DaemonHub) read(ctx context.Context, client *DaemonClient, l *TurnLoop) {
196 defer h.workers.Done()
199 scanner := bufio.NewScanner(client.conn)
200 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
202 for ctx.Err() == nil && scanner.Scan() {
203 var request SocketRequest
205 err := json.Unmarshal(scanner.Bytes(), &request)
207 err = daemonRunRequest(l, h.whatsapp, request, func(text string) {
208 h.Send(client, Event{
216 h.Send(client, Event{
224 // Send gives event to one client, or drops the client when its events do not
226 func (h *DaemonHub) Send(client *DaemonClient, event Event) {
228 defer h.mutex.Unlock()
230 h.send(client, event)
233 // drop removes client and closes its connection.
234 func (h *DaemonHub) drop(client *DaemonClient) {
236 defer h.mutex.Unlock()
241 // send gives event to client. The caller holds the mutex.
242 func (h *DaemonHub) send(client *DaemonClient, event Event) {
243 if !h.clients[client] {
248 case client.events <- event:
254 // remove removes client, closes its connection, and ends its writer. The
255 // caller holds the mutex.
256 func (h *DaemonHub) remove(client *DaemonClient) {
257 delete(h.clients, client)
258 client.once.Do(func() {
261 _ = client.conn.Close()
265 // Broadcast gives event to every client.
266 func (h *DaemonHub) Broadcast(event Event) {
268 defer h.mutex.Unlock()
270 for client := range h.clients {
271 h.send(client, event)
275 // CloseAll drops every client and waits for their readers and writers.
276 func (h *DaemonHub) CloseAll() {
279 for client := range h.clients {
288 // DaemonClient is one connected client. Its events wait in a channel for the
289 // writer, so a slow client does not stop the agent.
290 type DaemonClient struct {
296 // daemonListenSocket listens on the Unix socket at path, with mode 0600. The
297 // caller owns the chat, so a socket file at path is left from a daemon that
298 // ended, and daemonListenSocket removes it.
299 func daemonListenSocket(path string) (net.Listener, error) {
300 err := checkSocketPath(path)
305 err = os.Remove(path)
306 if err != nil && !errors.Is(err, os.ErrNotExist) {
307 return nil, fmt.Errorf("remove old socket: %w", err)
310 listener, err := net.Listen("unix", path)
312 return nil, fmt.Errorf("listen on socket: %w", err)
315 err = os.Chmod(path, 0o600)
317 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
323 // daemonServe runs the loop that start makes and serves the clients of listener
324 // until ctx ends or the loop fails. It closes listener. It runs whatsapp, which
325 // logs its batches and notes in the loop and tells all clients its notices, and
326 // a failure of whatsapp stops the agent. It runs schedules, which log their
327 // runs in the loop, and a failure of schedules stops the agent too. When bot is
328 // not nil, it runs the bot too, and a failure of the bot stops the agent.
329 func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, whatsapp *WhatsApp, schedules *Schedules, start func(notify func(Event)) (*TurnLoop, error)) error {
330 ctx, cancel := context.WithCancel(ctx)
335 clients: make(map[*DaemonClient]bool),
338 notify := hub.Broadcast
340 notify = func(event Event) {
346 l, err := start(notify)
348 return errors.Join(err, listener.Close())
351 var workers sync.WaitGroup
358 hub.Accept(ctx, listener, l)
361 var whatsappErr error
366 whatsappErr = whatsapp.Run(ctx, l, notify)
371 var schedulesErr error
378 schedulesErr = schedules.Run(ctx, l)
391 botErr = bot.Run(ctx, l, whatsapp)
398 if errors.Is(err, context.Canceled) {
404 err = errors.Join(err, listener.Close())
409 return errors.Join(err, whatsappErr, schedulesErr, botErr)
412 // daemonRunRequest runs one request of a client. The answers of a WhatsApp
413 // command go to answer.
414 func daemonRunRequest(l *TurnLoop, whatsapp *WhatsApp, request SocketRequest, answer func(text string)) error {
415 switch request.Type {
417 if request.Text == "" {
418 return errors.New("empty message")
421 _, err := l.Submit(terminalSource, request.Text)
426 return errors.New("no turn runs")
431 whatsapp.Command(request.Text, answer)
435 found, err := l.StopSubagent(request.Text)
436 if err == nil && !found {
437 err = fmt.Errorf("no subagent %s runs", request.Text)
442 return fmt.Errorf("unknown request %q", request.Type)