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): scope remembered reasoning steps to the current route

fmfsaisai7e8d9a8c3c57
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 bfa4235439..c3de75df15 100644
--- a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
+++ b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts
@@ -4134,7 +4134,7 @@ describe('utility one-shot candidates', () => {
});
});
- it('remembers the accepted step and continues down when it is later rejected', async () => {
+ it('remembers the accepted step and walks the plan again from the start when it is later rejected', async () => {
activeCatalog.mockReturnValue(customChatCatalog({
upstream: 'https://custom.example/v1',
model: { id: 'custom-thinker', efforts: ['low', 'medium', 'high'] },
@@ -4160,14 +4160,96 @@ describe('utility one-shot candidates', () => {
expect(bodyOf(0)).toMatchObject({ reasoning_effort: 'low' });
expect(bodyOf(0)).not.toHaveProperty('thinking');
+ // The upstream changed and now only accepts "off": the remembered `low` is
+ // rejected, the plan restarts from its first step, and "off" is remembered.
fetchMock.mockClear();
- fetchMock
- .mockResolvedValueOnce(rejected(400) as never)
- .mockResolvedValueOnce(chatOk('third') as never);
+ fetchMock.mockImplementation(async (_url, init) => {
+ const body = JSON.parse(String((init as { body: string }).body)) as Record<string, unknown>;
+ return (body.thinking ? chatOk('third') : rejected(400)) as never;
+ });
await expect(request()).resolves.toMatchObject({ ok: true, text: 'third' });
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(bodyOf(0)).toMatchObject({ reasoning_effort: 'low' });
- expect(bodyOf(1)).toMatchObject({ reasoning_effort: 'medium' });
+ expect(bodyOf(1)).toMatchObject({ thinking: { type: 'disabled' }, reasoning_effort: 'minimal' });
+
+ fetchMock.mockClear();
+ await expect(request()).resolves.toMatchObject({ ok: true, text: 'third' });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(bodyOf(0)).toMatchObject({ thinking: { type: 'disabled' } });
+ });
+
+ describe('remembered steps are scoped to the current route', () => {
+ const request = (model = 'custom-thinker') => requestExplicitUtilityText('hello', {
+ providerId: 'custom-chat',
+ agentKind: 'codex',
+ model,
+ disableReasoning: true,
+ });
+ const rememberLow = async (upstream: string, efforts: string[]) => {
+ activeCatalog.mockReturnValue(customChatCatalog({
+ upstream,
+ model: { id: 'custom-thinker', efforts },
+ }) as never);
+ fetchMock
+ .mockResolvedValueOnce(rejected(400) as never)
+ .mockResolvedValueOnce(chatOk('remembered') as never);
+ await expect(request()).resolves.toMatchObject({ ok: true });
+ expect(bodyOf(1)).toMatchObject({ reasoning_effort: 'low' });
+ fetchMock.mockClear();
+ };
+
+ beforeEach(() => {
+ readCustomKey.mockReturnValue('custom-secret');
+ });
+
+ it('does not reuse a step remembered for the old address after the upstream is edited', async () => {
+ await rememberLow('https://old.example/v1', ['low', 'medium']);
+ activeCatalog.mockReturnValue(customChatCatalog({
+ upstream: 'https://new.example/v1',
+ 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://new.example/v1/chat/completions');
+ expect(bodyOf(0)).toMatchObject({ thinking: { type: 'disabled' } });
+ });
+
+ it('does not reuse a remembered step after the catalog tiers change', async () => {
+ await rememberLow('https://custom.example/v1', ['low', 'medium']);
+ activeCatalog.mockReturnValue(customChatCatalog({
+ upstream: 'https://custom.example/v1',
+ model: { id: 'custom-thinker', efforts: ['low', 'high'] },
+ }) as never);
+ fetchMock.mockResolvedValueOnce(chatOk('fresh') as never);
+
+ await expect(request()).resolves.toMatchObject({ ok: true, text: 'fresh' });
+ expect(bodyOf(0)).toMatchObject({ thinking: { type: 'disabled' } });
+ });
+
+ it('keeps a restarted walk within the request cap', async () => {
+ activeCatalog.mockReturnValue(customChatCatalog({
+ upstream: 'https://custom.example/v1',
+ model: { id: 'custom-thinker', efforts: ['low', 'medium'] },
+ }) as never);
+ // Remember `medium` (the third step).
+ fetchMock
+ .mockResolvedValueOnce(rejected(400) as never)
+ .mockResolvedValueOnce(rejected(400) as never)
+ .mockResolvedValueOnce(chatOk('remembered') as never);
+ await expect(request()).resolves.toMatchObject({ ok: true });
+ expect(bodyOf(2)).toMatchObject({ reasoning_effort: 'medium' });
+
+ fetchMock.mockClear();
+ fetchMock.mockResolvedValue(rejected(400) as never);
+ await expect(request()).resolves.toMatchObject({ ok: false });
+ // medium, then off / low (restart, skipping medium), then the minimal body.
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ expect(bodyOf(0)).toMatchObject({ reasoning_effort: 'medium' });
+ expect(bodyOf(1)).toMatchObject({ thinking: { type: 'disabled' } });
+ expect(bodyOf(2)).toMatchObject({ reasoning_effort: 'low' });
+ expect(bodyOf(3)).toEqual({ model: 'custom-thinker', messages: [{ role: 'user', content: 'hello' }] });
+ });
});
it.each([401, 403, 429, 500, 503])('does not walk the plan after HTTP %i', async (status) => {
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 8d1fbb1338..70361d407a 100644
--- a/apps/desktop/src/main/utility-model/__tests__/utilityReasoningPlan.test.ts
+++ b/apps/desktop/src/main/utility-model/__tests__/utilityReasoningPlan.test.ts
@@ -5,6 +5,7 @@ import {
compatHasReasoningOff,
compatMarksNoReasoning,
nextUtilityRequestStep,
+ scopeUtilityMemoryKey,
rememberUtilityStep,
rememberedUtilityStepIndex,
resetUtilityReasoningMemory,
@@ -165,6 +166,32 @@ describe('remembered steps', () => {
});
});
+describe('scopeUtilityMemoryKey', () => {
+ const steps = buildUtilityRequestPlan({
+ wire: 'responses',
+ mode: { kind: 'ladder', declaration: { kind: 'declared', efforts: ['low', 'medium'] } },
+ chatFallback: true,
+ });
+
+ it('separates routes by endpoint and plan, and never keeps credentials', () => {
+ const key = scopeUtilityMemoryKey('base', steps, {
+ 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('secret');
+ expect(key).not.toContain('frag');
+ expect(scopeUtilityMemoryKey('base', steps, {
+ responses: 'https://other.example/v1/responses',
+ 'chat-completions': 'https://gateway.example/v1/chat/completions',
+ })).not.toBe(key);
+ expect(scopeUtilityMemoryKey('base', steps.slice(1), {
+ responses: 'https://user:[email protected]/v1/responses?api_key=secret-query#frag',
+ 'chat-completions': 'https://gateway.example/v1/chat/completions',
+ })).not.toBe(key);
+ });
+});
+
describe('compatHasReasoningOff', () => {
it('is true only for vendor profiles with their own off spelling', () => {
const route = (upstreamBase: string, model: string) => ({ harness: 'codex' as const, upstreamBase, model });
diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
index b6c244da93..ccbc5564ab 100644
--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts
+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
@@ -42,9 +42,12 @@ import {
buildUtilityRequestPlan,
compatHasReasoningOff,
compatMarksNoReasoning,
+ forgetUtilityStep,
+ isUtilityParameterRejection,
nextUtilityRequestStep,
rememberUtilityStep,
rememberedUtilityStepIndex,
+ scopeUtilityMemoryKey,
utilityReasoningDeclaration,
utilityReasoningMemoryKey,
utilityRequestStepKey,
@@ -1915,7 +1918,20 @@ async function requestProviderHttpText(input: {
});
};
- let index = rememberedUtilityStepIndex(input.memoryKey, input.steps);
+ // Remembered steps are scoped to this route's endpoints and plan, so an
+ // edited address or changed catalog tiers start from the first step again.
+ const memoryKey = input.memoryKey
+ ? scopeUtilityMemoryKey(input.memoryKey, input.steps, {
+ 'chat-completions': input.targets['chat-completions']?.endpoint,
+ responses: input.targets.responses?.endpoint,
+ 'anthropic-messages': input.targets['anthropic-messages']?.endpoint,
+ })
+ : 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.
+ let restartFromFirst = index > 0;
+ const tried = new Set<number>([index]);
let step = input.steps[index];
if (!step) throw new UtilityTextExecutionError({ reason: 'request_failed' });
currentWire = step.wire;
@@ -1923,20 +1939,37 @@ async function requestProviderHttpText(input: {
let response = await send(step, body);
let requests = 1;
while (!response.ok) {
- // Only parameter-class rejections advance the plan. Bodies identical to
- // the rejected one (for example a minimal body with nothing to strip)
- // would only be rejected again.
- let next: number | null = requests < MAX_REASONING_REQUESTS
- ? nextUtilityRequestStep(input.steps, index, response.status)
- : null;
+ // Only parameter-class rejections advance the plan. Steps already tried
+ // in this call, and bodies identical to the rejected one (for example a
+ // minimal body with nothing to strip), would only be rejected again.
+ let next: number | null = null;
+ 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;
+ next = restart >= 0 ? restart : null;
+ } else {
+ next = nextUtilityRequestStep(input.steps, index, response.status);
+ }
+ }
+ restartFromFirst = false;
let nextBody: Record<string, unknown> | undefined;
while (next !== null) {
const candidate = input.steps[next]!;
- nextBody = buildBody(candidate);
- if (candidate.wire !== step.wire || stableSnapshot(nextBody) !== stableSnapshot(body)) break;
- next = nextUtilityRequestStep(input.steps, next, response.status);
+ if (!tried.has(next)) {
+ const candidateBody = buildBody(candidate);
+ if (candidate.wire !== step.wire || stableSnapshot(candidateBody) !== stableSnapshot(body)) {
+ nextBody = candidateBody;
+ break;
+ }
+ }
+ next = next + 1 < input.steps.length ? next + 1 : null;
}
if (next === null || !nextBody) break;
+ tried.add(next);
await response.body?.cancel().catch(() => undefined);
log.debug('utility text request rejected, trying the next reasoning step', {
status: response.status,
@@ -1988,7 +2021,7 @@ 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);
+ if (input.steps.length > 1) rememberUtilityStep(memoryKey, step);
log.info('utility text request accepted', {
wire: step.wire,
step: utilityRequestStepKey(step),
diff --git a/apps/desktop/src/main/utility-model/utilityReasoningPlan.ts b/apps/desktop/src/main/utility-model/utilityReasoningPlan.ts
index 7e984036d6..473f6968a5 100644
--- a/apps/desktop/src/main/utility-model/utilityReasoningPlan.ts
+++ b/apps/desktop/src/main/utility-model/utilityReasoningPlan.ts
@@ -212,6 +212,11 @@ export function nextUtilityRequestStep(
return index + 1 < steps.length ? index + 1 : null;
}
+/** 参数类拒绝:400 / 422,以及 Cindy AI 原生接口的 404。只有它们才换写法重试。 */
+export function isUtilityParameterRejection(step: UtilityRequestStep | undefined, status: number): boolean {
+ return status === 400 || status === 422 || (status === 404 && step?.gatewayNative === true);
+}
+
/** 只记成功的写法,进程内有效;重启后清空。 */
const rememberedSteps = new Map<string, string>();
const REMEMBERED_STEP_LIMIT = 256;
@@ -227,7 +232,34 @@ export function utilityReasoningMemoryKey(parts: {
return JSON.stringify([parts.providerId, parts.agentKind, parts.model, parts.wire, mode]);
}
-/** 记住的写法若仍在本次计划里,就从它开始;它后来被拒时照常往下退。 */
+/**
+ * 把记忆限定到当前路由:本次计划用到的各请求格式的有效地址,加上计划签名(各步骤
+ * 的 key)。地址或目录档位一变,旧端点记住的写法就不再沿用。地址只取 origin + path,
+ * 不含 userinfo、查询参数与片段——这些位置可能带凭证;请求头也不进键。
+ */
+export function scopeUtilityMemoryKey(
+ memoryKey: string,
+ steps: readonly UtilityRequestStep[],
+ endpoints: Partial<Record<UtilityProviderWire, string>>,
+): string {
+ const wires = [...new Set(steps.map((step) => step.wire))].sort();
+ 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, ''];
+ }
+ });
+ return JSON.stringify([memoryKey, routes, steps.map(utilityRequestStepKey)]);
+}
+
+/**
+ * 记住的写法若仍在本次计划里,就从它开始。它后来被参数类错误拒绝时,调用方清掉这条
+ * 记忆并从计划第一步重走(见 forgetUtilityStep),上游变了也能自动修正。
+ */
export function rememberedUtilityStepIndex(
memoryKey: string | undefined,
steps: readonly UtilityRequestStep[],
@@ -250,6 +282,10 @@ export function rememberUtilityStep(memoryKey: string | undefined, step: Utility
rememberedSteps.set(memoryKey, utilityRequestStepKey(step));
}
+export function forgetUtilityStep(memoryKey: string | undefined): void {
+ if (memoryKey) rememberedSteps.delete(memoryKey);
+}
+
/** 测试用:清空进程内记住的写法。 */
export function resetUtilityReasoningMemory(): void {
rememberedSteps.clear();
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index 22dbcd393f..fb694fe182 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -459,8 +459,10 @@ Desktop 的 Auto 审核先按固定顺序尝试 `cindy/auto-review`、内置 Ope
严格判定解析器。设置说明须披露发往所选供应商的上下文范围:用户原话、引用内容、
委派任务、此前被阻止的操作、发起者身份与权限、待审操作参数、工作区及可写/参考
路径和操作系统;不能只列用户原话与操作参数,漏掉其余上下文。
-384 token 的短输出预算复用辅助模型的关闭可选思考策略;Messages/Chat 可关闭时关闭,
-Responses 沿用现有适配器的 `low` 档,不发送其不支持的思考关闭值。
+384 token 的短输出预算复用辅助模型的「最少思考」策略;Messages/Chat 先试关闭思考,
+Responses 没有关闭值,从模型目录声明的最低档开始(没有档位时用 `low`),不发送其
+不支持的思考关闭值;被参数类错误拒绝时按目录档位逐级调整,详见
+`apps/desktop/src/main/utility-model/utilityReasoningPlan.ts`。
审核开始时绑定账号、自定义链及所选供应商路由与停用状态快照,并复用现有供应商变更代次校验,
覆盖地址/鉴权配置、密钥修改和同 ID 删除重建。订阅请求同时绑定 OpenAI 原生授权凭证或