package runner import ( "bufio" "bytes" "context" "database/sql" "encoding/json" "errors" "fmt" "io" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/runnerproto" ) const MaxFrameBytes = 1 << 20 const maxDiagnostics = 64 << 10 const 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))` type captureFactory struct{ journal *Journal } func NewCaptureFactory(j *Journal) provider.CaptureFactory { return &captureFactory{j} } type containedCaptureProcess interface { provider.Process Contain(context.Context) error Record() containment.Record } type captureInput struct { journal *Journal process containedCaptureProcess launch provider.Launch input io.WriteCloser ctx context.Context mu sync.Mutex closed bool fail func(error) } func (c *captureInput) BindSession(ctx context.Context, s provider.Session) error { return c.journal.BindSession(ctx, s) } func (c *captureInput) BeginTurn(ctx context.Context, s provider.Session, t provider.Turn) error { return c.journal.BeginTurn(ctx, s, t) } func (c *captureInput) Close() error { return c.input.Close() } func (c *captureInput) Write(raw []byte) (int, error) { c.mu.Lock() defer c.mu.Unlock() if c.closed || c.ctx.Err() != nil { return 0, errDirectUncertain } if len(raw) > MaxFrameBytes+1 || !bytes.HasSuffix(raw, []byte{'\n'}) || !uniqueFrame(bytes.TrimSpace(raw)) { return 0, runnerproto.ErrInvalid } var v struct { Type, Method string Session string `json:"session_id"` Message struct{ Role, Content string } Params struct { Thread string `json:"threadId"` Input []struct{ Type, Text string } } } if json.Unmarshal(raw, &v) != nil { return 0, runnerproto.ErrInvalid } prompt, session := "", "" switch c.launch.Selection.Provider { case "claude": if v.Type != "user" || v.Message.Role != "user" { return 0, runnerproto.ErrInvalid } prompt, session = v.Message.Content, v.Session case "codex": if v.Method == "turn/start" { if len(v.Params.Input) != 1 || v.Params.Input[0].Type != "text" { return 0, runnerproto.ErrInvalid } prompt, session = v.Params.Input[0].Text, v.Params.Thread } else { switch v.Method { case "initialize", "initialized", "account/read", "config/read", "thread/start", "thread/resume", "turn/interrupt": default: return 0, runnerproto.ErrInvalid } } default: return 0, runnerproto.ErrInvalid } if prompt != "" { if err := c.journal.consumeTurn(c.ctx, c.launch.AttemptKey, session, prompt); err != nil { return 0, err } } else if v.Type == "user" || v.Method == "turn/start" { return 0, runnerproto.ErrInvalid } n, err := c.input.Write(raw) if err != nil || n != len(raw) { c.closed = true if err == nil { err = io.ErrShortWrite } c.fail(err) } return n, err } func (j *Journal) consumeTurn(ctx context.Context, attempt, session, prompt string) error { if err := j.AdmissionAllowed(ctx); err != nil { return err } tx, err := j.db.BeginTx(ctx, nil) if err != nil { return j.storageFailure(ctx, err) } err = func() error { defer tx.Rollback() var raw []byte var launch provider.Launch if err := tx.QueryRowContext(ctx, "SELECT launch FROM direct_attempts WHERE attempt=?", attempt).Scan(&raw); err != nil { return err } if json.Unmarshal(raw, &launch) != nil { return provider.ErrIdentity } if launch.Policy.Coordinator() { if launch.ResumeSessionID != "" { return provider.ErrIdentity } if _, err := runnerproto.CoordinatorTurnIntentPayload(launch.Selection.Provider, launch.Selection.Model, prompt); err != nil { return err } } 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) if e != nil { return e } n, e := result.RowsAffected() if e != nil { return e } if n != 1 { return errDirectUncertain } return tx.Commit() }() if err != nil && !errors.Is(err, errDirectUncertain) { return j.storageFailure(ctx, err) } return err } func (f *captureFactory) Open(ctx context.Context, p provider.Process, l provider.Launch) (*provider.Capture, error) { proc, ok := p.(containedCaptureProcess) if !ok || f.journal == nil { return nil, runnerproto.ErrInvalid } f.journal.captureMu.RLock() transferred := false defer func() { if !transferred { f.journal.captureMu.RUnlock() } }() contain := func() error { cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) defer cancel() return proc.Contain(cleanup) } if err := f.journal.AdmissionAllowed(ctx); err != nil { return nil, errors.Join(err, contain()) } if err := f.journal.recordDirectLaunch(ctx, l, proc.Record()); err != nil { return nil, errors.Join(err, contain()) } result, err := f.journal.db.ExecContext(ctx, "UPDATE direct_attempts SET opened=1 WHERE attempt=? AND opened=0 AND recovered=0", l.AttemptKey) if err != nil { return nil, errors.Join(f.journal.storageFailure(ctx, err), contain()) } if n, e := result.RowsAffected(); e != nil || n != 1 { return nil, errors.Join(errDirectUncertain, contain()) } input, stdout, stderr := p.Stdin(), p.Stdout(), p.Stderr() if input == nil || stdout == nil || stderr == nil { return nil, errors.Join(runnerproto.ErrInvalid, contain()) } transferred = true runCtx, cancel := context.WithCancel(ctx) frames := make(chan provider.Frame) done := make(chan error, 1) var once sync.Once var failure error var failureMu sync.Mutex var diagnosticMu sync.Mutex var diagnosticText string fail := func(e error) { once.Do(func() { failureMu.Lock() defer failureMu.Unlock() failure = e cancel() input.Close() stdout.Close() stderr.Close() containmentErr := contain() cleanup, stopCleanup := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) journalErr := f.journal.interruptDirect(cleanup, l.AttemptKey, containmentErr == nil) stopCleanup() failure = errors.Join(failure, containmentErr, journalErr) if errors.Is(e, ErrJournal) || journalErr != nil { _ = f.journal.fail() } }) } ci := &captureInput{journal: f.journal, process: proc, launch: l, input: input, ctx: runCtx, fail: fail} go func() { stop := context.AfterFunc(runCtx, func() { input.Close(); stdout.Close(); stderr.Close() }) defer stop() defer cancel() diagnostics := make(chan error, 1) go func() { b, e := io.ReadAll(io.LimitReader(stderr, maxDiagnostics)) diagnosticMu.Lock() diagnosticText = redactText(string(b), nil) diagnosticMu.Unlock() if e == nil { _, e = io.Copy(io.Discard, stderr) } if e == nil { _, e = f.journal.db.ExecContext(runCtx, "UPDATE direct_attempts SET diagnostics=? WHERE attempt=?", redactText(string(b), nil), l.AttemptKey) if e != nil { e = f.journal.storageFailure(runCtx, e) } } diagnostics <- e }() reader := stdoutFrames{reader: bufio.NewReaderSize(stdout, MaxFrameBytes+2), document: claude.AuthStatusDocument(l)} var seq int64 for { raw, e := reader.read() if e == io.EOF && len(raw) == 0 { break } if e != nil { fail(e) break } raw = bytes.TrimSuffix(raw, []byte{'\n'}) seq++ if e = f.journal.AppendFrame(runCtx, l.AttemptKey, p.ID(), seq, raw); e != nil { fail(e) break } var saved []byte if e = f.journal.db.QueryRowContext(runCtx, "SELECT body FROM direct_frames WHERE stream=? AND sequence=?", p.ID(), seq).Scan(&saved); e != nil { fail(f.journal.storageFailure(runCtx, e)) break } timer := time.NewTimer(5 * time.Second) select { case frames <- provider.Frame{Sequence: seq, Bytes: saved}: case <-runCtx.Done(): fail(runCtx.Err()) case <-timer.C: fail(errDirectUncertain) } timer.Stop() if runCtx.Err() != nil { break } } if e := <-diagnostics; e != nil { fail(e) } if runCtx.Err() != nil { fail(runCtx.Err()) } if runCtx.Err() == nil { waitCtx, stopWait := context.WithTimeout(runCtx, 5*time.Second) _, e := proc.Wait(waitCtx) stopWait() if e != nil { fail(e) } else if _, e = f.journal.db.ExecContext(runCtx, "UPDATE direct_attempts SET contained=1 WHERE attempt=?", l.AttemptKey); e != nil { fail(f.journal.storageFailure(runCtx, e)) } else if e = f.journal.releaseDirectFrames(runCtx); e != nil { fail(e) } } cleanup, stopCleanup := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) if e := f.journal.releaseDirectFrames(cleanup); e != nil { fail(e) } stopCleanup() input.Close() stdout.Close() stderr.Close() close(frames) failureMu.Lock() f.journal.captureMu.RUnlock() done <- failure failureMu.Unlock() close(done) }() return &provider.Capture{Input: ci, Frames: frames, Done: done, Diagnostics: func() string { diagnosticMu.Lock(); defer diagnosticMu.Unlock(); return diagnosticText }}, nil } func (j *Journal) AppendFrame(ctx context.Context, attempt, stream string, seq int64, frame []byte) error { if attempt == "" || stream == "" || seq <= 0 { return runnerproto.ErrInvalid } if len(frame) > MaxFrameBytes { return fmt.Errorf("stdout_frame_too_large: %w", runnerproto.ErrInvalid) } if !uniqueFrame(frame) { return fmt.Errorf("stdout_invalid_json: %w", runnerproto.ErrInvalid) } body := redactFrame(frame) if len(body) > MaxFrameBytes { return runnerproto.ErrInvalid } tx, err := j.db.BeginTx(ctx, nil) if err != nil { return j.storageFailure(ctx, err) } err = func() error { defer tx.Rollback() var saved string var recovered int if e := tx.QueryRowContext(ctx, "SELECT stream,recovered FROM direct_attempts WHERE attempt=?", attempt).Scan(&saved, &recovered); e != nil { if errors.Is(e, sql.ErrNoRows) { return provider.ErrIdentity } return e } if saved != stream || recovered != 0 { return provider.ErrIdentity } var last, size int64 var blocked int if e := tx.QueryRowContext(ctx, "SELECT COALESCE(MAX(sequence),0) FROM direct_frames WHERE stream=?", stream).Scan(&last); e != nil { return e } if seq <= last { return runnerproto.ErrInvalid } if e := tx.QueryRowContext(ctx, "SELECT blocked,"+directPendingSize+" FROM journal_state WHERE id=1").Scan(&blocked, &size); e != nil { return e } if size >= 0 && int64(len(body)) > j.maxBytes-size { return ErrJournalBudget } if blocked != 0 || size < 0 { return ErrJournal } if _, e := tx.ExecContext(ctx, "INSERT INTO direct_frames(stream,sequence,body) VALUES(?,?,?)", stream, seq, body); e != nil { return e } return tx.Commit() }() if err != nil && !errors.Is(err, provider.ErrIdentity) { return j.storageFailure(ctx, err) } return err } // Reject duplicate keys before redaction can collapse them or alter a decoder's // interpretation. Number tokens stay exact, including counters above 2^53. func uniqueFrame(raw []byte) bool { if len(bytes.TrimSpace(raw)) == 0 || bytes.TrimSpace(raw)[0] != '{' { return false } d := json.NewDecoder(bytes.NewReader(raw)) d.UseNumber() var value func() bool value = func() bool { v, e := d.Token() if e != nil { return false } delim, ok := v.(json.Delim) if !ok { return true } switch delim { case '{': seen := map[string]bool{} for d.More() { k, e := d.Token() s, ok := k.(string) if e != nil || !ok || seen[s] { return false } seen[s] = true if !value() { return false } } v, e = d.Token() return e == nil && v == json.Delim('}') case '[': for d.More() { if !value() { return false } } v, e = d.Token() return e == nil && v == json.Delim(']') } return false } if !value() { return false } _, e := d.Token() return e == io.EOF } func redactFrame(raw []byte) []byte { return redactFrameSecrets(raw, nil) } func redactFrameSecrets(raw []byte, secrets []string) []byte { var v any d := json.NewDecoder(bytes.NewReader(raw)) d.UseNumber() if d.Decode(&v) != nil { return nil } var walk func(any, bool) any walk = func(v any, secret bool) any { switch x := v.(type) { case map[string]any: for k, v := range x { key := strings.ToLower(strings.NewReplacer("_", "", "-", "").Replace(k)) 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" x[k] = walk(v, secret || s) } case []any: for i, v := range x { x[i] = walk(v, secret) } case string: if secret { return "***" } return redactText(x, secrets) } return v } b, _ := json.Marshal(walk(v, false)) return b }