Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/desktop/llm-host/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
20 changes: 16 additions & 4 deletions src/renderer/manage/tabs/settings/ModelsSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1897,15 +1897,24 @@ 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` +
(test.skippedNoTools ? ` (${test.skippedNoTools} without tool support hidden)` : '') +
// 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 (
Expand All @@ -1918,8 +1927,10 @@ function LocalServerAddForm({
— LM Studio loads one on first use, so its first reply can take a while. <strong>Custom endpoint</strong> is
any other URL: a gateway, a proxy, a server elsewhere on your network. Leave the flavor on{' '}
<em>Auto-detect</em> and Test connection classifies which chat route the endpoint exposes
(<code>/v1/chat/completions</code> vs <code>/v1/messages</code>) before listing its models — or pick a
flavor by hand if the server is picky about that OPTIONS probe. Stem strips a trailing <code>/v1</code>
(<code>/v1/chat/completions</code>, <code>/v1/responses</code> or <code>/v1/messages</code>) 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
<code>/v1/responses</code> is not routed to chat completions by accident. Stem strips a trailing <code>/v1</code>
from your URL and lets the client add the versioned path itself. The key goes on the wire the way the
target API expects (<code>Authorization: Bearer</code> for OpenAI-flavored servers, <code>X-Api-Key</code>
for Anthropic). Leave the model IDs empty and Stem uses whatever the endpoint lists, re-checked every
Expand Down Expand Up @@ -1993,6 +2004,7 @@ function LocalServerAddForm({
>
<option value="">Auto-detect (Test to classify)</option>
<option value="openai-completions">OpenAI Chat Completions</option>
<option value="openai-responses">OpenAI Responses</option>
<option value="anthropic-messages">Anthropic Messages</option>
</select>
<input
Expand Down
2 changes: 1 addition & 1 deletion src/server/ipc/guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ const IPC_ARGS: Record<string, ArgSpec[]> = {
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))
],
Expand Down
98 changes: 57 additions & 41 deletions src/server/pi/models-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<Response>) => r.status === 'fulfilled' && r.value.status !== 404;
return { oc: present(oc), or: present(or), am: present(am) };
}

/**
Expand Down Expand Up @@ -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]);
Expand All @@ -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 }`.
*/
Expand All @@ -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);
}

Expand Down Expand Up @@ -279,18 +289,20 @@ function localProviderBlock(
modelOverrides: Record<string, ModelOverride>
): 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<string, unknown> =
api === 'anthropic-messages' ? {} : { supportsDeveloperRole: false, supportsReasoningEffort: false };
api === 'openai-completions' ? { supportsDeveloperRole: false, supportsReasoningEffort: false } : {};
return {
baseUrl: finalBaseUrl,
api,
Expand Down Expand Up @@ -485,9 +497,13 @@ export function syncModelsConfig(): Promise<boolean> {
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).
Expand Down
4 changes: 3 additions & 1 deletion src/server/workspace/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,9 @@ function coerce(parsed: Partial<ServerSettings> | 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
Expand Down
9 changes: 8 additions & 1 deletion src/shared/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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[];
}

/**
Expand Down
19 changes: 18 additions & 1 deletion tests/unit/ipc-guard.test.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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[] = [];
Expand Down
3 changes: 3 additions & 0 deletions tests/unit/llm-relay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading
Loading