fix(assistant): keep OpenRouter turns in one routing session

Pass a stable conversation session to OpenRouter so turns can reuse the same provider route. Namespace locally allocated thread IDs across server processes.

Closes #3298
This commit is contained in:
Maurice
2026-12-02 09:45:19 +01:00
parent 3089aee593
commit d6184559e9
2 changed files with 44 additions and 4 deletions
@@ -9,6 +9,7 @@ import type {
AiSource,
AiToolCall,
} from '../ai-chat-client.interface';
import { AI_BASE_URLS } from '../ai-connections.constants';
import { AiProviderError, errorCodeOf, isReasoningEffortRefusal, providerFailure } from './provider-errors';
import {
asCount,
@@ -24,9 +25,15 @@ import { imageDataUrl, toolImageCaption, toolImagesEndingAt } from './provider-i
import { readSseEvents } from './sse-lines';
import type { AiConnectionKind } from '@trek/shared';
import { randomUUID } from 'node:crypto';
/** The end of an OpenAI-compatible stream. */
const DONE = '[DONE]';
// Thread IDs are local to the database. Keep routing sessions distinct across
// TREK processes that share an OpenRouter API key.
const OPENROUTER_SESSION_NAMESPACE = randomUUID();
/** The host of Gemini's OpenAI-compatible endpoint, which an admin may also enter as their own server. */
const GEMINI_HOST = 'generativelanguage.googleapis.com';
@@ -104,10 +111,10 @@ const FINISH_REASONS: Record<string, AiFinishReason> = { tool_calls: 'tool-calls
/**
* The OpenAI-compatible Chat Completions API, streamed: OpenAI itself, Gemini
* (its `/v1beta/openai` endpoint), OpenRouter and an admin's own server. The
* kind decides only what a request may carry: Gemini gets its narrower tool
* schemas, also when an admin enters its endpoint as their own server, and
* OpenAI the prompt cache key, which the others do not know. Gemini's thought
* signatures come back as the turn's provider state.
* endpoint decides what a request may carry: Gemini gets its narrower tool
* schemas, also when an admin enters its endpoint as their own server. OpenAI
* gets the prompt cache key, and the OpenRouter API uses it as the routing
* session. Gemini's thought signatures come back as the turn's provider state.
*
* No request names a reasoning effort, since a server that does not reason may
* refuse the field. A reasoning model that takes function tools only without
@@ -205,6 +212,9 @@ export class OpenAiChatClient implements AiChatClient {
: {}),
...(this.toolsWithoutReasoning && request.tools.length > 0 ? { reasoning_effort: 'none' } : {}),
...(this.kind === 'openai' && request.cacheKey ? { prompt_cache_key: request.cacheKey } : {}),
...(this.kind === 'openrouter' && this.baseUrl === AI_BASE_URLS.openrouter && request.cacheKey
? { session_id: `${OPENROUTER_SESSION_NAMESPACE}:${request.cacheKey}` }
: {}),
...(request.webSearch && this.webSearch ? { plugins: [{ id: 'web', max_results: 5 }] } : {}),
};
return openProviderStream(
@@ -574,6 +574,7 @@ describe('OpenAiChatClient', () => {
const body = http.body();
expect(dig(body, 'messages', 0)).toEqual({ role: 'system', content: 'You plan trips.\n\nTrip: Japan, 3 days' });
expect(body).toMatchObject({ prompt_cache_key: 'thread-12', stream_options: { include_usage: true } });
expect(body).not.toHaveProperty('session_id');
expect(dig(body, 'tools', 0, 'function', 'name')).toBe('create_place');
expect(toChatMessages(REQUEST).slice(2, 4)).toEqual([
{
@@ -632,10 +633,39 @@ describe('OpenAiChatClient', () => {
);
expect(custom.calls[0]?.init.headers).not.toHaveProperty('authorization');
expect(custom.body().tools).toBeUndefined();
expect(custom.body()).not.toHaveProperty('session_id');
// A server that closes after its finish_reason without [DONE] has still finished.
expect(events.at(-1)).toEqual({ type: 'finish', reason: 'stop' });
});
it('OACH-012: keeps OpenRouter turns on the same routing session as the trip context changes', async () => {
const http = fetchAnswering(
streamResponse(['[DONE]']),
streamResponse(['[DONE]']),
streamResponse(['[DONE]']),
streamResponse(['[DONE]']),
streamResponse(['[DONE]']),
);
const router = () =>
new OpenAiChatClient('openrouter', 'm', 'https://openrouter.ai/api/v1', 'sk-or-key', http.fetcher);
await run(router().stream(REQUEST, signal()));
await run(router().stream({ ...REQUEST, context: 'Trip: Japan, 4 days' }, signal()));
await run(router().stream({ ...REQUEST, cacheKey: 'thread-13' }, signal()));
await run(router().stream({ ...REQUEST, cacheKey: undefined }, signal()));
const hosted = new OpenAiChatClient('openrouter', 'm', 'https://hosted.example/ai/v1', 'token', http.fetcher);
await run(hosted.stream(REQUEST, signal()));
expect(http.calls[0]?.url).toBe('https://openrouter.ai/api/v1/chat/completions');
expect(dig(http.body(0), 'messages', 0)).not.toEqual(dig(http.body(1), 'messages', 0));
const sessionId = http.body(0).session_id;
expect(sessionId).toMatch(/^[a-f0-9-]{36}:thread-12$/);
expect(http.body(1).session_id).toBe(sessionId);
expect(http.body(2).session_id).toMatch(/^[a-f0-9-]{36}:thread-13$/);
expect(http.body(0)).not.toHaveProperty('prompt_cache_key');
expect(http.body(3)).not.toHaveProperty('session_id');
expect(http.body(4)).not.toHaveProperty('session_id');
});
it('OACH-004: a call without id or index gets one, a broken argument list becomes empty', async () => {
const events = await run(
new OpenAiChatClient(