diff --git a/src/desktop/llm-host/index.ts b/src/desktop/llm-host/index.ts index f50fc963..ebab36af 100644 --- a/src/desktop/llm-host/index.ts +++ b/src/desktop/llm-host/index.ts @@ -21,6 +21,7 @@ const HEARTBEAT_MS = 10_000; const MODEL_API_PATHS = [ '/v1/models', '/v1/chat/completions', + '/v1/responses', '/v1/completions', '/v1/messages', '/v1/messages/count_tokens', diff --git a/src/renderer/manage/tabs/settings/ModelsSettings.tsx b/src/renderer/manage/tabs/settings/ModelsSettings.tsx index 2c950a58..ba8b2790 100644 --- a/src/renderer/manage/tabs/settings/ModelsSettings.tsx +++ b/src/renderer/manage/tabs/settings/ModelsSettings.tsx @@ -1897,7 +1897,11 @@ function LocalServerAddForm({ } const flavorLabel = (a: LocalProviderApi): string => - a === 'anthropic-messages' ? 'Anthropic Messages' : 'OpenAI Chat Completions'; + a === 'anthropic-messages' + ? 'Anthropic Messages' + : a === 'openai-responses' + ? 'OpenAI Responses' + : 'OpenAI Chat Completions'; const testLabel = test ? test.ok ? `${test.models?.length ?? 0} model${(test.models?.length ?? 0) === 1 ? '' : 's'} found` + @@ -1905,7 +1909,12 @@ function LocalServerAddForm({ // When auto-detect classified the endpoint, name the flavor it picked so // the user can see (and re-confirm) the setting Enable will write. (custom && test.api ? ` — ${flavorLabel(test.api)}` : '') - : test.error ?? 'failed' + : test.ambiguous?.length + ? // Auto-detect found several APIs on one endpoint (a gateway serving both + // chat completions and responses). Name them and send the user to the + // flavor dropdown rather than guess and mis-route a reasoning model. + `Serves ${test.ambiguous.map(flavorLabel).join(' and ')}. Pick a flavor above and test again.` + : test.error ?? 'failed' : null; return ( @@ -1918,8 +1927,10 @@ function LocalServerAddForm({ — LM Studio loads one on first use, so its first reply can take a while. Custom endpoint is any other URL: a gateway, a proxy, a server elsewhere on your network. Leave the flavor on{' '} Auto-detect and Test connection classifies which chat route the endpoint exposes - (/v1/chat/completions vs /v1/messages) before listing its models — or pick a - flavor by hand if the server is picky about that OPTIONS probe. Stem strips a trailing /v1 + (/v1/chat/completions, /v1/responses or /v1/messages) before + listing its models — or pick a flavor by hand if the server is picky about that OPTIONS probe. An + endpoint that serves more than one of those routes asks you to pick, so a reasoning model that needs + /v1/responses is not routed to chat completions by accident. Stem strips a trailing /v1 from your URL and lets the client add the versioned path itself. The key goes on the wire the way the target API expects (Authorization: Bearer for OpenAI-flavored servers, X-Api-Key for Anthropic). Leave the model IDs empty and Stem uses whatever the endpoint lists, re-checked every @@ -1993,6 +2004,7 @@ function LocalServerAddForm({ > + = { a.string, a.string, a.optional(a.nullish(a.string)), - a.optional(a.nullish(a.oneOf(['openai-completions', 'anthropic-messages']))), + a.optional(a.nullish(a.oneOf(['openai-completions', 'openai-responses', 'anthropic-messages']))), // A paired computer to probe from; null/absent = from the server. a.optional(a.nullish(a.string)) ], diff --git a/src/server/pi/models-config.ts b/src/server/pi/models-config.ts index bfd336c7..3b75a416 100644 --- a/src/server/pi/models-config.ts +++ b/src/server/pi/models-config.ts @@ -114,8 +114,9 @@ async function isToolCapable(base: string, id: string, timeoutMs: number): Promi * Which chat/messages routes this endpoint exposes. Called by auto-detect to * pick between openai-completions and anthropic-messages: both flavors serve * `GET /v1/models` under the same route, so the listing can't tell them apart - * — the real signal is which of `/v1/chat/completions` (OpenAI) and - * `/v1/messages` (Anthropic) the proxy actually implements. + * — the real signal is which of `/v1/chat/completions` (OpenAI Chat + * Completions), `/v1/responses` (OpenAI Responses) and `/v1/messages` + * (Anthropic) the proxy actually implements. * * Uses OPTIONS to keep the probe cost-free (no completion tokens spent). A * 404 = route absent; anything else (200/400/401/405/…) = route present and @@ -130,18 +131,17 @@ async function classifyChatRoutes( base: string, apiKey: string | undefined, timeoutMs: number -): Promise<{ oc: boolean; am: boolean }> { +): Promise<{ oc: boolean; or: boolean; am: boolean }> { const key = apiKey?.trim(); const headers = { ...probeHeaders('openai-completions', key), ...probeHeaders('anthropic-messages', key) }; const options = { method: 'OPTIONS', headers, signal: AbortSignal.timeout(timeoutMs) }; - const [oc, am] = await Promise.allSettled([ + const [oc, or, am] = await Promise.allSettled([ fetch(`${base}/v1/chat/completions`, options), + fetch(`${base}/v1/responses`, options), fetch(`${base}/v1/messages`, options) ]); - return { - oc: oc.status === 'fulfilled' && oc.value.status !== 404, - am: am.status === 'fulfilled' && am.value.status !== 404 - }; + const present = (r: PromiseSettledResult) => r.status === 'fulfilled' && r.value.status !== 404; + return { oc: present(oc), or: present(or), am: present(am) }; } /** @@ -171,10 +171,11 @@ async function probeOneFlavor( .map((m) => (typeof m.id === 'string' ? m.id.trim() : '')) .filter(Boolean) .sort((a, b) => a.localeCompare(b)); - // Ollama is keyless and OpenAI-flavored, so any of {bearer key, anthropic - // flavor} means this isn't Ollama — skip the per-model capability probe. + // Ollama is keyless and speaks openai-completions, so any of {bearer key, + // a non-completions flavor} means this isn't Ollama — skip the per-model + // capability probe. const capable = - key || api === 'anthropic-messages' + key || api !== 'openai-completions' ? all.map(() => true) : await Promise.all(all.map((id) => isToolCapable(base, id, timeoutMs))); const models = all.filter((_, i) => capable[i]); @@ -195,15 +196,15 @@ async function probeOneFlavor( * returned as-is; on success the result carries `api` back so a caller can * confirm. * - * `api` omitted (auto-detect): first classify which chat route the endpoint - * exposes (OPTIONS on /v1/chat/completions and /v1/messages — non-404 wins), - * then probe GET /v1/models under that flavor's downstream expectations. - * openai-completions wins ties (a proxy that serves both routes is a matter of - * downstream preference; the current default matches Stem's pre-existing - * behavior). If neither chat route resolves, fall back to a plain - * openai-completions probe of /v1/models — some servers only expose the - * listing and refuse OPTIONS entirely; the user can still enable and test in - * a real turn. + * `api` omitted (auto-detect): first classify which chat routes the endpoint + * exposes (OPTIONS on /v1/chat/completions, /v1/responses and /v1/messages — + * non-404 = present), then probe GET /v1/models under the detected flavor's + * downstream expectations. One route present → probe that flavor. More than + * one → return `{ ok:false, ambiguous:[…] }`: a reasoning model needs Responses + * while the same gateway also serves Chat Completions, so a silent tie-break + * would route it wrong — the user picks the flavor and tests again. No route + * resolves (server refuses OPTIONS, or all 404) → fall back to a plain + * openai-completions probe of /v1/models, the pre-flavor behavior. * * Never throws — failures come back as `{ ok:false, error }`. */ @@ -217,15 +218,24 @@ export async function probeLocalProvider( const base = normalizeLocalBaseUrl(baseUrl); if (!/^https?:\/\//i.test(base)) return { ok: false, error: 'Enter a URL like http://localhost:11434.' }; const routes = await classifyChatRoutes(base, apiKey, timeoutMs); - // openai-completions wins ties: pre-existing default and more common. - const detected: LocalProviderApi | null = routes.oc - ? 'openai-completions' - : routes.am - ? 'anthropic-messages' - : null; - if (detected) return probeOneFlavor(baseUrl, apiKey, detected, timeoutMs); - // Neither OPTIONS resolved (server rejects OPTIONS, or both 404). Fall back - // to a plain openai-completions listing probe — same behavior as pre-flavor. + const detected: LocalProviderApi[] = [ + ...(routes.oc ? ['openai-completions' as const] : []), + ...(routes.or ? ['openai-responses' as const] : []), + ...(routes.am ? ['anthropic-messages' as const] : []) + ]; + // More than one API answered: refuse to guess. A reasoning model (gpt-6.1-sol) + // only works through Responses, yet the same gateway also serves Chat + // Completions — picking one here is how a turn silently hit the wrong route. + if (detected.length > 1) { + return { + ok: false, + ambiguous: detected, + error: 'This endpoint serves more than one API. Pick a flavor and test again.' + }; + } + if (detected.length === 1) return probeOneFlavor(baseUrl, apiKey, detected[0], timeoutMs); + // No OPTIONS resolved (server rejects OPTIONS, or all 404). Fall back to a + // plain openai-completions listing probe — same behavior as pre-flavor. return probeOneFlavor(baseUrl, apiKey, 'openai-completions', timeoutMs); } @@ -279,18 +289,20 @@ function localProviderBlock( modelOverrides: Record ): PiProviderConfig { const normalized = normalizeLocalBaseUrl(baseUrl); - // openai-completions: append /v1 so pi hits /v1/chat/completions (matches the - // Ollama/LM Studio flow that always did it). + // openai-completions/openai-responses: append /v1. pi's OpenAI SDK client + // appends /chat/completions or /responses to the baseURL it is given. // anthropic-messages: leave the normalized root as-is — pi's Anthropic client - // (@anthropic-ai/sdk) appends /v1/messages verbatim to whatever baseURL it - // receives. Appending /v1 here would produce /v1/v1/messages at request time. + // (@anthropic-ai/sdk) appends /v1/messages verbatim. Appending /v1 here would + // produce /v1/v1/messages at request time. const finalBaseUrl = api === 'anthropic-messages' ? normalized : `${normalized}/v1`; - // Per-flavor compat: OpenAI-compat servers get the local-server defaults; - // anthropic-messages providers get an empty block so pi's Anthropic defaults - // (eager tool streaming, cache retention, …) apply. Users needing proxy- - // specific overrides can hand-edit models.json. + // Per-flavor compat. Only openai-completions gets the local-server clamp: + // supportsReasoningEffort false stops pi sending reasoning_effort on + // /v1/chat/completions, which reasoning models reject alongside function + // tools. openai-responses and anthropic-messages get an empty block so pi's + // own defaults apply — the Responses API carries reasoning natively, and + // clamping it there is what forced reasoning models onto completions before. const compat: Record = - api === 'anthropic-messages' ? {} : { supportsDeveloperRole: false, supportsReasoningEffort: false }; + api === 'openai-completions' ? { supportsDeveloperRole: false, supportsReasoningEffort: false } : {}; return { baseUrl: finalBaseUrl, api, @@ -485,9 +497,13 @@ export function syncModelsConfig(): Promise { const parsed = parseModelOverrides(settings[id].modelOverrides); if (!parsed.ok) log('pi', `ignoring invalid model overrides for ${id}`, { errors: parsed.errors }); const overrides = parsed.ok ? parsed.value : {}; - // Only custom endpoints may speak anthropic-messages; the coercion enforces this too, - // this is defense in depth against a hand-edited settings.json. - const api: LocalProviderApi = isCustomProviderId(id) && rawApi === 'anthropic-messages' ? 'anthropic-messages' : 'openai-completions'; + // Only custom endpoints may speak anthropic-messages or openai-responses. + // The coercion enforces that too — defense in depth against a hand-edited + // settings.json. Everything else falls back to openai-completions. + const api: LocalProviderApi = + isCustomProviderId(id) && (rawApi === 'anthropic-messages' || rawApi === 'openai-responses') + ? rawApi + : 'openai-completions'; // Hand-entered ids are authoritative: an endpoint that names its models has // opted out of discovery, so don't probe it (and don't let a listing endpoint // it happens to serve override the user's choice). diff --git a/src/server/workspace/settings.ts b/src/server/workspace/settings.ts index 9aa56ffc..6af32eb2 100644 --- a/src/server/workspace/settings.ts +++ b/src/server/workspace/settings.ts @@ -638,7 +638,9 @@ function coerce(parsed: Partial | null): ServerSettings { // settings.json is self-describing and future debugging can tell an explicit // openai-completions pick from an absent field (= not yet configured). const api: LocalProviderApi | undefined = - custom && (r.api === 'anthropic-messages' || r.api === 'openai-completions') ? r.api : undefined; + custom && (r.api === 'anthropic-messages' || r.api === 'openai-completions' || r.api === 'openai-responses') + ? r.api + : undefined; // Per-model overrides: custom endpoints only, coerced only as far as their shape — // an entry that fails the deeper guard (pi/model-overrides.ts) is KEPT here // and dropped at sync time instead. Losing the text on read is the exact diff --git a/src/shared/types.ts b/src/shared/types.ts index b1b6773f..b24862bb 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -290,7 +290,7 @@ export type LocalProviderId = BuiltInLocalProviderId | CustomProviderId; * Anthropic's Messages API or a proxy that speaks it). Default (absent) is * `openai-completions` — matches the pre-existing single-flavor behavior. */ -export type LocalProviderApi = 'openai-completions' | 'anthropic-messages'; +export type LocalProviderApi = 'openai-completions' | 'openai-responses' | 'anthropic-messages'; /** * What one model of a custom endpoint needs said about it that its `/v1/models` @@ -410,6 +410,13 @@ export interface LocalProviderTestResult { skippedNoTools?: number; /** Human-readable failure, e.g. ECONNREFUSED (not ok only). */ error?: string; + /** + * Set when auto-detect found more than one API this endpoint can speak (e.g. a + * gateway serving both /v1/chat/completions and /v1/responses). The probe + * refuses to guess: the renderer offers these flavors so the user picks one, + * then tests again with an explicit `api`. `ok` is false when this is set. + */ + ambiguous?: LocalProviderApi[]; } /** diff --git a/tests/unit/ipc-guard.test.ts b/tests/unit/ipc-guard.test.ts index a14c2809..1b93eaf4 100644 --- a/tests/unit/ipc-guard.test.ts +++ b/tests/unit/ipc-guard.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import { ipcMain } from '../electron-stub'; -import { a, argsProblem, dispatchLocal, hasLocalHandler, registerServer, serverChannels } from '../../src/server/ipc'; +import { a, argsProblem, dispatchLocal, hasLocalHandler, ipcArgSpecs, registerServer, serverChannels } from '../../src/server/ipc'; import { bindServerChannels, handleLocal, senderProblem } from '../../src/desktop/ipc-bridge'; // The IPC guard, split across the two sides: src/server/ipc/guard.ts holds the @@ -60,6 +60,23 @@ describe('argsProblem', () => { }); }); +describe('providers:testLocal', () => { + it('accepts every custom API flavor as argument 4', () => { + // The flavor set here must track LocalProviderApi. A flavor the UI can send + // but the guard rejects dies as "request failed" before it reaches the probe + // — which is exactly how openai-responses was blocked before this entry. + const specs = ipcArgSpecs('providers:testLocal'); + for (const api of ['openai-completions', 'openai-responses', 'anthropic-messages']) { + expect(argsProblem(specs, ['custom', 'http://localhost:8080', 'key', api])).toBeNull(); + } + // Auto-detect still sends no flavor, and a bogus one is still rejected. + expect(argsProblem(specs, ['custom', 'http://localhost:8080'])).toBeNull(); + expect(argsProblem(specs, ['custom', 'http://localhost:8080', 'key', 'openai-bogus'])).toMatch( + /one of openai-completions\|openai-responses\|anthropic-messages/ + ); + }); +}); + describe('exec channels', () => { it('exec:resolveApproval takes a string id and a known decision', async () => { let got: unknown[] = []; diff --git a/tests/unit/llm-relay.test.ts b/tests/unit/llm-relay.test.ts index 091eb321..8ee07667 100644 --- a/tests/unit/llm-relay.test.ts +++ b/tests/unit/llm-relay.test.ts @@ -160,6 +160,9 @@ describe('device side of the relay', () => { const req = (url: string): DeviceLlmRequest => ({ requestId: 'x', url, method: 'GET', headers: {} }); expect(refusal(req('http://localhost:1234/v1/models'))).toBeNull(); expect(refusal(req('http://localhost:11434/api/show'))).toBeNull(); + // A reasoning model on a paired computer turns through /v1/responses; the + // host must relay it, or every turn 502s while /v1/models discovery passes. + expect(refusal(req('http://localhost:1234/v1/responses'))).toBeNull(); expect(refusal(req('http://localhost:8080/admin'))).toMatch(/model API/); expect(refusal(req('http://localhost:8080/v1/admin/users'))).toMatch(/model API/); expect(refusal(req('http://localhost:1234/lmstudio/v1/chat/completions'))).toBeNull(); diff --git a/tests/unit/models-config.test.ts b/tests/unit/models-config.test.ts index 926688bf..3b5fea95 100644 --- a/tests/unit/models-config.test.ts +++ b/tests/unit/models-config.test.ts @@ -201,6 +201,7 @@ describe('probeLocalProvider', () => { const path = new URL(String(url)).pathname; if (init?.method === 'OPTIONS') { if (path.endsWith('/v1/chat/completions')) return new Response(null, { status: 404 }); + if (path.endsWith('/v1/responses')) return new Response(null, { status: 404 }); if (path.endsWith('/v1/messages')) return new Response(null, { status: 405 }); } return new Response(JSON.stringify({ data: [{ id: 'anthropic--claude-4.8-opus' }] }), { status: 200 }); @@ -210,20 +211,43 @@ describe('probeLocalProvider', () => { expect(res).toEqual({ ok: true, api: 'anthropic-messages', models: ['anthropic--claude-4.8-opus'] }); }); - it('prefers openai-completions when both chat routes exist (tie-break to pre-existing default)', async () => { - // Both 200 on OPTIONS — the ambiguous case. Auto-detect must not silently - // pick anthropic when the more common flavor also works. - const fetchMock = vi.fn(async (_url: string, init?: RequestInit) => { - if (init?.method === 'OPTIONS') return new Response(null, { status: 200 }); + it('picks openai-responses when only /v1/responses exists', async () => { + // A Responses-only gateway: the flavor a reasoning model needs. Nothing + // else resolves, so auto-detect commits to it with no prompt. + const fetchMock = vi.fn(async (url: string, init?: RequestInit) => { + const path = new URL(String(url)).pathname; + if (init?.method === 'OPTIONS') { + return new Response(null, { status: path.endsWith('/v1/responses') ? 200 : 404 }); + } + return new Response(JSON.stringify({ data: [{ id: 'gpt-6.1-sol' }] }), { status: 200 }); + }); + vi.stubGlobal('fetch', fetchMock); + const res = await probeLocalProvider('http://localhost:8080', 'sk-secret'); + expect(res).toEqual({ ok: true, api: 'openai-responses', models: ['gpt-6.1-sol'] }); + }); + + it('refuses to guess when a gateway serves both chat completions and responses', async () => { + // The HAI shape: one endpoint answers OPTIONS on /v1/chat/completions AND + // /v1/responses. gpt-6.1-sol only works through Responses, so a silent + // tie-break to completions mis-routes the turn. Auto-detect returns the + // candidates and lets the user pick instead. + const fetchMock = vi.fn(async (url: string, init?: RequestInit) => { + const path = new URL(String(url)).pathname; + if (init?.method === 'OPTIONS') { + const present = path.endsWith('/v1/chat/completions') || path.endsWith('/v1/responses'); + return new Response(null, { status: present ? 200 : 404 }); + } return new Response(JSON.stringify({ data: [{ id: 'x' }] }), { status: 200 }); }); vi.stubGlobal('fetch', fetchMock); const res = await probeLocalProvider('http://localhost:8080', 'sk-secret'); - expect(res.ok).toBe(true); - expect(res.api).toBe('openai-completions'); + expect(res.ok).toBe(false); + expect(res.ambiguous).toEqual(['openai-completions', 'openai-responses']); + // No /v1/models listing was fetched — the probe stopped at classification. + expect(vi.mocked(fetch).mock.calls.every(([, init]) => (init as RequestInit)?.method === 'OPTIONS')).toBe(true); }); - it('falls back to an openai-completions listing when both OPTIONS return 404', async () => { + it('falls back to an openai-completions listing when every OPTIONS returns 404', async () => { // Some servers refuse OPTIONS entirely (405) or 404 every unknown path; // the fallback keeps the pre-existing default so Ollama/LM Studio still // probe as before. @@ -482,6 +506,30 @@ describe('syncModelsConfig', () => { }); }); + it('writes an openai-responses block with /v1 appended and an empty compat (no completions clamp)', async () => { + // The fix for gpt-6.1-sol: a Responses-flavor custom endpoint. baseUrl keeps + // /v1 (pi's OpenAI SDK appends /responses), and compat is EMPTY — the + // supportsReasoningEffort:false clamp is openai-completions-only, and keeping + // it here is exactly what forced the reasoning model onto chat/completions. + use({ + custom: { + enabled: true, + baseUrl: 'http://localhost:6655/openai/v1', + api: 'openai-responses', + apiKey: 'sk-secret', + models: ['gpt-6.1-sol'] + } + }); + expect(await syncModelsConfig()).toBe(true); + expect(readConfig().providers.custom).toEqual({ + baseUrl: 'http://localhost:6655/openai/v1', + api: 'openai-responses', + apiKey: 'sk-secret', + compat: {}, + models: [{ id: 'gpt-6.1-sol' }] + }); + }); + // The flavor and issue #1's empty-block guard meet on the same line. A merge // that keeps the flavor but drops the guard writes `custom` with no models — // and every pi spawn dies on "Unknown provider" again, this time for the diff --git a/tests/unit/responses-integration.test.ts b/tests/unit/responses-integration.test.ts new file mode 100644 index 00000000..f2b9f7ef --- /dev/null +++ b/tests/unit/responses-integration.test.ts @@ -0,0 +1,173 @@ +import { createServer, type Server, type IncomingMessage } from 'node:http'; +import { mkdir, mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { PiRuntime } from '../../src/server/pi/runtime'; +import { syncModelsConfig } from '../../src/server/pi/models-config'; +import { updateChatsSettings, updateLocalProvider } from '../../src/server/workspace/settings'; +import { settingsStorePath } from '../../src/server/workspace/paths'; + +// The whole point of the openai-responses flavor, proven against the REAL pinned +// pi rather than a stub, AND through Stem's own config path: a user who sets a +// custom endpoint to the Responses flavor ends up with a pi `--mode rpc` child +// that sends the turn — carrying its function tools — to POST /v1/responses, NOT +// /v1/chat/completions. That route is the exact thing gpt-6.1-sol rejected on +// completions, so it is the fix's load-bearing claim. +// +// The config is GENERATED, not hand-written: updateLocalProvider runs the same +// coerce() the fix touched, and syncModelsConfig writes the same block. On HEAD +// both drop the unknown flavor back to openai-completions, pi hits +// /v1/chat/completions, the mock 404s it, and this test fails — which is what +// makes it a real regression guard rather than a restatement of a pi fact. +// +// Scope on purpose: this asserts the ROUTE and that tools ride along, then shuts +// down. It does not replay a full Responses tool round-trip — pi owns that SSE +// parsing and tests it itself. Same real-pi spawn recipe as +// runtime-pool-live.test.ts. + +interface Captured { + path: string; + auth?: string; + body: string; +} + +/** + * A minimal OpenAI endpoint that records every request (path, auth, body). It + * answers /v1/responses with a tiny valid streamed completion so the turn can + * settle, and 404s /v1/chat/completions so a mis-route would fail loudly. + */ +function recordingOpenAI(): Promise<{ + server: Server; + port: number; + calls: Captured[]; + /** Resolves on the first POST to /v1/responses. */ + sawResponses: Promise; +}> { + const calls: Captured[] = []; + let resolveSaw!: (c: Captured) => void; + const sawResponses = new Promise((resolve) => { + resolveSaw = resolve; + }); + const readBody = (req: IncomingMessage) => + new Promise((resolve) => { + let raw = ''; + req.on('data', (c) => (raw += c)); + req.on('end', () => resolve(raw)); + }); + const server = createServer((req, res) => { + void readBody(req).then((body) => { + const path = new URL(req.url ?? '/', 'http://x').pathname; + const auth = req.headers.authorization; + const call: Captured = { path, auth, body }; + calls.push(call); + if (path.endsWith('/v1/responses')) { + resolveSaw(call); + res.writeHead(200, { 'content-type': 'text/event-stream' }); + const send = (type: string, payload: unknown) => + res.write(`event: ${type}\ndata: ${JSON.stringify(payload)}\n\n`); + const response = { + id: 'resp_1', + object: 'response', + status: 'completed', + output: [ + { + type: 'message', + id: 'msg_1', + status: 'completed', + role: 'assistant', + content: [{ type: 'output_text', text: 'hi', annotations: [] }] + } + ], + usage: { input_tokens: 5, output_tokens: 1, total_tokens: 6 } + }; + send('response.created', { type: 'response.created', response: { ...response, status: 'in_progress', output: [] } }); + send('response.completed', { type: 'response.completed', response }); + res.end(); + return; + } + // Any other route (notably /v1/chat/completions) must never be hit. + res.writeHead(404, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: { message: `unexpected ${path}` } })); + }); + }); + return new Promise((resolve) => { + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + resolve({ + server, + port: typeof address === 'object' && address ? address.port : 0, + calls, + sawResponses + }); + }); + }); +} + +const cleanups: Array<() => Promise | void> = []; + +afterEach(async () => { + for (const fn of cleanups.splice(0).reverse()) await fn(); +}); + +describe('openai-responses flavor against real pi', () => { + it( + 'routes the turn and its tools to POST /v1/responses, not /v1/chat/completions', + async () => { + // No subject naming after the turn — it would spawn a child against the + // unauthenticated default provider just to fail. + await mkdir(dirname(settingsStorePath()), { recursive: true }); + await updateChatsSettings({ subjects: 'off' }); + + const { server, port, calls, sawResponses } = await recordingOpenAI(); + cleanups.push(() => new Promise((resolve) => server.close(() => resolve()))); + + const root = await mkdtemp(join(tmpdir(), 'stem-responses-live-')); + cleanups.push(() => rm(root, { recursive: true, force: true })); + const piHome = join(root, 'pi'); + const sessions = join(piHome, 'sessions'); + const workspace = join(root, 'workspace'); + await Promise.all([mkdir(sessions, { recursive: true }), mkdir(workspace, { recursive: true })]); + + // Generate models.json through Stem's real path. updateLocalProvider runs + // coerce() (must keep the flavor), syncModelsConfig writes the block (must + // not clamp it onto completions). Point the writer at this child's home. + const prevModelsEnv = process.env.STEM_PI_MODELS_CONFIG; + process.env.STEM_PI_MODELS_CONFIG = join(piHome, 'models.json'); + cleanups.push(() => { + if (prevModelsEnv === undefined) delete process.env.STEM_PI_MODELS_CONFIG; + else process.env.STEM_PI_MODELS_CONFIG = prevModelsEnv; + }); + // Hand-entered model id so the sync skips its live probe. + await updateLocalProvider('custom', { + enabled: true, + baseUrl: `http://127.0.0.1:${port}/openai`, + api: 'openai-responses', + apiKey: 'test-key', + models: ['gpt-6.1-sol'] + }); + await syncModelsConfig(); + + const runtime = new PiRuntime({ piHome, sessionsDir: sessions, workspaceRoot: workspace, seedGlobalAuth: false }); + cleanups.push(() => runtime.shutdown()); + (runtime as unknown as { buildMessage: () => Promise<{ message: string; images: unknown[] }> }).buildMessage = + async () => ({ message: 'say hello', images: [] }); + + await runtime.startTurn({ input: 'hello', model: 'custom/gpt-6.1-sol' }); + + // The load-bearing fact: pi hit the Responses route with a bearer token. + const responsesCall = await sawResponses; + expect(responsesCall.auth).toBe('Bearer test-key'); + + // And the turn carried function tools — the exact combo gpt-6.1-sol + // rejected on chat/completions. pi always declares tools, so the body + // holds a non-empty `tools` array. + const payload = JSON.parse(responsesCall.body) as { tools?: unknown[] }; + expect(Array.isArray(payload.tools) && payload.tools.length > 0).toBe(true); + + // Never the completions route. A single mis-route would 404 here. + expect(calls.some((c) => c.path.endsWith('/v1/chat/completions'))).toBe(false); + }, + 120_000 + ); +});