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 config, err := loadConfig(dir)
64 tokens, err := lockTokens(dir)
70 err = errors.Join(err, tokens.Close())
73 address, auth, err := modelEndpoint(config, dir)
78 agent, err := openAgent(filepath.Join(dir, agentDirName))
83 client := newClient(address, auth, agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl"))
84 memory, err := openMemory(ctx, agent.dir, time.Now, newCompactor(client, agent.Prompt, config.Compactor))
90 err = errors.Join(err, memory.Close())
93 listener, err := listenSocket(filepath.Join(dir, socketFileName))
98 _, 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)
100 return errors.Join(err, listener.Close())
103 return serveAgent(ctx, listener, func(notify func(Event)) (*loop, error) {
104 return newLoop(agent, memory, client, time.Now, notify)
108 // serveAgent runs the loop that start makes and serves the clients of
109 // listener until ctx ends or the loop fails. It closes listener.
110 func serveAgent(ctx context.Context, listener net.Listener, start func(notify func(Event)) (*loop, error)) error {
111 ctx, cancel := context.WithCancel(ctx)
115 clients: make(map[*hubClient]bool),
118 l, err := start(hub.Broadcast)
120 return errors.Join(err, listener.Close())
123 var workers sync.WaitGroup
128 hub.Accept(ctx, listener, l)
133 err = errors.Join(err, listener.Close())
137 if errors.Is(err, context.Canceled) {
144 // hub holds the connected clients and sends each event to all of them.
147 clients map[*hubClient]bool
148 workers sync.WaitGroup
151 // hubClient is one connected client. Its events wait in a channel for the
152 // writer, so a slow client does not stop the agent.
153 type hubClient struct {
159 // Accept serves each client of listener until the listener closes. A new
160 // client gets a ready event with the name of the agent, and a busy event when a
162 func (h *hub) Accept(ctx context.Context, listener net.Listener, l *loop) {
164 conn, err := listener.Accept()
169 client := &hubClient{
171 events: make(chan Event, clientEvents),
175 h.clients[client] = true
180 go h.read(ctx, client, l)
182 h.Send(client, Event{
184 Text: l.agent.config.Name,
188 h.Send(client, Event{
195 // write sends the events of client as JSON lines until its channel closes.
196 func (h *hub) write(client *hubClient) {
197 defer h.workers.Done()
199 encoder := json.NewEncoder(client.conn)
200 for event := range client.events {
201 err := encoder.Encode(event)
208 // read runs the requests of client until it closes its connection.
209 func (h *hub) read(ctx context.Context, client *hubClient, l *loop) {
210 defer h.workers.Done()
213 scanner := bufio.NewScanner(client.conn)
214 scanner.Buffer(make([]byte, 64*1024), requestBytes)
215 for ctx.Err() == nil && scanner.Scan() {
216 var request clientRequest
217 err := json.Unmarshal(scanner.Bytes(), &request)
219 err = runRequest(l, request)
223 h.Send(client, Event{
231 // Send gives event to one client, or drops the client when its events do not
233 func (h *hub) Send(client *hubClient, event Event) {
235 defer h.mutex.Unlock()
237 h.send(client, event)
240 // send gives event to client. The caller holds the mutex.
241 func (h *hub) send(client *hubClient, event Event) {
242 if !h.clients[client] {
247 case client.events <- event:
253 // Broadcast gives event to every client.
254 func (h *hub) Broadcast(event Event) {
256 defer h.mutex.Unlock()
258 for client := range h.clients {
259 h.send(client, event)
263 // drop removes client and closes its connection.
264 func (h *hub) drop(client *hubClient) {
266 defer h.mutex.Unlock()
271 // remove removes client, closes its connection, and ends its writer. The
272 // caller holds the mutex.
273 func (h *hub) remove(client *hubClient) {
274 delete(h.clients, client)
275 client.once.Do(func() {
277 _ = client.conn.Close()
281 // CloseAll drops every client and waits for their readers and writers.
282 func (h *hub) CloseAll() {
284 for client := range h.clients {
292 // runRequest runs one request of a client.
293 func runRequest(l *loop, request clientRequest) error {
294 switch request.Type {
296 if request.Text == "" {
297 return errors.New("empty message")
300 _, err := l.Submit(request.Text)
305 return errors.New("no turn runs")
310 return fmt.Errorf("unknown request %q", request.Type)
314 // listenSocket listens on the Unix socket at path, with mode 0600. The caller
315 // owns the chat, so a socket file at path is left from a daemon that ended,
316 // and listenSocket removes it.
317 func listenSocket(path string) (net.Listener, error) {
318 err := checkSocketPath(path)
323 err = os.Remove(path)
324 if err != nil && !errors.Is(err, os.ErrNotExist) {
325 return nil, fmt.Errorf("remove old socket: %w", err)
328 listener, err := net.Listen("unix", path)
330 return nil, fmt.Errorf("listen on socket: %w", err)
333 err = os.Chmod(path, 0o600)
335 return nil, errors.Join(fmt.Errorf("set socket mode: %w", err), listener.Close())
341 // checkSocketPath makes sure that path fits in the address of a Unix socket.
342 func checkSocketPath(path string) error {
343 if len(path) > socketPathBytes {
344 return fmt.Errorf("socket path %s is longer than %d bytes: set ONECHAT_DIR to a shorter path", path, socketPathBytes)
350 // lockTokens takes the lock of the token file in dir. Each process that reads
351 // or refreshes the tokens holds it, because a refresh in one process rotates
352 // the refresh token of the other and logs it out.
353 func lockTokens(dir string) (*os.File, error) {
354 lock, err := lockFile(filepath.Join(dir, tokenLockFileName))
355 if errors.Is(err, errLocked) {
356 return nil, errTokensInUse