19 // agentDirName is the directory of the root agent in the data directory.
20 agentDirName = "agent"
22 // socketFileName is the Unix socket of the daemon in the data directory.
23 socketFileName = "onechat.sock"
25 // tokenLockFileName is the lock file of the token file in the data
27 tokenLockFileName = "auth.lock"
29 // requestBytes is the most bytes of one request line of a client.
30 requestBytes = 16 << 20
32 // clientEvents is the number of events that can wait for a slow client
33 // before the daemon drops it.
36 // socketPathBytes is the longest path of a Unix socket on Linux.
39 // terminalSource is the source of the user messages from the clients of
41 terminalSource = "terminal"
44 // errTokensInUse tells that another onechat process uses the token file.
45 var errTokensInUse = errors.New("another onechat process uses the token file, such as the daemon")
47 // clientRequest is one line from a client: "send" with the text of a user
48 // message, or "interrupt".
49 type clientRequest struct {
50 Type string `json:"type"`
51 Text string `json:"text,omitempty"`
54 // daemon runs "onechat daemon": it owns the root agent and its files and serves
55 // the clients on the Unix socket in the data directory until ctx ends. When
56 // telegram.json exists, it also runs the Telegram bot. It holds the lock of the
57 // token file, so it is the only process that refreshes the tokens.
58 func daemon(ctx context.Context, out io.Writer) (err error) {
64 // Check the socket path before the daemon writes a file, so that a data
65 // directory with a long path stays empty.
66 socket := filepath.Join(dir, socketFileName)
67 err = checkSocketPath(socket)
72 config, err := loadConfig(dir)
77 botSettings, hasBot, err := loadTelegramConfig(dir)
82 tokens, err := lockTokens(dir)
88 err = errors.Join(err, tokens.Close())
91 address, auth, err := modelEndpoint(config, dir)
96 agent, err := openAgent(filepath.Join(dir, agentDirName))
101 client := newClient(address, auth, agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl"))
102 memory, err := openMemory(ctx, agent.dir, time.Now, newCompactor(client, agent.Prompt, config.Compactor))
108 err = errors.Join(err, memory.Close())
111 listener, err := listenSocket(socket)
116 _, 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)
118 return errors.Join(err, listener.Close())
121 var telegram *TelegramBot
123 telegram = newTelegramBot(newTelegramAPI(telegramAPIURL, botSettings.Token), botSettings.Owner, filepath.Join(agent.dir, telegramOffsetFileName), log.New(out, "telegram: ", log.LstdFlags))
124 _, err = fmt.Fprintln(out, "onechat: the Telegram bot waits for messages of its owner")
126 return errors.Join(err, listener.Close())
130 return serveAgent(ctx, listener, telegram, func(notify func(Event)) (*loop, error) {
131 return newLoop(agent, memory, client, time.Now, notify)
135 // serveAgent runs the loop that start makes and serves the clients of
136 // listener until ctx ends or the loop fails. It closes listener. When bot is
137 // not nil, it runs the bot too, and a failure of the bot stops the agent.
138 func serveAgent(ctx context.Context, listener net.Listener, bot *TelegramBot, start func(notify func(Event)) (*loop, error)) error {
139 ctx, cancel := context.WithCancel(ctx)
143 clients: make(map[*hubClient]bool),
146 notify := hub.Broadcast
148 notify = func(event Event) {
154 l, err := start(notify)
156 return errors.Join(err, listener.Close())
159 var workers sync.WaitGroup
164 hub.Accept(ctx, listener, l)
173 botErr = bot.Run(ctx, l)
179 if errors.Is(err, context.Canceled) {
184 err = errors.Join(err, listener.Close())
188 return errors.Join(err, botErr)
191 // hub holds the connected clients and sends each event to all of them.
194 clients map[*hubClient]bool
195 workers sync.WaitGroup
198 // hubClient is one connected client. Its events wait in a channel for the
199 // writer, so a slow client does not stop the agent.
200 type hubClient struct {
206 // Accept serves each client of listener until the listener closes. A new
207 // client gets a ready event with the name of the agent, and a busy event when a
209 func (h *hub) Accept(ctx context.Context, listener net.Listener, l *loop) {
211 conn, err := listener.Accept()
216 client := &hubClient{
218 events: make(chan Event, clientEvents),
222 h.clients[client] = true
227 go h.read(ctx, client, l)
229 h.Send(client, Event{
231 Text: l.agent.config.Name,
235 h.Send(client, Event{
242 // write sends the events of client as JSON lines until its channel closes.
243 func (h *hub) write(client *hubClient) {
244 defer h.workers.Done()
246 encoder := json.NewEncoder(client.conn)
247 for event := range client.events {
248 err := encoder.Encode(event)
255 // read runs the requests of client until it closes its connection.
256 func (h *hub) read(ctx context.Context, client *hubClient, l *loop) {
257 defer h.workers.Done()
260 scanner := bufio.NewScanner(client.conn)
261 scanner.Buffer(make([]byte, 64*1024), requestBytes)
262 for ctx.Err() == nil && scanner.Scan() {
263 var request clientRequest
264 err := json.Unmarshal(scanner.Bytes(), &request)
266 err = runRequest(l, request)
270 h.Send(client, Event{
278 // Send gives event to one client, or drops the client when its events do not
280 func (h *hub) Send(client *hubClient, event Event) {
282 defer h.mutex.Unlock()
284 h.send(client, event)
287 // send gives event to client. The caller holds the mutex.
288 func (h *hub) send(client *hubClient, event Event) {
289 if !h.clients[client] {
294 case client.events <- event:
300 // Broadcast gives event to every client.
301 func (h *hub) Broadcast(event Event) {
303 defer h.mutex.Unlock()
305 for client := range h.clients {
306 h.send(client, event)
310 // drop removes client and closes its connection.
311 func (h *hub) drop(client *hubClient) {
313 defer h.mutex.Unlock()
318 // remove removes client, closes its connection, and ends its writer. The
319 // caller holds the mutex.
320 func (h *hub) remove(client *hubClient) {
321 delete(h.clients, client)
322 client.once.Do(func() {
324 _ = client.conn.Close()
328 // CloseAll drops every client and waits for their readers and writers.
329 func (h *hub) CloseAll() {
331 for client := range h.clients {
339 // runRequest runs one request of a client.
340 func runRequest(l *loop, request clientRequest) error {
341 switch request.Type {
343 if request.Text == "" {
344 return errors.New("empty message")
347 _, err := l.Submit(terminalSource, request.Text)
352 return errors.New("no turn runs")
357 return fmt.Errorf("unknown request %q", request.Type)
361 // listenSocket listens on the Unix socket at path, with mode 0600. The caller
362 // owns the chat, so a socket file at path is left from a daemon that ended,
363 // and listenSocket removes it.
364 func listenSocket(path string) (net.Listener, error) {
365 err := checkSocketPath(path)
370 err = os.Remove(path)
371 if err != nil && !errors.Is(err, os.ErrNotExist) {
372 return nil, fmt.Errorf("remove old socket: %w", err)
375 listener, err := net.Listen("unix", path)
377 return nil, fmt.Errorf("listen on socket: %w", err)
380 err = os.Chmod(path, 0o600)
382 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
388 // checkSocketPath makes sure that path fits in the address of a Unix socket.
389 func checkSocketPath(path string) error {
390 if len(path) > socketPathBytes {
391 return fmt.Errorf("socket path %s is longer than %d bytes: set ONECHAT_DIR to a shorter path", path, socketPathBytes)
397 // lockTokens takes the lock of the token file in dir. Each process that reads
398 // or refreshes the tokens holds it, because a refresh in one process rotates
399 // the refresh token of the other and logs it out.
400 func lockTokens(dir string) (*os.File, error) {
401 lock, err := lockFile(filepath.Join(dir, tokenLockFileName))
402 if errors.Is(err, errLocked) {
403 return nil, errTokensInUse