Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): keep goal continuation under Cindy ownership (#5395)
Dash88e224475a61
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex 9f10834f5d..3475d485f1 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -261,6 +261,11 @@ sessionRunningRetry 就停。每次因 replacement 关闭而重新入队都计- 打算用 prompt 解决某个问题前先自问:这件事用代码能不能做?能就用代码。- 把本应由代码保证的确定性逻辑(格式校验、字段抽取、流程跳转、是否调用某个工具等)交给模型自由发挥,会引入不可复现的行为漂移,属于本规则明确禁止的做法。+- Cindy 的目标模式由 `goal-host` 统一管理续跑、预算与暂停/恢复。Codex 创建和恢复线程时+ 使用会话级 `features.goals=false`,避免模型另建原生目标,形成绕过宿主调度与来源标记的+ 第二套循环;不写用户的全局 Codex 配置。不能仅把无来源事件改判为目标事件,否则用户+ 插话和停止边界仍会失真。实现与回归见 `agents/codex/index.ts`、`index.test.ts`;+ `goal-ownership.native.test.ts` 用隔离的原生运行时验证旧目标恢复后不再自行续跑。- **产品 turn 未结算不得结束。** provider `turn/completed` 可以立刻给 SDK turn 落墓碑并结算 usage;只有原子挂在该终态边界上的显式 continuation claim 才能挡住产品结束。Codex 提问/计划审阅尚待用户确认时同样保留产品边界:底层可继续独立工作并结束diff --git a/packages/maker-core/src/agents/codex/goal-ownership.native.test.ts b/packages/maker-core/src/agents/codex/goal-ownership.native.test.tsnew file mode 100644index 0000000000..591ea59f1a--- /dev/null+++ b/packages/maker-core/src/agents/codex/goal-ownership.native.test.ts@@ -0,0 +1,206 @@+/** Opt-in native regression; isolated Home and loopback fake model, no credentials.+ * CINDY_CODEX_TEST_BINARY=<binary> vitest run src/agents/codex/goal-ownership.native.test.ts+ */+import fs from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { createServer, type ServerResponse } 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)(+ "disables native goal tools and continuation even when resuming a persisted active goal",+ async () => {+ const root = await fs.mkdtemp(+ path.join(os.tmpdir(), "cindy-goal-ownership-"),+ );+ const requests: Array<{+ body: { input: Array<{ role?: string; content?: unknown }> };+ response: ServerResponse;+ }> = [];+ let replyAutomatically = false;+ const reply = (response: ServerResponse) => {+ const output = [+ {+ type: "message",+ id: "answer",+ role: "assistant",+ status: "completed",+ content: [+ {+ type: "output_text",+ text: "One step completed.",+ annotations: [],+ },+ ],+ },+ ];+ response.writeHead(200, { "Content-Type": "text/event-stream" });+ response.end(+ `event: response.completed\ndata: ${JSON.stringify({+ type: "response.completed",+ response: {+ id: "response",+ status: "completed",+ output,+ usage: { input_tokens: 10, output_tokens: 1, total_tokens: 11 },+ },+ })}\n\n`,+ );+ };+ const server = createServer(async (request, response) => {+ if (request.method !== "POST") {+ response.end('{"models":[]}');+ return;+ }+ let body = "";+ for await (const chunk of request) body += chunk;+ requests.push({ body: JSON.parse(body), response });+ if (replyAutomatically) reply(response);+ });+ const hosts: AppServerHost[] = [];+ try {+ await new Promise<void>((resolve) =>+ server.listen(0, "127.0.0.1", resolve),+ );+ const address = server.address();+ if (!address || typeof address === "string")+ throw new Error("Missing loopback address");+ const makeHost = () => {+ const host = new AppServerHost({+ logger,+ clientInfo: { name: "cindy-goal-ownership-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",+ "features.code_mode=false",+ "-c",+ "features.code_mode_only=false",+ ],+ }),+ });+ hosts.push(host);+ return host;+ };+ const original = makeHost();+ await original.ensureStarted();+ const { thread } = await original.request<{ thread: { id: string } }>(+ "thread/start",+ {+ cwd: root,+ model: "gpt-6-astra",+ modelProvider: "probe",+ approvalPolicy: "never",+ sandbox: "read-only",+ config: { "features.goals": true },+ },+ );+ await original.request("turn/start", {+ threadId: thread.id,+ input: [{ type: "text", text: "Complete the goal." }],+ });+ await expect.poll(() => requests.length, { timeout: 15_000 }).toBe(1);+ await original.request("thread/goal/set", {+ threadId: thread.id,+ objective: "Complete two steps",+ status: "active",+ });+ reply(requests[0]!.response);+ // Reproduce the second, provider-owned turn with no new Host send.+ await expect.poll(() => requests.length, { timeout: 15_000 }).toBe(2);+ expect(JSON.stringify(requests[0]!.body)).toContain("create_goal");+ await original.retire("cold resume fixture");++ replyAutomatically = true;+ const resumed = makeHost();+ await resumed.ensureStarted();+ await resumed.request("thread/resume", {+ threadId: thread.id,+ cwd: root,+ model: "gpt-6-astra",+ modelProvider: "probe",+ approvalPolicy: "never",+ sandbox: "read-only",+ config: { "features.goals": false },+ });+ const goal = await resumed.request<{ goal: { status: string } }>(+ "thread/goal/get",+ { threadId: thread.id },+ );+ expect(goal.goal.status).toBe("active");+ let completed = 0;+ const subscription = resumed.subscribeThread(thread.id, {+ turnCompleted: () => {+ completed += 1;+ },+ });+ try {+ for (const step of [1, 2]) {+ await resumed.request("turn/start", {+ threadId: thread.id,+ input: [{ type: "text", text: `Run Cindy-owned step ${step}.` }],+ });+ await expect.poll(() => completed, { timeout: 15_000 }).toBe(step);+ await new Promise((resolve) => setTimeout(resolve, 500));+ expect(requests).toHaveLength(2 + step);+ expect(JSON.stringify(requests[1 + step]!.body)).not.toContain(+ "create_goal",+ );+ expect(completed).toBe(step);+ }+ // Stable system/developer content across Host sends; no per-turn+ // workaround, changing prefix, or extra model request is introduced.+ const prefix = (index: number) =>+ requests[index]!.body.input.filter(+ (item) => item.role === "system" || item.role === "developer",+ ).map((item) => ({ role: item.role, content: item.content }));+ expect(prefix(3)).toEqual(prefix(2));+ } finally {+ await subscription.release();+ }+ } finally {+ for (const host of hosts) await host.retire("native goal test complete");+ await new Promise<void>((resolve) => {+ server.close(() => resolve());+ server.closeAllConnections();+ });+ await fs.rm(root, { recursive: true, force: true });+ }+ },+ 45_000,+);diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 7502a99235..f4ad65d8e2 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -1814,6 +1814,27 @@ describe('CodexAgent permissions', () => {});});+ it.each([false, true])('keeps goal continuation owned by Cindy on thread startup (resume=%s)', async (resume) => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'host-owned-goal',+ model: 'gpt-6-astra',+ workingDir: '/repo',+ ...(resume ? { resumeSessionId: '11111111-1111-1111-1111-111111111111' } : {}),+ });+ try {+ const params = host.request.mock.calls.find(+ ([method]) => method === (resume ? Method.ThreadResume : Method.ThreadStart),+ )?.[1] as { config: Record<string, unknown> };+ // A native create_goal would start a second loop outside the Host's+ // pause/budget controls and lose turnOrigin after its first completion.+ expect(params.config['features.goals']).toBe(false);+ } finally {+ await handle.close();+ }+ });+it.each([{ transport: 'absent', memoryConfig: undefined },{ transport: 'stdio', memoryConfig: { command: 'memory-server', enabled: true } },diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex a998f1d0c0..88864da612 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -6371,6 +6371,10 @@ assertRouteCurrent();// Install while the thread is created/resumed: a later switch to Auto// changes the turn reviewer without rebuilding this thread config....nativeContinuationConfig,+ // Cindy owns goal dispatch, budgets and pause/resume. A native goal+ // starts a second continuation loop whose turns bypass Session.send+ // and lose the Host origin after the first terminal event.+ 'features.goals': false,// Keep companion memory in its own Home. Native delegation uses the// same feature settings and permissions as an ordinary task....(opts.botRuntimeProfile ? {@@ -6412,7 +6416,6 @@ assertRouteCurrent();} : {}),web_search: 'disabled','features.apps': false,- 'features.goals': false,'features.hooks': false,'features.multi_agent': false,'features.remote_plugin': false,