X-Git-Url: https://git.giacomolli.uk/onechat/blobdiff_plain/522d7fd117285e4e4ce3ea5ec9b5a1722521b681..6915dbdfeb246551bf1132823d820beb321fd58c:/rebuild.go diff --git a/rebuild.go b/rebuild.go index 52c0861..598371c 100644 --- a/rebuild.go +++ b/rebuild.go @@ -7,7 +7,7 @@ import ( "fmt" "io" "io/fs" - "log" + "log/slog" "os" "path/filepath" "slices" @@ -15,13 +15,20 @@ import ( "time" ) +// rebuildCallLimit is the most model calls of a rebuild. A rebuild summarizes +// the whole merged log, which can need more calls than a probe sample, and the +// quota stop of the build run still guards the account. +const rebuildCallLimit = 1500 + // rebuild merges added messages with the log of agent, in date order, and // builds a new memory beside it. The caller holds the token lock. The model // uses the original agent prompt and cache key. A failed or stopped build // removes the new directory and leaves the original directory unchanged. // Success copies the other agent files, adds this run's usage, and swaps the // directories, with the original kept as a timestamped backup. Message IDs are -// new positions in the merged log, but kind, text, and date stay exact. +// new positions in the merged log, but kind, text, and date stay exact. A child +// keeps its staging directory and backup outside children so that neither is +// read as a configured child. func rebuild(ctx context.Context, agent *Agent, added []DatedMessage, client *ModelClient, summarizer Summarizer, out io.Writer) (backup string, err error) { err = rebuildIdle(agent.dir) if err != nil { @@ -38,7 +45,14 @@ func rebuild(ctx context.Context, agent *Agent, added []DatedMessage, client *Mo return "", fmt.Errorf("merge rebuild messages: %w", err) } - root, err := os.MkdirTemp(filepath.Dir(agent.dir), ".agent-rebuild-") + parent := filepath.Dir(agent.dir) + backupDir := agent.dir + if agent.config.Parent != "" { + parent = filepath.Dir(parent) + backupDir = filepath.Join(parent, agent.config.Name) + } + + root, err := os.MkdirTemp(parent, ".agent-rebuild-") if err != nil { return "", fmt.Errorf("create rebuild directory: %w", err) } @@ -50,12 +64,12 @@ func rebuild(ctx context.Context, agent *Agent, added []DatedMessage, client *Mo } }() - memory, err := openMemory(ctx, root, time.Now, summarizer, log.New(io.Discard, "", 0)) + memory, err := openMemory(ctx, root, time.Now, summarizer, slog.New(slog.DiscardHandler)) if err != nil { return "", fmt.Errorf("open rebuilt memory: %w", err) } - client.LimitCalls(buildCallLimit) + client.LimitCalls(rebuildCallLimit) run := BuildRun{ memory: memory, @@ -105,7 +119,7 @@ func rebuild(ctx context.Context, agent *Agent, added []DatedMessage, client *Mo return "", ctx.Err() } - backup = agent.dir + "-backup-" + time.Now().Format("20060102-150405.000000000") + backup = backupDir + "-backup-" + time.Now().Format("20060102-150405.000000000") err = os.Rename(agent.dir, backup) if err != nil { return "", fmt.Errorf("back up agent: %w", err)