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 holds the lock of the
31 // token file, so it is the only process that refreshes the tokens.
32 func daemon(ctx context.Context, out io.Writer) (err error) {
38 // Check the socket path before the daemon writes a file, so that a data
39 // directory with a long path stays empty.
40 socket := filepath.Join(dir, socketFileName)
41 err = checkSocketPath(socket)
46 config, err := loadConfig(dir)
51 botSettings, hasBot, err := loadTelegramConfig(dir)
56 tokens, err := lockTokens(dir)
62 err = errors.Join(err, tokens.Close())
65 address, auth, err := modelEndpoint(config, dir)
70 agent, err := openAgent(filepath.Join(dir, daemonAgentDirName))
75 client := newModelClient(address, auth, agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl"))
76 memory, err := openMemory(ctx, agent.dir, time.Now, newCompactor(client, agent.Prompt, config.Compactor))
82 err = errors.Join(err, memory.Close())
85 listener, err := daemonListenSocket(socket)
90 _, 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)
92 return errors.Join(err, listener.Close())
95 var telegram *TelegramBot
97 telegram = newTelegramBot(newTelegramAPI(telegramAPIURL, botSettings.Token), botSettings.Owner, filepath.Join(agent.dir, telegramOffsetFileName), log.New(out, "telegram: ", log.LstdFlags))
98 _, err = fmt.Fprintln(out, "onechat: the Telegram bot waits for messages of its owner")
100 return errors.Join(err, listener.Close())
104 return daemonServe(ctx, listener, telegram, func(notify func(Event)) (*loop, error) {
105 return newLoop(agent, memory, client, time.Now, notify)
109 // DaemonHub holds the connected clients and sends each event to all of them.
110 type DaemonHub struct {
112 clients map[*DaemonClient]bool
113 workers sync.WaitGroup
116 // Accept serves each client of listener until the listener closes. A new
117 // client gets a ready event with the name of the agent, and a busy event when a
119 func (h *DaemonHub) Accept(ctx context.Context, listener net.Listener, l *loop) {
121 conn, err := listener.Accept()
126 client := &DaemonClient{
128 events: make(chan Event, daemonClientEvents),
132 h.clients[client] = true
137 go h.read(ctx, client, l)
139 h.Send(client, Event{
141 Text: l.agent.config.Name,
145 h.Send(client, Event{
152 // write sends the events of client as JSON lines until its channel closes.
153 func (h *DaemonHub) write(client *DaemonClient) {
154 defer h.workers.Done()
156 encoder := json.NewEncoder(client.conn)
157 for event := range client.events {
158 err := encoder.Encode(event)
165 // read runs the requests of client until it closes its connection.
166 func (h *DaemonHub) read(ctx context.Context, client *DaemonClient, l *loop) {
167 defer h.workers.Done()
170 scanner := bufio.NewScanner(client.conn)
171 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
172 for ctx.Err() == nil && scanner.Scan() {
173 var request SocketRequest
174 err := json.Unmarshal(scanner.Bytes(), &request)
176 err = daemonRunRequest(l, request)
180 h.Send(client, Event{
188 // Send gives event to one client, or drops the client when its events do not
190 func (h *DaemonHub) Send(client *DaemonClient, event Event) {
192 defer h.mutex.Unlock()
194 h.send(client, event)
197 // drop removes client and closes its connection.
198 func (h *DaemonHub) drop(client *DaemonClient) {
200 defer h.mutex.Unlock()
205 // send gives event to client. The caller holds the mutex.
206 func (h *DaemonHub) send(client *DaemonClient, event Event) {
207 if !h.clients[client] {
212 case client.events <- event:
218 // remove removes client, closes its connection, and ends its writer. The
219 // caller holds the mutex.
220 func (h *DaemonHub) remove(client *DaemonClient) {
221 delete(h.clients, client)
222 client.once.Do(func() {
224 _ = client.conn.Close()
228 // Broadcast gives event to every client.
229 func (h *DaemonHub) Broadcast(event Event) {
231 defer h.mutex.Unlock()
233 for client := range h.clients {
234 h.send(client, event)
238 // CloseAll drops every client and waits for their readers and writers.
239 func (h *DaemonHub) CloseAll() {
241 for client := range h.clients {
249 // DaemonClient is one connected client. Its events wait in a channel for the
250 // writer, so a slow client does not stop the agent.
251 type DaemonClient struct {
257 // daemonListenSocket listens on the Unix socket at path, with mode 0600. The
258 // caller owns the chat, so a socket file at path is left from a daemon that
259 // ended, and daemonListenSocket removes it.
260 func daemonListenSocket(path string) (net.Listener, error) {
261 err := checkSocketPath(path)
266 err = os.Remove(path)
267 if err != nil && !errors.Is(err, os.ErrNotExist) {
268 return nil, fmt.Errorf("remove old socket: %w", err)
271 listener, err := net.Listen("unix", path)
273 return nil, fmt.Errorf("listen on socket: %w", err)
276 err = os.Chmod(path, 0o600)
278 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
284 // daemonServe runs the loop that start makes and serves the clients of listener
285 // until ctx ends or the loop fails. It closes listener. When bot is not nil, it
286 // runs the bot too, and a failure of the bot stops the agent.
287 func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, start func(notify func(Event)) (*loop, error)) error {
288 ctx, cancel := context.WithCancel(ctx)
292 clients: make(map[*DaemonClient]bool),
295 notify := hub.Broadcast
297 notify = func(event Event) {
303 l, err := start(notify)
305 return errors.Join(err, listener.Close())
308 var workers sync.WaitGroup
313 hub.Accept(ctx, listener, l)
322 botErr = bot.Run(ctx, l)
328 if errors.Is(err, context.Canceled) {
333 err = errors.Join(err, listener.Close())
337 return errors.Join(err, botErr)
340 // daemonRunRequest runs one request of a client.
341 func daemonRunRequest(l *loop, request SocketRequest) error {
342 switch request.Type {
344 if request.Text == "" {
345 return errors.New("empty message")
348 _, err := l.Submit(terminalSource, request.Text)
353 return errors.New("no turn runs")
358 return fmt.Errorf("unknown request %q", request.Type)