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(utility-model): keep the minimal-body fallback and treat missing tiers uniformly

fmfsaisai897df98dbabe
diff --git a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
index 6f6a0b9658..1f01f8da5d 100644
--- a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
+++ b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
@@ -3301,13 +3301,15 @@ describe('utility one-shot candidates', () => {
});
// The automatic chain's first request must stay byte-identical to the
- // pre-plan Chat body, whether or not the Gateway declared efforts.
- it.each([
- { id: 'deepseek/deepseek-v4-flash', efforts: ['low', 'high', 'max'] },
- { id: 'tencent/hy3', efforts: ['low', 'medium', 'high'] },
- { id: 'qwen/qwen3.8-flash', efforts: ['low', 'medium', 'xhigh'] },
- { id: 'deepseek/deepseek-v4-flash', efforts: [] },
- ])('keeps the automatic chain first Chat request unchanged for $id (efforts: $efforts)', async ({ id, efforts }) => {
+ // pre-plan Chat body however the Gateway describes efforts: omitted
+ // (projected as `[]` with no discovered declaration), an explicit `[]`,
+ // or a declared list.
+ const AUTO_CHAT_MODELS = ['deepseek/deepseek-v4-flash', 'tencent/hy3', 'qwen/qwen3.8-flash'];
+ it.each(AUTO_CHAT_MODELS.flatMap((id) => [
+ { id, case: 'omitted', efforts: [] as string[], discovered: undefined },
+ { id, case: 'explicit []', efforts: [] as string[], discovered: [] as string[] },
+ { id, case: 'declared', efforts: ['low', 'high', 'max'], discovered: ['low', 'high', 'max'] },
+ ]))('keeps the automatic chain first Chat request unchanged for $id (efforts $case)', async ({ id, efforts, discovered }) => {
const autoRef = AUTO_AUXILIARY_MODEL_CHAIN.find((ref) => ref.endsWith(`:${id}`));
expect(autoRef).toBeDefined();
chainState.source = 'auto';
@@ -3316,8 +3318,7 @@ describe('utility one-shot candidates', () => {
id,
nativeApi: 'openai-completions',
efforts,
- // Gateway omitted efforts: the catalog projects `[]` without a discovered declaration.
- ...(efforts.length > 0 ? { discoveredMetadata: { efforts } } : {}),
+ ...(discovered !== undefined ? { discoveredMetadata: { efforts: discovered } } : {}),
}]) as never);
readKey.mockReturnValue('xd-key');
fetchMock.mockResolvedValueOnce(chatOk('ok') as never);
@@ -3445,7 +3446,7 @@ describe('utility one-shot candidates', () => {
expect(urlOf(3)).toBe(`${GATEWAY}/v1/chat/completions`);
});
- it('climbs a declared Chat ladder and never sends a request without reasoning parameters', async () => {
+ it('climbs a declared Chat ladder with reasoning parameters, then only the legacy minimal body', async () => {
activeCatalog.mockReturnValue(customChatCatalog({
upstream: 'https://custom.example/v1',
model: { id: 'custom-thinker', efforts: ['high', 'low', 'medium'] },
@@ -3465,7 +3466,7 @@ describe('utility one-shot candidates', () => {
ok: false,
attempts: [expect.objectContaining({ reason: 'http_error', httpStatus: 400 })],
});
- expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(fetchMock).toHaveBeenCalledTimes(4);
expect(bodyOf(0)).toMatchObject({ thinking: { type: 'disabled' }, reasoning_effort: 'minimal' });
expect(bodyOf(1)).toMatchObject({ reasoning_effort: 'low' });
expect(bodyOf(1)).not.toHaveProperty('thinking');
@@ -3474,14 +3475,15 @@ describe('utility one-shot candidates', () => {
expect(bodyOf(index)).toHaveProperty('reasoning_effort');
expect(bodyOf(index)).toHaveProperty('max_tokens', 64);
}
+ expect(bodyOf(3)).toEqual({ model: 'custom-thinker', messages: [{ role: 'user', content: 'hello' }] });
});
- it('sends no reasoning parameters and does not retry when the catalog declares none', async () => {
+ it('sends no reasoning parameters and does not retry when the catalog says reasoning:false', async () => {
activeCatalog.mockReturnValue(xdCatalog('codex', [{
id: 'plain-chat',
nativeApi: 'openai-completions',
efforts: [],
- discoveredMetadata: { efforts: [] },
+ reasoning: false,
}]) as never);
readKey.mockReturnValue('xd-key');
fetchMock.mockResolvedValueOnce(rejected(400) as never);
@@ -3517,15 +3519,19 @@ describe('utility one-shot candidates', () => {
expect(bodyOf(0)).not.toHaveProperty('reasoning_effort');
});
- it('walks an undeclared custom model from off to low to the minimal body', async () => {
+ it.each([
+ { case: 'effortsUnknown', model: { id: 'mystery', efforts: [], effortsUnknown: true } },
+ { case: 'empty list', model: { id: 'mystery', efforts: [] } },
+ ])('walks a custom model without tiers ($case) from off to low to no reasoning to the minimal body', async ({ model }) => {
activeCatalog.mockReturnValue(customChatCatalog({
upstream: 'https://custom.example/v1',
- model: { id: 'mystery', efforts: [], effortsUnknown: true },
+ model,
}) as never);
readCustomKey.mockReturnValue('custom-secret');
fetchMock
.mockResolvedValueOnce(rejected(400) as never)
.mockResolvedValueOnce(rejected(422) as never)
+ .mockResolvedValueOnce(rejected(400) as never)
.mockResolvedValueOnce(chatOk('ok') as never);
const result = await requestExplicitUtilityText('hello', {
@@ -3537,11 +3543,150 @@ describe('utility one-shot candidates', () => {
});
expect(result).toMatchObject({ ok: true, text: 'ok' });
- expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(fetchMock).toHaveBeenCalledTimes(4);
expect(bodyOf(0)).toMatchObject({ max_tokens: 48, thinking: { type: 'disabled' }, reasoning_effort: 'minimal' });
expect(bodyOf(1)).toMatchObject({ max_tokens: 48, reasoning_effort: 'low' });
expect(bodyOf(1)).not.toHaveProperty('thinking');
- expect(bodyOf(2)).toEqual({ model: 'mystery', messages: [{ role: 'user', content: 'hello' }] });
+ expect(bodyOf(2)).toEqual({ model: 'mystery', max_tokens: 48, messages: [{ role: 'user', content: 'hello' }] });
+ expect(bodyOf(3)).toEqual({ model: 'mystery', messages: [{ role: 'user', content: 'hello' }] });
+ });
+
+ it('walks a Cindy AI chat model without tiers from off to low to no reasoning', async () => {
+ activeCatalog.mockReturnValue(xdCatalog('codex', [{
+ id: 'tencent/hy3',
+ nativeApi: 'openai-completions',
+ efforts: [],
+ discoveredMetadata: { efforts: [] },
+ }]) as never);
+ readKey.mockReturnValue('xd-key');
+ fetchMock
+ .mockResolvedValueOnce(rejected(400) as never)
+ .mockResolvedValueOnce(rejected(400) as never)
+ .mockResolvedValueOnce(chatOk('ok') as never);
+
+ const result = await requestExplicitUtilityText('hello', {
+ providerId: 'xd',
+ agentKind: 'codex',
+ model: 'tencent/hy3',
+ maxTokens: 32,
+ disableReasoning: true,
+ });
+
+ expect(result).toMatchObject({ ok: true, text: 'ok' });
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(bodyOf(0)).toMatchObject({ thinking: { type: 'disabled' }, reasoning_effort: 'minimal' });
+ expect(bodyOf(1)).toMatchObject({ reasoning_effort: 'low' });
+ expect(bodyOf(2)).toEqual({ model: 'tencent/hy3', max_tokens: 32, messages: [{ role: 'user', content: 'hello' }] });
+ });
+
+ // R1 regression matrix: custom routes keep origin/main's minimal-body
+ // fallback as their last step, declared tiers or not.
+ describe('custom-route minimal-body fallback', () => {
+ type Rule = 'rejectsMaxTokens' | 'rejectsAnyReasoning' | 'rejectsOffButAcceptsLow';
+ const rejectsBody = (rule: Rule, body: Record<string, unknown>): boolean => {
+ switch (rule) {
+ case 'rejectsMaxTokens':
+ return 'max_tokens' in body || 'max_output_tokens' in body;
+ case 'rejectsAnyReasoning':
+ return 'reasoning_effort' in body || 'thinking' in body || 'reasoning' in body;
+ case 'rejectsOffButAcceptsLow':
+ return 'thinking' in body
+ || body.reasoning_effort === 'minimal'
+ || body.reasoning_effort === 'none';
+ }
+ };
+ const cases = (['openai-chat', 'openai-responses'] as const).flatMap((wireProtocol) =>
+ (['declared', 'no tiers'] as const).flatMap((tiers) =>
+ (['rejectsMaxTokens', 'rejectsAnyReasoning', 'rejectsOffButAcceptsLow'] as const).map((rule) =>
+ ({ wireProtocol, tiers, rule }))));
+
+ it.each(cases)('$wireProtocol / $tiers / $rule', async ({ wireProtocol, tiers, rule }) => {
+ activeCatalog.mockReturnValue({
+ providers: [{
+ id: 'custom-route',
+ name: 'Custom Route',
+ source: 'user',
+ agents: ['codex'],
+ auth: { method: 'apiKey' },
+ routing: {
+ codex: { upstream: 'https://custom.example/v1', wireProtocol, authStrategy: 'api-key-header' },
+ },
+ models: {
+ codex: [{
+ id: 'custom-model',
+ name: 'Custom Model',
+ contextWindow: 100_000,
+ ...(tiers === 'declared'
+ ? { efforts: ['low', 'medium', 'high'] }
+ : { efforts: [], effortsUnknown: true }),
+ }],
+ },
+ }],
+ } as never);
+ readCustomKey.mockReturnValue('custom-secret');
+ fetchMock.mockImplementation(async (_url, init) => {
+ const body = JSON.parse(String((init as { body: string }).body)) as Record<string, unknown>;
+ if (rejectsBody(rule, body)) return rejected(400) as never;
+ return (wireProtocol === 'openai-chat' ? chatOk('ok') : responsesOk('ok')) as never;
+ });
+
+ const result = await requestExplicitUtilityText('hello', {
+ providerId: 'custom-route',
+ agentKind: 'codex',
+ model: 'custom-model',
+ maxTokens: 384,
+ disableReasoning: true,
+ });
+
+ expect(result).toMatchObject({ ok: true, text: 'ok' });
+ const last = bodyOf(fetchMock.mock.calls.length - 1);
+ const reasoningField = wireProtocol === 'openai-chat' ? 'reasoning_effort' : 'reasoning';
+ const minimalBody = wireProtocol === 'openai-chat'
+ ? { model: 'custom-model', messages: [{ role: 'user', content: 'hello' }] }
+ : {
+ model: 'custom-model',
+ input: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: 'hello' }] }],
+ };
+ if (rule === 'rejectsOffButAcceptsLow') {
+ // Stops at the lowest tier instead of dropping everything.
+ expect(last).toMatchObject(
+ wireProtocol === 'openai-chat' ? { reasoning_effort: 'low' } : { reasoning: { effort: 'low' } },
+ );
+ } else if (rule === 'rejectsAnyReasoning' && tiers === 'no tiers') {
+ // Models without tiers reach "no reasoning parameters" (output budget kept) first.
+ expect(last).not.toHaveProperty(reasoningField);
+ expect(last).not.toHaveProperty('thinking');
+ expect(last).toHaveProperty(wireProtocol === 'openai-chat' ? 'max_tokens' : 'max_output_tokens', 384);
+ } else {
+ expect(last).toEqual(minimalBody);
+ }
+ expect(fetchMock.mock.calls.length).toBeLessThanOrEqual(4);
+ });
+
+ it('never remembers the minimal body', async () => {
+ activeCatalog.mockReturnValue(customChatCatalog({
+ upstream: 'https://custom.example/v1',
+ model: { id: 'custom-thinker', efforts: ['low', 'medium'] },
+ }) as never);
+ readCustomKey.mockReturnValue('custom-secret');
+ fetchMock.mockImplementation(async (_url, init) => {
+ const body = JSON.parse(String((init as { body: string }).body)) as Record<string, unknown>;
+ return ('max_tokens' in body ? rejected(400) : chatOk('ok')) as never;
+ });
+ const request = () => requestExplicitUtilityText('hello', {
+ providerId: 'custom-chat',
+ agentKind: 'codex',
+ model: 'custom-thinker',
+ maxTokens: 384,
+ disableReasoning: true,
+ });
+
+ await expect(request()).resolves.toMatchObject({ ok: true });
+ fetchMock.mockClear();
+ await expect(request()).resolves.toMatchObject({ ok: true });
+ // Starts from the reasoning ladder again, not from the remembered minimal body.
+ expect(bodyOf(0)).toMatchObject({ thinking: { type: 'disabled' }, max_tokens: 384 });
+ });
});
it('remembers the accepted step and continues down when it is later rejected', async () => {
diff --git a/apps/desktop/src/main/utility-model/__tests__/utilityReasoningPlan.test.ts b/apps/desktop/src/main/utility-model/__tests__/utilityReasoningPlan.test.ts
index c16aef14d2..8ce80277f3 100644
--- a/apps/desktop/src/main/utility-model/__tests__/utilityReasoningPlan.test.ts
+++ b/apps/desktop/src/main/utility-model/__tests__/utilityReasoningPlan.test.ts
@@ -16,27 +16,20 @@ const keys = (steps: ReturnType<typeof buildUtilityRequestPlan>) => steps.map(ut
describe('utilityReasoningDeclaration', () => {
it('sorts declared efforts from least to most thinking', () => {
- expect(utilityReasoningDeclaration('custom', 'codex', { efforts: ['max', 'low', 'high'] })).toEqual({
+ expect(utilityReasoningDeclaration({ efforts: ['max', 'low', 'high'] })).toEqual({
kind: 'declared',
efforts: ['low', 'high', 'max'],
});
});
- it('treats an explicit empty list as declared-empty and a missing one as unknown', () => {
- expect(utilityReasoningDeclaration('anthropic', 'claude-code', { efforts: [] })).toEqual({ kind: 'empty' });
- expect(utilityReasoningDeclaration('custom', 'codex', { efforts: [], effortsUnknown: true })).toEqual({ kind: 'unknown' });
- expect(utilityReasoningDeclaration('custom', 'codex', undefined)).toEqual({ kind: 'unknown' });
+ it('treats an empty list and a missing model alike', () => {
+ expect(utilityReasoningDeclaration({ efforts: [] })).toEqual({ kind: 'undeclared' });
+ expect(utilityReasoningDeclaration(undefined)).toEqual({ kind: 'undeclared' });
});
- it('only trusts an empty Cindy AI list that the Gateway actually sent', () => {
- expect(utilityReasoningDeclaration('xd', 'codex', { efforts: [] })).toEqual({ kind: 'unknown' });
- expect(utilityReasoningDeclaration('xd', 'codex', { efforts: [], discoveredMetadata: { efforts: [] } }))
- .toEqual({ kind: 'empty' });
- });
-
- it('does not read a custom Pi placeholder list as declared-empty', () => {
- expect(utilityReasoningDeclaration('custom-pi', 'pi', { efforts: [] })).toEqual({ kind: 'unknown' });
- expect(utilityReasoningDeclaration('custom-pi', 'pi', { efforts: [], reasoning: false })).toEqual({ kind: 'empty' });
+ it('only an explicit reasoning:false means no reasoning parameters at all', () => {
+ expect(utilityReasoningDeclaration({ efforts: [], reasoning: false })).toEqual({ kind: 'no-reasoning' });
+ expect(utilityReasoningDeclaration({ efforts: ['low'], reasoning: false })).toEqual({ kind: 'no-reasoning' });
});
});
@@ -68,26 +61,40 @@ describe('buildUtilityRequestPlan', () => {
]);
});
- it('never adds the minimal body to a declared ladder', () => {
+ it('keeps the legacy minimal body as the last custom-route step for declared models', () => {
expect(keys(buildUtilityRequestPlan({
wire: 'chat-completions',
mode: { kind: 'ladder', declaration: declared },
minimalBodyFallback: true,
- }))).not.toContain('chat-completions|omit|minimal');
+ }))).toEqual([
+ 'chat-completions|off',
+ 'chat-completions|effort:low',
+ 'chat-completions|effort:medium',
+ 'chat-completions|omit|minimal',
+ ]);
});
- it('walks an unknown model from off to low to the minimal body', () => {
+ it('walks a model without tiers from off to low to no reasoning parameters', () => {
expect(keys(buildUtilityRequestPlan({
wire: 'chat-completions',
- mode: { kind: 'ladder', declaration: { kind: 'unknown' } },
+ mode: { kind: 'ladder', declaration: { kind: 'undeclared' } },
minimalBodyFallback: true,
- }))).toEqual(['chat-completions|off', 'chat-completions|effort:low', 'chat-completions|omit|minimal']);
+ }))).toEqual([
+ 'chat-completions|off',
+ 'chat-completions|effort:low',
+ 'chat-completions|omit',
+ 'chat-completions|omit|minimal',
+ ]);
+ expect(keys(buildUtilityRequestPlan({
+ wire: 'responses',
+ mode: { kind: 'ladder', declaration: { kind: 'undeclared' } },
+ }))).toEqual(['responses|effort:low', 'responses|omit']);
});
- it('sends nothing for a declared-empty model', () => {
+ it('sends nothing to a model known not to take reasoning parameters', () => {
expect(keys(buildUtilityRequestPlan({
wire: 'responses',
- mode: { kind: 'ladder', declaration: { kind: 'empty' } },
+ mode: { kind: 'ladder', declaration: { kind: 'no-reasoning' } },
chatFallback: true,
}))).toEqual(['responses|omit', 'chat-completions|omit']);
});
@@ -147,7 +154,7 @@ describe('remembered steps', () => {
it('never remembers the minimal body', () => {
const steps = buildUtilityRequestPlan({
wire: 'chat-completions',
- mode: { kind: 'ladder', declaration: { kind: 'unknown' } },
+ mode: { kind: 'ladder', declaration: { kind: 'undeclared' } },
minimalBodyFallback: true,
});
rememberUtilityStep('route', steps.at(-1)!);
diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
index b682e159e5..d627de7f5a 100644
--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts
+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
@@ -168,6 +168,13 @@ type UtilityTextExecutionFailure =
/** Credential-safe error raised by a concrete utility transport. */
class UtilityTextExecutionError extends Error {
+ /**
+ * Request format actually used when an HTTP route failed. Logs only: the
+ * shared UtilityTextAttempt.transport crosses IPC and scheduler MCP, and its
+ * two-value union cannot describe the Cindy AI native Responses / Messages wires.
+ */
+ wire?: string;
+
constructor(readonly failure: UtilityTextExecutionFailure) {
super(failure.reason);
this.name = 'UtilityTextExecutionError';
@@ -1371,6 +1378,8 @@ async function executeCandidates(
providerId: candidate.providerId,
model: candidate.model,
transport: candidate.transport,
+ // The wire actually used; `transport` above is the coarse shared label.
+ wire: error instanceof UtilityTextExecutionError ? error.wire : undefined,
reason: failure.reason,
httpStatus: failure.httpStatus,
});
@@ -1702,6 +1711,7 @@ async function requestProviderHttpText(input: {
if (input.signal?.aborted) abortFromParent();
else input.signal?.addEventListener('abort', abortFromParent, { once: true });
const timeout = setTimeout(() => controller.abort(), timeoutMs);
+ let currentWire: ProviderWire | undefined;
try {
const instructions = [input.systemPrompt, input.responseInstructions]
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
@@ -1806,6 +1816,7 @@ async function requestProviderHttpText(input: {
let index = rememberedUtilityStepIndex(input.memoryKey, input.steps);
let step = input.steps[index];
if (!step) throw new UtilityTextExecutionError({ reason: 'request_failed' });
+ currentWire = step.wire;
let body = buildBody(step);
let response = await send(step, body);
let requests = 1;
@@ -1832,6 +1843,7 @@ async function requestProviderHttpText(input: {
});
index = next;
step = input.steps[index]!;
+ currentWire = step.wire;
body = nextBody;
response = await send(step, body);
requests += 1;
@@ -1875,6 +1887,11 @@ async function requestProviderHttpText(input: {
// The step was accepted by the provider; remember it even when the model
// produced no usable text, because the wording itself was not rejected.
if (input.steps.length > 1) rememberUtilityStep(input.memoryKey, step);
+ log.info('utility text request accepted', {
+ wire: step.wire,
+ step: utilityRequestStepKey(step),
+ requests,
+ });
if (!text) {
if (step.wire === 'chat-completions') {
log.warn('utility text chat-completions empty content', chatCompletionEmptyFingerprint(parsed));
@@ -1883,11 +1900,13 @@ async function requestProviderHttpText(input: {
}
return text;
} catch (error) {
- if (error instanceof UtilityTextExecutionError) throw error;
- if (error instanceof Error && error.name === 'AbortError') {
- throw new UtilityTextExecutionError({ reason: 'timeout' });
- }
- throw new UtilityTextExecutionError({ reason: 'request_failed' });
+ const failure = error instanceof UtilityTextExecutionError
+ ? error
+ : new UtilityTextExecutionError({
+ reason: error instanceof Error && error.name === 'AbortError' ? 'timeout' : 'request_failed',
+ });
+ failure.wire ??= currentWire;
+ throw failure;
} finally {
clearTimeout(timeout);
input.signal?.removeEventListener('abort', abortFromParent);
@@ -1925,8 +1944,8 @@ function utilityRequestPlan(input: {
upstreamBase: input.upstreamBase,
model: input.model,
})
- ? { kind: 'empty' }
- : utilityReasoningDeclaration(input.providerId, input.agentKind, input.catalogModel);
+ ? { kind: 'no-reasoning' }
+ : utilityReasoningDeclaration(input.catalogModel);
mode = { kind: 'ladder', declaration };
} else {
mode = {
diff --git a/apps/desktop/src/main/utility-model/utilityReasoningPlan.ts b/apps/desktop/src/main/utility-model/utilityReasoningPlan.ts
index 608e52322d..bf4459a8de 100644
--- a/apps/desktop/src/main/utility-model/utilityReasoningPlan.ts
+++ b/apps/desktop/src/main/utility-model/utilityReasoningPlan.ts
@@ -29,13 +29,15 @@ export type UtilityReasoningRung =
/**
* 目录对该模型思考档位的说法:
* - declared:声明了档位(按强弱升序);
- * - empty:明确声明没有档位(或厂商档案标为不思考);
- * - unknown:没有任何来源声明过。
+ * - undeclared:没有档位——空列表与 `effortsUnknown` 一并按此处理。目录(尤其 Cindy AI
+ * 网关的下发)不表达「能不能关掉思考」,空列表不能当成「不思考」;
+ * - no-reasoning:明确已知不收思考参数(厂商档案 noReasoningModels、
+ * `supportsReasoning === false`、目录显式 `reasoning: false`)。
*/
export type UtilityReasoningDeclaration =
| { kind: 'declared'; efforts: readonly string[] }
- | { kind: 'empty' }
- | { kind: 'unknown' };
+ | { kind: 'undeclared' }
+ | { kind: 'no-reasoning' };
export type UtilityRequestStep = {
wire: UtilityProviderWire;
@@ -46,32 +48,17 @@ export type UtilityRequestStep = {
gatewayNative?: boolean;
};
-/** 写死的档位兜底只用于目录没声明的模型,与改动前 Responses 的取值一致。 */
+/** 写死的档位兜底只用于目录没有档位的模型,与改动前 Responses 的取值一致。 */
const UNKNOWN_MODEL_EFFORT = 'low';
/** 每次辅助请求因参数类错误而发出的请求总数上限(不含 #6098 的预算重试)。 */
export const MAX_REASONING_REQUESTS = 4;
-/**
- * Cindy AI 网关的模型档位由网关下发;下发里缺了 efforts 时目录会落成 `[]`,
- * 与「明确声明为空」不可区分。网关的原始声明保留在 discoveredMetadata 里,
- * 据此把「没下发」识别为未声明,而不是当成「这个模型不思考」。
- */
export function utilityReasoningDeclaration(
- providerId: string,
- agentKind: string,
- model: Pick<CatalogModel, 'efforts' | 'effortsUnknown' | 'discoveredMetadata' | 'reasoning'> | undefined,
+ model: Pick<CatalogModel, 'efforts' | 'reasoning'> | undefined,
): UtilityReasoningDeclaration {
- if (!model || model.effortsUnknown || !Array.isArray(model.efforts)) return { kind: 'unknown' };
- if (model.efforts.length === 0) {
- if (providerId === 'xd') {
- return Array.isArray(model.discoveredMetadata?.efforts) ? { kind: 'empty' } : { kind: 'unknown' };
- }
- // 自定义 Pi 模型从不打「未声明」标记,`[]` 只是 Pi 运行时的占位(见
- // model-providers user-provider.ts);只有显式 reasoning:false 才算声明为空。
- if (agentKind === 'pi' && model.reasoning !== false) return { kind: 'unknown' };
- return { kind: 'empty' };
- }
+ if (model?.reasoning === false) return { kind: 'no-reasoning' };
+ if (!model || !Array.isArray(model.efforts) || model.efforts.length === 0) return { kind: 'undeclared' };
const efforts = [...new Set(model.efforts)].sort(
(a, b) => effortRank(a as Effort) - effortRank(b as Effort),
);
@@ -118,17 +105,25 @@ export function compatHasReasoningOff(input: {
return typeof wireMap === 'object' && wireMap !== null && Object.hasOwn(wireMap, 'none');
}
-/** 同一声明在某个请求格式上的退让顺序:关掉(协议支持时)→ 最低档 → 高一档。 */
+/**
+ * 同一声明在某个请求格式上的退让顺序。「关掉」由协议决定,与目录写了什么无关:
+ * - 声明了档位:关掉(Chat / Messages)→ 最低档 → 高一档;
+ * - 没有档位:关掉(Chat / Messages)→ low → 不带思考参数;
+ * - 明确不收思考参数:一开始就不带。
+ */
export function utilityReasoningRungs(
wire: UtilityProviderWire,
declaration: UtilityReasoningDeclaration,
): UtilityReasoningRung[] {
- if (declaration.kind === 'empty') return [{ kind: 'omit' }];
+ if (declaration.kind === 'no-reasoning') return [{ kind: 'omit' }];
const off: UtilityReasoningRung[] = wire === 'responses' ? [] : [{ kind: 'off' }];
- const efforts = declaration.kind === 'declared'
- ? declaration.efforts.slice(0, 2)
- : [UNKNOWN_MODEL_EFFORT];
- return [...off, ...efforts.map((effort) => ({ kind: 'effort' as const, effort }))];
+ if (declaration.kind === 'declared') {
+ return [
+ ...off,
+ ...declaration.efforts.slice(0, 2).map((effort) => ({ kind: 'effort' as const, effort })),
+ ];
+ }
+ return [...off, { kind: 'effort', effort: UNKNOWN_MODEL_EFFORT }, { kind: 'omit' }];
}
export function utilityReasoningRungKey(rung: UtilityReasoningRung): string {
@@ -150,8 +145,9 @@ export type UtilityReasoningMode =
*
* - `chatFallback`:Cindy AI 按模型原生格式发,原生格式出参数 / 格式类错误时退回 Chat,
* Chat 从原生格式起步的那一档接着往下退(思考档位照常带上,不会丢)。
- * - `minimalBodyFallback`:自定义供应商沿用的「去掉所有可选参数」兜底;档位模式下
- * 只给目录没声明档位(或声明为空)的模型,声明了档位的绝不退到不带思考参数。
+ * - `minimalBodyFallback`:自定义供应商沿用的「去掉所有可选参数」兜底,内容与触发条件
+ * (400 / 422)和改动前一致,不论有没有声明档位都作为最后一步;它是旧保底,
+ * 「声明了档位就不退到不带思考参数」只约束上面新增的几步。
*/
export function buildUtilityRequestPlan(input: {
wire: UtilityProviderWire;
@@ -180,8 +176,7 @@ export function buildUtilityRequestPlan(input: {
for (const rung of chatRungs.slice(start)) steps.push({ wire: 'chat-completions', rung });
}
}
- const minimalAllowed = mode.kind === 'fixed' || mode.declaration.kind !== 'declared';
- if (input.minimalBodyFallback && minimalAllowed && wire !== 'anthropic-messages') {
+ if (input.minimalBodyFallback && wire !== 'anthropic-messages') {
steps.push({ wire, rung: { kind: 'omit' }, minimalBody: true });
}
return steps;