]> git.giacomolli.uk - onechat/blob - turn.go
Deliver messages between parent and child agents
[onechat] / turn.go
1 package main
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "log/slog"
8 "path/filepath"
9 "sync"
10 "time"
11 )
12
13 // newTurnLoop returns the loop of agent with its memory, its subagents, and the
14 // WhatsApp link and the schedules of its tools. Its calls go through client,
15 // and notify gets each event. The clock gives the date of a turn. logger gets
16 // the failed turns and the ends of the subagents. A child has no WhatsApp
17 // tools, even when the caller supplies a link.
18 func newTurnLoop(agent *Agent, memory *Memory, subagents *Subagents, whatsapp *WhatsApp, schedules *Schedules, client ChainClient, clock func() time.Time, logger *slog.Logger, notify func(Event)) (*TurnLoop, error) {
19 layout, err := loadViewLayout(filepath.Join(agent.dir, viewLayoutFileName))
20 if err != nil {
21 return nil, err
22 }
23
24 l := &TurnLoop{
25 agent: agent,
26 memory: memory,
27 client: client,
28 layout: layout,
29 clock: clock,
30 logger: logger,
31 notify: notify,
32 wake: make(chan struct{}, 1),
33 }
34
35 l.runs = &SubagentRuns{
36 agent: agent,
37 memory: memory,
38 subagents: subagents,
39 layout: layout,
40 client: client,
41 state: l.state,
42 report: l.Report,
43 note: l.note,
44 fail: l.fail,
45 logger: logger,
46 notify: notify,
47 running: make(map[string]*SubagentRun),
48 }
49
50 if agent.config.Parent != "" {
51 whatsapp = nil
52 }
53
54 l.tools = &Toolbox{
55 log: l,
56 chat: memory,
57 subagents: subagents,
58 runs: l.runs,
59 whatsapp: whatsapp,
60 schedules: schedules,
61 workdir: agent.config.Workdir,
62 }
63
64 return l, nil
65 }
66
67 // Event tells the clients what the agent does as it happens. Kind is the kind
68 // of a logged message (user, reply, tool, echo, note, work), or one of ready,
69 // busy, idle, error, and subagent, which tells that the subagent Text starts a
70 // run. ID is the ID of a logged message. Source names the client that sent a
71 // user message, such as terminal or telegram, so that each client can show the
72 // messages of the others, or the subagent of a report. Status tells how the run
73 // of a report ended: finished, stopped, or failed.
74 type Event struct {
75 Kind string `json:"kind"`
76 ID int `json:"id,omitempty"`
77 Text string `json:"text,omitempty"`
78 Source string `json:"source,omitempty"`
79 Status string `json:"status,omitempty"`
80 }
81
82 // TurnLoop runs the turns of one agent. A user message goes to the log when it
83 // comes, and it wakes the loop. A turn waits until every message before it is
84 // summarized. Then the turn runs a Chain whose first request holds the prompt,
85 // the tools, and the input of turnInput.
86 //
87 // The view goes out as the messages of a ViewLayout, so the first request of a
88 // turn reads the view of the turn before from the prompt cache. User messages
89 // that come during a turn join the next request of its chain after the tool
90 // results, and so do the reports of the subagents. The subagents run until the
91 // loop ends. Parent and child messages stay queued until the turn finishes.
92 // active belongs to the running turn. The mutex protects pending, cancel, and
93 // failure.
94 type TurnLoop struct {
95 agent *Agent
96 memory *Memory
97 client ChainClient
98 tools *Toolbox
99 runs *SubagentRuns
100 layout *ViewLayout
101 clock func() time.Time
102 logger *slog.Logger
103 notify func(Event)
104 wake chan struct{}
105 messages *DaemonMessages
106 active []Message
107
108 mutex sync.Mutex
109 pending []Message
110 cancel context.CancelFunc
111 failure error
112 }
113
114 // Submit logs a user message from the client source and wakes the loop. The
115 // message joins the next request: the first one of a new turn, or the next one
116 // of a running turn.
117 func (l *TurnLoop) Submit(source, text string) (Message, error) {
118 message, err := l.record("user", source, text)
119 if err != nil {
120 return Message{}, err
121 }
122
123 l.mutex.Lock()
124
125 l.pending = append(l.pending, message)
126 l.mutex.Unlock()
127
128 select {
129 case l.wake <- struct{}{}:
130 default:
131 }
132
133 return message, nil
134 }
135
136 // Report logs the report text of the subagent name as a work message and tells
137 // the clients, with the status of the run. Unless the subagent was stopped, the
138 // report joins the waiting messages and wakes the loop, as a user message of
139 // Submit does. A failed write stops the loop, because the log refuses all
140 // writes after it.
141 func (l *TurnLoop) Report(name, text, status string) {
142 message, err := l.Work(name, text, status)
143 switch {
144 case err != nil:
145 l.fail(fmt.Errorf("%w: %w", errChainLogWrite, err))
146 case status != subagentStopped:
147 l.Wake(message)
148 }
149 }
150
151 // Work logs text as a work message of source, such as the name of a subagent,
152 // and tells the clients, with status. The message starts no turn until it goes
153 // to Wake.
154 func (l *TurnLoop) Work(source, text, status string) (Message, error) {
155 message, err := l.memory.Append("work", text)
156 if err != nil {
157 return Message{}, err
158 }
159
160 l.notify(Event{
161 Kind: "work",
162 ID: message.ID,
163 Text: text,
164 Source: source,
165 Status: status,
166 })
167
168 return message, nil
169 }
170
171 // Wake adds the logged messages to the waiting messages and wakes the loop
172 // once, as a user message of Submit does. They join the first request of a new
173 // turn together, or the next request of a running turn after the tool results.
174 func (l *TurnLoop) Wake(messages ...Message) {
175 if len(messages) == 0 {
176 return
177 }
178
179 l.mutex.Lock()
180
181 l.pending = append(l.pending, messages...)
182 l.mutex.Unlock()
183
184 select {
185 case l.wake <- struct{}{}:
186 default:
187 }
188 }
189
190 // StopSubagent ends the run of the subagent name and tells if it ran. Its
191 // report is logged, but it starts no turn.
192 func (l *TurnLoop) StopSubagent(name string) (bool, error) {
193 return l.runs.Stop(name)
194 }
195
196 // Interrupt ends the running turn. A running tool is killed, and the turn sends
197 // no further request.
198 func (l *TurnLoop) Interrupt() bool {
199 l.mutex.Lock()
200 defer l.mutex.Unlock()
201
202 if l.cancel == nil {
203 return false
204 }
205
206 l.cancel()
207
208 return true
209 }
210
211 // Busy tells if a turn runs.
212 func (l *TurnLoop) Busy() bool {
213 l.mutex.Lock()
214 defer l.mutex.Unlock()
215
216 return l.cancel != nil
217 }
218
219 // Append logs a message and tells the clients. The toolbox logs its calls and
220 // results through it.
221 func (l *TurnLoop) Append(kind, text string) (Message, error) {
222 return l.record(kind, "", text)
223 }
224
225 // Flush makes the log durable.
226 func (l *TurnLoop) Flush(ctx context.Context) error {
227 return l.memory.Flush(ctx)
228 }
229
230 // Run runs a turn each time user messages or reports wait, until ctx ends. It
231 // returns the error of a failed log write, which stops the agent. At its start
232 // it resumes the subagents that a stop of the daemon cut, and at its end it
233 // ends the runs of the subagents and waits for them.
234 func (l *TurnLoop) Run(ctx context.Context) error {
235 defer l.runs.Close()
236
237 err := l.runs.Resume(ctx)
238 if err != nil {
239 return fmt.Errorf("resume subagents: %w", err)
240 }
241
242 for {
243 for ctx.Err() == nil && l.waiting() {
244 err := l.failed()
245 if err != nil {
246 return fmt.Errorf("check turn loop failure: %w", err)
247 }
248
249 err = l.turn(ctx)
250 if err != nil {
251 return fmt.Errorf("run turn: %w", err)
252 }
253 }
254
255 select {
256 case <-l.wake:
257 case <-ctx.Done():
258 return ctx.Err()
259 }
260
261 err := l.failed()
262 if err != nil {
263 return fmt.Errorf("check turn loop failure: %w", err)
264 }
265 }
266 }
267
268 // note logs a note and tells the clients. A note starts no turn.
269 func (l *TurnLoop) note(text string) error {
270 _, err := l.record("note", "", text)
271
272 return err
273 }
274
275 // record logs a message and tells the clients, with the client source of a user
276 // message.
277 func (l *TurnLoop) record(kind, source, text string) (Message, error) {
278 message, err := l.memory.Append(kind, text)
279 if err != nil {
280 return Message{}, err
281 }
282
283 l.notify(Event{
284 Kind: kind,
285 ID: message.ID,
286 Text: text,
287 Source: source,
288 })
289
290 return message, nil
291 }
292
293 // waiting tells if user messages or reports wait for a request.
294 func (l *TurnLoop) waiting() bool {
295 l.mutex.Lock()
296 defer l.mutex.Unlock()
297
298 return len(l.pending) > 0
299 }
300
301 // fail stops the loop with err.
302 func (l *TurnLoop) fail(err error) {
303 l.mutex.Lock()
304
305 l.failure = errors.Join(l.failure, err)
306 l.mutex.Unlock()
307
308 select {
309 case l.wake <- struct{}{}:
310 default:
311 }
312 }
313
314 // failed returns the error of a failed write of a report.
315 func (l *TurnLoop) failed() error {
316 l.mutex.Lock()
317 defer l.mutex.Unlock()
318
319 return l.failure
320 }
321
322 // turn runs one turn. A failed or interrupted model call ends the turn and
323 // tells the clients. A failure also goes to the logger, so that it is not lost
324 // when no client is connected, but an interrupt does not. The messages of the
325 // turn stay in the log and the view, and the next turn starts only with a new
326 // message, so a lasting failure such as a needed login does not repeat. Only a
327 // failed log or queue write is an error of turn. A daemon stop leaves taken
328 // parent and child messages queued for restart. A user interrupt completes them
329 // without a report.
330 func (l *TurnLoop) turn(ctx context.Context) error {
331 runCtx := ctx
332 ctx, cancel := context.WithCancel(ctx)
333 defer cancel()
334
335 l.mutex.Lock()
336
337 l.cancel = cancel
338 l.mutex.Unlock()
339
340 defer func() {
341 l.mutex.Lock()
342
343 l.cancel = nil
344 l.mutex.Unlock()
345 }()
346
347 l.notify(Event{
348 Kind: "busy",
349 })
350
351 if l.messages != nil {
352 l.logger.Info("turn started")
353 }
354
355 reply, err := l.chain(ctx)
356 if l.messages != nil && !errors.Is(err, errChainLogWrite) && (err == nil || runCtx.Err() == nil) {
357 finishErr := l.messages.Finish(l, l.active, reply)
358 if finishErr != nil {
359 err = errors.Join(err, fmt.Errorf("%w: finish agent messages: %w", errChainLogWrite, finishErr))
360 }
361 }
362
363 l.active = nil
364 if err != nil && !errors.Is(err, errChainLogWrite) {
365 if ctx.Err() == nil {
366 l.logger.Error("turn failed", "err", err)
367 }
368
369 l.notify(Event{
370 Kind: "error",
371 Text: turnError(ctx, err),
372 })
373
374 err = nil
375 }
376
377 if l.messages != nil {
378 l.logger.Info("turn done")
379 }
380
381 l.notify(Event{
382 Kind: "idle",
383 })
384
385 return err
386 }
387
388 // chain runs the request chain of a turn until the final answer.
389 func (l *TurnLoop) chain(ctx context.Context) (string, error) {
390 messages := l.take()
391 if len(messages) == 0 {
392 return "", nil
393 }
394
395 err := l.memory.Wait(ctx)
396 if err != nil {
397 return "", fmt.Errorf("wait for turn memory: %w", err)
398 }
399
400 instructions, err := l.agent.Prompt()
401 if err != nil {
402 return "", fmt.Errorf("read turn prompt: %w", err)
403 }
404
405 skip := make(map[int]bool, len(messages))
406 for _, message := range messages {
407 skip[message.ID] = true
408 }
409
410 view, err := l.layout.Split(l.memory.ViewLines(skip))
411 if err != nil {
412 return "", fmt.Errorf("split turn view: %w", err)
413 }
414
415 chain := &Chain{
416 client: l.client,
417 tools: l.tools,
418 request: ModelRequest{
419 Model: l.agent.config.Model,
420 Effort: l.agent.config.Effort,
421 Instructions: instructions,
422 Tools: l.agent.Tools(),
423 },
424 take: l.take,
425 }
426
427 reply, err := chain.Run(ctx, turnInput(view, l.state(), messages))
428 if err != nil {
429 return "", fmt.Errorf("run turn chain: %w", err)
430 }
431
432 return reply, nil
433 }
434
435 // take returns the user messages that wait for a request, and removes them.
436 func (l *TurnLoop) take() []Message {
437 l.mutex.Lock()
438 defer l.mutex.Unlock()
439
440 messages := l.pending
441 l.pending = nil
442 if l.messages != nil {
443 l.active = append(l.active, messages...)
444 }
445
446 return messages
447 }
448
449 // state returns the per-turn state: the end of the view, and the date and time
450 // of the turn.
451 func (l *TurnLoop) state() string {
452 return "</chat>\n\nNow: " + l.clock().Format("Monday 2006-01-02 15:04 -07:00")
453 }
454
455 // turnError returns the text of the error that ended a turn.
456 func turnError(ctx context.Context, err error) string {
457 if ctx.Err() != nil {
458 return "interrupted"
459 }
460
461 return err.Error()
462 }
463
464 // turnInput returns the input of the first request of a turn, stable parts
465 // first: a user message for each view message, one with the per-turn state,
466 // and one for each new message, whole. The view leaves out the leaf lines of
467 // the new messages.
468 func turnInput(view []string, state string, messages []Message) []any {
469 input := make([]any, 0, len(view)+1+len(messages))
470 for _, text := range view {
471 input = append(input, modelUserMessage(text))
472 }
473
474 input = append(input, modelUserMessage(state))
475 for _, message := range messages {
476 input = append(input, modelUserMessage(message.Text))
477 }
478
479 return input
480 }