Ver Fonte

fix: preserve query parameters in provider endpoint URLs

hetaoBackend há 2 meses atrás
pai
commit
5ea390da64

+ 175 - 0
packages/local-runtime-v2/src/service/model-system/connectivity/provider-request.test.ts

@@ -0,0 +1,175 @@
+import { createServer } from 'node:http';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+import { ModelDiscoveryClient } from './discover-models.js';
+import { ModelConnectionTester } from './test-connection.js';
+import {
+  normalizeProviderBaseUrl,
+  providerCompletionUrl,
+  providerModelsUrls,
+} from './provider-request.js';
+
+const query = '?tenant=a&tenant=b&encoded=%2F%23%3F&space=a%20b&plus=a+b&empty=';
+const fragment = '#local/messages?not-a-query=1/';
+const cases = [
+  ['openai-completions', '/v1', '/v1', '/v1/chat/completions', '/v1/models'],
+  ['openai-completions', '/v1///', '/v1', '/v1/chat/completions', '/v1/models'],
+  ['openai-completions', '/v1/chat/completions/', '/v1', '/v1/chat/completions', '/v1/models'],
+  ['openai-completions', '/v1/responses', '/v1', '/v1/chat/completions', '/v1/models'],
+  ['openai-responses', '/v1/responses/', '/v1', '/v1/responses', '/v1/models'],
+  ['openai-responses', '/v1/chat/completions', '/v1', '/v1/responses', '/v1/models'],
+  ['anthropic-messages', '/compat/', '/compat', '/compat/v1/messages', '/compat/v1/models'],
+  ['anthropic-messages', '/compat/v1/', '/compat', '/compat/v1/messages', '/compat/v1/models'],
+  [
+    'anthropic-messages',
+    '/compat/v1/messages/',
+    '/compat',
+    '/compat/v1/messages',
+    '/compat/v1/models',
+  ],
+  [
+    'anthropic-messages',
+    '/compat/messages',
+    '/compat',
+    '/compat/v1/messages',
+    '/compat/v1/models',
+  ],
+  ['anthropic-messages', '/v1/messages', '', '/v1/messages', '/v1/models'],
+  ['openai-completions', '', '', '/chat/completions', '/models'],
+] as const;
+
+describe('provider URL components', () => {
+  it.each(cases)(
+    'normalizes only the path for %s %s',
+    (api, path, base, completion, models) => {
+      for (const suffix of [
+        '',
+        query,
+        fragment,
+        `${query}${fragment}`,
+        '?tenant=/responses/',
+        '?',
+      ]) {
+        const input = `https://gateway.example${path}${suffix}`;
+        const normalized = `https://gateway.example${base}${suffix}`;
+        expect(normalizeProviderBaseUrl(api, input)).toBe(normalized);
+        expect(normalizeProviderBaseUrl(api, normalized)).toBe(normalized);
+        expect(providerCompletionUrl(api, input)).toBe(
+          `https://gateway.example${completion}${suffix}`,
+        );
+        expect(providerModelsUrls(api, input)[0]).toBe(
+          `https://gateway.example${models}${suffix}`,
+        );
+      }
+    },
+  );
+
+  it('keeps query parameters on each Messages candidate in native-first order', () => {
+    expect(
+      providerModelsUrls(
+        'anthropic-messages',
+        `https://gateway.example/compat/v1/messages${query}${fragment}`,
+      ),
+    ).toEqual([
+      `https://gateway.example/compat/v1/models${query}${fragment}`,
+      `https://gateway.example/compat/models${query}${fragment}`,
+      `https://gateway.example/models${query}${fragment}`,
+    ]);
+    expect(
+      providerModelsUrls('anthropic-messages', `https://gateway.example/v1${query}${fragment}`),
+    ).toEqual([
+      `https://gateway.example/v1/models${query}${fragment}`,
+      `https://gateway.example/models${query}${fragment}`,
+    ]);
+  });
+});
+
+describe('provider connectivity over loopback HTTP', () => {
+  let origin: string;
+  const requests: Array<{
+    method: string | undefined;
+    url: string | undefined;
+  }> = [];
+  let missingCandidates = 0;
+  const server = createServer((req, res) => {
+    requests.push({ method: req.method, url: req.url });
+    req.resume();
+    res.setHeader('Content-Type', 'application/json');
+    if (missingCandidates > 0) {
+      res.statusCode = missingCandidates-- === 2 ? 404 : 405;
+      res.end('{}');
+      return;
+    }
+    res.end(
+      JSON.stringify({
+        id: 'response_test',
+        object: 'response',
+        output: [],
+        content: [],
+        choices: [{ message: { role: 'assistant', content: 'pong' } }],
+        data: [{ id: 'synthetic-model' }],
+      }),
+    );
+  });
+
+  beforeAll(async () => {
+    await new Promise<void>((resolve, reject) => {
+      server.once('error', reject);
+      server.listen(0, '127.0.0.1', resolve);
+    });
+    const address = server.address();
+    if (!address || typeof address === 'string') throw new Error('Missing loopback address');
+    origin = `http://127.0.0.1:${address.port}`;
+  });
+
+  afterAll(async () => {
+    await new Promise<void>((resolve, reject) => {
+      server.close((error) => (error ? reject(error) : resolve()));
+      server.closeAllConnections();
+    });
+  });
+
+  it.each(cases)(
+    'sends endpoint paths and unmodified queries for %s %s',
+    async (api, path, _base, completion, models) => {
+      for (const suffix of ['', query, fragment, `${query}${fragment}`]) {
+        requests.length = 0;
+        const target = {
+          api,
+          baseUrl: `${origin}${path}${suffix}`,
+          apiKey: 'test-key',
+          modelId: 'synthetic-model',
+        };
+        expect(await new ModelConnectionTester().test('loopback', target)).toEqual({
+          ok: true,
+        });
+        expect(await new ModelDiscoveryClient().discover(target)).toEqual({
+          ok: true,
+          models: [{ modelId: 'synthetic-model' }],
+        });
+        const sentQuery = suffix.startsWith('?') ? query : '';
+        expect(requests).toEqual([
+          { method: 'POST', url: `${completion}${sentQuery}` },
+          { method: 'GET', url: `${models}${sentQuery}` },
+        ]);
+      }
+    },
+  );
+
+  it('preserves the query through 404/405 fallback to the origin model list', async () => {
+    requests.length = 0;
+    missingCandidates = 2;
+    expect(
+      await new ModelDiscoveryClient().discover({
+        api: 'anthropic-messages',
+        baseUrl: `${origin}/compat/v1/messages/${query}${fragment}`,
+        apiKey: 'test-key',
+      }),
+    ).toEqual({ ok: true, models: [{ modelId: 'synthetic-model' }] });
+    expect(requests).toEqual([
+      { method: 'GET', url: `/compat/v1/models${query}` },
+      { method: 'GET', url: `/compat/models${query}` },
+      { method: 'GET', url: `/models${query}` },
+    ]);
+  });
+});

