package runner import ( "bytes" "context" "encoding/json" "io" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) // WriteAnswer is a separate, durable path for replies in an admitted turn. func (c *captureInput) WriteAnswer(ctx context.Context, s provider.Session, turn string, raw []byte) (int, error) { c.mu.Lock() defer c.mu.Unlock() if c.closed || c.ctx.Err() != nil || ctx.Err() != nil || c.launch.Selection.Provider != "codex" || s.Validate(c.launch) != nil || len(raw) > MaxFrameBytes+1 || !bytes.HasSuffix(raw, []byte{'\n'}) || !uniqueFrame(bytes.TrimSpace(raw)) { return 0, runnerproto.ErrInvalid } var v struct { ID json.RawMessage `json:"id"` Method string `json:"method,omitempty"` Params json.RawMessage `json:"params,omitempty"` Result json.RawMessage `json:"result,omitempty"` Error json.RawMessage `json:"error,omitempty"` } if runnerproto.DecodeLimit(bytes.NewReader(raw), &v, MaxFrameBytes) != nil || len(v.ID) == 0 || string(v.ID) == "null" { return 0, runnerproto.ErrInvalid } var idString string var idNumber int64 if json.Unmarshal(v.ID, &idString) != nil && json.Unmarshal(v.ID, &idNumber) != nil { return 0, runnerproto.ErrInvalid } if len(v.Error) > 0 { var denial struct { Code int `json:"code"` Message string `json:"message"` } if v.Method != "" || len(v.Result) > 0 || len(v.Params) > 0 || runnerproto.DecodeLimit(bytes.NewReader(v.Error), &denial, MaxFrameBytes) != nil || denial.Code != -32000 || denial.Message != provider.ErrPolicy.Error() { return 0, runnerproto.ErrInvalid } } else if v.Method == "turn/steer" { var p struct { Thread string `json:"threadId"` Expected string `json:"expectedTurnId"` Input []struct { Type string `json:"type"` Text string `json:"text"` } `json:"input"` } if len(v.Result) != 0 || runnerproto.DecodeLimit(bytes.NewReader(v.Params), &p, MaxFrameBytes) != nil || p.Thread != s.ID || p.Expected == "" || len(p.Input) != 1 || p.Input[0].Type != "text" || p.Input[0].Text == "" { return 0, runnerproto.ErrInvalid } } else if v.Method == "" && len(v.Params) == 0 { var r struct { Action string `json:"action,omitempty"` Content json.RawMessage `json:"content,omitempty"` Meta json.RawMessage `json:"_meta,omitempty"` Decision string `json:"decision,omitempty"` Answers map[string]struct { Answers []string `json:"answers"` } `json:"answers,omitempty"` } if runnerproto.DecodeLimit(bytes.NewReader(v.Result), &r, MaxFrameBytes) != nil { return 0, runnerproto.ErrInvalid } if r.Action != "" { if (r.Action != "accept" && r.Action != "decline") || r.Decision != "" || len(r.Answers) != 0 || string(r.Meta) != "null" || (r.Action == "accept" && string(r.Content) != "{}") || (r.Action == "decline" && string(r.Content) != "null") { return 0, runnerproto.ErrInvalid } } else if r.Decision != "" { if (r.Decision != "accept" && r.Decision != "decline") || len(r.Answers) != 0 { return 0, runnerproto.ErrInvalid } } else if len(r.Answers) == 0 { return 0, runnerproto.ErrInvalid } } else { return 0, runnerproto.ErrInvalid } if e := c.journal.AdmissionAllowed(ctx); e != nil { return 0, e } key := runnerproto.EventHash([]any{"direct-wire", s.AttemptKey, turn, v.Method, v.ID}) hash := runnerproto.EventHash(json.RawMessage(bytes.TrimSpace(raw))) tx, e := c.journal.db.BeginTx(ctx, nil) if e != nil { return 0, e } defer tx.Rollback() var count int if e = tx.QueryRowContext(ctx, `SELECT count(*) FROM direct_turns t JOIN direct_attempts a ON a.attempt=t.attempt WHERE t.attempt=? AND t.session=? AND t.turn=? AND t.state='dispatched' AND a.recovered=0`, s.AttemptKey, s.ID, turn).Scan(&count); e != nil || count != 1 { return 0, runnerproto.ErrInvalid } if _, e = tx.ExecContext(ctx, "INSERT INTO journal_answers VALUES(?,?,'pending')", key, hash); e != nil { return 0, runnerproto.ErrInvalid } if _, e = tx.ExecContext(ctx, "INSERT INTO direct_answer_scopes VALUES(?,?,?)", key, s.AttemptKey, turn); e != nil { return 0, e } if e = tx.Commit(); e != nil { return 0, c.journal.storageFailure(ctx, e) } if e = c.journal.currentDirectTurn(ctx, s, turn); e != nil { return 0, e } n, e := c.input.Write(raw) if e != nil || n != len(raw) { c.closed = true if e == nil { e = io.ErrShortWrite } c.fail(e) return n, e } if _, e = c.journal.db.ExecContext(ctx, "UPDATE journal_answers SET state='delivered' WHERE answer_key=? AND state='pending'", key); e != nil { return n, c.journal.storageFailure(ctx, e) } return n, nil }