oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package runner
2
3import (
4 "context"
5 "database/sql"
6 "encoding/base64"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "time"
11
12 "amadan.net/oficina/equipo/internal/equipo/team"
13 "amadan.net/oficina/equipo/internal/runner/provider"
14 "amadan.net/oficina/equipo/internal/runnerproto"
15)
16
17func directEventKey(s provider.Session, e provider.Event) string {
18 if e.Sequence > 0 {
19 return runnerproto.EventHash([]any{s.AttemptKey, e.Sequence, e.Kind})
20 }
21 return runnerproto.EventHash([]any{s.AttemptKey, e})
22}
23func (j *Journal) ObserveDirect(ctx context.Context, s provider.Session, e provider.Event) (*team.Usage, error) {
24 return j.appendDirect(ctx, s, e, nil)
25}
26func (p *EventPump) AppendDirect(ctx context.Context, s provider.Session, e provider.Event, template Event) error {
27 if p.Journal == nil || p.Contain == nil {
28 return runnerproto.ErrInvalid
29 }
30 if e.Kind == "turn.failed" && len(e.Payload) == 0 {
31 e.Payload = json.RawMessage(`{}`)
32 }
33 if !uniqueFrame(e.Payload) {
34 return p.directFailure(ctx, s.AttemptKey, runnerproto.ErrInvalid)
35 }
36 e.Payload = redactFrameSecrets(e.Payload, p.Secrets)
37 _, err := p.Journal.appendDirect(ctx, s, e, &template)
38 if err != nil {
39 return p.directFailure(ctx, s.AttemptKey, err)
40 }
41 return nil
42}
43func (p *EventPump) directFailure(ctx context.Context, attempt string, err error) error {
44 _ = p.Journal.storageFailure(ctx, err)
45 cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
46 defer cancel()
47 containmentErr := p.Contain(cleanup)
48 journalErr := p.Journal.interruptDirect(cleanup, attempt, containmentErr == nil)
49 if journalErr != nil {
50 _ = p.Journal.fail()
51 }
52 return errors.Join(err, containmentErr, journalErr)
53}
54func (j *Journal) appendDirect(ctx context.Context, s provider.Session, e provider.Event, template *Event) (*team.Usage, error) {
55 if e.Kind == "turn.failed" && len(e.Payload) == 0 {
56 e.Payload = json.RawMessage(`{}`)
57 }
58 if e.SessionID != s.ID || e.Kind == "" || len(e.Payload) > MaxFrameBytes || !uniqueFrame(e.Payload) {
59 return nil, runnerproto.ErrInvalid
60 }
61 e.Payload = redactFrame(e.Payload)
62 tx, err := j.db.BeginTx(ctx, nil)
63 if err != nil {
64 return nil, j.storageFailure(ctx, err)
65 }
66 var usage *team.Usage
67 err = func() error {
68 defer tx.Rollback()
69 l, err := directLaunchTx(ctx, tx, s)
70 if err != nil {
71 return err
72 }
73 key := directEventKey(s, e)
74 body, _ := json.Marshal(e)
75 body = redactFrame(body)
76 var old, receipt []byte
77 var projected int
78 err = tx.QueryRowContext(ctx, "SELECT body,usage,projected FROM direct_events WHERE event_key=?", key).Scan(&old, &receipt, &projected)
79 if err == nil {
80 if string(old) != string(body) {
81 return runnerproto.ErrInvalid
82 }
83 if len(receipt) > 0 && json.Unmarshal(receipt, &usage) != nil {
84 return ErrJournal
85 }
86 if template == nil || projected == 1 {
87 return nil
88 }
89 } else {
90 if !errors.Is(err, sql.ErrNoRows) {
91 return err
92 }
93 if e.TurnID != "" {
94 var state string
95 if err = tx.QueryRowContext(ctx, "SELECT state FROM direct_turns WHERE attempt=? AND session=? AND turn=?", s.AttemptKey, s.ID, e.TurnID).Scan(&state); err != nil {
96 if !errors.Is(err, sql.ErrNoRows) {
97 return err
98 }
99 return provider.ErrIdentity
100 }
101 if (e.Kind == "turn.completed" || e.Kind == "turn.failed") && (state == "intent" || state == "completed") {
102 return errDirectUncertain
103 }
104 profile := directProfile(l)
105 stream, _ := usageKeys(profile, e)
106 acc := NewUsageAccumulator(profile)
107 var saved []byte
108 err = tx.QueryRowContext(ctx, "SELECT body FROM direct_usage WHERE stream=?", stream).Scan(&saved)
109 if err == nil {
110 if json.Unmarshal(saved, &acc.direct) != nil {
111 return ErrJournal
112 }
113 } else if !errors.Is(err, sql.ErrNoRows) {
114 return err
115 }
116 if state == "dispatched" {
117 usage = acc.Observe(e)
118 }
119 checkpoint, _ := json.Marshal(acc.direct)
120 if _, err = tx.ExecContext(ctx, "INSERT INTO direct_usage VALUES(?,?) ON CONFLICT(stream) DO UPDATE SET body=excluded.body", stream, checkpoint); err != nil {
121 return err
122 }
123 receipt, _ = json.Marshal(usage)
124 if (e.Kind == "turn.completed" || e.Kind == "turn.failed") && state == "dispatched" {
125 next := "waiting_for_person"
126 if e.Kind == "turn.completed" {
127 next = "completed"
128 }
129 if _, err = tx.ExecContext(ctx, "UPDATE direct_turns SET state=?,usage=? WHERE attempt=? AND turn=?", next, receipt, s.AttemptKey, e.TurnID); err != nil {
130 return err
131 }
132 }
133 }
134 var size int64
135 var blocked int
136 if err = tx.QueryRowContext(ctx, "SELECT blocked,"+directPendingSize+" FROM journal_state WHERE id=1").Scan(&blocked, &size); err != nil {
137 return err
138 }
139 if size >= 0 && int64(len(body)) > j.maxBytes-size {
140 return ErrJournalBudget
141 }
142 if blocked != 0 || size < 0 {
143 return ErrJournal
144 }
145 if _, err = tx.ExecContext(ctx, "INSERT INTO direct_events(event_key,attempt,body,usage) VALUES(?,?,?,?)", key, s.AttemptKey, body, receipt); err != nil {
146 return err
147 }
148 }
149 if template != nil {
150 events, err := projectDirect(s, e, usage, *template, key)
151 if err != nil {
152 return err
153 }
154 for _, event := range events {
155 raw, _ := json.Marshal(event)
156 if err = j.appendTx(ctx, tx, event, event.ContentHash(), raw); err != nil {
157 return err
158 }
159 }
160 if _, err = tx.ExecContext(ctx, "UPDATE direct_events SET projected=1 WHERE event_key=?", key); err != nil {
161 return err
162 }
163 }
164 return tx.Commit()
165 }()
166 if err != nil {
167 if errors.Is(err, provider.ErrIdentity) || errors.Is(err, runnerproto.ErrInvalid) {
168 return nil, err
169 }
170 return nil, j.storageFailure(ctx, err)
171 }
172 return usage, nil
173}
174func projectDirect(s provider.Session, e provider.Event, u *team.Usage, template Event, key string) ([]Event, error) {
175 envelope := struct {
176 Provider string `json:"provider"`
177 Event provider.Event `json:"event"`
178 Usage *team.Usage `json:"usage"`
179 }{s.Provider, e, u}
180 body, err := json.Marshal(envelope)
181 if err != nil {
182 return nil, err
183 }
184 template.ServerID = "direct"
185 template.AgentID = s.AttemptKey
186 template.SessionID = s.ID
187 template.TurnID = e.TurnID
188 template.RequestID = e.RequestID
189 template.Sequence = nil
190 template.Epoch = "direct-v2"
191 template.Kind = e.Kind
192 template.ID = key
193 template.RequestID = key
194 var result []Event
195 if len(body) > runnerproto.MaxEventBytes {
196 // Preserve the complete normalized envelope in ordered chunks. The final
197 // lifecycle/usage event remains small and references the durable chunks.
198 const chunkBytes = 8 << 10
199 total := (len(body) + chunkBytes - 1) / chunkBytes
200 for offset, index := 0, 0; offset < len(body); offset, index = offset+chunkBytes, index+1 {
201 end := offset + chunkBytes
202 if end > len(body) {
203 end = len(body)
204 }
205 part := template
206 part.Kind = "direct_chunk"
207 part.ID = fmt.Sprintf("%s-%d", key, index)
208 part.RequestID = part.ID
209 part.Payload, _ = json.Marshal(struct {
210 Key string `json:"key"`
211 Index, Total int
212 Data string `json:"base64"`
213 }{key, index, total, base64.StdEncoding.EncodeToString(body[offset:end])})
214 if err = part.Validate(); err != nil {
215 return nil, err
216 }
217 result = append(result, part)
218 }
219 template.Payload, _ = json.Marshal(struct {
220 Key string `json:"chunks"`
221 Count int `json:"count"`
222 Kind string `json:"kind"`
223 Usage *team.Usage `json:"usage"`
224 }{key, total, e.Kind, u})
225 } else {
226 template.Payload = body
227 }
228 if err = template.Validate(); err != nil {
229 return nil, err
230 }
231 return append(result, template), nil
232}
233