+// state returns the per-turn state: the end of the view, and the date and time
+// of the turn, then the names and responsibilities of its children.
+func (l *TurnLoop) state() string {
+ state := "</chat>\n\nNow: " + l.clock().Format("Monday 2006-01-02 15:04 -07:00")
+ if l.messages != nil {
+ state += l.messages.ChildState(l.agent.config.Name)
+ }
+
+ return state
+}
+
+// Report logs the report text of the subagent name as a work message and tells
+// the clients, with the status of the run. Unless the subagent was stopped, the
+// report joins the waiting messages and wakes the loop, as a user message of
+// Submit does. A failed write stops the loop, because the log refuses all
+// writes after it.
+func (l *TurnLoop) Report(name, text, status string) {
+ message, err := l.Work(name, text, status)
+ switch {
+ case err != nil:
+ l.fail(fmt.Errorf("%w: %w", errChainLogWrite, err))
+ case status != subagentStopped:
+ l.Wake(message)
+ }
+}
+
+// note logs a note and tells the clients. A note starts no turn.
+func (l *TurnLoop) note(text string) error {
+ _, err := l.record("note", "", text)
+
+ return err
+}
+
+// fail stops the loop with err.
+func (l *TurnLoop) fail(err error) {
+ l.mutex.Lock()
+
+ l.failure = errors.Join(l.failure, err)
+ l.mutex.Unlock()
+
+ select {
+ case l.wake <- struct{}{}:
+ default:
+ }
+}
+
+// Work logs text as a work message of source, such as the name of a subagent,
+// and tells the clients, with status. The message starts no turn until it goes
+// to Wake.
+func (l *TurnLoop) Work(source, text, status string) (Message, error) {
+ message, err := l.memory.Append("work", text)
+ if err != nil {
+ return Message{}, err
+ }
+
+ l.notify(Event{
+ Kind: "work",
+ ID: message.ID,
+ Text: text,
+ Source: source,
+ Status: status,
+ })
+
+ return message, nil
+}
+
+// Wake adds the logged messages to the waiting messages and wakes the loop
+// once, as a user message of Submit does. They join the first request of a new
+// turn together, or the next request of a running turn after the tool results.
+func (l *TurnLoop) Wake(messages ...Message) {
+ if len(messages) == 0 {
+ return
+ }
+
+ l.mutex.Lock()
+
+ l.pending = append(l.pending, messages...)
+ l.mutex.Unlock()
+
+ select {
+ case l.wake <- struct{}{}:
+ default:
+ }
+}
+
+// record logs a message and tells the clients, with the client source of a user
+// message.
+func (l *TurnLoop) record(kind, source, text string) (Message, error) {
+ message, err := l.memory.Append(kind, text)
+ if err != nil {
+ return Message{}, err
+ }
+
+ l.notify(Event{
+ Kind: kind,
+ ID: message.ID,
+ Text: text,
+ Source: source,
+ })
+
+ return message, nil
+}
+