+ 27 - 11
packages/local-runtime-v2/src/service/model-system/connectivity/provider-request.ts

@@ -47,10 +47,10 @@ export function buildModelDiscoveryHeaders(input: {
 }
 }
 
 
 export function providerCompletionUrl(api: ModelProviderApi, baseUrl: string): string {
 export function providerCompletionUrl(api: ModelProviderApi, baseUrl: string): string {
-  const base = normalizeProviderBaseUrl(api, baseUrl);
-  if (api === 'anthropic-messages') return `${base}/v1/messages`;
-  if (api === 'openai-responses') return `${base}/responses`;
-  return `${base}/chat/completions`;
+  const [base, suffix] = splitProviderUrlSuffix(normalizeProviderBaseUrl(api, baseUrl));
+  if (api === 'anthropic-messages') return `${base}/v1/messages${suffix}`;
+  if (api === 'openai-responses') return `${base}/responses${suffix}`;
+  return `${base}/chat/completions${suffix}`;
 }
 }
 
 
 /**
 /**
@@ -61,25 +61,41 @@ export function providerCompletionUrl(api: ModelProviderApi, baseUrl: string): s
  * OpenAI-style candidates.
  * OpenAI-style candidates.
  */
  */
 export function providerModelsUrls(api: ModelProviderApi, baseUrl: string): [string, ...string[]] {
 export function providerModelsUrls(api: ModelProviderApi, baseUrl: string): [string, ...string[]] {
-  const base = normalizeProviderBaseUrl(api, baseUrl);
-  if (api !== 'anthropic-messages') return [`${base}/models`];
-  const primary = `${base}/v1/models`;
-  const fallbacks = [`${base}/models`, originModelsUrl(base)].filter((url): url is string =>
-    Boolean(url),
+  const normalized = normalizeProviderBaseUrl(api, baseUrl);
+  const [base, suffix] = splitProviderUrlSuffix(normalized);
+  if (api !== 'anthropic-messages') return [`${base}/models${suffix}`];
+  const primary = `${base}/v1/models${suffix}`;
+  const fallbacks = [`${base}/models${suffix}`, originModelsUrl(normalized)].filter(
+    (url): url is string => Boolean(url),
   );
   );
   return [primary, ...new Set(fallbacks)];
   return [primary, ...new Set(fallbacks)];
 }
 }
 
 
 function originModelsUrl(base: string): string | undefined {
 function originModelsUrl(base: string): string | undefined {
   try {
   try {
-    return `${new URL(base).origin}/models`;
+    const [path, suffix] = splitProviderUrlSuffix(base);
+    return `${new URL(path).origin}/models${suffix}`;
   } catch {
   } catch {
     return undefined;
     return undefined;
   }
   }
 }
 }
 
 
 export function normalizeProviderBaseUrl(api: ModelProviderApi, baseUrl: string): string {
 export function normalizeProviderBaseUrl(api: ModelProviderApi, baseUrl: string): string {
-  let base = baseUrl.replace(/\/+$/u, '');
+  const [path, suffix] = splitProviderUrlSuffix(baseUrl);
+  return `${normalizeProviderBasePath(api, path)}${suffix}`;
+}
+
+// Keep the raw query (including repeated keys and encoding) and fragment outside
+// path edits. Preserve fragments for config consumers; HTTP fetch omits them.
+// Splitting instead of reserializing also preserves existing base URL spelling
+// and leaves validation/error handling to the existing callers.
+function splitProviderUrlSuffix(baseUrl: string): [string, string] {
+  const index = baseUrl.search(/[?#]/u);
+  return index < 0 ? [baseUrl, ''] : [baseUrl.slice(0, index), baseUrl.slice(index)];
+}
+
+function normalizeProviderBasePath(api: ModelProviderApi, path: string): string {
+  let base = path.replace(/\/+$/u, '');
   if (api === 'anthropic-messages') {
   if (api === 'anthropic-messages') {
     if (base.endsWith('/v1/messages')) base = base.slice(0, -'/v1/messages'.length);
     if (base.endsWith('/v1/messages')) base = base.slice(0, -'/v1/messages'.length);
     else if (base.endsWith('/messages')) base = base.slice(0, -'/messages'.length);
     else if (base.endsWith('/messages')) base = base.slice(0, -'/messages'.length);

+ 40 - 28
packages/local-runtime-v2/src/service/model-system/management/service-context.test.ts

@@ -4,6 +4,7 @@ import { join } from 'node:path';
 import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
 import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
 
 
 import { LocalModelCache } from '../catalog/model-cache.js';
 import { LocalModelCache } from '../catalog/model-cache.js';
+import { byokModelTestStatus } from '../catalog/config-fingerprint.js';
 import type {
 import type {
   LocalByokConfigDraft,
   LocalByokConfigDraft,
   LocalRuntimeConfig,
   LocalRuntimeConfig,
@@ -166,34 +167,45 @@ describe('LocalModelProviderService context', () => {
     });
     });
   });
   });
 
 
-  it('uses shared request rules for tests and records the result in the model cache', async () => {
-    const harness = createHarness();
-    const provider = await harness.service.createUserProvider({
-      name: 'Work',
-      baseUrl: 'https://api.example.com/v1/responses',
-      apiKey: CUSTOM_KEY,
-      apiFormat: 'openai-responses',
-      headers: { Authorization: 'Api-Key custom', 'X-Tenant': 'tenant-a' },
-      models: [{ modelId: 'gpt-5' }],
-    });
-
-    await expect(harness.service.testModel(provider.providerId, 'gpt-5')).resolves.toMatchObject({
-      ok: true,
-      status: { state: 'available', lastTestedAt: 1_750_000_000_000 },
-    });
-    expect(harness.testCalls).toHaveLength(1);
-    expect(harness.testCalls[0]?.target).toMatchObject({
-      api: 'openai-responses',
-      baseUrl: 'https://api.example.com/v1',
-      apiKey: CUSTOM_KEY,
-      modelId: 'gpt-5',
-      headers: { Authorization: 'Api-Key custom', 'X-Tenant': 'tenant-a' },
-    });
-    expect(harness.cache.load().model_status['custom_provider:work/gpt-5']).toMatchObject({
-      state: 'available',
-      last_tested_at: 1_750_000_000_000,
-    });
-  });
+  it.each(['', '?tenant=a&tenant=b&encoded=%2F#local'])(
+    'uses shared request rules and cache fingerprints for saved URLs: %s',
+    async (suffix) => {
+      const harness = createHarness();
+      const provider = await harness.service.createUserProvider({
+        name: 'Work',
+        baseUrl: `https://api.example.com/v1/responses${suffix}`,
+        apiKey: CUSTOM_KEY,
+        apiFormat: 'openai-responses',
+        headers: { Authorization: 'Api-Key custom', 'X-Tenant': 'tenant-a' },
+        models: [{ modelId: 'gpt-5' }],
+      });
+
+      await expect(
+        harness.service.testModel(provider.providerId, 'gpt-5'),
+      ).resolves.toMatchObject({
+        ok: true,
+        status: { state: 'available', lastTestedAt: 1_750_000_000_000 },
+      });
+      expect(harness.testCalls).toHaveLength(1);
+      expect(harness.testCalls[0]?.target).toMatchObject({
+        api: 'openai-responses',
+        baseUrl: `https://api.example.com/v1${suffix}`,
+        apiKey: CUSTOM_KEY,
+        modelId: 'gpt-5',
+        headers: { Authorization: 'Api-Key custom', 'X-Tenant': 'tenant-a' },
+      });
+      expect(harness.config.custom_provider?.work?.options?.baseURL).toBe(
+        `https://api.example.com/v1/responses${suffix}`,
+      );
+      expect(
+        byokModelTestStatus(harness.config, harness.cache.load(), provider.providerId, 'gpt-5'),
+      ).toMatchObject({ state: 'available' });
+      expect(harness.cache.load().model_status['custom_provider:work/gpt-5']).toMatchObject({
+        state: 'available',
+        last_tested_at: 1_750_000_000_000,
+      });
+    },
+  );
 
 
   it('keeps a failed connectivity result as diagnostic state rather than a selection gate', async () => {
   it('keeps a failed connectivity result as diagnostic state rather than a selection gate', async () => {
     const harness = createHarness();
     const harness = createHarness();

+ 24 - 19
packages/local-runtime-v2/src/service/model-system/resolution/local-model-resolver.test.ts

@@ -628,28 +628,33 @@ describe('LocalModelResolver custom-provider endpoint normalization', () => {
   ] as const)(
   ] as const)(
     'normalizes an endpoint-form $api URL with the shared connectivity rule',
     'normalizes an endpoint-form $api URL with the shared connectivity rule',
     async ({ api, baseUrl, expectedBaseUrl }) => {
     async ({ api, baseUrl, expectedBaseUrl }) => {
-      const resolver = new LocalModelResolver({
-        byokConfigGetter: () => ({
-          custom_provider: {
-            work: {
-              api,
-              options: { apiKey: 'custom-user-key', baseURL: baseUrl },
-              models: { model: {} },
+      for (const suffix of ['', '?tenant=a&tenant=b&encoded=%2F#local']) {
+        const resolver = new LocalModelResolver({
+          byokConfigGetter: () => ({
+            custom_provider: {
+              work: {
+                api,
+                options: {
+                  apiKey: 'custom-user-key',
+                  baseURL: `${baseUrl}${suffix}`,
+                },
+                models: { model: {} },
+              },
             },
             },
-          },
-        }),
-      });
+          }),
+        });
 
 
-      const resolved = await resolver.resolveModel({
-        sessionId: 'session-endpoint-base-url',
-        turnId: 'turn-endpoint-base-url',
-        agentConfig: {
-          ...AGENT_CONFIG,
-          model: { provider: 'custom_provider:work', model_id: 'model' },
-        },
-      });
+        const resolved = await resolver.resolveModel({
+          sessionId: 'session-endpoint-base-url',
+          turnId: 'turn-endpoint-base-url',
+          agentConfig: {
+            ...AGENT_CONFIG,
+            model: { provider: 'custom_provider:work', model_id: 'model' },
+          },
+        });
 
 
-      expect(resolved.model.baseUrl).toBe(expectedBaseUrl);
+        expect(resolved.model.baseUrl).toBe(`${expectedBaseUrl}${suffix}`);
+      }
     },
     },
   );
   );
 });
 });

