7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
fix(proxy): preserve the Moonshot assistant partial prefill flag (#1040)
suantea (asuan_suan)c6269d22a9e8
diff --git a/server/src/__tests__/providers/openai-compat.test.ts b/server/src/__tests__/providers/openai-compat.test.tsindex d7ab31f6..78e7aa6f 100644--- a/server/src/__tests__/providers/openai-compat.test.ts+++ b/server/src/__tests__/providers/openai-compat.test.ts@@ -1,4 +1,5 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import dns from 'node:dns';import { OpenAICompatProvider } from '../../providers/openai-compat.js';describe('OpenAICompatProvider', () => {@@ -69,6 +70,91 @@ describe('OpenAICompatProvider', () => {expect(capturedBody.messages[0].role).toBe('user');});+ describe('Moonshot assistant `partial` prefill flag (#1038)', () => {+ beforeEach(() => {+ // The custom-platform SSRF guard resolves public hosts before every+ // request; answer with a public address so no real DNS is needed.+ vi.spyOn(dns.promises, 'lookup').mockResolvedValue([{ address: '203.0.113.10', family: 4 }] as any);+ });+ function captureBody(): { body: () => any } {+ let captured: any = null;+ vi.spyOn(global, 'fetch').mockImplementation(async (_url, init) => {+ captured = JSON.parse((init as any).body);+ return {+ ok: true,+ json: () => Promise.resolve({+ id: 'test-id',+ object: 'chat.completion',+ created: 123,+ model: 'test-model',+ choices: [{ index: 0, message: { role: 'assistant', content: 'hi' }, finish_reason: 'stop' }],+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },+ }),+ } as any;+ });+ return { body: () => captured };+ }+ const prefill: any = { role: 'assistant', content: 'continue this', partial: true };+ const custom = (baseUrl: string) => new OpenAICompatProvider({ platform: 'custom', name: 'Custom', baseUrl });++ it('forwards `partial` to a custom endpoint on a Moonshot host', async () => {+ const captured = captureBody();+ await custom('https://api.moonshot.ai/v1').chatCompletion('k', [prefill], 'kimi-k2-0905-preview');+ expect(captured.body().messages[0].partial).toBe(true);++ await custom('https://api.moonshot.cn/v1').chatCompletion('k', [prefill], 'moonshot-v1-8k');+ expect(captured.body().messages[0].partial).toBe(true);++ await custom('https://api.kimi.com/coding/v1').chatCompletion('k', [prefill], 'kimi-for-coding');+ expect(captured.body().messages[0].partial).toBe(true);+ });++ it('strips `partial` for a custom endpoint on any other host, even for a Kimi model id', async () => {+ const captured = captureBody();+ await custom('http://127.0.0.1:11434/v1').chatCompletion('k', [prefill], 'kimi-k2:1t-cloud');+ expect(captured.body().messages[0]).not.toHaveProperty('partial');+ expect(captured.body().messages[0].content).toBe('continue this');++ // A look-alike host is not Moonshot.+ await custom('https://moonshot.ai.example.com/v1').chatCompletion('k', [prefill], 'kimi-latest');+ expect(captured.body().messages[0]).not.toHaveProperty('partial');+ });++ it('strips `partial` on Groq even when the model id is a Kimi model', async () => {+ const captured = captureBody();+ const groq = new OpenAICompatProvider({ platform: 'groq', name: 'Groq', baseUrl: 'https://api.groq.com/openai/v1' });+ await groq.chatCompletion('k', [prefill], 'moonshotai/kimi-k2-instruct-0905');+ expect(captured.body().messages[0]).not.toHaveProperty('partial');+ expect(captured.body().messages[0].content).toBe('continue this');+ });++ it('strips `partial` on a non-strict built-in gateway that serves Kimi models', async () => {+ const captured = captureBody();+ const openrouter = new OpenAICompatProvider({ platform: 'openrouter', name: 'OpenRouter', baseUrl: 'https://openrouter.ai/api/v1' });+ await openrouter.chatCompletion('k', [+ { role: 'user', content: 'hi' },+ { ...prefill, reasoning_content: 'kept: only partial is Moonshot-private' },+ ], 'moonshotai/kimi-k2:free');+ const msgs = captured.body().messages;+ expect(msgs[1]).not.toHaveProperty('partial');+ expect(msgs[1].reasoning_content).toBe('kept: only partial is Moonshot-private');+ expect(msgs[0]).toEqual({ role: 'user', content: 'hi' });+ });++ it('also strips `partial` on the streaming path for non-Moonshot endpoints', async () => {+ let captured: any = null;+ vi.spyOn(global, 'fetch').mockImplementation(async (_url, init) => {+ captured = JSON.parse((init as any).body);+ return sseResponse(['data: [DONE]\n\n']);+ });+ await collect(custom('http://127.0.0.1:1234/v1').streamChatCompletion('k', [prefill], 'kimi-latest'));+ expect(captured.messages[0]).not.toHaveProperty('partial');++ await collect(custom('https://api.moonshot.ai/v1').streamChatCompletion('k', [prefill], 'kimi-latest'));+ expect(captured.messages[0].partial).toBe(true);+ });+ });+it('uses a 60s chat timeout by default for OpenAI-compatible providers (#530)', async () => {const delays: number[] = [];const origSetTimeout = global.setTimeout;diff --git a/server/src/__tests__/routes/proxy-moonshot-partial.test.ts b/server/src/__tests__/routes/proxy-moonshot-partial.test.tsnew file mode 100644index 00000000..400afd1e--- /dev/null+++ b/server/src/__tests__/routes/proxy-moonshot-partial.test.ts@@ -0,0 +1,148 @@+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';+import dns from 'node:dns';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';+import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';++// Moonshot's assistant `partial: true` prefill flag (#1038) must survive the+// whole proxy path — request schema → message build → provider body — when the+// route lands on Moonshot's own API (a custom endpoint on a Moonshot host), and+// must be stripped for any other endpoint, even one serving a Kimi model.++let dashToken = '';++async function request(app: Express, method: string, path: string, body?: any, headers: Record<string, string> = {}) {+ const server = app.listen(0, '127.0.0.1');+ if (!server.listening) await new Promise<void>(resolve => server.once('listening', () => resolve()));+ const addr = server.address() as any;+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {+ method,+ headers: {+ ...(body ? { 'Content-Type': 'application/json' } : {}),+ ...(isGatedApiPath(path) && !('Authorization' in headers) ? { Authorization: `Bearer ${dashToken}` } : {}),+ ...headers,+ },+ body: body ? JSON.stringify(body) : undefined,+ });+ const data = await res.text();+ server.close();+ let json: any = null;+ try { json = JSON.parse(data); } catch {}+ return { status: res.status, body: json };+}++function authHeaders() {+ return { Authorization: `Bearer ${getUnifiedApiKey()}` };+}++/** Stub the upstream chat call and capture what reached it. */+function stubUpstream(modelId: string): { url: () => string; body: () => any } {+ const origFetch = global.fetch;+ let url = '';+ let body: any = null;+ vi.spyOn(global, 'fetch').mockImplementation(async (input, init) => {+ const u = typeof input === 'string' ? input : input.toString();+ // Only the two registered upstreams; the app under test also lives on+ // 127.0.0.1 (random port) and must keep going through the real fetch.+ if (u.startsWith('https://api.moonshot.ai/') || u.startsWith('http://127.0.0.1:11434/')) {+ url = u;+ body = JSON.parse((init as any).body);+ return {+ ok: true,+ json: () => Promise.resolve({+ id: 'chatcmpl-partial',+ object: 'chat.completion',+ created: 123,+ model: modelId,+ choices: [{ index: 0, message: { role: 'assistant', content: ' 42.' }, finish_reason: 'stop' }],+ usage: { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 },+ }),+ } as any;+ }+ return origFetch(input, init);+ });+ return { url: () => url, body: () => body };+}++const conversation = [+ { role: 'user', content: 'What is six times seven? Answer with the number only.' },+ { role: 'assistant', content: 'The answer is', partial: true },+];++describe('Moonshot `partial` prefill round trip (#1038)', () => {+ let app: Express;++ beforeAll(async () => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ getDb().prepare("DELETE FROM settings WHERE key = 'active_profile_id'").run();+ app = createApp();+ dashToken = mintDashboardToken();++ // The custom-platform SSRF guard resolves public hosts at save time and on+ // every request; answer with a public address so no real DNS is needed.+ vi.spyOn(dns.promises, 'lookup').mockResolvedValue([{ address: '203.0.113.10', family: 4 }] as any);++ const moonshot = await request(app, 'POST', '/api/keys/custom', {+ baseUrl: 'https://api.moonshot.ai/v1',+ model: 'kimi-k2-0905-preview',+ apiKey: 'sk-moonshot-test',+ label: 'Moonshot',+ });+ expect(moonshot.status).toBe(201);++ const ollama = await request(app, 'POST', '/api/keys/custom', {+ baseUrl: 'http://127.0.0.1:11434/v1',+ model: 'kimi-k2:1t-cloud',+ label: 'Ollama box',+ });+ expect(ollama.status).toBe(201);+ });++ beforeEach(() => {+ vi.spyOn(dns.promises, 'lookup').mockResolvedValue([{ address: '203.0.113.10', family: 4 }] as any);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('forwards a trailing assistant partial:true to a Moonshot custom endpoint', async () => {+ const upstream = stubUpstream('kimi-k2-0905-preview');+ const { status, body } = await request(app, 'POST', '/v1/chat/completions', {+ model: 'kimi-k2-0905-preview',+ messages: conversation,+ }, authHeaders());++ expect(status).toBe(200);+ expect(body.choices[0].message.content).toBe(' 42.');+ expect(upstream.url()).toBe('https://api.moonshot.ai/v1/chat/completions');+ const sent = upstream.body().messages;+ expect(sent).toHaveLength(2);+ expect(sent[1]).toMatchObject({ role: 'assistant', content: 'The answer is', partial: true });+ expect(sent[0]).not.toHaveProperty('partial');+ });++ it('strips partial for a custom endpoint on any other host, even for a Kimi model', async () => {+ const upstream = stubUpstream('kimi-k2:1t-cloud');+ const { status } = await request(app, 'POST', '/v1/chat/completions', {+ model: 'kimi-k2:1t-cloud',+ messages: conversation,+ }, authHeaders());++ expect(status).toBe(200);+ expect(upstream.url()).toBe('http://127.0.0.1:11434/v1/chat/completions');+ const sent = upstream.body().messages;+ expect(sent[1]).toMatchObject({ role: 'assistant', content: 'The answer is' });+ expect(sent[1]).not.toHaveProperty('partial');+ });++ it('rejects a non-boolean partial at the request schema', async () => {+ const { status } = await request(app, 'POST', '/v1/chat/completions', {+ model: 'kimi-k2-0905-preview',+ messages: [conversation[0], { role: 'assistant', content: 'The answer is', partial: 'yes' }],+ }, authHeaders());+ expect(status).toBe(400);+ });+});diff --git a/server/src/providers/openai-compat.ts b/server/src/providers/openai-compat.tsindex 52de8bfa..6e167fcd 100644--- a/server/src/providers/openai-compat.ts+++ b/server/src/providers/openai-compat.ts@@ -15,6 +15,28 @@ import { recordQuotaObservationsFromResponse, type QuotaObservationContext } froimport { providerTimeoutMs } from '../lib/provider-timeout.js';import { isAbortLikeError } from '../lib/error-classify.js';+/** Hosts that ARE Moonshot's OpenAI-compatible API (api.moonshot.ai,+ * api.moonshot.cn, api.kimi.com and their subdomains). */+const MOONSHOT_HOST_SUFFIXES = ['moonshot.ai', 'moonshot.cn', 'kimi.com'];++/**+ * Whether a base URL points at Moonshot's own API. Moonshot documents an+ * assistant-message `partial: true` prefill flag that no other OpenAI-compatible+ * upstream understands, and there is no built-in moonshot platform — Kimi+ * models are otherwise served by Groq, Cloudflare, OpenRouter, Hugging Face,+ * Ollama, ... — so the flag is gated on the endpoint host, never on the model+ * id. Returns false for anything that does not parse as a URL. (#1038)+ */+export function isMoonshotEndpoint(baseUrl: string): boolean {+ let host: string;+ try {+ host = new URL(baseUrl).hostname.toLowerCase();+ } catch {+ return false;+ }+ return MOONSHOT_HOST_SUFFIXES.some((d) => host === d || host.endsWith(`.${d}`));+}+/*** Generic provider for platforms that use an OpenAI-compatible API.* Covers: Groq, Cerebras, NVIDIA NIM, Mistral, OpenRouter,@@ -34,6 +56,9 @@ export class OpenAICompatProvider extends BaseProvider {* `400 This model only supports single tool-calls at once!`. When set, pin* parallel_tool_calls to false whenever tools are in play. See issue #255. */private readonly forceSingleToolCall: boolean;+ /** True only for a custom endpoint whose host is Moonshot's own API; see+ * isMoonshotEndpoint(). Gates the assistant `partial` prefill flag (#1038). */+ private readonly forwardsPartial: boolean;constructor(opts: {platform: Platform;@@ -55,6 +80,7 @@ export class OpenAICompatProvider extends BaseProvider {this.timeoutMs = providerTimeoutMs(opts.platform, opts.timeoutMs ?? 60_000);this.keyless = opts.keyless ?? false;this.forceSingleToolCall = opts.forceSingleToolCall ?? false;+ this.forwardsPartial = opts.platform === 'custom' && isMoonshotEndpoint(opts.baseUrl);}/** Resolve the parallel_tool_calls flag to send upstream. For providers that@@ -151,39 +177,56 @@ export class OpenAICompatProvider extends BaseProvider {*/private static readonly STRICT_PLATFORMS = new Set(['mistral', 'groq', 'cerebras']);private messagesForPlatform(messages: ChatMessage[]): ChatMessage[] {- if (!OpenAICompatProvider.STRICT_PLATFORMS.has(this.platform)) return messages;-- return messages.map((m) => {- if (m.role === 'assistant') {- return {- role: m.role,- content: m.content,- ...(m.name ? { name: m.name } : {}),- ...(m.tool_calls && m.tool_calls.length > 0 ? {- tool_calls: m.tool_calls.map((tc) => ({- id: tc.id,- type: tc.type,- function: {- name: tc.function.name,- arguments: tc.function.arguments,- },- })),- } : {}),- };- }- if (m.role === 'tool') {+ if (OpenAICompatProvider.STRICT_PLATFORMS.has(this.platform)) {+ // Rebuild every message from a whitelist of keys, so `partial` and the+ // reasoning extensions never reach these platforms.+ return messages.map((m) => {+ if (m.role === 'assistant') {+ return {+ role: m.role,+ content: m.content,+ ...(m.name ? { name: m.name } : {}),+ ...(m.tool_calls && m.tool_calls.length > 0 ? {+ tool_calls: m.tool_calls.map((tc) => ({+ id: tc.id,+ type: tc.type,+ function: {+ name: tc.function.name,+ arguments: tc.function.arguments,+ },+ })),+ } : {}),+ };+ }+ if (m.role === 'tool') {+ return {+ role: m.role,+ content: m.content,+ ...(m.tool_call_id ? { tool_call_id: m.tool_call_id } : {}),+ ...(m.name ? { name: m.name } : {}),+ };+ }return {role: m.role,content: m.content,- ...(m.tool_call_id ? { tool_call_id: m.tool_call_id } : {}),...(m.name ? { name: m.name } : {}),};+ });+ }++ // Moonshot's assistant `partial` prefill flag only survives to the wire+ // when this provider IS Moonshot's own API (a custom endpoint on a+ // Moonshot/Kimi host). Every other OpenAI-compatible gateway — including+ // the ones that serve Kimi models, like Groq, Cloudflare or OpenRouter —+ // gets it stripped, since strict upstreams 400/422 on unknown message keys+ // and the rest would ignore it anyway. (#1038)+ if (this.forwardsPartial) return messages;+ return messages.map((m) => {+ if (m.role === 'assistant' && m.partial !== undefined) {+ const { partial: _partial, ...rest } = m;+ return rest;}- return {- role: m.role,- content: m.content,- ...(m.name ? { name: m.name } : {}),- };+ return m;});}diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex 6665e6f9..38e2dac7 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -505,6 +505,10 @@ const assistantMessageSchema = z.object({// unless the prior turn's reasoning_content is replayed, so keep it through// validation instead of stripping it. See issue #255.reasoning_content: z.string().nullable().optional(),+ // Moonshot's "partial" prefill flag. A plain z.object (no .passthrough())+ // would silently strip it; keep it through validation so it can be forwarded+ // to Moonshot/Kimi models, which document it. See issue #1038.+ partial: z.boolean().optional(),});// Tool results may arrive with null/missing content (a tool that returned@@ -1474,6 +1478,10 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {...(typeof m.reasoning_content === 'string' && m.reasoning_content.length > 0? { reasoning_content: m.reasoning_content }: {}),+ // Moonshot's "partial" prefill flag: keep it through the message build+ // (the schema already preserves it); the provider layer decides whether+ // the routed model understands it and strips it otherwise. (#1038)+ ...(m.partial === true ? { partial: true } : {}),// hasToolCalls (not a bare truthiness check) so null AND empty-array// tool_calls are dropped rather than forwarded — strict upstreams// reject both shapes. (#200)diff --git a/shared/types.ts b/shared/types.tsindex da958ce0..ea3ab5e4 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -391,6 +391,11 @@ export interface ChatMessage {// (DeepSeek on OpenCode Zen) require it to be replayed verbatim on the next// turn or they 400; the proxy preserves and forwards it. See issue #255.reasoning_content?: string;+ // Moonshot's "partial" prefill flag on an assistant turn: when true, the+ // model continues the given text instead of starting a fresh turn. Only+ // forwarded to models that understand it (Moonshot/Kimi); stripped for all+ // other providers. See issue #1038.+ partial?: boolean;}export interface ChatCompletionRequest {