diff --git a/api/coach/core/adapters/http.js b/api/coach/core/adapters/http.js index 2900e8c..196deeb 100644 --- a/api/coach/core/adapters/http.js +++ b/api/coach/core/adapters/http.js @@ -53,9 +53,48 @@ async function call(fetchImpl, url, init, timeoutMs, signal) { } } +/** + * The first complete JSON object or array in `text`, or null if it never closes. + * + * Braces are counted outside of strings only, so a `}` inside a rationale cannot end the scan + * early — and an answer cut off by the token limit returns null, which is the honest reading: a + * half-written object is not a response. + */ +function firstJsonValue(text) { + const start = text.search(/[[{]/); + if (start === -1) return null; + const open = text[start], close = open === '{' ? '}' : ']'; + let depth = 0, inString = false, escaped = false; + for (let i = start; i < text.length; i++) { + const c = text[i]; + if (inString) { + if (escaped) escaped = false; + else if (c === '\\') escaped = true; + else if (c === '"') inString = false; + continue; + } + if (c === '"') inString = true; + else if (c === open) depth++; + else if (c === close && --depth === 0) return text.slice(start, i + 1); + } + return null; +} + async function readJson(res) { const text = await res.text(); - try { return { data: JSON.parse(text), text }; } catch { return { data: null, text }; } + try { return { data: JSON.parse(text), text }; } catch { /* lenient read below */ } + // Some gateways answer a request that did not ask for streaming with SSE framing anyway: the + // whole `chat.completion` object followed by the streaming terminator, `data: [DONE]`. That + // body is not JSON, so the strict parse above rejects it and the job dies with "unexpected + // response shape" (a null body) while the answer it wanted is in the first few kilobytes. + // Taking the first complete JSON value covers that and any other trailing bytes, without + // needing to know which gateway appended what — and it cannot paper over a truncated answer, + // whose object never closes. + const head = firstJsonValue(text); + if (head) { + try { return { data: JSON.parse(head), text }; } catch { /* not JSON after all */ } + } + return { data: null, text }; } export function httpAdapter(spec) { diff --git a/api/test/adapters-http.test.js b/api/test/adapters-http.test.js index 583f6c5..4b99c4a 100644 --- a/api/test/adapters-http.test.js +++ b/api/test/adapters-http.test.js @@ -107,6 +107,36 @@ test('compatible: the configured base URL, max_tokens, and no Authorization head assert.equal(g.calls[0].headers.authorization, 'Bearer compat-1'); }); +// A gateway that answers a request which did NOT ask for streaming with the streaming terminator +// glued to the end: the whole completion object, then "\ndata: [DONE]". That body is not JSON, so +// the strict parse rejects it and the job died with "unexpected response shape" — a null body — +// while the answer it wanted sat in the first few kilobytes. This is not hypothetical: the router +// behind gym.dploy.lol answers exactly this way. +test('compatible: a body with an SSE [DONE] terminator appended is still the answer', async () => { + const body = JSON.stringify({ choices: [{ message: { content: ANSWER }, finish_reason: 'stop' }] }) + '\ndata: [DONE]\n\n'; + const f = fakeFetch([{ status: 200, body }]); + const r = await compatible.invoke({ cfg: cfgCompat, prompt: 'P', env, model: 'llama3', fetch: f }); + assert.equal(r.code, 0); + assert.equal(r.text, ANSWER); +}); + +// The lenient read must not paper over a half-written answer: an object that never closes is a +// failure, which is what the token-limit path depends on. +test('compatible: a body whose object never closes is still a failure', async () => { + const f = fakeFetch([{ status: 200, body: '{"choices":[{"message":{"content":"{\\"coach' }]); + const r = await compatible.invoke({ cfg: cfgCompat, prompt: 'P', env, model: 'llama3', fetch: f }); + assert.equal(r.code, 1); + assert.match(r.stderr, /unexpected response shape/); +}); + +// …and an earlier, complete value followed by a broken one is read from the first value only. +test('compatible: trailing junk after a complete object is ignored, not parsed', async () => { + const f = fakeFetch([{ status: 200, body: JSON.stringify({ choices: [{ message: { content: ANSWER }, finish_reason: 'stop' }] }) + '{"broken":' }]); + const r = await compatible.invoke({ cfg: cfgCompat, prompt: 'P', env, model: 'llama3', fetch: f }); + assert.equal(r.code, 0); + assert.equal(r.text, ANSWER); +}); + test('compatible: no endpoint configured, or no model chosen, is a clean failure rather than a request', async () => { const f = fakeFetch([]); const none = await compatible.invoke({ cfg: {}, prompt: 'P', env: {}, model: 'x', fetch: f });