]> git.giacomolli.uk - onechat/blobdiff - subagent_run.go
Rewrite the README as a user guide
[onechat] / subagent_run.go
index ca4ebd4247fd3038cd8a9902ad2ea77482d3872c..8084c390a7012d5213019f1f784ec3214ce08bbe 100644 (file)
@@ -5,13 +5,14 @@ import (
        "encoding/json"
        "errors"
        "fmt"
        "encoding/json"
        "errors"
        "fmt"
-       "log"
+       "log/slog"
        "maps"
        "os"
        "path/filepath"
        "slices"
        "strings"
        "sync"
        "maps"
        "os"
        "path/filepath"
        "slices"
        "strings"
        "sync"
+       "time"
 )
 
 const (
 )
 
 const (
@@ -68,7 +69,7 @@ type SubagentRuns struct {
        report    func(name, text, status string)
        note      func(text string) error
        fail      func(err error)
        report    func(name, text, status string)
        note      func(text string) error
        fail      func(err error)
-       logger    *log.Logger
+       logger    *slog.Logger
        notify    func(Event)
 
        mutex   sync.Mutex
        notify    func(Event)
 
        mutex   sync.Mutex
@@ -86,6 +87,7 @@ func (r *SubagentRuns) Spawn(ctx context.Context, tasks []string, effort *string
        }
 
        r.mutex.Lock()
        }
 
        r.mutex.Lock()
+
        closed := r.closed
        r.mutex.Unlock()
 
        closed := r.closed
        r.mutex.Unlock()
 
@@ -136,6 +138,7 @@ func (r *SubagentRuns) Spawn(ctx context.Context, tasks []string, effort *string
 // its log with a new run, with the view of now and the effort of its note.
 func (r *SubagentRuns) Tell(ctx context.Context, name, message string) (string, error) {
        r.mutex.Lock()
 // its log with a new run, with the view of now and the effort of its note.
 func (r *SubagentRuns) Tell(ctx context.Context, name, message string) (string, error) {
        r.mutex.Lock()
+
        run, found := r.running[name]
        if found {
                defer r.mutex.Unlock()
        run, found := r.running[name]
        if found {
                defer r.mutex.Unlock()
@@ -240,7 +243,7 @@ func (r *SubagentRuns) Resume(ctx context.Context) error {
        for _, name := range names {
                _, err = r.Tell(ctx, name, text)
                if err != nil {
        for _, name := range names {
                _, err = r.Tell(ctx, name, text)
                if err != nil {
-                       r.logger.Printf("subagent %s lost at restart: %v", name, err)
+                       r.logger.Error("subagent lost at restart", "name", name, "err", err)
                        r.report(name, subagentReport(name, []string{"failed: " + err.Error()}), subagentFailed)
                }
        }
                        r.report(name, subagentReport(name, []string{"failed: " + err.Error()}), subagentFailed)
                }
        }
@@ -253,13 +256,27 @@ func (r *SubagentRuns) Resume(ctx context.Context) error {
        return r.save()
 }
 
        return r.save()
 }
 
+// Snapshot locks the run state, memory, and subagent logs while snapshot reads
+// the agent files. The lock order agrees with Stop, which logs under the run
+// lock.
+func (r *SubagentRuns) Snapshot(ctx context.Context, snapshot func() error) error {
+       r.mutex.Lock()
+       defer r.mutex.Unlock()
+
+       return r.memory.Snapshot(ctx, func() error {
+               return r.subagents.Snapshot(ctx, snapshot)
+       })
+}
+
 // 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()
+
        r.closed = true
        for _, run := range r.running {
                run.cancel()
        }
        r.closed = true
        for _, run := range r.running {
                run.cancel()
        }
+
        r.mutex.Unlock()
 
        r.workers.Wait()
        r.mutex.Unlock()
 
        r.workers.Wait()
@@ -317,12 +334,13 @@ func (r *SubagentRuns) effort(subagent *Subagent) (string, error) {
        return "", fmt.Errorf("the log of %s does not start with a subagent note", subagent.name)
 }
 
        return "", fmt.Errorf("the log of %s does not start with a subagent note", subagent.name)
 }
 
-// start runs run in the background. Its context keeps the values of ctx, but
-// only Stop and Close end it.
+// start runs run in the background and logs its start. Its context keeps the
+// values of ctx, but only Stop and Close end it.
 func (r *SubagentRuns) start(ctx context.Context, run *SubagentRun) error {
        ctx, run.cancel = context.WithCancel(context.WithoutCancel(ctx))
 
        r.mutex.Lock()
 func (r *SubagentRuns) start(ctx context.Context, run *SubagentRun) error {
        ctx, run.cancel = context.WithCancel(context.WithoutCancel(ctx))
 
        r.mutex.Lock()
+
        _, found := r.running[run.subagent.name]
        if r.closed || found {
                r.mutex.Unlock()
        _, found := r.running[run.subagent.name]
        if r.closed || found {
                r.mutex.Unlock()
@@ -348,6 +366,8 @@ func (r *SubagentRuns) start(ctx context.Context, run *SubagentRun) error {
        r.workers.Add(1)
        r.mutex.Unlock()
 
        r.workers.Add(1)
        r.mutex.Unlock()
 
+       run.started = r.subagents.clock()
+       r.logger.Info("subagent started", "name", run.subagent.name)
        r.notify(Event{
                Kind: "subagent",
                Text: run.subagent.name,
        r.notify(Event{
                Kind: "subagent",
                Text: run.subagent.name,
@@ -370,6 +390,7 @@ func (r *SubagentRuns) load() ([]string, error) {
        }
 
        var file SubagentWorkFile
        }
 
        var file SubagentWorkFile
+
        err = json.Unmarshal(data, &file)
        if err != nil {
                return nil, fmt.Errorf("decode running subagents: %w", err)
        err = json.Unmarshal(data, &file)
        if err != nil {
                return nil, fmt.Errorf("decode running subagents: %w", err)
@@ -402,21 +423,25 @@ func (r *SubagentRuns) workPath() string {
        return filepath.Join(r.agent.dir, subagentWorkFileName)
 }
 
        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
+// run runs the chains of run and reports and logs its end with the length of
+// the run, 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".
 func (r *SubagentRuns) run(ctx context.Context, run *SubagentRun) {
        defer r.workers.Done()
        defer run.cancel()
 
 // it, and no chain failed. A chain that Stop ends gives the reply "stopped".
 func (r *SubagentRuns) run(ctx context.Context, run *SubagentRun) {
        defer r.workers.Done()
        defer run.cancel()
 
-       var replies []string
-       var failure error
+       var (
+               replies []string
+               failure error
+       )
+
        stopped := false
        status := subagentFinished
        for more := true; more; {
                reply, err := r.chain(ctx, run)
 
                r.mutex.Lock()
        stopped := false
        status := subagentFinished
        for more := true; more; {
                reply, err := r.chain(ctx, run)
 
                r.mutex.Lock()
+
                stopped = run.stopped
                switch {
                case err != nil && stopped:
                stopped = run.stopped
                switch {
                case err != nil && stopped:
@@ -429,13 +454,17 @@ func (r *SubagentRuns) run(ctx context.Context, run *SubagentRun) {
 
                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
                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()
                        }
                }
                        if !r.closed {
                                saveErr = r.save()
                        }
                }
+
                r.mutex.Unlock()
 
                if saveErr != nil {
                r.mutex.Unlock()
 
                if saveErr != nil {
@@ -453,13 +482,14 @@ func (r *SubagentRuns) run(ctx context.Context, run *SubagentRun) {
                status = subagentStopped
        }
 
                status = subagentStopped
        }
 
+       length := r.subagents.clock().Sub(run.started)
        switch status {
        case subagentStopped:
        switch status {
        case subagentStopped:
-               r.logger.Printf("subagent %s stopped", run.subagent.name)
+               r.logger.Info("subagent stopped", "name", run.subagent.name, "after", length)
        case subagentFailed:
        case subagentFailed:
-               r.logger.Printf("subagent %s failed: %v", run.subagent.name, failure)
+               r.logger.Error("subagent failed", "name", run.subagent.name, "after", length, "err", failure)
        default:
        default:
-               r.logger.Printf("subagent %s done", run.subagent.name)
+               r.logger.Info("subagent done", "name", run.subagent.name, "after", length)
        }
 
        r.report(run.subagent.name, subagentReport(run.subagent.name, replies), status)
        }
 
        r.report(run.subagent.name, subagentReport(run.subagent.name, replies), status)
@@ -520,7 +550,7 @@ func (r *SubagentRuns) take(run *SubagentRun) []Message {
 
 // SubagentRun is one run of a subagent: the view that its requests get, its
 // effort, the end of its context, the messages of Tell that wait for a request,
 
 // SubagentRun is one run of a subagent: the view that its requests get, its
 // effort, the end of its context, the messages of Tell that wait for a request,
-// and whether Stop ended it. The mutex of SubagentRuns protects the messages
+// whether Stop ended it, and the time it started. The mutex of SubagentRuns protects the messages
 // and the stop.
 type SubagentRun struct {
        subagent *Subagent
 // and the stop.
 type SubagentRun struct {
        subagent *Subagent
@@ -529,6 +559,7 @@ type SubagentRun struct {
        cancel   context.CancelFunc
        pending  []Message
        stopped  bool
        cancel   context.CancelFunc
        pending  []Message
        stopped  bool
+       started  time.Time
 }
 
 // SubagentWorkFile is the content of work.json.
 }
 
 // SubagentWorkFile is the content of work.json.