| 223 | * Total: never throws, and an empty answer is a refusal like any other. |
| 224 | */ |
| 225 | export function applyReaderRewrite( |
| 226 | lines: readonly ReaderLine[], |
| 227 | answer: string, |
| 228 | ): ReaderRewriteOutcome { |
| 229 | const incoming = refinedLines(unfence(answer)); |
| 230 | if (lines.length === 0) { |
| 231 | return { kind: 'refused', reason: 'there was nothing on this level to reword' }; |
| 232 | } |
| 233 | if (incoming.length === 0) { |
| 234 | return { kind: 'refused', reason: 'the model answered with nothing' }; |
| 235 | } |
| 236 | if (incoming.length !== lines.length) { |
| 237 | return { |
| 238 | kind: 'refused', |
| 239 | reason: `the rewrite has ${incoming.length} sentences instead of ${lines.length}`, |
| 240 | }; |
| 241 | } |
| 242 | for (let index = 0; index < lines.length; index += 1) { |
| 243 | const refusal = lineRefusal(lines[index], incoming[index], index); |
| 244 | if (refusal.length > 0) { |
| 245 | return { kind: 'refused', reason: refusal }; |
| 246 | } |
| 247 | } |
| 248 | const reordered = orderRefusal(lines, incoming); |
| 249 | if (reordered.length > 0) { |
| 250 | return { kind: 'refused', reason: reordered }; |
| 251 | } |
| 252 | return { |
| 253 | kind: 'applied', |
| 254 | lines: lines.map((line, index) => ({ ...line, text: incoming[index] })), |
| 255 | }; |
| 256 | } |
| 257 | |
| 258 | /** The reworded sentences by id, for a renderer that has to put them back. */ |
| 259 | export function rewriteMap(lines: readonly ReaderLine[]): Readonly<Record<string, string>> { |