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", "version", version, "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 if request.Type == "backup" {
210 size, err = backupData(ctx, filepath.Dir(l.agent.dir), request.Text, h.whatsapp, l.runs.Snapshot)
212 h.Send(client, Event{
214 Text: fmt.Sprintf("%s (%d bytes)", request.Text, size),
218 err = daemonRunRequest(l, h.whatsapp, request, func(text string) {
219 h.Send(client, Event{
228 h.Send(client, Event{
236 // Send gives event to one client, or drops the client when its events do not
238 func (h *DaemonHub) Send(client *DaemonClient, event Event) {
240 defer h.mutex.Unlock()
242 h.send(client, event)
245 // drop removes client and closes its connection.
246 func (h *DaemonHub) drop(client *DaemonClient) {
248 defer h.mutex.Unlock()
253 // send gives event to client. The caller holds the mutex.
254 func (h *DaemonHub) send(client *DaemonClient, event Event) {
255 if !h.clients[client] {
260 case client.events <- event:
266 // remove removes client, closes its connection, and ends its writer. The
267 // caller holds the mutex.
268 func (h *DaemonHub) remove(client *DaemonClient) {
269 delete(h.clients, client)
270 client.once.Do(func() {
273 _ = client.conn.Close()
277 // Broadcast gives event to every client.
278 func (h *DaemonHub) Broadcast(event Event) {
280 defer h.mutex.Unlock()
282 for client := range h.clients {
283 h.send(client, event)
287 // CloseAll drops every client and waits for their readers and writers.
288 func (h *DaemonHub) CloseAll() {
291 for client := range h.clients {
300 // DaemonClient is one connected client. Its events wait in a channel for the
301 // writer, so a slow client does not stop the agent.
302 type DaemonClient struct {
308 // daemonListenSocket listens on the Unix socket at path, with mode 0600. The
309 // caller owns the chat, so a socket file at path is left from a daemon that
310 // ended, and daemonListenSocket removes it.
311 func daemonListenSocket(path string) (net.Listener, error) {
312 err := checkSocketPath(path)
317 err = os.Remove(path)
318 if err != nil && !errors.Is(err, os.ErrNotExist) {
319 return nil, fmt.Errorf("remove old socket: %w", err)
322 listener, err := net.Listen("unix", path)
324 return nil, fmt.Errorf("listen on socket: %w", err)
327 err = os.Chmod(path, 0o600)
329 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
335 // daemonServe runs the loop that start makes and serves the clients of listener
336 // until ctx ends or the loop fails. It closes listener. It runs whatsapp, which
337 // logs its batches and notes in the loop and tells all clients its notices, and
338 // a failure of whatsapp stops the agent. It runs schedules, which log their
339 // runs in the loop, and a failure of schedules stops the agent too. When bot is
340 // not nil, it runs the bot too, and a failure of the bot stops the agent.
341 func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, whatsapp *WhatsApp, schedules *Schedules, start func(notify func(Event)) (*TurnLoop, error)) error {
342 ctx, cancel := context.WithCancel(ctx)
347 clients: make(map[*DaemonClient]bool),
350 notify := hub.Broadcast
352 notify = func(event Event) {
358 l, err := start(notify)
360 return errors.Join(err, listener.Close())
363 var workers sync.WaitGroup
370 hub.Accept(ctx, listener, l)
373 var whatsappErr error
378 whatsappErr = whatsapp.Run(ctx, l, notify)
383 var schedulesErr error
390 schedulesErr = schedules.Run(ctx, l)
403 botErr = bot.Run(ctx, l, whatsapp)
410 if errors.Is(err, context.Canceled) {
416 err = errors.Join(err, listener.Close())
421 return errors.Join(err, whatsappErr, schedulesErr, botErr)
424 // daemonRunRequest runs one request of a client. The answers of a WhatsApp
425 // command go to answer.
426 func daemonRunRequest(l *TurnLoop, whatsapp *WhatsApp, request SocketRequest, answer func(text string)) error {
427 switch request.Type {
429 if request.Text == "" {
430 return errors.New("empty message")
433 _, err := l.Submit(terminalSource, request.Text)
438 return errors.New("no turn runs")
443 whatsapp.Command(request.Text, answer)
447 found, err := l.StopSubagent(request.Text)
448 if err == nil && !found {
449 err = fmt.Errorf("no subagent %s runs", request.Text)
454 return fmt.Errorf("unknown request %q", request.Type)