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 subagents := newSubagents(filepath.Join(agent.dir, subagentDirName), time.Now, subagentNameRandom)
87 err = errors.Join(err, subagents.Close())
90 listener, err := daemonListenSocket(socket)
95 _, 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)
97 return errors.Join(err, listener.Close())
100 var telegram *TelegramBot
102 telegram = newTelegramBot(newTelegramAPI(telegramAPIURL, botSettings.Token), botSettings.Owner, filepath.Join(agent.dir, telegramOffsetFileName), log.New(out, "telegram: ", log.LstdFlags))
103 _, err = fmt.Fprintln(out, "onechat: the Telegram bot waits for messages of its owner")
105 return errors.Join(err, listener.Close())
109 return daemonServe(ctx, listener, telegram, func(notify func(Event)) (*TurnLoop, error) {
110 return newTurnLoop(agent, memory, subagents, client, time.Now, notify)
114 // DaemonHub holds the connected clients and sends each event to all of them.
115 type DaemonHub struct {
117 clients map[*DaemonClient]bool
118 workers sync.WaitGroup
121 // Accept serves each client of listener until the listener closes. A new
122 // client gets a ready event with the name of the agent, and a busy event when a
124 func (h *DaemonHub) Accept(ctx context.Context, listener net.Listener, l *TurnLoop) {
126 conn, err := listener.Accept()
131 client := &DaemonClient{
133 events: make(chan Event, daemonClientEvents),
137 h.clients[client] = true
142 go h.read(ctx, client, l)
144 h.Send(client, Event{
146 Text: l.agent.config.Name,
150 h.Send(client, Event{
157 // write sends the events of client as JSON lines until its channel closes.
158 func (h *DaemonHub) write(client *DaemonClient) {
159 defer h.workers.Done()
161 encoder := json.NewEncoder(client.conn)
162 for event := range client.events {
163 err := encoder.Encode(event)
170 // read runs the requests of client until it closes its connection.
171 func (h *DaemonHub) read(ctx context.Context, client *DaemonClient, l *TurnLoop) {
172 defer h.workers.Done()
175 scanner := bufio.NewScanner(client.conn)
176 scanner.Buffer(make([]byte, 64*1024), socketRequestBytes)
177 for ctx.Err() == nil && scanner.Scan() {
178 var request SocketRequest
179 err := json.Unmarshal(scanner.Bytes(), &request)
181 err = daemonRunRequest(l, request)
185 h.Send(client, Event{
193 // Send gives event to one client, or drops the client when its events do not
195 func (h *DaemonHub) Send(client *DaemonClient, event Event) {
197 defer h.mutex.Unlock()
199 h.send(client, event)
202 // drop removes client and closes its connection.
203 func (h *DaemonHub) drop(client *DaemonClient) {
205 defer h.mutex.Unlock()
210 // send gives event to client. The caller holds the mutex.
211 func (h *DaemonHub) send(client *DaemonClient, event Event) {
212 if !h.clients[client] {
217 case client.events <- event:
223 // remove removes client, closes its connection, and ends its writer. The
224 // caller holds the mutex.
225 func (h *DaemonHub) remove(client *DaemonClient) {
226 delete(h.clients, client)
227 client.once.Do(func() {
229 _ = client.conn.Close()
233 // Broadcast gives event to every client.
234 func (h *DaemonHub) Broadcast(event Event) {
236 defer h.mutex.Unlock()
238 for client := range h.clients {
239 h.send(client, event)
243 // CloseAll drops every client and waits for their readers and writers.
244 func (h *DaemonHub) CloseAll() {
246 for client := range h.clients {
254 // DaemonClient is one connected client. Its events wait in a channel for the
255 // writer, so a slow client does not stop the agent.
256 type DaemonClient struct {
262 // daemonListenSocket listens on the Unix socket at path, with mode 0600. The
263 // caller owns the chat, so a socket file at path is left from a daemon that
264 // ended, and daemonListenSocket removes it.
265 func daemonListenSocket(path string) (net.Listener, error) {
266 err := checkSocketPath(path)
271 err = os.Remove(path)
272 if err != nil && !errors.Is(err, os.ErrNotExist) {
273 return nil, fmt.Errorf("remove old socket: %w", err)
276 listener, err := net.Listen("unix", path)
278 return nil, fmt.Errorf("listen on socket: %w", err)
281 err = os.Chmod(path, 0o600)
283 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
289 // daemonServe runs the loop that start makes and serves the clients of listener
290 // until ctx ends or the loop fails. It closes listener. When bot is not nil, it
291 // runs the bot too, and a failure of the bot stops the agent.
292 func daemonServe(ctx context.Context, listener net.Listener, bot *TelegramBot, start func(notify func(Event)) (*TurnLoop, error)) error {
293 ctx, cancel := context.WithCancel(ctx)
297 clients: make(map[*DaemonClient]bool),
300 notify := hub.Broadcast
302 notify = func(event Event) {
308 l, err := start(notify)
310 return errors.Join(err, listener.Close())
313 var workers sync.WaitGroup
318 hub.Accept(ctx, listener, l)
327 botErr = bot.Run(ctx, l)
333 if errors.Is(err, context.Canceled) {
338 err = errors.Join(err, listener.Close())
342 return errors.Join(err, botErr)
345 // daemonRunRequest runs one request of a client.
346 func daemonRunRequest(l *TurnLoop, request SocketRequest) error {
347 switch request.Type {
349 if request.Text == "" {
350 return errors.New("empty message")
353 _, err := l.Submit(terminalSource, request.Text)
358 return errors.New("no turn runs")
363 return fmt.Errorf("unknown request %q", request.Type)