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。

Merge origin/main into issue-5878-cache-recovery

xuzini-xzn38820e16c55a
diff --cc apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
index 78fdfcb933,aa44190574..0379891cec
--- a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
@@@ -17,9 -17,10 +17,11 @@@ import
shouldRebuildForContextPressure,
shouldRebuildForModelWindowSwitch,
shouldRebuildPiNativeSession,
+ type ContextOverflowRolloverDeps,
type OverflowSourceMessage,
withReplaySourceNotes,
+ BOT_IDLE_GAP_REBUILD_MS,
+ measureIdleGap,
} from '../contextOverflowRollover';
import { buildHandoffText } from '../agentHandoff';
diff --cc apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
index 11d6725304,72b9c7eb65..d41ca3436d
--- a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
+++ b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
@@@ -511,8 -486,53 +532,55 @@@ export function canContinueContextRecov
return row.source === 'desktop' || isCanonicalBotContext(row);
}
+type RecoveryTurnIdentity = { instanceId?: string; generation?: number };
+
+ export type ContextRebuildReason =
+ | 'context-overflow'
+ | 'model-window-switch'
+ | 'pi-prompt-timeout'
+ | 'native-session-recovery'
+ | 'idle-gap';
+
+ /**
+ * 伙伴的对话(主对话 + IM 群 / 话题 / 外部私聊专线 + 伙伴群聊专线)共用同一套上下文自管理
+ * 规则:到线换窗、工具结果入交接、空闲间隔刷新。委派 / 历史任务不是对话,不在此列。
+ */
+ export function isBotChatContext(row: { source?: string | null; botRole?: string | null }): boolean {
+ return (
+ row.source === 'bot' &&
+ (row.botRole === 'canonical' || row.botRole === 'channel' || row.botRole === 'group')
+ );
+ }
+
+ /**
+ * 伙伴对话空闲这么久之后的下一条消息,先换一个干净的原生会话再发:老话题不再占着模型
+ * 工作上下文把新话题带偏。完整记录仍在同一条任务里,交接只带最近一段 + 检索指引。
+ * 主对话与 IM 专线同一条线,不按渠道各设一套。
+ */
+ export const BOT_IDLE_GAP_REBUILD_MS = 12 * 60 * 60 * 1000;
+
+ /**
+ * 空闲间隔 = 上一次活动到本次发送之间的时长。本次要发的 user 若已落库(IM 群预落库、
+ * 桌面先写后发),它自己不算活动,基准取它的落库时刻;否则基准取现在。createdAt 缺失 /
+ * 非正数的记录不参与(老数据或测试桩),算不出就不触发。
+ */
+ export function measureIdleGap(
+ source: ReadonlyArray<Pick<OverflowSourceMessage, 'createdAt'>>,
+ pendingUserIndex: number,
+ now: number,
+ ): number | null {
+ const activity = pendingUserIndex >= 0 ? source.slice(0, pendingUserIndex) : source;
+ let latest = 0;
+ for (const message of activity) {
+ if (Number.isFinite(message.createdAt) && message.createdAt > latest) latest = message.createdAt;
+ }
+ if (latest <= 0) return null;
+ const pending = pendingUserIndex >= 0 ? source[pendingUserIndex] : undefined;
+ const reference =
+ pending && Number.isFinite(pending.createdAt) && pending.createdAt > 0 ? pending.createdAt : now;
+ return Math.max(0, reference - latest);
+ }
+
export type OverflowClaimResult = 'claimed' | 'in-flight' | 'idle';
export type ModelWindowSwitchPreparationResult =
@@@ -584,18 -599,38 +652,47 @@@ export function createContextOverflowRo
): Promise<ModelWindowSwitchPreparationResult>;
} {
const inFlight = new Map<string, AbortController | undefined>();
+ const claimTurns = new WeakMap<AbortController, RecoveryTurnIdentity>();
// One automatic continuation per source input, not one per replacement thread.
const continuedInputs = new Map<string, string>();
+ // 自愈成功时那一轮的 turn 身份:同身份再次到达 = 同一轮的重复终态投递(丢弃);
+ // 新身份 = 重放后的新一轮失败(必须 surface,不能静默吞掉)。
+ const healedCompatTurns = new Map<string, { instanceId?: string; generation?: number }>();
+ /**
+ * (会话, provider, model) 已经用「已学覆盖」重建过:再失败就不再自动重建,交常规
+ * 错误面。必须带上 pair:同一会话换模型后,旧模型的记录不能挡住新模型的自愈。
+ */
+ const rebuiltWithLearnedCompat = new Set<string>();
+ // 账本是增强:读不到、抛错都按没有,绝不挡住换窗。
+ const readWorkingMemoryNote = async (sessionId: string): Promise<string | null> => {
+ try {
+ return (await deps.readWorkingMemoryNote?.(sessionId)) ?? null;
+ } catch {
+ return null;
+ }
+ };
+ const isWorkingMemoryFresh = async (sessionId: string): Promise<boolean> => {
+ try {
+ return (await deps.isWorkingMemoryFresh?.(sessionId)) === true;
+ } catch {
+ return false;
+ }
+ };
+ // 伙伴自有会话清单同样是增强:非伙伴不查,读不到按只认当前对话。
+ const companionRecall = async (
+ sessionId: string,
+ companion: boolean,
+ ): Promise<{ companionSessionIds: string[]; companionSessionIdsTruncated: boolean }> => {
+ const none = { companionSessionIds: [], companionSessionIdsTruncated: false };
+ if (!companion) return none;
+ try {
+ const own = await deps.listCompanionSessionIds?.(sessionId);
+ return own ? { companionSessionIds: own.sessionIds, companionSessionIdsTruncated: own.chatsTruncated } : none;
+ } catch {
+ return none;
+ }
+ };
const runRecover = async (
sessionId: string,
errorData: unknown,
diff --cc apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index 4ac1038506,826bc8e4be..1b1b2a5471
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@@ -246,7 -248,8 +249,9 @@@ export function revokeTrustedDesktopQue
}
type MakerSendOptions = {
+ readonly [PI_CACHE_RECOVERY_EXPECTATION]?: import('@cindy/maker-core').SendOptions[typeof PI_CACHE_RECOVERY_EXPECTATION];
+ /** Main-only live card guard, never serialized to queue history or provider options. */
+ readonly [MCP_APP_MESSAGE_GUARD]?: McpAppMessageGuard;
readonly [AUTO_REVIEW_DELEGATED_CONTINUATION]?: true;
retryUserClientId?: string;
toolsDisabled?: boolean;
diff --cc packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
index 8ee3ebdb55,23766525be..552d7c1223
--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts
@@@ -2494,22 -2498,152 +2498,170 @@@ it('lets cindy_mcp_call_tool omit args
name: 'call_tool',
arguments: { name: 'memory_list', args: {} },
});
+ // 2026-10-15 回归: args 就是「所选工具自己的参数」, 直调形态合法, schema 不得收窄;
+ // 同时必须把通用 call_tool 的信封 {name, args} 作为提示属性挂在 args 上 —— 此前 args 是
+ // 无声明字段的自由袋子, 模型看不到信封就把内层字段平铺进来并丢掉 name。
+ const argsSchema = callTool.parameters.properties.args;
+ expect(argsSchema.additionalProperties).toBe(true);
+ expect(argsSchema.properties).toHaveProperty('name');
+ expect(argsSchema.properties).toHaveProperty('args');
+ expect(argsSchema.properties.name.type).toBeUndefined();
+ expect(argsSchema.properties.args.type).toBeUndefined();
+ });
+
+ it('tells the model the call_tool envelope instead of forwarding a flattened envelope', async () => {
+ const source = CINDY_BRIDGE_EXTENSION_SOURCE;
+ const compiled = ts.transpileModule(
+ source.slice(source.indexOf('const CINDY_MCP_LIST_TOOLS'), source.indexOf('async function connectServer'))
+ + '\n(globalThis as any).Gateway = CindyMcpGateway;',
+ { compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 } },
+ ).outputText;
+ const context: Record<string, any> = {
+ recordInput: (value: unknown) => value && typeof value === 'object' ? value : {},
+ mcpContentToPi: (content: unknown) => content,
+ };
+ runInNewContext(compiled, context);
+ const requests: Array<{ method: string; params: any }> = [];
+ const client = { request: async (method: string, params: unknown) => {
+ requests.push({ method, params });
+ return { content: [{ type: 'text', text: 'ok' }] };
+ } };
+ const gateway = new context.Gateway();
+ gateway.add('cindy_memory', client, [
+ { name: 'list_tools', inputSchema: { type: 'object' } },
+ // 真实 cindy server 的 call_tool schema 形状指纹: name:string + args:object + required 含 name。
+ { name: 'call_tool', inputSchema: { type: 'object', properties: { name: { type: 'string' }, args: { type: 'object' } }, required: ['name'] } },
+ ]);
+ gateway.register({ registerTool: () => undefined });
+ await gateway.listResult({ server: 'cindy_memory', tool: 'call_tool' });
+ // 模型把内层参数平铺进 args、丢掉 name: 不触达 MCP, 一次说清正确形态。
+ await expect(gateway.executeCall({
+ server: 'cindy_memory',
+ tool: 'call_tool',
+ args: { filename: 'project_x.md' },
+ })).rejects.toThrow(/envelope \{"name": <tool>, "args"/);
+ expect(requests).toHaveLength(0);
+ // 直调形态不受影响: 所选工具不是 call_tool 时, args 仍原样转发 (含参数名恰好叫 args/name)。
+ gateway.add('cindy_workspace', client, [{ name: 'status', inputSchema: { type: 'object' } }]);
+ await gateway.listResult({ server: 'cindy_workspace', tool: 'status' });
+ await gateway.executeCall({ server: 'cindy_workspace', tool: 'status', args: { args: ['x'], name: 'y' } });
+ expect(requests[0].params).toEqual({ name: 'status', arguments: { args: ['x'], name: 'y' } });
+ });
+
+ it('does not apply the Cindy envelope rule to a third-party tool also named call_tool', async () => {
+ const source = CINDY_BRIDGE_EXTENSION_SOURCE;
+ const compiled = ts.transpileModule(
+ source.slice(source.indexOf('const CINDY_MCP_LIST_TOOLS'), source.indexOf('async function connectServer'))
+ + '\n(globalThis as any).Gateway = CindyMcpGateway;',
+ { compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 } },
+ ).outputText;
+ const context: Record<string, any> = {
+ recordInput: (value: unknown) => value && typeof value === 'object' ? value : {},
+ mcpContentToPi: (content: unknown) => content,
+ };
+ runInNewContext(compiled, context);
+ const requests: Array<{ method: string; params: any }> = [];
+ const client = { request: async (method: string, params: unknown) => {
+ requests.push({ method, params });
+ return { content: [{ type: 'text', text: 'ok' }] };
+ } };
+ const gateway = new context.Gateway();
+ // 用户自接的第三方 MCP: 工具同样叫 call_tool, 但信封是 {tool_name, arguments}。
+ gateway.add('third_party', client, [{
+ name: 'call_tool',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tool_name: { type: 'string' },
+ arguments: { type: 'object', additionalProperties: true },
+ },
+ required: ['tool_name'],
+ },
+ }]);
+ gateway.register({ registerTool: () => undefined });
+ await gateway.listResult({ server: 'third_party', tool: 'call_tool' });
+ // 模型完全照检视到的 schema 调用: 必须放行到服务端, 不能被 Cindy 的信封规则连坐。
+ await gateway.executeCall({
+ server: 'third_party',
+ tool: 'call_tool',
+ args: { tool_name: 'inner', arguments: { a: 1 } },
+ });
+ expect(requests[0].params).toEqual({
+ name: 'call_tool',
+ arguments: { tool_name: 'inner', arguments: { a: 1 } },
+ });
+ // 同一 server 里, schema 形状指纹齐全 (name+args+required) 的工具仍走信封自纠错
+ // (判据是形状不是名字)。
+ gateway.add('mixed', client, [{
+ name: 'call_tool',
+ inputSchema: {
+ type: 'object',
+ properties: { name: { type: 'string' }, args: { type: 'object' } },
+ required: ['name'],
+ },
+ }]);
+ await gateway.listResult({ server: 'mixed', tool: 'call_tool' });
+ await expect(gateway.executeCall({ server: 'mixed', tool: 'call_tool', args: { filename: 'x.md' } }))
+ .rejects.toThrow(/envelope \{"name": <tool>, "args"/);
+ expect(requests).toHaveLength(1);
+ });
+
+ it('leaves a direct tool alone when its required name is not the Cindy envelope', async () => {
+ const source = CINDY_BRIDGE_EXTENSION_SOURCE;
+ const compiled = ts.transpileModule(
+ source.slice(source.indexOf('const CINDY_MCP_LIST_TOOLS'), source.indexOf('async function connectServer'))
+ + '\n(globalThis as any).Gateway = CindyMcpGateway;',
+ { compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 } },
+ ).outputText;
+ const context: Record<string, any> = {
+ recordInput: (value: unknown) => value && typeof value === 'object' ? value : {},
+ mcpContentToPi: (content: unknown) => content,
+ };
+ runInNewContext(compiled, context);
+ const requests: Array<{ method: string; params: any }> = [];
+ const client = { request: async (method: string, params: unknown) => {
+ requests.push({ method, params });
+ // 服务端按真实 schema 报缺 content —— 这才是模型该看到的修正信息。
+ throw Object.assign(new Error('MCP error -32602: missing content'), { invalidParams: true });
+ } };
+ const gateway = new context.Gateway();
+ // 第三方直调工具: name 是文件名, content 是正文, 没有 args 信封。
+ gateway.add('files', client, [{
+ name: 'write_file',
+ inputSchema: {
+ type: 'object',
+ properties: { name: { type: 'string' }, content: { type: 'string' } },
+ required: ['name', 'content'],
+ },
+ }]);
+ gateway.register({ registerTool: () => undefined });
+ await gateway.listResult({ server: 'files', tool: 'write_file' });
+ // 缺 name 时必须原样走到服务端, 由服务端报它真实的参数要求 (缺 name 与缺 content);
+ // 桥不得把它引向「把 name 当工具名、其余塞进 args」的错误形状。
+ // 关键: 参数里**不能带 name** —— 带了它新旧判据都不会进信封分支, 撤掉修复这测试照样绿,
+ // 就盖不住「普通工具又收到信封提示」这个回归。
+ // 错误正文过 safeMcpFailure 脱敏 (不外泄上游 body), 所以断言错误来自服务端那条路径,
+ // 关键证据是下面两条: 请求确实发出了, 且 arguments 逐字未被桥改写。
+ await expect(gateway.executeCall({ server: 'files', tool: 'write_file', args: { content: 'text' } }))
+ .rejects.toThrow(/write_file failed/);
+ expect(requests).toHaveLength(1);
+ expect(requests[0].params).toEqual({ name: 'write_file', arguments: { content: 'text' } });
});
+
+it('removes cache fields only for an exact learned Chat Completions route and preserves Fast', () => {
+ const start = CINDY_BRIDGE_EXTENSION_SOURCE.indexOf(' function learnedCachePayload(');
+ const end = CINDY_BRIDGE_EXTENSION_SOURCE.indexOf(" pi.on('before_provider_request'", start);
+ const model = { provider: 'connection-a', id: 'wire', baseUrl: 'http://localhost/api.openai.com/v1', api: 'openai-completions' };
+ let rules = JSON.stringify([model]);
+ const adapt = new Function('path', 'process', 'statSync', 'readFileSync', CINDY_BRIDGE_EXTENSION_SOURCE.slice(start, end) + '; return learnedCachePayload;')(
+ { join: (...v: string[]) => v.join('/') }, { env: { PI_CODING_AGENT_DIR: '/isolated' } }, () => ({ size: rules.length }), () => rules,
+ );
+ const original = { messages: [], prompt_cache_key: 'key', prompt_cache_retention: '24h', service_tier: 'priority' };
+ expect(adapt(original, model)).toEqual({ messages: [], service_tier: 'priority' });
+ expect(original.prompt_cache_key).toBe('key');
+ expect(adapt(original, { ...model, provider: 'connection-b' })).toBe(original);
+ expect(adapt(original, { ...model, baseUrl: 'http://other/v1' })).toBe(original);
+ expect(adapt(original, { ...model, api: 'openai-responses' })).toBe(original);
+ rules = '{bad-json';
+ expect(adapt(original, model)).toBe(original);
+});
diff --cc packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
index d009760739,3564987cdb..f7f9da7231
--- a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
@@@ -2422,18 -2360,20 +2427,36 @@@ describe('pi translator live token spee
});
});
+it.each(['none', 'thinking', 'tool'])('reports a route receipt and blocks recovery after %s output', (kind) => {
+ const ctx = createPiTranslateContext(noopLogger);
+ const { queue, events } = makeQueue();
+ const receipt = { providerId: 'connection-a', modelId: 'public', wireModelId: 'wire', routeKey: 'a'.repeat(64), applied: false };
+ ctx.getCacheCompatibility = () => receipt;
+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);
+ if (kind === 'thinking') translatePiEvent(ev({ type: 'message_update', assistantMessageEvent: { type: 'thinking_delta', delta: 'working' } }), queue, ctx);
+ if (kind === 'tool') translatePiEvent(ev({ type: 'tool_execution_start', toolCallId: 'one', toolName: 'bash', args: { command: 'true' } }), queue, ctx);
+ translatePiEvent(ev({ type: 'message_end', message: { role: 'assistant', content: [], stopReason: 'error', errorMessage: '400: {"message":"Unsupported parameter(s): prompt_cache_key"}' } }), queue, ctx);
+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
+ expect(events.find((event) => event.type === 'error')?.data).toMatchObject({
+ reason: 'unsupported-request-option', piCacheCompatibility: receipt, piCacheRecoverySafe: kind === 'none',
+ });
+ disposePiTranslateContext(ctx);
+});
++
+ // Regression: [image] retained text but lost the actual media. Unit, native RPC entry.
+ it('retains tool image bytes and a video resource alongside text', () => {
+ const ctx = createPiTranslateContext(noopLogger);
+ const { queue, events } = makeQueue();
+ translatePiEvent(ev({ type: 'tool_execution_end', toolCallId: 'media', result: {
+ content: [{ type: 'text', text: 'preview' },
+ { type: 'image', mimeType: 'image/png', data: 'aW1hZ2U=' },
+ { type: 'resource_link', mimeType: 'video/mp4', uri: 'https://example.com/clip.mp4' }],
+ } }), queue, ctx);
+ expect(events.find(e => e.type === 'tool_result_full')?.data).toMatchObject({
+ toolUseId: 'media', fullText: 'preview\n[image]', processMedia: [
+ { kind: 'image', mimeType: 'image/png', data: 'aW1hZ2U=' },
+ { kind: 'video', url: 'https://example.com/clip.mp4' },
+ ],
+ });
+ disposePiTranslateContext(ctx);
+ });