18 // agentDirName is the directory of the root agent in the data directory.
19 agentDirName = "agent"
21 // socketFileName is the Unix socket of the daemon in the data directory.
22 socketFileName = "onechat.sock"
24 // tokenLockFileName is the lock file of the token file in the data
26 tokenLockFileName = "auth.lock"
28 // requestBytes is the most bytes of one request line of a client.
29 requestBytes = 16 << 20
31 // clientEvents is the number of events that can wait for a slow client
32 // before the daemon drops it.
35 // socketPathBytes is the longest path of a Unix socket on Linux.
38 // terminalSource is the source of the user messages from the clients of
40 terminalSource = "terminal"
43 // errTokensInUse tells that another onechat process uses the token file.
44 var errTokensInUse = errors.New("another onechat process uses the token file, such as the daemon")
46 // clientRequest is one line from a client: "send" with the text of a user
47 // message, or "interrupt".
48 type clientRequest struct {
49 Type string `json:"type"`
50 Text string `json:"text,omitempty"`
53 // daemon runs "onechat daemon": it owns the root agent and its files and serves
54 // the clients on the Unix socket in the data directory until ctx ends. It holds
55 // the lock of the token file, so it is the only process that refreshes the
57 func daemon(ctx context.Context, out io.Writer) (err error) {
63 // Check the socket path before the daemon writes a file, so that a data
64 // directory with a long path stays empty.
65 socket := filepath.Join(dir, socketFileName)
66 err = checkSocketPath(socket)
71 config, err := loadConfig(dir)
76 tokens, err := lockTokens(dir)
82 err = errors.Join(err, tokens.Close())
85 address, auth, err := modelEndpoint(config, dir)
90 agent, err := openAgent(filepath.Join(dir, agentDirName))
95 client := newClient(address, auth, agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl"))
96 memory, err := openMemory(ctx, agent.dir, time.Now, newCompactor(client, agent.Prompt, config.Compactor))
102 err = errors.Join(err, memory.Close())
105 listener, err := listenSocket(socket)
110 _, 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)
112 return errors.Join(err, listener.Close())
115 return serveAgent(ctx, listener, func(notify func(Event)) (*loop, error) {
116 return newLoop(agent, memory, client, time.Now, notify)
120 // serveAgent runs the loop that start makes and serves the clients of
121 // listener until ctx ends or the loop fails. It closes listener.
122 func serveAgent(ctx context.Context, listener net.Listener, start func(notify func(Event)) (*loop, error)) error {
123 ctx, cancel := context.WithCancel(ctx)
127 clients: make(map[*hubClient]bool),
130 l, err := start(hub.Broadcast)
132 return errors.Join(err, listener.Close())
135 var workers sync.WaitGroup
140 hub.Accept(ctx, listener, l)
145 err = errors.Join(err, listener.Close())
149 if errors.Is(err, context.Canceled) {
156 // hub holds the connected clients and sends each event to all of them.
159 clients map[*hubClient]bool
160 workers sync.WaitGroup
163 // hubClient is one connected client. Its events wait in a channel for the
164 // writer, so a slow client does not stop the agent.
165 type hubClient struct {
171 // Accept serves each client of listener until the listener closes. A new
172 // client gets a ready event with the name of the agent, and a busy event when a
174 func (h *hub) Accept(ctx context.Context, listener net.Listener, l *loop) {
176 conn, err := listener.Accept()
181 client := &hubClient{
183 events: make(chan Event, clientEvents),
187 h.clients[client] = true
192 go h.read(ctx, client, l)
194 h.Send(client, Event{
196 Text: l.agent.config.Name,
200 h.Send(client, Event{
207 // write sends the events of client as JSON lines until its channel closes.
208 func (h *hub) write(client *hubClient) {
209 defer h.workers.Done()
211 encoder := json.NewEncoder(client.conn)
212 for event := range client.events {
213 err := encoder.Encode(event)
220 // read runs the requests of client until it closes its connection.
221 func (h *hub) read(ctx context.Context, client *hubClient, l *loop) {
222 defer h.workers.Done()
225 scanner := bufio.NewScanner(client.conn)
226 scanner.Buffer(make([]byte, 64*1024), requestBytes)
227 for ctx.Err() == nil && scanner.Scan() {
228 var request clientRequest
229 err := json.Unmarshal(scanner.Bytes(), &request)
231 err = runRequest(l, request)
235 h.Send(client, Event{
243 // Send gives event to one client, or drops the client when its events do not
245 func (h *hub) Send(client *hubClient, event Event) {
247 defer h.mutex.Unlock()
249 h.send(client, event)
252 // send gives event to client. The caller holds the mutex.
253 func (h *hub) send(client *hubClient, event Event) {
254 if !h.clients[client] {
259 case client.events <- event:
265 // Broadcast gives event to every client.
266 func (h *hub) Broadcast(event Event) {
268 defer h.mutex.Unlock()
270 for client := range h.clients {
271 h.send(client, event)
275 // drop removes client and closes its connection.
276 func (h *hub) drop(client *hubClient) {
278 defer h.mutex.Unlock()
283 // remove removes client, closes its connection, and ends its writer. The
284 // caller holds the mutex.
285 func (h *hub) remove(client *hubClient) {
286 delete(h.clients, client)
287 client.once.Do(func() {
289 _ = client.conn.Close()
293 // CloseAll drops every client and waits for their readers and writers.
294 func (h *hub) CloseAll() {
296 for client := range h.clients {
304 // runRequest runs one request of a client.
305 func runRequest(l *loop, request clientRequest) error {
306 switch request.Type {
308 if request.Text == "" {
309 return errors.New("empty message")
312 _, err := l.Submit(terminalSource, request.Text)
317 return errors.New("no turn runs")
322 return fmt.Errorf("unknown request %q", request.Type)
326 // listenSocket listens on the Unix socket at path, with mode 0600. The caller
327 // owns the chat, so a socket file at path is left from a daemon that ended,
328 // and listenSocket removes it.
329 func listenSocket(path string) (net.Listener, error) {
330 err := checkSocketPath(path)
335 err = os.Remove(path)
336 if err != nil && !errors.Is(err, os.ErrNotExist) {
337 return nil, fmt.Errorf("remove old socket: %w", err)
340 listener, err := net.Listen("unix", path)
342 return nil, fmt.Errorf("listen on socket: %w", err)
345 err = os.Chmod(path, 0o600)
347 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
353 // checkSocketPath makes sure that path fits in the address of a Unix socket.
354 func checkSocketPath(path string) error {
355 if len(path) > socketPathBytes {
356 return fmt.Errorf("socket path %s is longer than %d bytes: set ONECHAT_DIR to a shorter path", path, socketPathBytes)
362 // lockTokens takes the lock of the token file in dir. Each process that reads
363 // or refreshes the tokens holds it, because a refresh in one process rotates
364 // the refresh token of the other and logs it out.
365 func lockTokens(dir string) (*os.File, error) {
366 lock, err := lockFile(filepath.Join(dir, tokenLockFileName))
367 if errors.Is(err, errLocked) {
368 return nil, errTokensInUse