]> git.giacomolli.uk - onechat/blobdiff - subagent_run.go
Convert WhatsApp events with pure functions
[onechat] / subagent_run.go
index 20b15f24dbd4374329ff3cb138912fca9da5b53b..16cf2bd03340a7271c985859f739777811810b46 100644 (file)
@@ -2,9 +2,12 @@ package main
 
 import (
        "context"
 
 import (
        "context"
+       "encoding/json"
        "errors"
        "fmt"
        "errors"
        "fmt"
+       "maps"
        "os"
        "os"
+       "path/filepath"
        "slices"
        "strings"
        "sync"
        "slices"
        "strings"
        "sync"
@@ -17,6 +20,17 @@ const (
        // subagentNoteEffort follows subagentNote when the subagent has its own
        // effort.
        subagentNoteEffort = " at effort "
        // subagentNoteEffort follows subagentNote when the subagent has its own
        // effort.
        subagentNoteEffort = " at effort "
+
+       // subagentWorkFileName is the file of the names of the running
+       // subagents in the directory of an agent.
+       subagentWorkFileName = "work.json"
+)
+
+// The statuses of the end of a run, in the work event of its report.
+const (
+       subagentFinished = "finished"
+       subagentStopped  = "stopped"
+       subagentFailed   = "failed"
 )
 
 // errSubagentClosed tells that the runs of the subagents ended with the loop.
 )
 
 // errSubagentClosed tells that the runs of the subagents ended with the loop.
@@ -33,6 +47,12 @@ var errSubagentClosed = errors.New("the daemon stops, so no subagent starts")
 // ends one run, and its report says that it stopped. At the stop of the daemon
 // the runs end with no report.
 //
 // ends one run, and its report says that it stopped. At the stop of the daemon
 // the runs end with no report.
 //
+// work.json in the directory of the agent holds the names of the running
+// subagents. Each start and each end of a run writes it whole, but Close does
+// not, so after a stop of the daemon it names the runs that the stop cut, and
+// Resume goes on with them. The logs alone cannot tell this, because a stop
+// can cut a run just after its final reply.
+//
 // Spawn and Tell split the view with the layout of the agent, which has no
 // lock. They are tools, so they run in the goroutine of the turns, as each
 // split of a turn does.
 // Spawn and Tell split the view with the layout of the agent, which has no
 // lock. They are tools, so they run in the goroutine of the turns, as each
 // split of a turn does.
@@ -43,8 +63,9 @@ type SubagentRuns struct {
        layout    *ViewLayout
        client    ChainClient
        state     func() string
        layout    *ViewLayout
        client    ChainClient
        state     func() string
-       report    func(text string, stopped bool)
+       report    func(name, text, status string)
        note      func(text string) error
        note      func(text string) error
+       fail      func(err error)
        notify    func(Event)
 
        mutex   sync.Mutex
        notify    func(Event)
 
        mutex   sync.Mutex
@@ -197,6 +218,37 @@ func (r *SubagentRuns) Stop(name string) (bool, error) {
        return true, nil
 }
 
        return true, nil
 }
 
+// Resume goes on with the runs that a stop of the daemon cut, as work.json
+// names them. The chat gets the note "The daemon restarted, cutting NAMES;
+// nothing was lost: go on.", and each cut subagent gets the same text as a
+// message of Tell. A subagent that cannot go on gets a failed report.
+func (r *SubagentRuns) Resume(ctx context.Context) error {
+       names, err := r.load()
+       if err != nil || len(names) == 0 {
+               return err
+       }
+
+       text := "The daemon restarted, cutting " + strings.Join(names, ", ") + "; nothing was lost: go on."
+       err = r.note(text)
+       if err != nil {
+               return err
+       }
+
+       for _, name := range names {
+               _, err = r.Tell(ctx, name, text)
+               if err != nil {
+                       r.report(name, subagentReport(name, []string{"failed: " + err.Error()}), subagentFailed)
+               }
+       }
+
+       // A subagent that cannot go on does not run, so work.json no longer
+       // names it, and the next start does not try it again.
+       r.mutex.Lock()
+       defer r.mutex.Unlock()
+
+       return r.save()
+}
+
 // Close ends every run and waits for them. No subagent starts after Close.
 func (r *SubagentRuns) Close() {
        r.mutex.Lock()
 // Close ends every run and waits for them. No subagent starts after Close.
 func (r *SubagentRuns) Close() {
        r.mutex.Lock()
@@ -280,6 +332,15 @@ func (r *SubagentRuns) start(ctx context.Context, run *SubagentRun) error {
        }
 
        r.running[run.subagent.name] = run
        }
 
        r.running[run.subagent.name] = run
+       err := r.save()
+       if err != nil {
+               delete(r.running, run.subagent.name)
+               r.mutex.Unlock()
+               run.cancel()
+
+               return err
+       }
+
        r.workers.Add(1)
        r.mutex.Unlock()
 
        r.workers.Add(1)
        r.mutex.Unlock()
 
@@ -293,6 +354,50 @@ func (r *SubagentRuns) start(ctx context.Context, run *SubagentRun) error {
        return nil
 }
 
        return nil
 }
 
+// load reads the names of work.json. A missing file names none.
+func (r *SubagentRuns) load() ([]string, error) {
+       data, err := os.ReadFile(r.workPath())
+       if errors.Is(err, os.ErrNotExist) {
+               return nil, nil
+       }
+
+       if err != nil {
+               return nil, fmt.Errorf("read running subagents: %w", err)
+       }
+
+       var file SubagentWorkFile
+       err = json.Unmarshal(data, &file)
+       if err != nil {
+               return nil, fmt.Errorf("decode running subagents: %w", err)
+       }
+
+       return file.Running, nil
+}
+
+// save writes the names of the running subagents to work.json. The caller
+// holds the mutex.
+func (r *SubagentRuns) save() error {
+       file := SubagentWorkFile{
+               Running: append([]string{}, slices.Sorted(maps.Keys(r.running))...),
+       }
+
+       data, err := json.Marshal(file)
+       if err != nil {
+               return fmt.Errorf("encode running subagents: %w", err)
+       }
+
+       err = writeFileAtomic(r.workPath(), append(data, '\n'))
+       if err != nil {
+               return fmt.Errorf("save running subagents: %w", err)
+       }
+
+       return nil
+}
+
+func (r *SubagentRuns) workPath() string {
+       return filepath.Join(r.agent.dir, subagentWorkFileName)
+}
+
 // run runs the chains of run and reports its end, unless Close ended it. A
 // chain follows while messages wait after the final answer of the chain before
 // it, and no chain failed. A chain that Stop ends gives the reply "stopped".
 // run runs the chains of run and reports its end, unless Close ended it. A
 // chain follows while messages wait after the final answer of the chain before
 // it, and no chain failed. A chain that Stop ends gives the reply "stopped".
@@ -302,6 +407,7 @@ func (r *SubagentRuns) run(ctx context.Context, run *SubagentRun) {
 
        var replies []string
        stopped := false
 
        var replies []string
        stopped := false
+       status := subagentFinished
        for more := true; more; {
                reply, err := r.chain(ctx, run)
 
        for more := true; more; {
                reply, err := r.chain(ctx, run)
 
@@ -312,15 +418,24 @@ func (r *SubagentRuns) run(ctx context.Context, run *SubagentRun) {
                        reply = "stopped"
                case err != nil:
                        reply = "failed: " + err.Error()
                        reply = "stopped"
                case err != nil:
                        reply = "failed: " + err.Error()
+                       status = subagentFailed
                }
 
                more = err == nil && ctx.Err() == nil && len(run.pending) > 0
                run.pending = nil
                }
 
                more = err == nil && ctx.Err() == nil && len(run.pending) > 0
                run.pending = nil
+               var saveErr error
                if !more {
                        delete(r.running, run.subagent.name)
                if !more {
                        delete(r.running, run.subagent.name)
+                       if !r.closed {
+                               saveErr = r.save()
+                       }
                }
                r.mutex.Unlock()
 
                }
                r.mutex.Unlock()
 
+               if saveErr != nil {
+                       r.fail(saveErr)
+               }
+
                replies = append(replies, reply)
        }
 
                replies = append(replies, reply)
        }
 
@@ -328,7 +443,11 @@ func (r *SubagentRuns) run(ctx context.Context, run *SubagentRun) {
                return
        }
 
                return
        }
 
-       r.report(subagentReport(run.subagent.name, replies), stopped)
+       if stopped {
+               status = subagentStopped
+       }
+
+       r.report(run.subagent.name, subagentReport(run.subagent.name, replies), status)
 }
 
 // chain runs one request chain of run and returns its final answer.
 }
 
 // chain runs one request chain of run and returns its final answer.
@@ -397,6 +516,11 @@ type SubagentRun struct {
        stopped  bool
 }
 
        stopped  bool
 }
 
+// SubagentWorkFile is the content of work.json.
+type SubagentWorkFile struct {
+       Running []string `json:"running"`
+}
+
 // subagentReport returns the report of the subagent name with its replies: the
 // name in brackets, a new line, the replies, and the zoom that gives its whole
 // chat.
 // subagentReport returns the report of the subagent name with its replies: the
 // name in brackets, a new line, the replies, and the zoom that gives its whole
 // chat.