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.
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 whatsapp, err := openWhatsApp(ctx, dir, time.Now, log.New(out, "whatsapp: ", log.LstdFlags), whatsappNewClient)
72 err = errors.Join(err, whatsapp.Close())
75 address, auth, err := modelEndpoint(config, dir)
80 agent, err := openAgent(filepath.Join(dir, daemonAgentDirName))
85 client := newModelClient(address, auth, agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl"))
86 memory, err := openMemory(ctx, agent.dir, time.Now, newCompactor(client, agent.Prompt, config.Compactor))
92 err = errors.Join(err, memory.Close())
95 subagents := newSubagents(filepath.Join(agent.dir, subagentDirName), time.Now, subagentNameRandom)
97 err = errors.Join(err, subagents.Close())
100 listener, err := daemonListenSocket(socket)
105 _, err = fmt.Fprintf(out, "onechat: %s on %s, %s at %s effort, in %s\n", agent.config.Name, listener.Addr(), agent.config.Model, agent.config.Effort, agent.config.Workdir)
107 return errors.Join(err, listener.Close())
110 var telegram *TelegramBot
112 telegram = newTelegramBot(newTelegramAPI(telegramAPIURL, botSettings.Token), botSettings.Owner, filepath.Join(agent.dir, telegramOffsetFileName), log.New(out, "telegram: ", log.LstdFlags))
113 _, err = fmt.Fprintln(out, "onechat: the Telegram bot waits for messages of its owner")
115 return errors.Join(err, listener.Close())
119 return daemonServe(ctx, listener, telegram, whatsapp, func(notify func(Event)) (*TurnLoop, error) {
120 return newTurnLoop(agent, memory, subagents, client, time.Now, notify)
124 // DaemonHub holds the connected clients and sends each event to all of them. It
125 // runs the WhatsApp commands of the clients on whatsapp.
126 type DaemonHub struct {
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),
150 h.clients[client] = true
155 go h.read(ctx, client, l)
157 h.Send(client, Event{
159 Text: l.agent.config.Name,
163 h.Send(client, Event{
170 // write sends the events of client as JSON lines until its channel closes.
171 func (h *DaemonHub) write(client *DaemonClient) {
172 defer h.workers.Done()
174 encoder := json.NewEncoder(client.conn)
175 for event := range client.events {
176 err := encoder.Encode(event)
183 // read runs the requests of client until it closes its connection.
184 func (h *DaemonHub) read(ctx context.Context, client *DaemonClient, l *TurnLoop) {
185 defer h.workers.Done()
188 scanner := bufio.NewScanner(client.conn)
189 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
190 for ctx.Err() == nil && scanner.Scan() {
191 var request SocketRequest
192 err := json.Unmarshal(scanner.Bytes(), &request)
194 err = daemonRunRequest(l, h.whatsapp, request, func(text string) {
195 h.Send(client, Event{
203 h.Send(client, Event{
211 // Send gives event to one client, or drops the client when its events do not
213 func (h *DaemonHub) Send(client *DaemonClient, event Event) {
215 defer h.mutex.Unlock()
217 h.send(client, event)
220 // drop removes client and closes its connection.
221 func (h *DaemonHub) drop(client *DaemonClient) {
223 defer h.mutex.Unlock()
228 // send gives event to client. The caller holds the mutex.
229 func (h *DaemonHub) send(client *DaemonClient, event Event) {
230 if !h.clients[client] {
235 case client.events <- event:
241 // remove removes client, closes its connection, and ends its writer. The
242 // caller holds the mutex.
243 func (h *DaemonHub) remove(client *DaemonClient) {
244 delete(h.clients, client)
245 client.once.Do(func() {
247 _ = client.conn.Close()
251 // Broadcast gives event to every client.
252 func (h *DaemonHub) Broadcast(event Event) {
254 defer h.mutex.Unlock()
256 for client := range h.clients {
257 h.send(client, event)
261 // CloseAll drops every client and waits for their readers and writers.
262 func (h *DaemonHub) CloseAll() {
264 for client := range h.clients {
272 // DaemonClient is one connected client. Its events wait in a channel for the
273 // writer, so a slow client does not stop the agent.
274 type DaemonClient struct {
280 // daemonListenSocket listens on the Unix socket at path, with mode 0600. The
281 // caller owns the chat, so a socket file at path is left from a daemon that
282 // ended, and daemonListenSocket removes it.
283 func daemonListenSocket(path string) (net.Listener, error) {
284 err := checkSocketPath(path)
289 err = os.Remove(path)
290 if err != nil && !errors.Is(err, os.ErrNotExist) {
291 return nil, fmt.Errorf("remove old socket: %w", err)
294 listener, err := net.Listen("unix", path)
296 return nil, fmt.Errorf("listen on socket: %w", err)
299 err = os.Chmod(path, 0o600)
301 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
307 // daemonServe runs the loop that start makes and serves the clients of listener
308 // until ctx ends or the loop fails. It closes listener. It keeps whatsapp
309 // connected. When bot is not nil, it runs the bot too, and a failure of the bot
311 func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, whatsapp *WhatsApp, start func(notify func(Event)) (*TurnLoop, error)) error {
312 ctx, cancel := context.WithCancel(ctx)
317 clients: make(map[*DaemonClient]bool),
320 notify := hub.Broadcast
322 notify = func(event Event) {
328 l, err := start(notify)
330 return errors.Join(err, listener.Close())
333 var workers sync.WaitGroup
338 hub.Accept(ctx, listener, l)
353 botErr = bot.Run(ctx, l, whatsapp)
359 if errors.Is(err, context.Canceled) {
364 err = errors.Join(err, listener.Close())
368 return errors.Join(err, botErr)
371 // daemonRunRequest runs one request of a client. The answers of a WhatsApp
372 // command go to answer.
373 func daemonRunRequest(l *TurnLoop, whatsapp *WhatsApp, request SocketRequest, answer func(text string)) error {
374 switch request.Type {
376 if request.Text == "" {
377 return errors.New("empty message")
380 _, err := l.Submit(terminalSource, request.Text)
385 return errors.New("no turn runs")
390 whatsapp.Command(request.Text, answer)
394 found, err := l.StopSubagent(request.Text)
395 if err == nil && !found {
396 err = fmt.Errorf("no subagent %s runs", request.Text)
401 return fmt.Errorf("unknown request %q", request.Type)