+ 1 - 0
release/public-source.json

@@ -910,6 +910,7 @@
     "packages/local-runtime-v2/src/service/model-system/connectivity/codex-model-discovery.ts",
     "packages/local-runtime-v2/src/service/model-system/connectivity/codex-model-discovery.ts",
     "packages/local-runtime-v2/src/service/model-system/connectivity/discover-models.test.ts",
     "packages/local-runtime-v2/src/service/model-system/connectivity/discover-models.test.ts",
     "packages/local-runtime-v2/src/service/model-system/connectivity/discover-models.ts",
     "packages/local-runtime-v2/src/service/model-system/connectivity/discover-models.ts",
+    "packages/local-runtime-v2/src/service/model-system/connectivity/provider-request.test.ts",
     "packages/local-runtime-v2/src/service/model-system/connectivity/provider-request.ts",
     "packages/local-runtime-v2/src/service/model-system/connectivity/provider-request.ts",
     "packages/local-runtime-v2/src/service/model-system/connectivity/test-connection.test.ts",
     "packages/local-runtime-v2/src/service/model-system/connectivity/test-connection.test.ts",
     "packages/local-runtime-v2/src/service/model-system/connectivity/test-connection.ts",
     "packages/local-runtime-v2/src/service/model-system/connectivity/test-connection.ts",

