Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Coach: a schema the provider can't serve, wrapped by OpenRouter, falls back to JSON mode
David Young214f70453726
diff --git a/api/coach/core/adapters/http.js b/api/coach/core/adapters/http.jsindex 982580586..a04e6b289 100644--- a/api/coach/core/adapters/http.js+++ b/api/coach/core/adapters/http.js@@ -188,8 +188,10 @@ export function httpAdapter(spec) {transientRetries++;continue;}- // Some OpenAI-compatible servers reject the JSON-mode flag outright. Once, without it.- if (res.status === 400 && spec.withoutJsonMode && !retriedWithoutJsonMode && /response_format|json_schema|json_object|json mode|structured/i.test(msg)) {+ // Some OpenAI-compatible servers reject the JSON-mode flag outright, and some providers+ // reject a schema they cannot serve (Gemini: "the specified schema produces a constraint+ // that has too many states"). Once, without it: the validator still judges the answer.+ if (res.status === 400 && spec.withoutJsonMode && !retriedWithoutJsonMode && /response_format|json_schema|json_object|json mode|structured|\bschema\b/i.test(msg)) {body = spec.withoutJsonMode(body);retriedWithoutJsonMode = true;continue;diff --git a/api/coach/core/adapters/openai.js b/api/coach/core/adapters/openai.jsindex f206fb010..5c4630879 100644--- a/api/coach/core/adapters/openai.js+++ b/api/coach/core/adapters/openai.js@@ -36,7 +36,22 @@ export function chatCompletionsSpec(id, { maxTokensField = 'max_completion_tokenwithoutJsonMode: body => (body.response_format && body.response_format.type === 'json_schema'? { ...body, response_format: { type: 'json_object' } }: (() => { const { response_format: _rf, ...rest } = body; return rest; })()),- errorMessage: data => data && data.error && (typeof data.error === 'string' ? data.error : data.error.message),+ errorMessage: data => {+ const e = data && data.error;+ if (!e || typeof e === 'string') return e || null;+ // OpenRouter wraps the upstream provider's own error: its message is a generic "Provider+ // returned error" and the provider's words are in metadata.raw, usually as JSON. Those words+ // are what an owner needs to see, and what the JSON-mode fallback in http.js matches on.+ const raw = e.metadata && e.metadata.raw;+ let inner = null;+ if (typeof raw === 'string' && raw) {+ try {+ const j = JSON.parse(raw);+ inner = (j && j.error && (typeof j.error === 'string' ? j.error : j.error.message)) || null;+ } catch { inner = raw; }+ }+ return inner && inner !== e.message ? `${e.message}: ${inner}` : e.message;+ },readText: data => {const choice = (data.choices || [])[0];if (!choice) return { error: 'the answer had no choices' };diff --git a/api/coach/core/pipeline.js b/api/coach/core/pipeline.jsindex 8de136fce..5af5d0188 100644--- a/api/coach/core/pipeline.js+++ b/api/coach/core/pipeline.js@@ -39,7 +39,12 @@ export async function attemptOnce({ adapter, cfg, kind, payload, model, timeoutMif (r.spawnError) return { ok: false, errorClass: 'missing', detail: r.stderr?.slice(0, 300) };if (r.code !== 0) {const err = (r.stderr || r.text || '').toLowerCase();- const authish = /auth|unauthor|api key|credential|token|401|403|login/.test(err);+ // An HTTP adapter's stderr starts with the status, and the status is the answer: once a+ // provider's own words ride along ("the input token count exceeds…"), a word match would+ // call a budget error a rejected key. The CLIs have no status, so they keep the words.+ const status = /^(\d{3})\b/.exec(err);+ const authish = status ? status[1] === '401' || status[1] === '403'+ : /auth|unauthor|api key|credential|token|401|403|login/.test(err);return { ok: false, errorClass: authish ? 'auth' : 'provider', detail: (r.stderr || r.text || '').slice(0, 300) };}diff --git a/api/test/adapters-http.test.js b/api/test/adapters-http.test.jsindex 6849c2f37..852151430 100644--- a/api/test/adapters-http.test.js+++ b/api/test/adapters-http.test.js@@ -211,6 +211,51 @@ test('compatible: a server that rejects JSON mode gets the same request once morassert.ok(!('response_format' in f.calls[1].body));});+// OpenRouter in front of Gemini, as it really answers a schema Gemini cannot serve: the+// provider's words are only in metadata.raw (JSON in a string), the outer message is generic.+const openRouterWrapped = providerMessage => ({+ status: 400,+ body: { error: { message: 'Provider returned error', code: 400, metadata: {+ raw: JSON.stringify({ error: { code: 400, message: providerMessage, status: 'INVALID_ARGUMENT' } }),+ provider_name: 'Google AI Studio'+ } } }+});++test('compatible: a schema the provider cannot serve, wrapped by OpenRouter, is retried once in plain JSON mode', async () => {+ const f = fakeFetch(n => n === 1+ ? openRouterWrapped('The specified schema produces a constraint that has too many states for serving.')+ : ok({ choices: [{ message: { content: ANSWER }, finish_reason: 'stop' }] }));+ const schema = { type: 'object', properties: { coach_contract: { type: 'integer' } } };+ const r = await compatible.invoke({ cfg: cfgCompat, prompt: 'P', schema, env: {}, model: 'google/gemini-2.5-flash-lite', fetch: f });+ assert.equal(r.code, 0, r.stderr);+ assert.equal(f.calls.length, 2);+ assert.equal(f.calls[0].body.response_format.type, 'json_schema');+ assert.deepEqual(f.calls[1].body.response_format, { type: 'json_object' });+});++test('a provider error wrapped by OpenRouter reaches stderr in the provider’s own words', async () => {+ const f = fakeFetch([openRouterWrapped('Request contains an invalid argument: temperature out of range.')]);+ const r = await openai.invoke({ cfg: {}, prompt: 'P', env, fetch: f });+ assert.equal(r.code, 1);+ assert.equal(f.calls.length, 1, 'not a JSON-mode problem, so no second request');+ assert.ok(r.stderr.includes('Provider returned error'), r.stderr);+ assert.ok(r.stderr.includes('temperature out of range'), r.stderr);+});++test('a wrapped provider error that mentions tokens is still "provider", not "auth"', async () => {+ const f = fakeFetch([openRouterWrapped('The input token count exceeds the maximum number of tokens allowed.')]);+ const payload = { plan: { routines: [], week: {} } };+ const cls = await attemptOnce({ adapter: openai, cfg: {}, kind: 'review', payload, invokeOpts: { env, fetch: f } }, null);+ assert.equal(cls.errorClass, 'provider', cls.detail);+ assert.ok(cls.detail.includes('token count'), cls.detail);+});++test('a wrapped provider error whose raw text is not JSON is passed through as it is', async () => {+ const f = fakeFetch([{ status: 400, body: { error: { message: 'Provider returned error', metadata: { raw: 'upstream said no' } } } }]);+ const r = await openai.invoke({ cfg: {}, prompt: 'P', env, fetch: f });+ assert.ok(r.stderr.includes('upstream said no'), r.stderr);+});+test('a missing key is "missing", like an absent CLI — no request is made', async () => {const f = fakeFetch([]);const r = await anthropic.invoke({ cfg: {}, prompt: 'P', env: {}, fetch: f });