| 1 | package conversation |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/ownermode" |
| 5 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 6 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 7 | "context" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "gorm.io/gorm" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | func decodeCoordinator(raw string, v any) error { return json.Unmarshal([]byte(raw), v) } |
| 15 | func (e *Engine) claimCoordinator(ctx context.Context, p RunnerPrincipal, turnID string, revision int64) (CoordinatorClaim, error) { |
| 16 | var result CoordinatorClaim |
| 17 | var parked error |
| 18 | if revision <= 0 || turnID == "" { |
| 19 | return result, e.Invalid |
| 20 | } |
| 21 | err := e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| 22 | if err := e.Core.AdmissionAvailable(ctx); err != nil { |
| 23 | return err |
| 24 | } |
| 25 | b, row, sel, err := e.Current(ctx, tx, p, turnID) |
| 26 | if err != nil { |
| 27 | return err |
| 28 | } |
| 29 | if row.Revision != revision { |
| 30 | return e.Conflict |
| 31 | } |
| 32 | if row.State == "running" { |
| 33 | if err = decodeCoordinator(row.Claim, &result); err != nil { |
| 34 | return err |
| 35 | } |
| 36 | if err = e.Core.ValidateHandle(ctx, result.Scope, result.Handle); err != nil { |
| 37 | return err |
| 38 | } |
| 39 | // Replays return the same admission, including its original expiry. |
| 40 | _, err = e.Core.AdmitOnce(ctx, result.Scope, result.Handle, result.Admission.Dispatch.Action, row.RequestID) |
| 41 | return err |
| 42 | } |
| 43 | if row.State != "queued" && row.State != "waiting_connection" && row.State != "waiting_task" && row.State != "budget_needed" && row.State != "admission_denied" { |
| 44 | return e.Conflict |
| 45 | } |
| 46 | blocked, err := ownermode.CoordinatorBlocked(tx, row.TeamID, row.Person, row.ID, row.Generation, row.Sequence) |
| 47 | if err != nil { |
| 48 | return err |
| 49 | } |
| 50 | if blocked { |
| 51 | return e.Conflict |
| 52 | } |
| 53 | // A shared credential home remains unavailable while specialist work holds it. |
| 54 | var n int64 |
| 55 | if err = tx.Table("runner_assignments").Where("person=? AND state IN ('claimed','reconcile','fenced') AND attempt_id IN (SELECT id FROM attempts WHERE containment='pending') AND json_extract(selection,'$.ConnectionID')=?", p.Person, b.ConnectionID).Count(&n).Error; err != nil { |
| 56 | return err |
| 57 | } |
| 58 | if n > 0 { |
| 59 | return e.Unavailable |
| 60 | } |
| 61 | cleared := tx.Where("principal=? AND operation='coordinator.waiting' AND resource=?", row.Person, b.ID).Delete(&requestRecord{}) |
| 62 | if cleared.Error != nil { |
| 63 | return cleared.Error |
| 64 | } |
| 65 | if cleared.RowsAffected > 0 { |
| 66 | if err = tx.Model(&Main{}).Where("id=?", row.ConversationID).Select("revision").Updates(map[string]any{"revision": gorm.Expr("revision+1")}).Error; err != nil { |
| 67 | return err |
| 68 | } |
| 69 | } |
| 70 | contextValue, err := e.contextStore(tx).CoordinatorContext(ctx, CoordinatorClaim{Binding: b.CoordinatorBinding, Turn: row.CoordinatorTurn, Brief: runnerproto.RunnerBrief{Selection: sel}}) |
| 71 | if errors.Is(err, runnerproto.ErrPromptTooLarge) { |
| 72 | parked = e.ContextLimit |
| 73 | if parked == nil { |
| 74 | parked = runnerproto.ErrPromptTooLarge |
| 75 | } |
| 76 | return e.waitCoordinator(tx, b, row, "context_limit") |
| 77 | } |
| 78 | if errors.Is(err, errCoordinatorContextUnavailable) { |
| 79 | parked = e.ContextUnavailable |
| 80 | if parked == nil { |
| 81 | parked = e.Invalid |
| 82 | } |
| 83 | return e.waitCoordinator(tx, b, row, "context_unavailable") |
| 84 | } |
| 85 | if err != nil { |
| 86 | return err |
| 87 | } |
| 88 | hash := contextValue.Hash |
| 89 | row.ContextHash = hash |
| 90 | if row.ProjectID > 0 { |
| 91 | row.ProjectRevision, err = e.CheckProject(tx, p.Person, row.ProjectID, sel) |
| 92 | if err != nil { |
| 93 | return err |
| 94 | } |
| 95 | } |
| 96 | if e.Defaults != nil { |
| 97 | if err = e.Defaults(ctx, tx, sel); err != nil { |
| 98 | return err |
| 99 | } |
| 100 | } |
| 101 | limits, _, err := e.Core.CoordinatorLimits(ctx, team.AccountID(row.TeamID), p.Person) |
| 102 | if err != nil { |
| 103 | return err |
| 104 | } |
| 105 | policy, err := team.RunnerPolicy("subscription", limits, team.Limits{Calls: 1, InputTokens: min(limits.InputTokens, 32000), OutputTokens: min(limits.OutputTokens, 4000)}, team.Rates{}) |
| 106 | if err != nil { |
| 107 | return err |
| 108 | } |
| 109 | policy.MaxAttemptsPerStep = 1 |
| 110 | policy.AttemptSeconds = int(min(limits.Seconds, 1200)) |
| 111 | policy.JobSeconds = policy.AttemptSeconds |
| 112 | spec := team.JobSpec{RequestKey: "coordinator:" + row.ID, Account: team.AccountID(row.TeamID), Requester: p.Person, GrantRef: team.CoordinatorGrantRef(p.Person), Target: team.TargetBinding{Kind: team.TargetConversation, Subject: p.Person}, Policy: policy, Steps: []team.StepSpec{{Key: "coordinate", Capability: team.CapCoordinate, Version: 1}}} |
| 113 | job, err := e.Core.CreateJob(ctx, spec) |
| 114 | if err != nil { |
| 115 | return err |
| 116 | } |
| 117 | scope := team.Scope{Account: job.Account, Job: job.ID} |
| 118 | handle, err := e.Core.Claim(ctx, scope, "coordinate", p.RunnerID, "coordinator:"+row.ID) |
| 119 | if err != nil { |
| 120 | return err |
| 121 | } |
| 122 | payload, err := json.Marshal(struct { |
| 123 | TurnID, MessageID, ContextHash, BindingID string |
| 124 | Generation int64 |
| 125 | }{row.ID, row.MessageID, hash, b.ID, b.Generation}) |
| 126 | if err != nil { |
| 127 | return err |
| 128 | } |
| 129 | action, err := e.Core.Intend(ctx, scope, handle, team.IntentSpec{Key: row.ID, Operation: team.OpProviderCall, Payload: payload}) |
| 130 | if err != nil { |
| 131 | return err |
| 132 | } |
| 133 | ticket, err := e.Core.AdmitOnce(ctx, scope, handle, action, row.RequestID) |
| 134 | if err != nil { |
| 135 | return err |
| 136 | } |
| 137 | attempts, err := e.Core.Attempts(ctx, scope) |
| 138 | if err != nil { |
| 139 | return err |
| 140 | } |
| 141 | var lease, deadline time.Time |
| 142 | for _, attempt := range attempts { |
| 143 | if attempt.ID == handle.Attempt { |
| 144 | lease = attempt.LeaseDeadline |
| 145 | deadline = attempt.CreatedAt.Add(time.Duration(policy.AttemptSeconds) * time.Second) |
| 146 | } |
| 147 | } |
| 148 | if lease.IsZero() { |
| 149 | return e.Unavailable |
| 150 | } |
| 151 | if end := job.CreatedAt.Add(time.Duration(policy.JobSeconds) * time.Second); end.Before(deadline) { |
| 152 | deadline = end |
| 153 | } |
| 154 | row.State = "running" |
| 155 | row.JobID = int64(job.ID) |
| 156 | row.AttemptID = int64(handle.Attempt) |
| 157 | row.Fence = handle.Fence |
| 158 | row.Selection = string(mustCoordinatorJSON(sel)) |
| 159 | result = CoordinatorClaim{ToolCopy: e.ToolCopy, Binding: b.CoordinatorBinding, Turn: row.CoordinatorTurn, Scope: scope, Handle: handle, Context: contextValue, Admission: ticket, LeaseDeadline: lease, AttemptDeadline: deadline, Brief: runnerproto.RunnerBrief{AttemptDeadline: deadline, Step: runnerproto.StepBrief{StepKey: "coordinate", Action: "coordinate", SpecialistKey: "coordinator"}, Policy: policy, Target: spec.Target, Selection: sel}} |
| 160 | row.Claim = string(mustCoordinatorJSON(result)) |
| 161 | if err = tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("state", "job_id", "attempt_id", "fence", "claim", "selection", "context_hash", "project_revision").Updates(&row).Error; err != nil { |
| 162 | return err |
| 163 | } |
| 164 | return e.Audit(tx, b, "coordinator.claim", row.ID) |
| 165 | }) |
| 166 | if err != nil { |
| 167 | return CoordinatorClaim{}, err |
| 168 | } |
| 169 | if parked != nil { |
| 170 | return CoordinatorClaim{}, parked |
| 171 | } |
| 172 | return result, nil |
| 173 | } |
| 174 | func mustCoordinatorJSON(v any) []byte { raw, _ := json.Marshal(v); return raw } |
| 175 | func (e *Engine) validateCoordinatorClaim(ctx context.Context, tx *gorm.DB, p RunnerPrincipal, c CoordinatorClaim) (BindingRecord, TurnRecord, error) { |
| 176 | b, row, _, err := e.Current(ctx, tx, p, c.Turn.ID) |
| 177 | if err != nil { |
| 178 | return b, row, err |
| 179 | } |
| 180 | var saved CoordinatorClaim |
| 181 | if err = decodeCoordinator(row.Claim, &saved); err != nil { |
| 182 | return b, row, err |
| 183 | } |
| 184 | if runnerproto.EventHash(saved) != runnerproto.EventHash(c) { |
| 185 | return b, row, e.Forbidden |
| 186 | } |
| 187 | return b, row, nil |
| 188 | } |
| 189 | func (e *Engine) ValidateCoordinator(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim) error { |
| 190 | return e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| 191 | _, row, err := e.validateCoordinatorClaim(ctx, tx, p, c) |
| 192 | if err != nil { |
| 193 | return err |
| 194 | } |
| 195 | if row.State != "running" { |
| 196 | return e.Conflict |
| 197 | } |
| 198 | return e.Core.ValidateHandle(ctx, c.Scope, c.Handle) |
| 199 | }) |
| 200 | } |
| 201 | func (e *Engine) RenewCoordinator(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim) (time.Time, error) { |
| 202 | var deadline time.Time |
| 203 | err := e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| 204 | _, row, err := e.validateCoordinatorClaim(ctx, tx, p, c) |
| 205 | if err != nil { |
| 206 | return err |
| 207 | } |
| 208 | if row.State != "running" { |
| 209 | return e.Conflict |
| 210 | } |
| 211 | deadline, err = e.Core.Renew(ctx, c.Scope, c.Handle) |
| 212 | return err |
| 213 | }) |
| 214 | return deadline, err |
| 215 | } |
| 216 | |