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 "bufio"
5 "bytes"
6 "context"
7 "database/sql"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "io"
12 "strings"
13 "sync"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/runner/containment"
17 "amadan.net/oficina/equipo/internal/runner/provider"
18 "amadan.net/oficina/equipo/internal/runner/provider/claude"
19 "amadan.net/oficina/equipo/internal/runnerproto"
20)
21
22const MaxFrameBytes = 1 << 20
23const maxDiagnostics = 64 << 10
24const directPendingSize = `((SELECT COALESCE(SUM(length(body)),0) FROM coordinator_tool_claims)+(SELECT COALESCE(SUM(length(body)+COALESCE(length(result),0)),0) FROM coordinator_tools)+(SELECT COALESCE(SUM(size),0) FROM journal_events WHERE acked=0)+(SELECT COALESCE(SUM(length(body)),0) FROM journal_tools WHERE acked=0)+(SELECT COALESCE(SUM(length(body)),0) FROM direct_frames WHERE pending=1)+(SELECT COALESCE(SUM(length(body)),0) FROM direct_events WHERE projected=0))`
25
26type captureFactory struct{ journal *Journal }
27
28func NewCaptureFactory(j *Journal) provider.CaptureFactory { return &captureFactory{j} }
29
30type containedCaptureProcess interface {
31 provider.Process
32 Contain(context.Context) error
33 Record() containment.Record
34}
35type captureInput struct {
36 journal *Journal
37 process containedCaptureProcess
38 launch provider.Launch
39 input io.WriteCloser
40 ctx context.Context
41 mu sync.Mutex
42 closed bool
43 fail func(error)
44}
45
46func (c *captureInput) BindSession(ctx context.Context, s provider.Session) error {
47 return c.journal.BindSession(ctx, s)
48}
49func (c *captureInput) BeginTurn(ctx context.Context, s provider.Session, t provider.Turn) error {
50 return c.journal.BeginTurn(ctx, s, t)
51}
52func (c *captureInput) Close() error { return c.input.Close() }
53func (c *captureInput) Write(raw []byte) (int, error) {
54 c.mu.Lock()
55 defer c.mu.Unlock()
56 if c.closed || c.ctx.Err() != nil {
57 return 0, errDirectUncertain
58 }
59 if len(raw) > MaxFrameBytes+1 || !bytes.HasSuffix(raw, []byte{'\n'}) || !uniqueFrame(bytes.TrimSpace(raw)) {
60 return 0, runnerproto.ErrInvalid
61 }
62 var v struct {
63 Type, Method string
64 Session string `json:"session_id"`
65 Message struct{ Role, Content string }
66 Params struct {
67 Thread string `json:"threadId"`
68 Input []struct{ Type, Text string }
69 }
70 }
71 if json.Unmarshal(raw, &v) != nil {
72 return 0, runnerproto.ErrInvalid
73 }
74 prompt, session := "", ""
75 switch c.launch.Selection.Provider {
76 case "claude":
77 if v.Type != "user" || v.Message.Role != "user" {
78 return 0, runnerproto.ErrInvalid
79 }
80 prompt, session = v.Message.Content, v.Session
81 case "codex":
82 if v.Method == "turn/start" {
83 if len(v.Params.Input) != 1 || v.Params.Input[0].Type != "text" {
84 return 0, runnerproto.ErrInvalid
85 }
86 prompt, session = v.Params.Input[0].Text, v.Params.Thread
87 } else {
88 switch v.Method {
89 case "initialize", "initialized", "account/read", "config/read", "thread/start", "thread/resume", "turn/interrupt":
90 default:
91 return 0, runnerproto.ErrInvalid
92 }
93 }
94 default:
95 return 0, runnerproto.ErrInvalid
96 }
97 if prompt != "" {
98 if err := c.journal.consumeTurn(c.ctx, c.launch.AttemptKey, session, prompt); err != nil {
99 return 0, err
100 }
101 } else if v.Type == "user" || v.Method == "turn/start" {
102 return 0, runnerproto.ErrInvalid
103 }
104 n, err := c.input.Write(raw)
105 if err != nil || n != len(raw) {
106 c.closed = true
107 if err == nil {
108 err = io.ErrShortWrite
109 }
110 c.fail(err)
111 }
112 return n, err
113}
114func (j *Journal) consumeTurn(ctx context.Context, attempt, session, prompt string) error {
115 if err := j.AdmissionAllowed(ctx); err != nil {
116 return err
117 }
118 tx, err := j.db.BeginTx(ctx, nil)
119 if err != nil {
120 return j.storageFailure(ctx, err)
121 }
122 err = func() error {
123 defer tx.Rollback()
124 var raw []byte
125 var launch provider.Launch
126 if err := tx.QueryRowContext(ctx, "SELECT launch FROM direct_attempts WHERE attempt=?", attempt).Scan(&raw); err != nil {
127 return err
128 }
129 if json.Unmarshal(raw, &launch) != nil {
130 return provider.ErrIdentity
131 }
132 if launch.Policy.Coordinator() {
133 if launch.ResumeSessionID != "" {
134 return provider.ErrIdentity
135 }
136 if _, err := runnerproto.CoordinatorTurnIntentPayload(launch.Selection.Provider, launch.Selection.Model, prompt); err != nil {
137 return err
138 }
139 }
140 result, e := tx.ExecContext(ctx, `UPDATE direct_turns SET state='dispatched' WHERE attempt=? AND session=? AND prompt_hash=? AND state='intent' AND EXISTS(SELECT 1 FROM direct_attempts WHERE attempt=? AND recovered=0)`, attempt, session, runnerproto.EventHash(prompt), attempt)
141 if e != nil {
142 return e
143 }
144 n, e := result.RowsAffected()
145 if e != nil {
146 return e
147 }
148 if n != 1 {
149 return errDirectUncertain
150 }
151 return tx.Commit()
152 }()
153 if err != nil && !errors.Is(err, errDirectUncertain) {
154 return j.storageFailure(ctx, err)
155 }
156 return err
157}
158func (f *captureFactory) Open(ctx context.Context, p provider.Process, l provider.Launch) (*provider.Capture, error) {
159 proc, ok := p.(containedCaptureProcess)
160 if !ok || f.journal == nil {
161 return nil, runnerproto.ErrInvalid
162 }
163 f.journal.captureMu.RLock()
164 transferred := false
165 defer func() {
166 if !transferred {
167 f.journal.captureMu.RUnlock()
168 }
169 }()
170 contain := func() error {
171 cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
172 defer cancel()
173 return proc.Contain(cleanup)
174 }
175 if err := f.journal.AdmissionAllowed(ctx); err != nil {
176 return nil, errors.Join(err, contain())
177 }
178 if err := f.journal.recordDirectLaunch(ctx, l, proc.Record()); err != nil {
179 return nil, errors.Join(err, contain())
180 }
181 result, err := f.journal.db.ExecContext(ctx, "UPDATE direct_attempts SET opened=1 WHERE attempt=? AND opened=0 AND recovered=0", l.AttemptKey)
182 if err != nil {
183 return nil, errors.Join(f.journal.storageFailure(ctx, err), contain())
184 }
185 if n, e := result.RowsAffected(); e != nil || n != 1 {
186 return nil, errors.Join(errDirectUncertain, contain())
187 }
188 input, stdout, stderr := p.Stdin(), p.Stdout(), p.Stderr()
189 if input == nil || stdout == nil || stderr == nil {
190 return nil, errors.Join(runnerproto.ErrInvalid, contain())
191 }
192 transferred = true
193 runCtx, cancel := context.WithCancel(ctx)
194 frames := make(chan provider.Frame)
195 done := make(chan error, 1)
196 var once sync.Once
197 var failure error
198 var failureMu sync.Mutex
199 var diagnosticMu sync.Mutex
200 var diagnosticText string
201 fail := func(e error) {
202 once.Do(func() {
203 failureMu.Lock()
204 defer failureMu.Unlock()
205 failure = e
206 cancel()
207 input.Close()
208 stdout.Close()
209 stderr.Close()
210 containmentErr := contain()
211 cleanup, stopCleanup := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
212 journalErr := f.journal.interruptDirect(cleanup, l.AttemptKey, containmentErr == nil)
213 stopCleanup()
214 failure = errors.Join(failure, containmentErr, journalErr)
215 if errors.Is(e, ErrJournal) || journalErr != nil {
216 _ = f.journal.fail()
217 }
218 })
219 }
220 ci := &captureInput{journal: f.journal, process: proc, launch: l, input: input, ctx: runCtx, fail: fail}
221 go func() {
222 stop := context.AfterFunc(runCtx, func() { input.Close(); stdout.Close(); stderr.Close() })
223 defer stop()
224 defer cancel()
225 diagnostics := make(chan error, 1)
226 go func() {
227 b, e := io.ReadAll(io.LimitReader(stderr, maxDiagnostics))
228 diagnosticMu.Lock()
229 diagnosticText = redactText(string(b), nil)
230 diagnosticMu.Unlock()
231 if e == nil {
232 _, e = io.Copy(io.Discard, stderr)
233 }
234 if e == nil {
235 _, e = f.journal.db.ExecContext(runCtx, "UPDATE direct_attempts SET diagnostics=? WHERE attempt=?", redactText(string(b), nil), l.AttemptKey)
236 if e != nil {
237 e = f.journal.storageFailure(runCtx, e)
238 }
239 }
240 diagnostics <- e
241 }()
242 reader := stdoutFrames{reader: bufio.NewReaderSize(stdout, MaxFrameBytes+2), document: claude.AuthStatusDocument(l)}
243 var seq int64
244 for {
245 raw, e := reader.read()
246 if e == io.EOF && len(raw) == 0 {
247 break
248 }
249 if e != nil {
250 fail(e)
251 break
252 }
253 raw = bytes.TrimSuffix(raw, []byte{'\n'})
254 seq++
255 if e = f.journal.AppendFrame(runCtx, l.AttemptKey, p.ID(), seq, raw); e != nil {
256 fail(e)
257 break
258 }
259 var saved []byte
260 if e = f.journal.db.QueryRowContext(runCtx, "SELECT body FROM direct_frames WHERE stream=? AND sequence=?", p.ID(), seq).Scan(&saved); e != nil {
261 fail(f.journal.storageFailure(runCtx, e))
262 break
263 }
264 timer := time.NewTimer(5 * time.Second)
265 select {
266 case frames <- provider.Frame{Sequence: seq, Bytes: saved}:
267 case <-runCtx.Done():
268 fail(runCtx.Err())
269 case <-timer.C:
270 fail(errDirectUncertain)
271 }
272 timer.Stop()
273 if runCtx.Err() != nil {
274 break
275 }
276 }
277 if e := <-diagnostics; e != nil {
278 fail(e)
279 }
280 if runCtx.Err() != nil {
281 fail(runCtx.Err())
282 }
283 if runCtx.Err() == nil {
284 waitCtx, stopWait := context.WithTimeout(runCtx, 5*time.Second)
285 _, e := proc.Wait(waitCtx)
286 stopWait()
287 if e != nil {
288 fail(e)
289 } else if _, e = f.journal.db.ExecContext(runCtx, "UPDATE direct_attempts SET contained=1 WHERE attempt=?", l.AttemptKey); e != nil {
290 fail(f.journal.storageFailure(runCtx, e))
291 } else if e = f.journal.releaseDirectFrames(runCtx); e != nil {
292 fail(e)
293 }
294 }
295 cleanup, stopCleanup := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
296 if e := f.journal.releaseDirectFrames(cleanup); e != nil {
297 fail(e)
298 }
299 stopCleanup()
300 input.Close()
301 stdout.Close()
302 stderr.Close()
303 close(frames)
304 failureMu.Lock()
305 f.journal.captureMu.RUnlock()
306 done <- failure
307 failureMu.Unlock()
308 close(done)
309 }()
310 return &provider.Capture{Input: ci, Frames: frames, Done: done, Diagnostics: func() string { diagnosticMu.Lock(); defer diagnosticMu.Unlock(); return diagnosticText }}, nil
311}
312func (j *Journal) AppendFrame(ctx context.Context, attempt, stream string, seq int64, frame []byte) error {
313 if attempt == "" || stream == "" || seq <= 0 {
314 return runnerproto.ErrInvalid
315 }
316 if len(frame) > MaxFrameBytes {
317 return fmt.Errorf("stdout_frame_too_large: %w", runnerproto.ErrInvalid)
318 }
319 if !uniqueFrame(frame) {
320 return fmt.Errorf("stdout_invalid_json: %w", runnerproto.ErrInvalid)
321 }
322 body := redactFrame(frame)
323 if len(body) > MaxFrameBytes {
324 return runnerproto.ErrInvalid
325 }
326 tx, err := j.db.BeginTx(ctx, nil)
327 if err != nil {
328 return j.storageFailure(ctx, err)
329 }
330 err = func() error {
331 defer tx.Rollback()
332 var saved string
333 var recovered int
334 if e := tx.QueryRowContext(ctx, "SELECT stream,recovered FROM direct_attempts WHERE attempt=?", attempt).Scan(&saved, &recovered); e != nil {
335 if errors.Is(e, sql.ErrNoRows) {
336 return provider.ErrIdentity
337 }
338 return e
339 }
340 if saved != stream || recovered != 0 {
341 return provider.ErrIdentity
342 }
343 var last, size int64
344 var blocked int
345 if e := tx.QueryRowContext(ctx, "SELECT COALESCE(MAX(sequence),0) FROM direct_frames WHERE stream=?", stream).Scan(&last); e != nil {
346 return e
347 }
348 if seq <= last {
349 return runnerproto.ErrInvalid
350 }
351 if e := tx.QueryRowContext(ctx, "SELECT blocked,"+directPendingSize+" FROM journal_state WHERE id=1").Scan(&blocked, &size); e != nil {
352 return e
353 }
354 if size >= 0 && int64(len(body)) > j.maxBytes-size {
355 return ErrJournalBudget
356 }
357 if blocked != 0 || size < 0 {
358 return ErrJournal
359 }
360 if _, e := tx.ExecContext(ctx, "INSERT INTO direct_frames(stream,sequence,body) VALUES(?,?,?)", stream, seq, body); e != nil {
361 return e
362 }
363 return tx.Commit()
364 }()
365 if err != nil && !errors.Is(err, provider.ErrIdentity) {
366 return j.storageFailure(ctx, err)
367 }
368 return err
369}
370
371// Reject duplicate keys before redaction can collapse them or alter a decoder's
372// interpretation. Number tokens stay exact, including counters above 2^53.
373func uniqueFrame(raw []byte) bool {
374 if len(bytes.TrimSpace(raw)) == 0 || bytes.TrimSpace(raw)[0] != '{' {
375 return false
376 }
377 d := json.NewDecoder(bytes.NewReader(raw))
378 d.UseNumber()
379 var value func() bool
380 value = func() bool {
381 v, e := d.Token()
382 if e != nil {
383 return false
384 }
385 delim, ok := v.(json.Delim)
386 if !ok {
387 return true
388 }
389 switch delim {
390 case '{':
391 seen := map[string]bool{}
392 for d.More() {
393 k, e := d.Token()
394 s, ok := k.(string)
395 if e != nil || !ok || seen[s] {
396 return false
397 }
398 seen[s] = true
399 if !value() {
400 return false
401 }
402 }
403 v, e = d.Token()
404 return e == nil && v == json.Delim('}')
405 case '[':
406 for d.More() {
407 if !value() {
408 return false
409 }
410 }
411 v, e = d.Token()
412 return e == nil && v == json.Delim(']')
413 }
414 return false
415 }
416 if !value() {
417 return false
418 }
419 _, e := d.Token()
420 return e == io.EOF
421}
422func redactFrame(raw []byte) []byte { return redactFrameSecrets(raw, nil) }
423func redactFrameSecrets(raw []byte, secrets []string) []byte {
424 var v any
425 d := json.NewDecoder(bytes.NewReader(raw))
426 d.UseNumber()
427 if d.Decode(&v) != nil {
428 return nil
429 }
430 var walk func(any, bool) any
431 walk = func(v any, secret bool) any {
432 switch x := v.(type) {
433 case map[string]any:
434 for k, v := range x {
435 key := strings.ToLower(strings.NewReplacer("_", "", "-", "").Replace(k))
436 s := strings.HasSuffix(key, "token") || strings.HasSuffix(key, "password") || strings.HasSuffix(key, "secret") || strings.HasSuffix(key, "apikey") || strings.HasSuffix(key, "privatekey") || key == "authorization" || key == "credentials" || key == "credential" || key == "bearer"
437 x[k] = walk(v, secret || s)
438 }
439 case []any:
440 for i, v := range x {
441 x[i] = walk(v, secret)
442 }
443 case string:
444 if secret {
445 return "***"
446 }
447 return redactText(x, secrets)
448 }
449 return v
450 }
451 b, _ := json.Marshal(walk(v, false))
452 return b
453}
454