]> git.giacomolli.uk - onechat/blob - subagent.go
024875161aae991f57028182c1e560ad7983745a
[onechat] / subagent.go
1 package main
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "io/fs"
8 "os"
9 "path/filepath"
10 "strconv"
11 "strings"
12 "sync"
13 "time"
14 )
15
16 const (
17 // subagentDirName is the directory of the subagents in the directory of
18 // an agent.
19 subagentDirName = "subagents"
20
21 // subagentNameDraws is the most names that Create draws before it
22 // fails.
23 subagentNameDraws = 1000
24 )
25
26 // newSubagents returns the subagents in dir, one directory for each name. The
27 // clock gives the dates of their messages, and draw gives the names of new
28 // subagents.
29 func newSubagents(dir string, clock func() time.Time, draw func() string) *Subagents {
30 return &Subagents{
31 dir: dir,
32 clock: clock,
33 draw: draw,
34 open: make(map[string]*Subagent),
35 }
36 }
37
38 // Subagents holds the subagents of one agent. Each subagent has a directory
39 // named for it, which holds its log. A log takes an exclusive lock, so
40 // Subagents opens the log of a name once and keeps it open until Close. Its
41 // mutex protects the open logs.
42 type Subagents struct {
43 dir string
44 clock func() time.Time
45 draw func() string
46
47 mutex sync.Mutex
48 open map[string]*Subagent
49 }
50
51 // Create makes the directory and the log of a new subagent. It draws a name
52 // again when the directory of the name exists.
53 func (s *Subagents) Create(ctx context.Context) (*Subagent, error) {
54 err := os.MkdirAll(s.dir, 0o700)
55 if err != nil {
56 return nil, fmt.Errorf("create subagent directory: %w", err)
57 }
58
59 for range subagentNameDraws {
60 name := s.draw()
61 err = os.Mkdir(filepath.Join(s.dir, name), 0o700)
62 if errors.Is(err, fs.ErrExist) {
63 continue
64 }
65
66 if err != nil {
67 return nil, fmt.Errorf("create subagent directory: %w", err)
68 }
69
70 return s.Get(ctx, name)
71 }
72
73 return nil, fmt.Errorf("no free subagent name after %d draws", subagentNameDraws)
74 }
75
76 // Get returns the subagent name with its log open. A name that is not valid or
77 // that has no directory is an unknown agent.
78 func (s *Subagents) Get(ctx context.Context, name string) (*Subagent, error) {
79 s.mutex.Lock()
80 defer s.mutex.Unlock()
81
82 subagent, found := s.open[name]
83 if found {
84 return subagent, nil
85 }
86
87 unknown := fmt.Errorf("no agent %s", name)
88 if !subagentNameValid(name) {
89 return nil, unknown
90 }
91
92 root := filepath.Join(s.dir, name)
93 info, err := os.Stat(root)
94 if errors.Is(err, fs.ErrNotExist) {
95 return nil, unknown
96 }
97
98 if err != nil {
99 return nil, fmt.Errorf("read subagent directory: %w", err)
100 }
101
102 if !info.IsDir() {
103 return nil, unknown
104 }
105
106 log, err := openLog(ctx, root, s.clock)
107 if err != nil {
108 return nil, fmt.Errorf("open log of %s: %w", name, err)
109 }
110
111 syncer, err := openSyncer(root)
112 if err != nil {
113 return nil, errors.Join(fmt.Errorf("open log of %s: %w", name, err), log.Close())
114 }
115
116 subagent = &Subagent{
117 name: name,
118 log: log,
119 syncer: syncer,
120 }
121 s.open[name] = subagent
122
123 return subagent, nil
124 }
125
126 // Close makes the writes of each open log durable and closes it.
127 func (s *Subagents) Close() error {
128 s.mutex.Lock()
129 defer s.mutex.Unlock()
130
131 var err error
132 for name, subagent := range s.open {
133 err = errors.Join(err, subagent.close())
134 delete(s.open, name)
135 }
136
137 return err
138 }
139
140 // Subagent is one subagent and its log. Its mutex protects the log, because
141 // the run of the subagent writes it while the agent reads it with zoom.
142 type Subagent struct {
143 name string
144 mutex sync.Mutex
145 log *Log
146 syncer *Syncer
147 }
148
149 // Append logs a message of the subagent.
150 func (a *Subagent) Append(kind, text string) (Message, error) {
151 a.mutex.Lock()
152 defer a.mutex.Unlock()
153
154 message, err := a.log.Append(kind, text)
155 if err != nil {
156 return Message{}, err
157 }
158
159 a.syncer.Written()
160
161 return message, nil
162 }
163
164 // Flush returns when every write before the call is durable.
165 func (a *Subagent) Flush(ctx context.Context) error {
166 return a.syncer.Flush(ctx)
167 }
168
169 // Show returns the whole log, each message as "i|kind: text", with a blank line
170 // between messages.
171 func (a *Subagent) Show() (string, error) {
172 a.mutex.Lock()
173 defer a.mutex.Unlock()
174
175 lines := make([]string, 0, a.log.Len())
176 for id := range a.log.Len() {
177 message, err := a.log.Message(id)
178 if err != nil {
179 return "", err
180 }
181
182 lines = append(lines, strconv.Itoa(id)+"|"+leafSource(message))
183 }
184
185 return strings.Join(lines, "\n\n"), nil
186 }
187
188 // close makes the writes durable and closes the log.
189 func (a *Subagent) close() error {
190 a.mutex.Lock()
191 defer a.mutex.Unlock()
192
193 return errors.Join(a.syncer.Close(), a.log.Close())
194 }