+ 1 - 0
test/vitest-suites.json

@@ -52,6 +52,7 @@
       "packages/local-runtime-v2/src/service/model-system/catalog/model-selection.test.ts",
       "packages/local-runtime-v2/src/service/model-system/catalog/model-selection.test.ts",
       "packages/local-runtime-v2/src/service/model-system/catalog/provider-presets/provider-presets.service.test.ts",
       "packages/local-runtime-v2/src/service/model-system/catalog/provider-presets/provider-presets.service.test.ts",
       "packages/local-runtime-v2/src/service/model-system/connectivity/discover-models.test.ts",
       "packages/local-runtime-v2/src/service/model-system/connectivity/discover-models.test.ts",
+      "packages/local-runtime-v2/src/service/model-system/connectivity/provider-request.test.ts",
       "packages/local-runtime-v2/src/service/model-system/connectivity/test-connection.test.ts",
       "packages/local-runtime-v2/src/service/model-system/connectivity/test-connection.test.ts",
       "packages/local-runtime-v2/src/service/model-system/management/service-context.test.ts",
       "packages/local-runtime-v2/src/service/model-system/management/service-context.test.ts",
       "packages/local-runtime-v2/src/service/model-system/management/service-input.test.ts",
       "packages/local-runtime-v2/src/service/model-system/management/service-input.test.ts",