Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(provider): 保留原生请求失败的安全 HTTP 分类

ficowang12c5f86aeea2
diff --git a/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts b/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts
index 4b2ebfefb9..20431b248c 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts
@@ -1,7 +1,12 @@
import { describe, expect, it, vi } from 'vitest';
+import * as openaiCompletions from '@earendil-works/pi-ai/api/openai-completions';
import { PROVIDER_MODEL_CATALOG, BUNDLED_CATALOG, buildUserProvider } from '@cindy/model-providers';
import { createPiProviderFetch, hostCredentialEndpointAllowed, invocationModelRecord, nativeBridgeApiKey, NATIVE_ADAPTER_ERROR_BODY_LIMIT, readBoundedResponseText } from '../pi-provider-transport.js';
+vi.mock('@earendil-works/pi-ai/api/openai-completions', async (importOriginal) => ({
+ ...await importOriginal<typeof import('@earendil-works/pi-ai/api/openai-completions')>(),
+}));
+
const reply = [
{ id: 'fixture-reply', object: 'chat.completion.chunk', choices: [{ index: 0, delta: { role: 'assistant', content: 'Hello' } }] },
{ id: 'fixture-reply', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: 9, completion_tokens: 2 } },
@@ -215,3 +220,82 @@ it('reads only a prefix of native adapter error bodies', async () => {
expect(text).toHaveLength(NATIVE_ADAPTER_ERROR_BODY_LIMIT);
expect(text).toBe('a'.repeat(NATIVE_ADAPTER_ERROR_BODY_LIMIT));
});
+
+
+describe('native provider failure diagnostics', () => {
+ const row = PROVIDER_MODEL_CATALOG.providers.together.find(
+ row => row.execution.pi.api === 'openai-completions',
+ )!;
+ const request = () => ({ body: JSON.stringify({ model: row.id, input: 'ping', stream: true }) });
+
+ it.each([
+ [401, 'authentication'], [403, 'permission'], [429, 'rate_limit'],
+ [503, 'provider_unavailable'], [400, 'request_rejected'],
+ ])('reports HTTP %s without exposing the provider response', async (status, category) => {
+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify({ error: {
+ message: 'secret-fixture-key private prompt /Users/private/source.ts',
+ } }), { status: Number(status), headers: { 'content-type': 'application/json' } }));
+ const send = createPiProviderFetch({ row, providerId: 'together', apiKey: 'fixture-key', fetchImpl });
+ const text = await (await send('https://unused.invalid', request())).text();
+ expect(text).toContain('response.failed');
+ expect(text).toContain(`HTTP ${status}`);
+ expect(text).toContain(`category=${category}`);
+ expect(text).toContain('phase=adapter-event');
+ expect(text).toMatch(/request=[a-f0-9-]{36}/);
+ expect(text).not.toMatch(/secret-fixture-key|private prompt|Users\/private/);
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps unknown transport failures unknown and allows a later request to succeed', async () => {
+ const fetchImpl = vi.fn<typeof fetch>()
+ .mockRejectedValueOnce(new Error('secret-fixture-key https://private.invalid/credential'))
+ .mockResolvedValueOnce(new Response(reply, { headers: { 'content-type': 'text/event-stream' } }));
+ const send = createPiProviderFetch({ row, providerId: 'together', apiKey: 'fixture-key', fetchImpl });
+ const failed = await (await send('https://unused.invalid', request())).text();
+ expect(failed).toContain('category=unknown');
+ expect(failed).not.toMatch(/secret-fixture-key|private.invalid|HTTP 401|category=authentication/);
+ const succeeded = await (await send('https://unused.invalid', request())).text();
+ expect(succeeded).toContain('response.completed');
+ expect(succeeded).not.toContain('response.failed');
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not reuse HTTP failure status from an earlier request', async () => {
+ const fetchImpl = vi.fn<typeof fetch>()
+ .mockResolvedValueOnce(new Response('{}', { status: 401 }))
+ .mockRejectedValueOnce(new Error('fixture transport failure'));
+ const send = createPiProviderFetch({ row, providerId: 'together', apiKey: 'fixture-key', fetchImpl });
+ const first = await (await send('https://unused.invalid', request())).text();
+ const second = await (await send('https://unused.invalid', request())).text();
+ expect(first).toContain('HTTP 401');
+ expect(second).toContain('category=unknown');
+ expect(second).not.toContain('HTTP 401');
+ });
+});
+
+
+it('keeps iterator exceptions private and labels the stream-read phase', async () => {
+ const row = PROVIDER_MODEL_CATALOG.providers.together.find(row => row.execution.pi.api === 'openai-completions')!;
+ const iterator = {
+ async *[Symbol.asyncIterator]() {
+ yield { type: 'text_delta', delta: 'fixture prefix' };
+ throw new Error('secret-fixture-key private prompt');
+ },
+ };
+ const stream = vi.spyOn(openaiCompletions, 'streamSimple').mockReturnValueOnce(
+ iterator as unknown as ReturnType<typeof openaiCompletions.streamSimple>,
+ );
+ try {
+ const send = createPiProviderFetch({ row, providerId: 'together', apiKey: 'fixture-key',
+ fetchImpl: async () => { throw new Error('unused'); },
+ });
+ const response = await send('https://unused.invalid', { body: JSON.stringify({ model: row.id, input: 'ping' }) });
+ const error = await response.text().catch(error => error as Error);
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toContain('phase=stream-read');
+ expect((error as Error).message).toContain('category=unknown');
+ expect((error as Error).message).not.toMatch(/secret-fixture-key|private prompt/);
+ } finally {
+ stream.mockRestore();
+ }
+});
diff --git a/apps/desktop/src/main/maker-host/pi-provider-transport.ts b/apps/desktop/src/main/maker-host/pi-provider-transport.ts
index 7f90366f89..2359bda977 100644
--- a/apps/desktop/src/main/maker-host/pi-provider-transport.ts
+++ b/apps/desktop/src/main/maker-host/pi-provider-transport.ts
@@ -240,6 +240,25 @@ export function createPiProviderFetch(options: PiProviderTransportOptions): type
if (!adapter) throw new Error('Native API is not supported by the bundled Pi adapter');
const abort = new AbortController();
const signal = init?.signal ? AbortSignal.any([init.signal, abort.signal]) : abort.signal;
+ // Keep diagnostics local to this invocation. Adapter error messages may contain
+ // response bodies, credentials or user content, so never forward those strings.
+ let httpStatus: number | undefined;
+ const diagnosticFetch: typeof fetch = async (input, init) => {
+ httpStatus = undefined;
+ const response = await options.fetchImpl(input, init);
+ httpStatus = response.status;
+ return response;
+ };
+ const failureMessage = (phase: 'adapter-event' | 'stream-read') => {
+ const category = httpStatus === 401 ? 'authentication'
+ : httpStatus === 403 ? 'permission'
+ : httpStatus === 429 ? 'rate_limit'
+ : httpStatus !== undefined && httpStatus >= 500 ? 'provider_unavailable'
+ : httpStatus !== undefined && httpStatus >= 400 ? 'request_rejected'
+ : 'unknown';
+ const status = httpStatus === undefined ? '' : `; HTTP ${httpStatus}`;
+ return `Native provider request failed [phase=${phase}${status}; category=${category}; request=${responseId}]`;
+ };
const cloudflareGateway = model.provider === 'cloudflare-ai-gateway';
const events = adapter.streamSimple(model, context, {
apiKey: cloudflareGateway ? undefined : options.apiKey, env: options.env,
@@ -247,7 +266,7 @@ export function createPiProviderFetch(options: PiProviderTransportOptions): type
// Pi's Google SDK rejects injected fetch. Its native transport must be used; all other
// adapters that support injection use Cindy's existing outbound route.
...(!['google-generative-ai', 'google-vertex', 'bedrock-converse-stream'].includes(model.api)
- ? { fetch: options.fetchImpl } : {}),
+ ? { fetch: diagnosticFetch } : {}),
signal, maxRetries: 0,
reasoning: request.reasoning?.effort && request.reasoning.effort !== 'none'
? request.reasoning.effort as ThinkingLevel : undefined,
@@ -298,11 +317,11 @@ export function createPiProviderFetch(options: PiProviderTransportOptions): type
{ type: 'response.output_item.done', output_index, item: historyItem }]);
}
emit(translator.finish(true)); ended = true;
- } else if (event.type === 'error') { emit(translator.fail('Native provider request failed')); ended = true; }
+ } else if (event.type === 'error') { emit(translator.fail(failureMessage('adapter-event'))); ended = true; }
}
if (pending.length) controller.enqueue(pending.shift()!);
else controller.close();
- } catch { abort.abort(); controller.error(new Error('Native provider request failed')); }
+ } catch { abort.abort(); controller.error(new Error(failureMessage('stream-read'))); }
},
async cancel() { abort.abort(); await iterator.return?.(); },
}), { headers: { 'content-type': 'text/event-stream' } });