feat(agent): 云端 Agent - 增加上下文预算、任务事实与终态恢复保障

This commit is contained in:
ddCat committed 2026-09-19 20:43:20 +08:00
1 parent 3bf21d79af
commit b52bc9d5f2
61 files changed
+3512 -309

No files matched your search

@@ -0,0 +1,14 @@
package repository
import "infinite-canvas/backend/internal/model"
func billingChargeLimitApplies(order model.BillingOrder) bool {
return order.ChargeLimitSet || order.ChargeLimitMicrocredits > 0
}
func validateBillingChargeLimit(order model.BillingOrder, amount int64) error {
if amount < 0 || (billingChargeLimitApplies(order) && (order.ChargeLimitMicrocredits < 0 || amount > order.ChargeLimitMicrocredits)) {
return ErrBillingChargeLimit
}
return nil
}
@@ -0,0 +1,75 @@
package repository
import (
"errors"
"testing"
"infinite-canvas/backend/internal/model"
)
func TestAgentRouteReplacementCannotExpandApprovedCharge(t *testing.T) {
repo, db := newRefundedBillingRecoveryRepository(t)
if err := db.AutoMigrate(&model.Task{}); err != nil {
t.Fatal(err)
}
task := model.Task{ID: "generation-task", UserID: "user", AgentRunID: "run", GenerationID: "generation", Status: model.TaskStatusRunning, RouteID: "original", BillingOrderID: "order", AuthorizedChargeMicrocredits: 100}
order := model.BillingOrder{ID: "order", TaskID: task.ID, UserID: task.UserID, Status: model.BillingStatusRunning, BillingMode: "per_second", AmountMicrocredits: 100, ReservedAmountMicrocredits: 100, ChargeLimitSet: true, ChargeLimitMicrocredits: 100}
for _, item := range []any{&task, &order, &model.CreditAccount{UserID: "user", AvailableMicrocredits: 1000, ReservedMicrocredits: 100}} {
if err := db.Create(item).Error; err != nil {
t.Fatal(err)
}
}
replacement := order
replacement.AmountMicrocredits = 101
if err := repo.SwitchTaskLogicalRoute(task.ID, "original", "expensive", "{}", order.ID, "channel", "model", &replacement, model.BillingCostSnapshot{}); !errors.Is(err, ErrBillingChargeLimit) {
t.Fatalf("expensive fallback accepted: %v", err)
}
stored, err := repo.Task(task.ID)
if err != nil || stored.RouteID != "original" {
t.Fatalf("route not rolled back: %+v %v", stored, err)
}
var account model.CreditAccount
if err := db.First(&account, "user_id = ?", "user").Error; err != nil {
t.Fatal(err)
}
if account.AvailableMicrocredits != 1000 || account.ReservedMicrocredits != 100 {
t.Fatalf("credits changed: %+v", account)
}
replacement.AmountMicrocredits = 90
if err := repo.SwitchTaskLogicalRoute(task.ID, "original", "cheaper", "{}", order.ID, "channel", "model", &replacement, model.BillingCostSnapshot{}); err != nil {
t.Fatal(err)
}
if err := repo.SettleBillingOrder(order.ID, "provider"); err != nil {
t.Fatal(err)
}
var settled model.BillingOrder
if err := db.First(&settled, "id = ?", order.ID).Error; err != nil {
t.Fatal(err)
}
if !settled.ChargeLimitSet || settled.ChargeLimitMicrocredits != 100 || settled.ActualAmountMicrocredits != 90 {
t.Fatalf("lost authorization: %+v", settled)
}
}
func TestBillingSettlementRejectsFixedChargeBeyondAuthorization(t *testing.T) {
for _, restored := range []bool{false, true} {
repo, db := newRefundedBillingRecoveryRepository(t)
status := model.BillingStatusRunning
if restored {
status = model.BillingStatusRefunded
}
order := model.BillingOrder{ID: "order", UserID: "user", Status: status, BillingMode: "fixed_request", AmountMicrocredits: 10, ChargeLimitSet: true, ChargeLimitMicrocredits: 0}
if err := db.Create(&order).Error; err != nil {
t.Fatal(err)
}
var err error
if restored {
err = repo.RestoreRefundedBillingOrder(order.ID, "")
} else {
err = repo.SettleBillingOrder(order.ID, "")
}
if !errors.Is(err, ErrBillingChargeLimit) {
t.Fatalf("zero authorization treated as uncapped: %v", err)
}
}
}
+121 -1
View File
@@ -1,6 +1,9 @@
package repository
import (
"bytes"
"encoding/json"
"fmt"
"time"
"gorm.io/gorm"
@@ -9,17 +12,51 @@ import (
)
func (r *Repository) EnsureCloudAgent(run *model.CloudAgentExecution) error {
if run.ConversationID == "" {
run.ConversationID = run.ID
if run.ParentID != "" {
var parent model.CloudAgentExecution
if err := r.db.Select("id", "conversation_id", "title").First(&parent, "id = ? AND user_id = ?", run.ParentID, run.UserID).Error; err != nil {
return err
}
if parent.ConversationID != "" {
run.ConversationID = parent.ConversationID
} else {
run.ConversationID = parent.ID
}
run.Title = parent.Title
}
}
return r.db.Clauses(clause.OnConflict{DoNothing: true}).Create(run).Error
}
func (r *Repository) CloudAgent(userID, id string) (*model.CloudAgentExecution, error) {
var run model.CloudAgentExecution
err := r.db.First(&run, "id = ? AND user_id = ?", id, userID).Error
if err == nil {
err = r.hydrateCloudAgent(&run)
}
return &run, err
}
func (r *Repository) hydrateCloudAgent(run *model.CloudAgentExecution) error {
if run.CheckpointVersion < 2 {
return nil
}
if err := r.db.Where("run_id = ? AND user_id = ?", run.ID, run.UserID).Order("sequence").Find(&run.Journal).Error; err != nil {
return err
}
if err := r.db.Where("run_id = ? AND user_id = ?", run.ID, run.UserID).Order("kind, sequence").Find(&run.Transcript).Error; err != nil {
return err
}
return nil
}
func (r *Repository) CloudAgentForActiveTask(userID, taskID string) (*model.CloudAgentExecution, error) {
var run model.CloudAgentExecution
err := r.db.Where("user_id = ? AND active_task_id = ? AND status IN ?", userID, taskID, []string{"running", "queued"}).First(&run).Error
if err == nil {
err = r.hydrateCloudAgent(&run)
}
return &run, err
}
func (r *Repository) CloudAgentRoots() ([]model.Task, error) {
@@ -35,6 +72,13 @@ func (r *Repository) ActiveCloudAgentsAfter(after string, limit int) ([]model.Cl
limit = 50
}
err := r.db.Where("(status IN ? OR cleanup_pending = ?) AND id > ?", []string{"running", "queued"}, true, after).Order("id").Limit(limit).Find(&runs).Error
if err == nil {
for i := range runs {
if err = r.hydrateCloudAgent(&runs[i]); err != nil {
break
}
}
}
return runs, err
}
@@ -63,13 +107,89 @@ func (r *Repository) MutateCloudAgent(userID, id string, revision int64, fn func
if err != nil {
return err
}
previousEvents := run.EventCount
previousEventBodies := make(map[int]string, len(run.Journal))
for _, event := range run.Journal {
previousEventBodies[event.Sequence] = event.EventJSON
}
previousMessages := make(map[string]string, len(run.Transcript))
for _, message := range run.Transcript {
previousMessages[fmt.Sprintf("%s:%d", message.Kind, message.Sequence)] = message.MessageJSON
}
if err = fn(run, New(tx)); err != nil {
return err
}
return tx.Save(run).Error
if run.EventCount < previousEvents || len(run.Journal) != run.EventCount {
return fmt.Errorf("cloud Agent journal cannot be truncated")
}
for sequence, body := range previousEventBodies {
if sequence > len(run.Journal) || run.Journal[sequence-1].Sequence != sequence || !sameJSONDocument(run.Journal[sequence-1].EventJSON, body) {
return fmt.Errorf("cloud Agent journal is append-only")
}
}
if err = tx.Omit("Journal", "Transcript").Save(run).Error; err != nil {
return err
}
for _, event := range run.Journal {
if event.Sequence <= previousEvents {
continue
}
if err = tx.Create(&event).Error; err != nil {
return err
}
}
for _, message := range run.Transcript {
key := fmt.Sprintf("%s:%d", message.Kind, message.Sequence)
if previousMessages[key] == message.MessageJSON {
continue
}
if err = tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "run_id"}, {Name: "kind"}, {Name: "sequence"}}, DoUpdates: clause.AssignmentColumns([]string{"message_json"})}).Create(&message).Error; err != nil {
return err
}
}
for _, kind := range []string{"canonical", "history"} {
count := 0
for _, message := range run.Transcript {
if message.Kind == kind {
count++
}
}
if err = tx.Where("run_id = ? AND user_id = ? AND kind = ? AND sequence > ?", run.ID, run.UserID, kind, count).Delete(&model.CloudAgentMessageRecord{}).Error; err != nil {
return err
}
}
return nil
})
}
// sameJSONDocument compares event records by JSON meaning rather than source
// bytes. Event payloads may contain json.RawMessage (for example tool arguments),
// so decode/re-encode can legally normalize whitespace or object key order while
// preserving the immutable event contract.
func sameJSONDocument(left, right string) bool {
decode := func(raw string) (any, error) {
decoder := json.NewDecoder(bytes.NewReader([]byte(raw)))
decoder.UseNumber()
var value any
if err := decoder.Decode(&value); err != nil {
return nil, err
}
var extra any
if err := decoder.Decode(&extra); err == nil {
return nil, fmt.Errorf("multiple JSON documents")
}
return value, nil
}
leftValue, leftErr := decode(left)
rightValue, rightErr := decode(right)
if leftErr != nil || rightErr != nil {
return left == right
}
leftCanonical, leftErr := json.Marshal(leftValue)
rightCanonical, rightErr := json.Marshal(rightValue)
return leftErr == nil && rightErr == nil && bytes.Equal(leftCanonical, rightCanonical)
}
func (r *Repository) CreateCloudAgentCanvasMutation(mutation *model.CloudAgentCanvasMutation) error {
return r.db.Create(mutation).Error
}
@@ -0,0 +1,104 @@
package repository
import (
"sort"
"time"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"infinite-canvas/backend/internal/model"
)
func (r *Repository) UpsertCloudAgentResourceLeases(userID, runID, ownerID string, resourceIDs []string, expiresAt time.Time) error {
resourceIDs = uniqueSortedStrings(resourceIDs)
for _, id := range resourceIDs {
lease := model.CloudAgentResourceLease{UserID: userID, RunID: runID, OwnerID: ownerID, ResourceID: id, ExpiresAt: expiresAt}
if err := r.db.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "user_id"}, {Name: "owner_id"}, {Name: "resource_id"}}, DoUpdates: clause.AssignmentColumns([]string{"run_id", "expires_at"})}).Create(&lease).Error; err != nil {
return err
}
}
return nil
}
// ReplaceCloudAgentResourceLeases makes an approval owner's resource set
// authoritative after the user changes generation settings.
func (r *Repository) ReplaceCloudAgentResourceLeases(userID, runID, ownerID string, resourceIDs []string, expiresAt time.Time) error {
return r.db.Transaction(func(tx *gorm.DB) error {
if err := tx.Where("user_id = ? AND owner_id = ?", userID, ownerID).Delete(&model.CloudAgentResourceLease{}).Error; err != nil {
return err
}
for _, id := range uniqueSortedStrings(resourceIDs) {
lease := model.CloudAgentResourceLease{UserID: userID, RunID: runID, OwnerID: ownerID, ResourceID: id, ExpiresAt: expiresAt}
if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "user_id"}, {Name: "owner_id"}, {Name: "resource_id"}}, DoUpdates: clause.AssignmentColumns([]string{"run_id", "expires_at"})}).Create(&lease).Error; err != nil {
return err
}
}
return nil
})
}
func (r *Repository) ReleaseCloudAgentResourceLeases(userID, ownerID string) error {
return r.db.Where("user_id = ? AND owner_id = ?", userID, ownerID).Delete(&model.CloudAgentResourceLease{}).Error
}
func (r *Repository) ReleaseCloudAgentResourceLeasesByRun(userID, runID string) error {
return r.db.Where("user_id = ? AND run_id = ?", userID, runID).Delete(&model.CloudAgentResourceLease{}).Error
}
func (r *Repository) TransferCloudAgentResourceLeases(userID, fromOwner, toOwner, runID string, expiresAt time.Time) error {
if fromOwner == "" || toOwner == "" || fromOwner == toOwner {
return nil
}
return r.db.Transaction(func(tx *gorm.DB) error {
var leases []model.CloudAgentResourceLease
if err := tx.Where("user_id = ? AND owner_id = ?", userID, fromOwner).Find(&leases).Error; err != nil {
return err
}
if err := tx.Where("user_id = ? AND owner_id = ?", userID, toOwner).Delete(&model.CloudAgentResourceLease{}).Error; err != nil {
return err
}
for _, lease := range leases {
lease.OwnerID, lease.RunID, lease.ExpiresAt = toOwner, runID, expiresAt
if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "user_id"}, {Name: "owner_id"}, {Name: "resource_id"}}, DoUpdates: clause.AssignmentColumns([]string{"run_id", "expires_at"})}).Create(&lease).Error; err != nil {
return err
}
}
return tx.Where("user_id = ? AND owner_id = ?", userID, fromOwner).Delete(&model.CloudAgentResourceLease{}).Error
})
}
func (r *Repository) ReleaseExpiredCloudAgentResourceLeases(now time.Time) error {
return r.db.Where("expires_at <= ?", now).Delete(&model.CloudAgentResourceLease{}).Error
}
func uniqueSortedStrings(values []string) []string {
seen := make(map[string]struct{}, len(values))
result := make([]string, 0, len(values))
for _, value := range values {
if value == "" {
continue
}
if _, ok := seen[value]; ok {
continue
}
seen[value] = struct{}{}
result = append(result, value)
}
sort.Strings(result)
return result
}
func (r *Repository) CloudAgentCanvasMutationChain(userID, runID, canvasID string) ([]model.CloudAgentCanvasMutation, error) {
var records []model.CloudAgentCanvasMutation
err := r.db.Where("user_id = ? AND run_id = ? AND canvas_id = ? AND status IN ?", userID, runID, canvasID, []string{"applied", "not_undoable"}).Order("created_at, id").Find(&records).Error
return records, err
}
// LatestCloudAgentCanvasMutationForCanvas is used to distinguish a current-run
// write from a later Agent run write. Manual canvas edits have no mutation row;
// comparing the row's after hash with the live document then rejects them too.
func (r *Repository) LatestCloudAgentCanvasMutationForCanvas(userID, canvasID string) (*model.CloudAgentCanvasMutation, error) {
var mutation model.CloudAgentCanvasMutation
err := r.db.Where("user_id = ? AND canvas_id = ? AND status IN ?", userID, canvasID, []string{"applied", "not_undoable"}).Order("created_at DESC, id DESC").First(&mutation).Error
return &mutation, err
}
+17 -2
View File
@@ -23,6 +23,7 @@ var (
ErrTaskNotRetryable = errors.New("task is not retryable")
ErrBillingStateConflict = errors.New("billing state conflict")
ErrBillingUsageUnavailable = errors.New("billing usage unavailable")
ErrBillingChargeLimit = errors.New("billing amount exceeds authorized charge limit")
ErrChannelModelInUse = errors.New("channel model is in use")
)
@@ -463,6 +464,7 @@ func (r *Repository) RetryTaskWithBilling(userID string, prepared *model.Task, o
}
updates := map[string]any{
"status": model.TaskStatusQueued, "stage": "等待队列调度", "progress": 5, "error": "", "result_json": "",
"execution_diagnostic_json": "", "cancellation_source": "", "cancellation_actor_id": "", "cancellation_requested_at": nil,
"text_draft": "", "started_at": nil, "completed_at": nil,
"provider_request_id": "", "poll_stage": "", "next_poll_at": nil,
"provider_cancel_status": "", "provider_cancel_error": "", "provider_cancel_attempts": 0,
@@ -514,6 +516,9 @@ func (r *Repository) ReserveBillingOrder(order *model.BillingOrder) error {
}
func reserveBillingOrder(tx *gorm.DB, order *model.BillingOrder) error {
if err := validateBillingChargeLimit(*order, order.AmountMicrocredits); err != nil {
return err
}
if order.ReservedAmountMicrocredits <= 0 {
order.ReservedAmountMicrocredits = order.AmountMicrocredits
}
@@ -743,6 +748,11 @@ func (r *Repository) SettleBillingOrder(id string, providerRequestID string) err
if order.Status == model.BillingStatusRefunded {
return errors.New("billing order already refunded")
}
if order.BillingMode != "token" {
if err := validateBillingChargeLimit(order, order.AmountMicrocredits); err != nil {
return err
}
}
if order.BillingMode == "token" && !zeroPricedTokenOrder(order) {
usage, usageSource, err := tokenSettlementUsage(tx, order)
if err != nil {
@@ -758,7 +768,7 @@ func (r *Repository) SettleBillingOrder(id string, providerRequestID string) err
if err != nil {
return err
}
chargeCapped := order.ChargeLimitMicrocredits > 0 && actual > order.ChargeLimitMicrocredits
chargeCapped := billingChargeLimitApplies(order) && actual > order.ChargeLimitMicrocredits
if chargeCapped {
actual = order.ChargeLimitMicrocredits
}
@@ -900,6 +910,11 @@ func (r *Repository) RestoreRefundedBillingOrder(id string, providerRequestID st
if order.Status != model.BillingStatusRefunded {
return ErrBillingStateConflict
}
if order.BillingMode != "token" {
if err := validateBillingChargeLimit(order, order.AmountMicrocredits); err != nil {
return err
}
}
actual := order.AmountMicrocredits
var usage *BillingUsage
@@ -919,7 +934,7 @@ func (r *Repository) RestoreRefundedBillingOrder(id string, providerRequestID st
}
}
}
chargeCapped := order.BillingMode == "token" && order.ChargeLimitMicrocredits > 0 && actual > order.ChargeLimitMicrocredits
chargeCapped := billingChargeLimitApplies(order) && actual > order.ChargeLimitMicrocredits
if chargeCapped {
actual = order.ChargeLimitMicrocredits
}
@@ -310,6 +310,11 @@ func (r *Repository) SwitchTaskLogicalRoute(taskID string, expectedRouteID strin
if replacement.UserID != order.UserID || replacement.TaskID != taskID || replacement.AmountMicrocredits <= 0 {
return ErrBillingStateConflict
}
// The new supplier price cannot expand the user's original authorization.
// Keep the existing cap; replacement is a price snapshot, not a new grant.
if err := validateBillingChargeLimit(order, replacement.AmountMicrocredits); err != nil {
return err
}
reserved := order.ReservedAmountMicrocredits
if reserved <= 0 {
reserved = order.AmountMicrocredits
+43 -6
View File
@@ -2,6 +2,7 @@ package repository
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
@@ -564,13 +565,49 @@ func (r *Repository) UpdateTaskTerminalState(id string, owner string, expected m
return result.RowsAffected == 1, result.Error
}
func (r *Repository) CancelTaskIfStatus(userID string, id string, expected model.TaskStatus, now time.Time) (bool, error) {
func (r *Repository) UpdateTaskTerminalDiagnostic(task *model.Task, completedAt time.Time) (bool, error) {
result := taskLeaseWriter(r.db.Model(&model.Task{}), task.LeaseOwner).
Where("id = ? AND status = ?", task.ID, model.TaskStatusRunning).
Updates(map[string]any{
"status": task.Status, "stage": task.Stage, "error": task.Error, "completed_at": &completedAt,
"execution_diagnostic_json": task.ExecutionDiagnosticJSON,
"cancellation_source": task.CancellationSource, "cancellation_actor_id": task.CancellationActorID,
"cancellation_requested_at": task.CancellationRequestedAt,
"lease_owner": "", "lease_expires_at": nil, "updated_at": completedAt,
})
return result.RowsAffected == 1, result.Error
}
func (r *Repository) UpdateTaskExecutionDiagnostic(userID, taskID, diagnosticJSON string) error {
result := r.db.Model(&model.Task{}).
Where("id = ? AND user_id = ?", taskID, userID).
Update("execution_diagnostic_json", diagnosticJSON)
if result.Error != nil {
return result.Error
}
if result.RowsAffected != 1 {
return gorm.ErrRecordNotFound
}
return nil
}
func (r *Repository) CancelTaskIfStatus(userID string, id string, expected model.TaskStatus, now time.Time, intents ...model.TaskCancellationIntent) (bool, error) {
updates := map[string]any{
"status": model.TaskStatusCancelled, "stage": "任务已取消", "error": "任务已取消", "completed_at": &now,
"lease_owner": "", "lease_expires_at": nil, "updated_at": now,
}
if len(intents) > 0 {
intent := intents[0]
diagnostic, err := json.Marshal(intent.Diagnostic)
if err != nil {
return false, err
}
updates["cancellation_source"], updates["cancellation_actor_id"], updates["cancellation_requested_at"] = intent.Source, intent.ActorID, intent.RequestedAt
updates["execution_diagnostic_json"] = string(diagnostic)
}
result := r.db.Model(&model.Task{}).
Where("id = ? AND user_id = ? AND status = ?", id, userID, expected).
Updates(map[string]any{
"status": model.TaskStatusCancelled, "stage": "任务已取消", "error": "任务已取消", "completed_at": &now,
"lease_owner": "", "lease_expires_at": nil, "updated_at": now,
})
Updates(updates)
return result.RowsAffected == 1, result.Error
}
@@ -659,7 +696,7 @@ func (r *Repository) Tasks(userID string, limit int, projectID string, activeOnl
if limit <= 0 || limit > 100 {
limit = 50
}
query := r.db.Select("id", "project_id", "type", "status", "stage", "progress", "prompt", "operation", "provider", "model", "input_json", "result_json", "billing_order_id", "provider_request_id", "provider_cancel_status", "provider_cancel_error", "provider_cancel_attempts", "provider_cancel_requested_at", "provider_cancelled_at", "provider_cancel_next_check_at", "attempts", "started_at", "completed_at", "created_at", "updated_at").
query := r.db.Select("id", "project_id", "type", "status", "stage", "progress", "prompt", "operation", "provider", "model", "input_json", "result_json", "billing_order_id", "provider_request_id", "provider_cancel_status", "provider_cancel_error", "provider_cancel_attempts", "provider_cancel_requested_at", "provider_cancelled_at", "provider_cancel_next_check_at", "attempts", "started_at", "completed_at", "created_at", "updated_at", "agent_run_id", "generation_id", "approval_id", "authorized_charge_microcredits", "execution_diagnostic_json", "cancellation_source", "cancellation_actor_id", "cancellation_requested_at").
Where("user_id = ?", userID)
if strings.TrimSpace(projectID) != "" {
query = query.Where("project_id = ?", strings.TrimSpace(projectID))
@@ -3,6 +3,7 @@ package repository
import (
"slices"
"strings"
"time"
"infinite-canvas/backend/internal/model"
@@ -91,6 +92,13 @@ func (r *Repository) ResourceReferenceSnapshot(userID string, excludingAssetID s
return snapshot, err
}
snapshot.Direct = append(snapshot.Direct, history...)
var leases []model.CloudAgentResourceLease
if err := r.db.Where("user_id = ? AND resource_id IN ? AND expires_at > ?", userID, resourceIDs, time.Now()).Find(&leases).Error; err != nil {
return snapshot, err
}
for _, lease := range leases {
snapshot.Direct = append(snapshot.Direct, ResourceDirectReference{Kind: "Agent 待执行引用", ID: lease.OwnerID, Title: "已准备的生成输入", ResourceID: lease.ResourceID})
}
var assets []model.Asset
assetQuery := r.db.Where("user_id = ? AND id <> ?", userID, excludingAssetID)