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.
39 // errTokensInUse tells that another onechat process uses the token file.
40 var errTokensInUse = errors.New("another onechat process uses the token file, such as the daemon")
42 // clientRequest is one line from a client: "send" with the text of a user
43 // message, or "interrupt".
44 type clientRequest struct {
45 Type string `json:"type"`
46 Text string `json:"text,omitempty"`
49 // daemon runs "onechat daemon": it owns the root agent and its files and serves
50 // the clients on the Unix socket in the data directory until ctx ends. It holds
51 // the lock of the token file, so it is the only process that refreshes the
53 func daemon(ctx context.Context, out io.Writer) (err error) {
59 // Check the socket path before the daemon writes a file, so that a data
60 // directory with a long path stays empty.
61 socket := filepath.Join(dir, socketFileName)
62 err = checkSocketPath(socket)
67 config, err := loadConfig(dir)
72 tokens, err := lockTokens(dir)
78 err = errors.Join(err, tokens.Close())
81 address, auth, err := modelEndpoint(config, dir)
86 agent, err := openAgent(filepath.Join(dir, agentDirName))
91 client := newClient(address, auth, agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl"))
92 memory, err := openMemory(ctx, agent.dir, time.Now, newCompactor(client, agent.Prompt, config.Compactor))
98 err = errors.Join(err, memory.Close())
101 listener, err := listenSocket(socket)
106 _, 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)
108 return errors.Join(err, listener.Close())
111 return serveAgent(ctx, listener, func(notify func(Event)) (*loop, error) {
112 return newLoop(agent, memory, client, time.Now, notify)
116 // serveAgent runs the loop that start makes and serves the clients of
117 // listener until ctx ends or the loop fails. It closes listener.
118 func serveAgent(ctx context.Context, listener net.Listener, start func(notify func(Event)) (*loop, error)) error {
119 ctx, cancel := context.WithCancel(ctx)
123 clients: make(map[*hubClient]bool),
126 l, err := start(hub.Broadcast)
128 return errors.Join(err, listener.Close())
131 var workers sync.WaitGroup
136 hub.Accept(ctx, listener, l)
141 err = errors.Join(err, listener.Close())
145 if errors.Is(err, context.Canceled) {
152 // hub holds the connected clients and sends each event to all of them.
155 clients map[*hubClient]bool
156 workers sync.WaitGroup
159 // hubClient is one connected client. Its events wait in a channel for the
160 // writer, so a slow client does not stop the agent.
161 type hubClient struct {
167 // Accept serves each client of listener until the listener closes. A new
168 // client gets a ready event with the name of the agent, and a busy event when a
170 func (h *hub) Accept(ctx context.Context, listener net.Listener, l *loop) {
172 conn, err := listener.Accept()
177 client := &hubClient{
179 events: make(chan Event, clientEvents),
183 h.clients[client] = true
188 go h.read(ctx, client, l)
190 h.Send(client, Event{
192 Text: l.agent.config.Name,
196 h.Send(client, Event{
203 // write sends the events of client as JSON lines until its channel closes.
204 func (h *hub) write(client *hubClient) {
205 defer h.workers.Done()
207 encoder := json.NewEncoder(client.conn)
208 for event := range client.events {
209 err := encoder.Encode(event)
216 // read runs the requests of client until it closes its connection.
217 func (h *hub) read(ctx context.Context, client *hubClient, l *loop) {
218 defer h.workers.Done()
221 scanner := bufio.NewScanner(client.conn)
222 scanner.Buffer(make([]byte, 64*1024), requestBytes)
223 for ctx.Err() == nil && scanner.Scan() {
224 var request clientRequest
225 err := json.Unmarshal(scanner.Bytes(), &request)
227 err = runRequest(l, request)
231 h.Send(client, Event{
239 // Send gives event to one client, or drops the client when its events do not
241 func (h *hub) Send(client *hubClient, event Event) {
243 defer h.mutex.Unlock()
245 h.send(client, event)
248 // send gives event to client. The caller holds the mutex.
249 func (h *hub) send(client *hubClient, event Event) {
250 if !h.clients[client] {
255 case client.events <- event:
261 // Broadcast gives event to every client.
262 func (h *hub) Broadcast(event Event) {
264 defer h.mutex.Unlock()
266 for client := range h.clients {
267 h.send(client, event)
271 // drop removes client and closes its connection.
272 func (h *hub) drop(client *hubClient) {
274 defer h.mutex.Unlock()
279 // remove removes client, closes its connection, and ends its writer. The
280 // caller holds the mutex.
281 func (h *hub) remove(client *hubClient) {
282 delete(h.clients, client)
283 client.once.Do(func() {
285 _ = client.conn.Close()
289 // CloseAll drops every client and waits for their readers and writers.
290 func (h *hub) CloseAll() {
292 for client := range h.clients {
300 // runRequest runs one request of a client.
301 func runRequest(l *loop, request clientRequest) error {
302 switch request.Type {
304 if request.Text == "" {
305 return errors.New("empty message")
308 _, err := l.Submit(request.Text)
313 return errors.New("no turn runs")
318 return fmt.Errorf("unknown request %q", request.Type)
322 // listenSocket listens on the Unix socket at path, with mode 0600. The caller
323 // owns the chat, so a socket file at path is left from a daemon that ended,
324 // and listenSocket removes it.
325 func listenSocket(path string) (net.Listener, error) {
326 err := checkSocketPath(path)
331 err = os.Remove(path)
332 if err != nil && !errors.Is(err, os.ErrNotExist) {
333 return nil, fmt.Errorf("remove old socket: %w", err)
336 listener, err := net.Listen("unix", path)
338 return nil, fmt.Errorf("listen on socket: %w", err)
341 err = os.Chmod(path, 0o600)
343 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
349 // checkSocketPath makes sure that path fits in the address of a Unix socket.
350 func checkSocketPath(path string) error {
351 if len(path) > socketPathBytes {
352 return fmt.Errorf("socket path %s is longer than %d bytes: set ONECHAT_DIR to a shorter path", path, socketPathBytes)
358 // lockTokens takes the lock of the token file in dir. Each process that reads
359 // or refreshes the tokens holds it, because a refresh in one process rotates
360 // the refresh token of the other and logs it out.
361 func lockTokens(dir string) (*os.File, error) {
362 lock, err := lockFile(filepath.Join(dir, tokenLockFileName))
363 if errors.Is(err, errLocked) {
364 return nil, errTokensInUse