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(codex): restore scheduler MCP in existing threads

Dash18660d9128e3
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 2ddbd20a29..e184a10ada 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -10028,6 +10028,106 @@ describe('CodexAgent MCP thread context hooks', () => {
await resumeHandle.close();
});
+ it('cold-resumes the same Codex thread when its configured scheduler MCP is missing', async () => {
+ const threadId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
+ const agent = new CodexAgent(createDeps());
+ let resumeCount = 0;
+ const host = installFakeHost(agent, (method, params) => {
+ if (method === Method.ThreadResume) {
+ resumeCount++;
+ return { thread: { id: threadId }, model: 'gpt-5.4', modelProvider: 'openai' };
+ }
+ if (method === Method.McpServerStatusList) {
+ expect(params).toMatchObject({ threadId, detail: 'toolsAndAuthOnly' });
+ return {
+ data: resumeCount > 1 ? [{ name: 'cindy_scheduler', tools: { list_tools: {}, call_tool: {} } }] : [],
+ nextCursor: null,
+ };
+ }
+ if (method === Method.TurnStart) return { turn: { id: 'scheduler-turn' } };
+ return undefined;
+ }, {
+ buildSessionMcpConfig: () => ({ 'mcp_servers.cindy_scheduler.url': 'http://127.0.0.1:47100/mcp/cindy_scheduler' }),
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-scheduler-recovery', resumeSessionId: threadId,
+ model: 'gpt-5.4', workingDir: '/repo',
+ });
+ const originalSubscription = host.subscribeThread.mock.results[0]!.value;
+ await handle.send({ type: 'user', content: 'Create the heartbeat.' });
+ expect(originalSubscription.release).toHaveBeenCalledOnce();
+ expect(host.subscribeThread).toHaveBeenCalledTimes(2);
+ expect(host.request.mock.calls.filter(([method]) => method === Method.ThreadResume)).toHaveLength(2);
+ const coldResume = host.request.mock.calls.filter(([method]) => method === Method.ThreadResume)[1]![1];
+ expect(coldResume).toMatchObject({ threadId, config: { 'mcp_servers.cindy_scheduler.url': 'http://127.0.0.1:47100/mcp/cindy_scheduler' } });
+ expect(host.request.mock.calls.map(([method]) => method).lastIndexOf(Method.McpServerStatusList))
+ .toBeLessThan(host.request.mock.calls.findIndex(([method]) => method === Method.TurnStart));
+ await handle.close();
+ });
+
+ it('leaves a resumed Codex thread intact when its scheduler MCP is available', async () => {
+ const threadId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method, params) => {
+ if (method === Method.ThreadResume) {
+ return { thread: { id: threadId }, model: 'gpt-5.4', modelProvider: 'openai' };
+ }
+ if (method === Method.McpServerStatusList) {
+ expect(params).toMatchObject({ threadId });
+ return { data: [{ name: 'cindy_scheduler', tools: { list_tools: {}, call_tool: {} } }], nextCursor: null };
+ }
+ if (method === Method.TurnStart) return { turn: { id: 'available-scheduler-turn' } };
+ return undefined;
+ }, {
+ buildSessionMcpConfig: () => ({ 'mcp_servers.cindy_scheduler.url': 'http://127.0.0.1:47100/mcp/cindy_scheduler' }),
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-scheduler-available', resumeSessionId: threadId,
+ model: 'gpt-5.4', workingDir: '/repo',
+ });
+ await handle.send({ type: 'user', content: 'Continue.' });
+ expect(host.request.mock.calls.filter(([method]) => method === Method.ThreadResume)).toHaveLength(1);
+ expect(host.subscribeThread).toHaveBeenCalledOnce();
+ await handle.close();
+ });
+
+ it('does not recover a scheduler MCP explicitly disabled for the task', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'disabled-scheduler-turn' } };
+ return undefined;
+ }, {
+ buildSessionMcpConfig: () => ({
+ 'mcp_servers.cindy_scheduler.url': 'http://127.0.0.1:47100/mcp/cindy_scheduler',
+ 'mcp_servers.cindy_scheduler.enabled': false,
+ }),
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-scheduler-disabled', model: 'gpt-5.4', workingDir: '/repo',
+ });
+ await handle.send({ type: 'user', content: 'Continue.' });
+ expect(host.request.mock.calls.some(([method]) => method === Method.McpServerStatusList)).toBe(false);
+ expect(host.request.mock.calls.some(([method]) => method === Method.ThreadResume)).toBe(false);
+ await handle.close();
+ });
+
+ it('waits for a saved rollout before checking a new thread scheduler MCP', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'new-thread-turn' } };
+ return undefined;
+ }, {
+ buildSessionMcpConfig: () => ({ 'mcp_servers.cindy_scheduler.url': 'http://127.0.0.1:47100/mcp/cindy_scheduler' }),
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-scheduler-new-thread', model: 'gpt-5.4', workingDir: '/repo',
+ });
+ await handle.send({ type: 'user', content: 'First turn.' });
+ expect(host.request.mock.calls.some(([method]) => method === Method.McpServerStatusList)).toBe(false);
+ expect(host.request.mock.calls.some(([method]) => method === Method.ThreadResume)).toBe(false);
+ await handle.close();
+ });
+
it('unsubscribes the app-server thread when closing a local session without stopping the shared host', async () => {
const agent = new CodexAgent(createDeps());
const handle = await agent.startSession({
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index d9e6827975..a7f2c60f59 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -7275,9 +7275,9 @@ assertRouteCurrent();
// Loaded-thread resume ignores arbitrary config. Release only this thread,
// then cold-resume its intact rollout before accepting another turn.
- const ensureContextLimitForNextTurn = (signal?: AbortSignal): Promise<void> | null => {
+ const ensureContextLimitForNextTurn = (signal?: AbortSignal, forceMcpRefresh = false): Promise<void> | null => {
const desired = currentContextLimit();
- if (desired === appliedContextLimit) return null;
+ if (desired === appliedContextLimit && !forceMcpRefresh) return null;
return (async () => {
if (signal?.aborted || closed) throw new Error('Codex context settings update cancelled');
if (!threadMayHaveRollout) {
@@ -7328,6 +7328,74 @@ assertRouteCurrent();
})();
};
+ // The host-level MCP probe can be green while a loaded thread still has an
+ // older per-thread catalog. Codex ignores MCP config on a loaded-thread
+ // resume; the release + cold resume above is required to add the server.
+ let schedulerMcpChecked = false;
+ const ensureSchedulerMcpForNextTurn = (signal?: AbortSignal): Promise<void> | null => {
+ // A brand-new thread may still be connecting its MCPs before the first
+ // turn. Wait until it has a saved rollout so recovery can preserve it.
+ if (schedulerMcpChecked || reviewMode || !threadMayHaveRollout) return null;
+ const config = currentThreadWorkspaceConfig().config;
+ if ((typeof config?.['mcp_servers.cindy_scheduler.url'] !== 'string' &&
+ typeof config?.['mcp_servers.cindy_scheduler.command'] !== 'string') ||
+ config?.['mcp_servers.cindy_scheduler.enabled'] === false) return null;
+
+ const verifyAndRecover = async (): Promise<void> => {
+ const hasScheduler = async (): Promise<boolean> => {
+ let cursor: string | null = null;
+ do {
+ const status: CodexMcpServerStatusListResponse = await host.request<CodexMcpServerStatusListResponse>(
+ Method.McpServerStatusList,
+ { cursor, limit: 100, detail: 'toolsAndAuthOnly', threadId },
+ { timeoutMs: 10_000 },
+ );
+ const scheduler = status.data.find((server) => server.name === 'cindy_scheduler');
+ if (scheduler && Object.hasOwn(scheduler.tools, 'list_tools') &&
+ Object.hasOwn(scheduler.tools, 'call_tool')) return true;
+ cursor = status.nextCursor;
+ } while (cursor !== null);
+ return false;
+ };
+
+ let available: boolean;
+ try {
+ available = await hasScheduler();
+ } catch (error) {
+ // A failed diagnostic must not prevent unrelated work.
+ schedulerMcpChecked = true;
+ log.warn('scheduler MCP verification failed', {
+ threadId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return;
+ }
+ if (available) {
+ schedulerMcpChecked = true;
+ return;
+ }
+ log.warn('expected scheduler MCP is missing from Codex thread; cold-resuming', { threadId });
+ // The existing refresh path closes this handle if the cold resume cannot
+ // be confirmed. Propagate that failure instead of sending on a stale one.
+ await ensureContextLimitForNextTurn(signal, true);
+ try {
+ available = await hasScheduler();
+ } catch (error) {
+ schedulerMcpChecked = true;
+ log.warn('scheduler MCP verification after cold resume failed', {
+ threadId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return;
+ }
+ schedulerMcpChecked = true;
+ if (!available) {
+ log.warn('scheduler MCP remains unavailable after Codex thread cold resume', { threadId });
+ }
+ };
+ return verifyAndRecover();
+ };
+
// ── dispatchInteraction + pendingApprovals (Claude 同款 dismissAllPending 模式) ──
//
// 为什么需要 pendingApprovals Map: server 发来 ServerRequest, 我们 await
@@ -13012,6 +13080,8 @@ assertRouteCurrent();
if (contextRefresh) await contextRefresh;
const profileRefresh = ensureWorkspacePermissionProfileForNextTurn(sendOpts?.signal);
if (profileRefresh) await profileRefresh;
+ const schedulerRefresh = ensureSchedulerMcpForNextTurn(sendOpts?.signal);
+ if (schedulerRefresh) await schedulerRefresh;
turnWorkspaceConfig = currentTurnWorkspaceConfig();
// A stale-daemon retry must hydrate the exact thread-level profile
// that matches this turn, not mutable settings changed while the
diff --git a/packages/maker-core/src/agents/codex/mcp-resume.native.test.ts b/packages/maker-core/src/agents/codex/mcp-resume.native.test.ts
new file mode 100644
index 0000000000..e29eb4d14a
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/mcp-resume.native.test.ts
@@ -0,0 +1,129 @@
+/** Opt-in native MCP recovery check. No credentials or external requests. */
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { createServer } from 'node:http';
+import { expect, it } from 'vitest';
+import { AppServerHost } from './app-server/host.js';
+import { createStdioTransport } from './app-server/stdioTransport.js';
+import type { Logger } from '../../interfaces/logger.js';
+
+const binaryPath = process.env.CINDY_CODEX_TEST_BINARY;
+const logger: Logger = {
+ trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {},
+ child: () => logger,
+};
+
+it.skipIf(!binaryPath)('loads an authorized MCP on cold resume of the same thread', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-mcp-resume-'));
+ let modelRequests = 0;
+ let codeModeSawScheduler = false;
+ const modelServer = createServer(async (request, response) => {
+ if (request.method !== 'POST') {
+ response.writeHead(200, { 'content-type': 'application/json' });
+ response.end('{"models":[]}');
+ return;
+ }
+ let text = '';
+ for await (const chunk of request) text += chunk;
+ const body = JSON.parse(text) as { model: string; input?: unknown[] };
+ const number = ++modelRequests;
+ if (number === 3) codeModeSawScheduler = JSON.stringify(body.input).includes('SCHEDULER_PRESENT');
+ const output = number === 2
+ ? [{ type: 'custom_tool_call', name: 'exec', call_id: 'check-scheduler',
+ input: 'text(["list_tools", "call_tool"].every(name => ALL_TOOLS.some(x => x.name === `mcp__cindy_scheduler__${name}`)) ? "SCHEDULER_PRESENT" : "SCHEDULER_MISSING")' }]
+ : [{
+ type: 'message', role: 'assistant', id: 'done', status: 'completed',
+ content: [{ type: 'output_text', text: 'Done.', annotations: [] }],
+ }];
+ response.writeHead(200, { 'content-type': 'text/event-stream' });
+ response.write(`data: ${JSON.stringify({ type: 'response.output_item.done', output_index: 0, item: output[0] })}\n\n`);
+ response.end(`data: ${JSON.stringify({
+ type: 'response.completed',
+ response: {
+ id: 'resp_test', object: 'response', status: 'completed', model: body.model, output,
+ usage: { input_tokens: 10, output_tokens: 1, total_tokens: 11 },
+ },
+ })}\n\n`);
+ });
+ await new Promise<void>((resolve) => modelServer.listen(0, '127.0.0.1', resolve));
+ const address = modelServer.address();
+ if (!address || typeof address === 'string') throw new Error('Missing loopback address');
+ const mcpPath = path.join(root, 'mcp.mjs');
+ await fs.writeFile(mcpPath, `import { createInterface } from 'node:readline';
+for await (const line of createInterface({ input: process.stdin })) {
+ const request = JSON.parse(line);
+ if (request.id === undefined) continue;
+ let result = {};
+ if (request.method === 'initialize') result = { protocolVersion: '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'cindy_scheduler', version: '1' } };
+ if (request.method === 'tools/list') result = { tools: [
+ { name: 'list_tools', description: 'List scheduler tools', inputSchema: { type: 'object' } },
+ { name: 'call_tool', description: 'Call scheduler tool', inputSchema: { type: 'object' } },
+ ] };
+ console.log(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }));
+}`);
+ const host = new AppServerHost({
+ logger,
+ clientInfo: { name: 'cindy-mcp-resume-test', version: '1' },
+ createTransport: () => createStdioTransport({
+ binaryPath: binaryPath!, cwd: root,
+ env: {
+ PATH: process.env.PATH ?? '', HOME: root, USERPROFILE: root, CODEX_HOME: root,
+ ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}),
+ },
+ extraArgs: [
+ '-c', 'model_provider="probe"',
+ '-c', 'model_providers.probe.name="Probe"',
+ '-c', `model_providers.probe.base_url="http://127.0.0.1:${address.port}"`,
+ '-c', 'model_providers.probe.wire_api="responses"',
+ '-c', 'model_providers.probe.requires_openai_auth=false',
+ '-c', `mcp_servers.cindy_scheduler.command=${JSON.stringify(process.execPath)}`,
+ '-c', `mcp_servers.cindy_scheduler.args=[${JSON.stringify(mcpPath)}]`,
+ ],
+ }),
+ });
+ try {
+ await host.ensureStarted();
+ const started = await host.request<{ thread: { id: string } }>('thread/start', {
+ cwd: root, model: 'gpt-5.6-luna', modelProvider: 'probe',
+ config: { 'mcp_servers.cindy_scheduler.enabled': false },
+ });
+ const threadId = started.thread.id;
+ const list = () => host.request<{ data: Array<{ name: string; tools: Record<string, unknown> }>; nextCursor: string | null }>(
+ 'mcpServerStatus/list', { threadId, detail: 'toolsAndAuthOnly', limit: 100, cursor: null },
+ );
+ const before = await list();
+ expect(before.data.some((server) => server.name === 'cindy_scheduler' && 'list_tools' in server.tools)).toBe(false);
+ let complete = false;
+ const subscription = host.subscribeThread(threadId, { turnCompleted: () => { complete = true; } });
+ await host.request('turn/start', { threadId, input: [{ type: 'text', text: 'Say done.' }] });
+ await expect.poll(() => complete, { timeout: 15_000 }).toBe(true);
+ await host.request('thread/resume', {
+ threadId, cwd: root, excludeTurns: true,
+ model: 'gpt-5.6-luna', modelProvider: 'probe',
+ config: { 'mcp_servers.cindy_scheduler.enabled': true },
+ });
+ const loaded = await list();
+ expect(loaded.data.some((server) => server.name === 'cindy_scheduler' && 'list_tools' in server.tools)).toBe(false);
+ await subscription.release();
+ await host.request('thread/resume', {
+ threadId, cwd: root, excludeTurns: true,
+ model: 'gpt-5.6-luna', modelProvider: 'probe',
+ config: { 'mcp_servers.cindy_scheduler.enabled': true },
+ });
+ const after = await list();
+ expect(after.data.some((server) => server.name === 'cindy_scheduler' &&
+ 'list_tools' in server.tools && 'call_tool' in server.tools)).toBe(true);
+ let secondComplete = false;
+ const resumedSubscription = host.subscribeThread(threadId, { turnCompleted: () => { secondComplete = true; } });
+ await host.request('turn/start', { threadId, input: [{ type: 'text', text: 'Check scheduler.' }] });
+ await expect.poll(() => secondComplete, { timeout: 15_000 }).toBe(true);
+ expect(modelRequests).toBe(3);
+ expect(codeModeSawScheduler).toBe(true);
+ await resumedSubscription.release();
+ } finally {
+ await host.retire('native MCP recovery test complete');
+ await new Promise<void>((resolve) => { modelServer.close(() => resolve()); modelServer.closeAllConnections(); });
+ await fs.rm(root, { recursive: true, force: true });
+ }
+}, 30_000);