From 8cbda4103a3405661257893b07aa3aa6555f7a05 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 00:34:42 -0800 Subject: [PATCH 1/3] feat(evals): route morph- models to Morph's free API Group eval runs needed paid Anthropic or OpenAI keys. Morph serves Kimi and DeepSeek over the OpenAI Responses API for free, so morph- models now call it, with the key from MORPH_API_KEY or the user's OpenCode morph provider. Co-Authored-By: Claude Opus 5.5 --- evals/group-conversation/README.md | 2 +- evals/group-conversation/client.ts | 18 ++++++++++++++---- evals/shared/proxy.ts | 27 +++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 5 deletions(-) diff --git a/evals/group-conversation/README.md b/evals/group-conversation/README.md index 38342585e0d11..c92ed3ecb9eb0 100644 --- a/evals/group-conversation/README.md +++ b/evals/group-conversation/README.md @@ -23,7 +23,7 @@ The four judge criteria are distinct useful ideas, explicit engagement with a pe ## Run -Put `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` in the repo root `.env`. The package script loads that file. Direct APIs are the default. `--proxy` explicitly uses the existing MCP eval's `vibeproxy` configuration for GPT models instead. Missing credentials produce error rows, never model substitutions or passing samples. +Put `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` in the repo root `.env`. The package script loads that file. Direct APIs are the default. `--proxy` explicitly uses the existing MCP eval's `vibeproxy` configuration for GPT models instead. `morph-` models, such as `morph-kimik31` and `morph-dsv41flash`, call Morph's free OpenAI-compatible API with `MORPH_API_KEY`, or the `morph` provider in `~/.config/opencode/opencode.json`. Missing credentials produce error rows, never model substitutions or passing samples. The model IDs below are the intended design pairings. They are not cheap shell models. diff --git a/evals/group-conversation/client.ts b/evals/group-conversation/client.ts index d300f65317bc1..1a2f6981d4580 100644 --- a/evals/group-conversation/client.ts +++ b/evals/group-conversation/client.ts @@ -3,7 +3,7 @@ import * as NodePerfHooks from "node:perf_hooks"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"; -import { proxyConfig } from "../shared/proxy.ts"; +import { morphConfig, proxyConfig } from "../shared/proxy.ts"; export interface ApiTool { readonly name: string; @@ -78,6 +78,14 @@ export function makeClient(options: { readonly proxy: boolean; readonly effort: return process.env.ANTHROPIC_API_KEY ? null : "ANTHROPIC_API_KEY missing from repo-root .env and process environment."; + if (model.startsWith("morph-")) { + try { + morphConfig(); + return null; + } catch { + return "Morph unavailable; set MORPH_API_KEY or add a morph provider to ~/.config/opencode/opencode.json. No substitution."; + } + } if (!model.startsWith("gpt-")) return `Unsupported model family for ${model}. No substitution.`; if (!options.proxy) return process.env.OPENAI_API_KEY @@ -101,7 +109,9 @@ export function makeClient(options: { readonly proxy: boolean; readonly effort: const missing = unavailable(model); if (missing) throw new Error(missing); const claude = model.startsWith("claude-"); - const proxy = !claude && options.proxy ? proxyConfig() : undefined; + const morph = model.startsWith("morph-"); + const proxy = morph ? undefined : !claude && options.proxy ? proxyConfig() : undefined; + const responsesEndpoint = morph ? morphConfig() : proxy; const request = claude ? { model, @@ -182,14 +192,14 @@ export function makeClient(options: { readonly proxy: boolean; readonly effort: attempts.push(attempt); const headers = claude ? { "x-api-key": process.env.ANTHROPIC_API_KEY!, "anthropic-version": "2023-06-01" } - : (proxy?.headers ?? { Authorization: `Bearer ${process.env.OPENAI_API_KEY!}` }); + : (responsesEndpoint?.headers ?? { Authorization: `Bearer ${process.env.OPENAI_API_KEY!}` }); const body = await Effect.runPromise( Effect.gen(function* () { const client = yield* HttpClient.HttpClient; const response = yield* HttpClientRequest.post( claude ? "https://api.anthropic.com/v1/messages" - : `${proxy?.url ?? "https://api.openai.com/v1"}/responses`, + : `${responsesEndpoint?.url ?? "https://api.openai.com/v1"}/responses`, ).pipe( HttpClientRequest.setHeaders(headers), HttpClientRequest.bodyJson(request), diff --git a/evals/shared/proxy.ts b/evals/shared/proxy.ts index ede72be8fdab2..993e619f08216 100644 --- a/evals/shared/proxy.ts +++ b/evals/shared/proxy.ts @@ -31,3 +31,30 @@ print(json.dumps({'url': p['base_url'].rstrip('/'), 'headers': h})) ), ), ); + +/** + * Morph's free OpenAI-compatible API, for evals that should not spend on paid models. The key is + * `MORPH_API_KEY`, else the `morph` provider in `~/.config/opencode/opencode.json`. + */ +export const morphConfig = () => + decodeProxyConfig( + JSON.parse( + NodeChildProcess.execFileSync( + "python3", + [ + "-c", + ` +import json, os, pathlib +key = os.environ.get('MORPH_API_KEY') +url = os.environ.get('MORPH_BASE_URL', 'https://api.morphllm.com/v1') +if not key: + config = pathlib.Path.home() / '.config' / 'opencode' / 'opencode.json' + settings = json.loads(config.read_text(), strict=False)['providers']['morph']['settings'] + key, url = settings['apiKey'], settings.get('baseURL', url) +print(json.dumps({'url': url.rstrip('/'), 'headers': {'Authorization': 'Bearer ' + key}})) +`, + ], + { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }, + ), + ), + ); From 5d4e979e977a1c595374cd3d44272a38a01514ca Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 03:14:12 -0800 Subject: [PATCH 2/3] fix(evals): Morph runs retry rate limits and read their config once The comparison run lost 4 of 18 samples to HTTP 429. Rate limits and server errors now retry twice, honoring Retry-After. The Morph config is read once per run, honors XDG_CONFIG_HOME, and rejects an empty key. Model ids move into the README's model table. Co-Authored-By: Claude Opus 5.5 --- evals/group-conversation/README.md | 15 ++++---- evals/group-conversation/client.ts | 55 +++++++++++++++++++----------- evals/shared/proxy.ts | 11 +++--- 3 files changed, 50 insertions(+), 31 deletions(-) diff --git a/evals/group-conversation/README.md b/evals/group-conversation/README.md index c92ed3ecb9eb0..9ef39a3405181 100644 --- a/evals/group-conversation/README.md +++ b/evals/group-conversation/README.md @@ -23,15 +23,16 @@ The four judge criteria are distinct useful ideas, explicit engagement with a pe ## Run -Put `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` in the repo root `.env`. The package script loads that file. Direct APIs are the default. `--proxy` explicitly uses the existing MCP eval's `vibeproxy` configuration for GPT models instead. `morph-` models, such as `morph-kimik31` and `morph-dsv41flash`, call Morph's free OpenAI-compatible API with `MORPH_API_KEY`, or the `morph` provider in `~/.config/opencode/opencode.json`. Missing credentials produce error rows, never model substitutions or passing samples. +Put `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` in the repo root `.env`. The package script loads that file. Direct APIs are the default. `--proxy` explicitly uses the existing MCP eval's `vibeproxy` configuration for GPT models instead. `morph-` models, listed under Free in the table below, call Morph's free OpenAI-compatible API with `MORPH_API_KEY`, or the `morph` provider in OpenCode's config (`$XDG_CONFIG_HOME` or `~/.config`). Missing credentials produce error rows, never model substitutions or passing samples. The model IDs below are the intended design pairings. They are not cheap shell models. -| Purpose | Models | -| ----------- | ------------------------------- | -| Pairing 1 | `claude-opus-5-5,gpt-6-astra` | -| Pairing 2 | `claude-sonnet-5-5,gpt-6.1-sol` | -| Blind judge | `claude-sonnet-5-5` | +| Purpose | Models | +| ----------- | ------------------------------------------------------ | +| Pairing 1 | `claude-opus-5-5,gpt-6-astra` | +| Pairing 2 | `claude-sonnet-5-5,gpt-6.1-sol` | +| Blind judge | `claude-sonnet-5-5` | +| Free | `morph-kimik31,morph-dsv41flash`, judge `morph-kimik3` | ```sh cd evals @@ -40,7 +41,7 @@ pnpm group-conversation --out runs/group-small --model claude-opus-5-5,gpt-6-ast pnpm group-conversation --out runs/group-dry --model claude-opus-5-5,gpt-6-astra --judge claude-sonnet-5-5 --samples 1 --dry-run ``` -`--out` is required. `--model` accepts one model for behavior cases, or a comma-separated primary/seat pair for design cases. Repeat it for the two pairings. `--case` accepts comma-separated IDs. `--baseline ` compares behavior rates only with identical models, cases, settings, and grader hashes. Prompt hashes may differ because the purpose is to measure text changes. `--samples` defaults to 3. `--effort` defaults to high. The fixed reply budget is 220 words. Each API call has a 120-second deadline and no retries. Errors stay out of pass rates but prevent promotion. Existing output directories with results are rejected to prevent accidental overwrites. +`--out` is required. `--model` accepts one model for behavior cases, or a comma-separated primary/seat pair for design cases. Repeat it for the two pairings. `--case` accepts comma-separated IDs. `--baseline ` compares behavior rates only with identical models, cases, settings, and grader hashes. Prompt hashes may differ because the purpose is to measure text changes. `--samples` defaults to 3. `--effort` defaults to high. The fixed reply budget is 220 words. Each request has a 120-second deadline. HTTP 429 and 5xx responses retry up to twice, waiting for `Retry-After` or 2 then 4 seconds, because they are transport, not model behaviour. Errors stay out of pass rates but prevent promotion. Existing output directories with results are rejected to prevent accidental overwrites. Start with one case and one sample, inspect all requests and outputs, then run the small set. The default set has three design cases and fourteen behavior cases. Three samples and both pairings cost at most 312 participant turns and 174 judge calls before tool continuations. PASS and early closure can reduce design calls. File operations and delegation are simulated in memory. No real agent, file write, or child task is launched by a participant. Tools in the simulation can still fail the case. A behavior case passes only when a strict majority of its samples pass; errors make it incomplete. diff --git a/evals/group-conversation/client.ts b/evals/group-conversation/client.ts index 1a2f6981d4580..43ae18dfd3b36 100644 --- a/evals/group-conversation/client.ts +++ b/evals/group-conversation/client.ts @@ -61,6 +61,8 @@ const decodePreserved = Schema.decodeUnknownSync( }), ); +const MAX_ATTEMPTS = 3; + export function makeClient(options: { readonly proxy: boolean; readonly effort: string }) { const attempts: Array<{ model: string; purpose: string; completed: boolean }> = []; const ledger: Array<{ @@ -73,6 +75,8 @@ export function makeClient(options: { readonly proxy: boolean; readonly effort: request: unknown; response: unknown; }> = []; + // Read once per run: each read spawns python, and a mid-run config edit must not split the run. + let morph: ReturnType | undefined; const unavailable = (model: string) => { if (model.startsWith("claude-")) return process.env.ANTHROPIC_API_KEY @@ -80,7 +84,7 @@ export function makeClient(options: { readonly proxy: boolean; readonly effort: : "ANTHROPIC_API_KEY missing from repo-root .env and process environment."; if (model.startsWith("morph-")) { try { - morphConfig(); + morph ??= morphConfig(); return null; } catch { return "Morph unavailable; set MORPH_API_KEY or add a morph provider to ~/.config/opencode/opencode.json. No substitution."; @@ -109,9 +113,9 @@ export function makeClient(options: { readonly proxy: boolean; readonly effort: const missing = unavailable(model); if (missing) throw new Error(missing); const claude = model.startsWith("claude-"); - const morph = model.startsWith("morph-"); - const proxy = morph ? undefined : !claude && options.proxy ? proxyConfig() : undefined; - const responsesEndpoint = morph ? morphConfig() : proxy; + const isMorph = model.startsWith("morph-"); + const proxy = isMorph ? undefined : !claude && options.proxy ? proxyConfig() : undefined; + const responsesEndpoint = isMorph ? morph : proxy; const request = claude ? { model, @@ -196,23 +200,34 @@ export function makeClient(options: { readonly proxy: boolean; readonly effort: const body = await Effect.runPromise( Effect.gen(function* () { const client = yield* HttpClient.HttpClient; - const response = yield* HttpClientRequest.post( - claude - ? "https://api.anthropic.com/v1/messages" - : `${responsesEndpoint?.url ?? "https://api.openai.com/v1"}/responses`, - ).pipe( - HttpClientRequest.setHeaders(headers), - HttpClientRequest.bodyJson(request), - Effect.flatMap(client.execute), - ); - if (response.status !== 200) - return yield* Effect.die( - new Error( - `Model API HTTP ${response.status}. Response body omitted to avoid leaking credentials.`, - ), + for (let attempt = 1; ; attempt++) { + const response = yield* HttpClientRequest.post( + claude + ? "https://api.anthropic.com/v1/messages" + : `${responsesEndpoint?.url ?? "https://api.openai.com/v1"}/responses`, + ).pipe( + HttpClientRequest.setHeaders(headers), + HttpClientRequest.bodyJson(request), + Effect.flatMap(client.execute), + Effect.timeout("120 seconds"), ); - return yield* response.text; - }).pipe(Effect.timeout("120 seconds"), Effect.provide(FetchHttpClient.layer)), + // Rate limits and server errors are transport, not model behaviour, so they get retries. + if ((response.status === 429 || response.status >= 500) && attempt < MAX_ATTEMPTS) { + const retryAfter = Number(response.headers["retry-after"]); + yield* Effect.sleep( + `${retryAfter > 0 ? Math.min(retryAfter, 60) : 2 ** attempt} seconds`, + ); + continue; + } + if (response.status !== 200) + return yield* Effect.die( + new Error( + `Model API HTTP ${response.status}. Response body omitted to avoid leaking credentials.`, + ), + ); + return yield* response.text; + } + }).pipe(Effect.provide(FetchHttpClient.layer)), ); const raw: unknown = proxy ? body diff --git a/evals/shared/proxy.ts b/evals/shared/proxy.ts index 993e619f08216..fb4f123a2ad4e 100644 --- a/evals/shared/proxy.ts +++ b/evals/shared/proxy.ts @@ -34,7 +34,7 @@ print(json.dumps({'url': p['base_url'].rstrip('/'), 'headers': h})) /** * Morph's free OpenAI-compatible API, for evals that should not spend on paid models. The key is - * `MORPH_API_KEY`, else the `morph` provider in `~/.config/opencode/opencode.json`. + * `MORPH_API_KEY`, else the `morph` provider in OpenCode's config (`$XDG_CONFIG_HOME` or `~/.config`). */ export const morphConfig = () => decodeProxyConfig( @@ -48,9 +48,12 @@ import json, os, pathlib key = os.environ.get('MORPH_API_KEY') url = os.environ.get('MORPH_BASE_URL', 'https://api.morphllm.com/v1') if not key: - config = pathlib.Path.home() / '.config' / 'opencode' / 'opencode.json' - settings = json.loads(config.read_text(), strict=False)['providers']['morph']['settings'] - key, url = settings['apiKey'], settings.get('baseURL', url) + home = pathlib.Path(os.environ.get('XDG_CONFIG_HOME') or pathlib.Path.home() / '.config') + # OpenCode writes literal control characters inside strings, which strict parsing rejects. + settings = json.loads((home / 'opencode' / 'opencode.json').read_text(), strict=False)['providers']['morph']['settings'] + key, url = settings.get('apiKey'), settings.get('baseURL', url) +if not key: + raise SystemExit('no morph key') print(json.dumps({'url': url.rstrip('/'), 'headers': {'Authorization': 'Bearer ' + key}})) `, ], From 41f51e011f3f780e5a1890b3f00c16178fd1111e Mon Sep 17 00:00:00 2001 From: Zack Jackson <25274700+ScriptedAlchemy@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:24:18 -0800 Subject: [PATCH 3/3] fix(evals): bound response bodies and retries by request timeout --- evals/group-conversation/client.test.ts | 43 +++++++++++++++++++++++++ evals/group-conversation/client.ts | 3 +- 2 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 evals/group-conversation/client.test.ts diff --git a/evals/group-conversation/client.test.ts b/evals/group-conversation/client.test.ts new file mode 100644 index 0000000000000..3e59e7f594c86 --- /dev/null +++ b/evals/group-conversation/client.test.ts @@ -0,0 +1,43 @@ +import { expect, it, vi } from "vite-plus/test"; + +import { makeClient } from "./client.ts"; + +it("times out when response headers arrive but the body stalls", async () => { + vi.useFakeTimers(); + vi.stubEnv("OPENAI_API_KEY", "eval-test-key"); + const reading = Promise.withResolvers(); + const body = Promise.withResolvers(); + const response = new Response(null, { status: 200 }); + using _body = vi.spyOn(response, "arrayBuffer").mockImplementation(() => { + reading.resolve(); + return body.promise; + }); + using _fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(response); + const completed = new TextEncoder().encode( + JSON.stringify({ + status: "completed", + output: [{ type: "message", content: [{ type: "output_text", text: "Finished" }] }], + usage: { input_tokens: 1, output_tokens: 1 }, + }), + ).buffer; + try { + const client = makeClient({ proxy: false, effort: "low" }); + const result = client.call("gpt-test", "Answer", [], [], "timeout regression").then( + (value) => ({ value }), + (error: unknown) => ({ error }), + ); + await vi.advanceTimersByTimeAsync(0); + await reading.promise; + await vi.advanceTimersByTimeAsync(120_001); + body.resolve(completed); + expect(await result).toMatchObject({ error: { _tag: "TimeoutError" } }); + expect(client.attempts).toEqual([ + { model: "gpt-test", purpose: "timeout regression", completed: false }, + ]); + expect(client.ledger).toEqual([]); + } finally { + body.resolve(completed); + vi.unstubAllEnvs(); + vi.useRealTimers(); + } +}); diff --git a/evals/group-conversation/client.ts b/evals/group-conversation/client.ts index 43ae18dfd3b36..bf37a1aa9c70d 100644 --- a/evals/group-conversation/client.ts +++ b/evals/group-conversation/client.ts @@ -209,7 +209,6 @@ export function makeClient(options: { readonly proxy: boolean; readonly effort: HttpClientRequest.setHeaders(headers), HttpClientRequest.bodyJson(request), Effect.flatMap(client.execute), - Effect.timeout("120 seconds"), ); // Rate limits and server errors are transport, not model behaviour, so they get retries. if ((response.status === 429 || response.status >= 500) && attempt < MAX_ATTEMPTS) { @@ -227,7 +226,7 @@ export function makeClient(options: { readonly proxy: boolean; readonly effort: ); return yield* response.text; } - }).pipe(Effect.provide(FetchHttpClient.layer)), + }).pipe(Effect.timeout("120 seconds"), Effect.provide(FetchHttpClient.layer)), ); const raw: unknown = proxy ? body