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
@@ -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(