-// errTokensInUse tells that another onechat process uses the token file.
-var errTokensInUse = errors.New("another onechat process uses the token file, such as the daemon")
-
-// clientRequest is one line from a client: "send" with the text of a user
-// message, or "interrupt".
-type clientRequest struct {
- Type string `json:"type"`
- Text string `json:"text,omitempty"`
-}
-
-// daemon runs "onechat daemon": it owns the root agent and its files and serves
-// the clients on the Unix socket in the data directory until ctx ends. It holds
-// the lock of the token file, so it is the only process that refreshes the
-// tokens.
-func daemon(ctx context.Context, out io.Writer) (err error) {
- dir, err := dataDir()
- if err != nil {
- return err
- }
-
- // Check the socket path before the daemon writes a file, so that a data
- // directory with a long path stays empty.
- socket := filepath.Join(dir, socketFileName)
- err = checkSocketPath(socket)
- if err != nil {
- return err
- }
-
- config, err := loadConfig(dir)
- if err != nil {
- return err
- }
-
- tokens, err := lockTokens(dir)
- if err != nil {
- return err
- }
-
- defer func() {
- err = errors.Join(err, tokens.Close())
- }()
-
- address, auth, err := modelEndpoint(config, dir)
- if err != nil {
- return err
- }
-
- agent, err := openAgent(filepath.Join(dir, agentDirName))
- if err != nil {
- return err
- }
-
- client := newClient(address, auth, agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl"))
- memory, err := openMemory(ctx, agent.dir, time.Now, newCompactor(client, agent.Prompt, config.Compactor))
- if err != nil {
- return err
- }
-
- defer func() {
- err = errors.Join(err, memory.Close())
- }()
-
- listener, err := listenSocket(socket)
- if err != nil {
- return err
- }
-
- _, 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)
- if err != nil {
- return errors.Join(err, listener.Close())
- }
-
- return serveAgent(ctx, listener, func(notify func(Event)) (*loop, error) {
- return newLoop(agent, memory, client, time.Now, notify)
- })
-}
-
-// serveAgent runs the loop that start makes and serves the clients of
-// listener until ctx ends or the loop fails. It closes listener.
-func serveAgent(ctx context.Context, listener net.Listener, start func(notify func(Event)) (*loop, error)) error {
- ctx, cancel := context.WithCancel(ctx)
- defer cancel()
-
- hub := &hub{
- clients: make(map[*hubClient]bool),
- }
-
- l, err := start(hub.Broadcast)
- if err != nil {
- return errors.Join(err, listener.Close())
- }
-
- var workers sync.WaitGroup
- workers.Add(1)
- go func() {
- defer workers.Done()
-
- hub.Accept(ctx, listener, l)
- }()
-
- err = l.Run(ctx)
- cancel()
- err = errors.Join(err, listener.Close())
- hub.CloseAll()
- workers.Wait()
-
- if errors.Is(err, context.Canceled) {
- return nil
- }
-
- return err
-}