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): key remembered steps by the full URL and restart within the rejected wire

fmfsaisaib98fbc8fd07a
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 c3de75df15..46767c8dc0 100644
--- a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
+++ b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
@@ -4227,6 +4227,62 @@ describe('utility one-shot candidates', () => {
expect(bodyOf(0)).toMatchObject({ thinking: { type: 'disabled' } });
});
+ it('does not reuse a remembered step after only the query string changes', async () => {
+ await rememberLow('https://custom.example/v1?tenant=a', ['low', 'medium']);
+ activeCatalog.mockReturnValue(customChatCatalog({
+ upstream: 'https://custom.example/v1?tenant=b',
+ model: { id: 'custom-thinker', efforts: ['low', 'medium'] },
+ }) as never);
+ fetchMock.mockResolvedValueOnce(chatOk('fresh') as never);
+
+ await expect(request()).resolves.toMatchObject({ ok: true, text: 'fresh' });
+ expect(urlOf(0)).toBe('https://custom.example/v1/chat/completions?tenant=b');
+ expect(bodyOf(0)).toMatchObject({ thinking: { type: 'disabled' } });
+ });
+
+ it('restarts a remembered Chat fallback on the Chat steps, not on the rejected native wire', async () => {
+ activeCatalog.mockReturnValue(xdCatalog('claude-code', [{
+ id: 'claude-sonnet-4-6',
+ nativeApi: 'anthropic-messages',
+ efforts: ['low', 'medium'],
+ }]) as never);
+ readKey.mockReturnValue('xd-key');
+ const xdRequest = () => requestExplicitUtilityText('hello', {
+ providerId: 'xd',
+ agentKind: 'claude-code',
+ model: 'claude-sonnet-4-6',
+ disableReasoning: true,
+ });
+ let acceptChat: (body: Record<string, unknown>) => boolean = (body) => Boolean(body.thinking);
+ fetchMock.mockImplementation(async (url, init) => {
+ const body = JSON.parse(String((init as { body: string }).body)) as Record<string, unknown>;
+ const isChat = String(url).endsWith('/v1/chat/completions');
+ return (isChat && acceptChat(body) ? chatOk('ok') : rejected(400)) as never;
+ });
+
+ // Messages off / low / medium are rejected; Chat "off" succeeds and is remembered.
+ await expect(xdRequest()).resolves.toMatchObject({ ok: true });
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ expect(urlOf(3)).toBe(`${GATEWAY}/v1/chat/completions`);
+
+ // The upstream now only accepts Chat `low`.
+ fetchMock.mockClear();
+ acceptChat = (body) => !body.thinking && body.reasoning_effort === 'low';
+ await expect(xdRequest()).resolves.toMatchObject({ ok: true });
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ `${GATEWAY}/v1/chat/completions`,
+ `${GATEWAY}/v1/chat/completions`,
+ ]);
+ expect(bodyOf(0)).toMatchObject({ thinking: { type: 'disabled' } });
+ expect(bodyOf(1)).toMatchObject({ reasoning_effort: 'low' });
+
+ // Chat `low` is remembered now.
+ fetchMock.mockClear();
+ await expect(xdRequest()).resolves.toMatchObject({ ok: true });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(bodyOf(0)).toMatchObject({ reasoning_effort: 'low' });
+ });
+
it('keeps a restarted walk within the request cap', async () => {
activeCatalog.mockReturnValue(customChatCatalog({
upstream: 'https://custom.example/v1',
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 70361d407a..5d63abec41 100644
--- a/apps/desktop/src/main/utility-model/__tests__/utilityReasoningPlan.test.ts
+++ b/apps/desktop/src/main/utility-model/__tests__/utilityReasoningPlan.test.ts
@@ -178,9 +178,20 @@ describe('scopeUtilityMemoryKey', () => {
responses: 'https://user:[email protected]/v1/responses?api_key=secret-query#frag',
'chat-completions': 'https://gateway.example/v1/chat/completions',
});
- expect(key).toContain('https://gateway.example/v1/responses');
+ expect(key).not.toContain('gateway.example');
+ expect(key).not.toContain('user:');
expect(key).not.toContain('secret');
+ expect(key).not.toContain('api_key');
expect(key).not.toContain('frag');
+ // The fragment never reaches the provider; the query string may be part of the route.
+ expect(scopeUtilityMemoryKey('base', steps, {
+ responses: 'https://user:[email protected]/v1/responses?api_key=secret-query#other',
+ 'chat-completions': 'https://gateway.example/v1/chat/completions',
+ })).toBe(key);
+ expect(scopeUtilityMemoryKey('base', steps, {
+ responses: 'https://user:[email protected]/v1/responses?api_key=secret-query-2#frag',
+ 'chat-completions': 'https://gateway.example/v1/chat/completions',
+ })).not.toBe(key);
expect(scopeUtilityMemoryKey('base', steps, {
responses: 'https://other.example/v1/responses',
'chat-completions': 'https://gateway.example/v1/chat/completions',
diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
index ccbc5564ab..cd8501a794 100644
--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts
+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
@@ -1929,7 +1929,8 @@ async function requestProviderHttpText(input: {
: undefined;
let index = rememberedUtilityStepIndex(memoryKey, input.steps);
// A remembered step rejected on its first try means the upstream changed:
- // forget it and walk the plan from the start instead of only moving on.
+ // forget it and walk its wire's steps again from the first one instead of
+ // only moving on.
let restartFromFirst = index > 0;
const tried = new Set<number>([index]);
let step = input.steps[index];
@@ -1946,10 +1947,12 @@ async function requestProviderHttpText(input: {
if (requests < MAX_REASONING_REQUESTS && isUtilityParameterRejection(step, response.status)) {
if (restartFromFirst) {
forgetUtilityStep(memoryKey);
- // A missing native endpoint stays missing; restart on the Chat steps.
- const restart = response.status === 404
- ? input.steps.findIndex((candidate) => candidate.wire === 'chat-completions')
- : 0;
+ // Restart at the first step of the rejected step's wire: a remembered
+ // Chat fallback means the native wire was already rejected, so keep the
+ // request budget for Chat. A missing native endpoint stays missing, so
+ // a native 404 restarts on the Chat steps as well.
+ const restartWire = response.status === 404 ? 'chat-completions' : step.wire;
+ const restart = input.steps.findIndex((candidate) => candidate.wire === restartWire);
next = restart >= 0 ? restart : null;
} else {
next = nextUtilityRequestStep(input.steps, index, response.status);
diff --git a/apps/desktop/src/main/utility-model/utilityReasoningPlan.ts b/apps/desktop/src/main/utility-model/utilityReasoningPlan.ts
index 473f6968a5..c784bcabd9 100644
--- a/apps/desktop/src/main/utility-model/utilityReasoningPlan.ts
+++ b/apps/desktop/src/main/utility-model/utilityReasoningPlan.ts
@@ -17,6 +17,7 @@ import {
type CompatibilityHarness,
} from '@cindy/model-compat';
import { effortRank, type CatalogModel, type Effort } from '@cindy/model-providers';
+import { createHash } from 'node:crypto';
export type UtilityProviderWire = 'chat-completions' | 'anthropic-messages' | 'responses';
@@ -234,8 +235,8 @@ export function utilityReasoningMemoryKey(parts: {
/**
* 把记忆限定到当前路由:本次计划用到的各请求格式的有效地址,加上计划签名(各步骤
- * 的 key)。地址或目录档位一变,旧端点记住的写法就不再沿用。地址只取 origin + path,
- * 不含 userinfo、查询参数与片段——这些位置可能带凭证;请求头也不进键。
+ * 的 key)。地址或目录档位一变,旧端点记住的写法就不再沿用。地址取完整 URL(含查询
+ * 参数、不含片段)的 sha256 摘要,不以明文保存;请求头也不进键。
*/
export function scopeUtilityMemoryKey(
memoryKey: string,
@@ -246,19 +247,17 @@ export function scopeUtilityMemoryKey(
const routes = wires.map((wire) => {
const endpoint = endpoints[wire];
if (!endpoint) return [wire, ''];
- try {
- const url = new URL(endpoint);
- return [wire, `${url.origin}${url.pathname}`];
- } catch {
- return [wire, ''];
- }
+ // 查询参数可能是路由的一部分(appendProviderRequestPath 会保留它),所以取完整
+ // URL;只去掉片段。用摘要而不是原文,URL 里可能带的凭证不会明文进键。
+ const withoutFragment = endpoint.split('#', 1)[0]!;
+ return [wire, createHash('sha256').update(withoutFragment).digest('hex')];
});
return JSON.stringify([memoryKey, routes, steps.map(utilityRequestStepKey)]);
}
/**
* 记住的写法若仍在本次计划里,就从它开始。它后来被参数类错误拒绝时,调用方清掉这条
- * 记忆并从计划第一步重走(见 forgetUtilityStep),上游变了也能自动修正。
+ * 记忆,从这一步所在请求格式的第一步重走(见 forgetUtilityStep),上游变了也能自动修正。
*/
export function rememberedUtilityStepIndex(
memoryKey: string | undefined,