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(